diff --git a/.changeset/eleven-aliens-sell.md b/.changeset/eleven-aliens-sell.md new file mode 100644 index 00000000..604e63b4 --- /dev/null +++ b/.changeset/eleven-aliens-sell.md @@ -0,0 +1,12 @@ +--- +'@modelscope-studio/lint-config': major +'@modelscope-studio/changelog': major +'@modelscope-studio/antdx': major +'@modelscope-studio/antd': major +'@modelscope-studio/base': major +'@modelscope-studio/pro': major +'@modelscope-studio/frontend': major +'modelscope_studio': major +--- + +refactor: migrate to Gradio 6.0, Ant Design 6.0, Ant Design X 2.0 diff --git a/.changeset/pink-sails-itch.md b/.changeset/pink-sails-itch.md new file mode 100644 index 00000000..3a8e7eb4 --- /dev/null +++ b/.changeset/pink-sails-itch.md @@ -0,0 +1,12 @@ +--- +'@modelscope-studio/lint-config': patch +'@modelscope-studio/changelog': patch +'@modelscope-studio/antdx': patch +'@modelscope-studio/antd': patch +'@modelscope-studio/base': patch +'@modelscope-studio/pro': patch +'@modelscope-studio/frontend': patch +'modelscope_studio': patch +--- + +feat: complete new features of antd & antdx diff --git a/.changeset/pre.json b/.changeset/pre.json new file mode 100644 index 00000000..edd5cdf2 --- /dev/null +++ b/.changeset/pre.json @@ -0,0 +1,15 @@ +{ + "mode": "pre", + "tag": "beta", + "initialVersions": { + "modelscope_studio": "1.6.1", + "@modelscope-studio/changelog": "1.6.1", + "@modelscope-studio/lint-config": "1.6.1", + "@modelscope-studio/frontend": "1.6.1", + "@modelscope-studio/antd": "1.6.1", + "@modelscope-studio/antdx": "1.6.1", + "@modelscope-studio/base": "1.6.1", + "@modelscope-studio/pro": "1.6.1" + }, + "changesets": ["eleven-aliens-sell", "pink-sails-itch"] +} diff --git a/.github/workflows/publish.yaml b/.github/workflows/publish.yaml index a99fcebe..ad4c67a7 100644 --- a/.github/workflows/publish.yaml +++ b/.github/workflows/publish.yaml @@ -4,6 +4,7 @@ on: push: branches: - main + - next env: CI: true @@ -37,7 +38,7 @@ jobs: github.event.head_commit.message == 'chore: update versions' uses: actions/setup-node@v3 with: - node-version: 20 + node-version: 22 - name: Install Pnpm if: | github.event.head_commit.message == 'chore: update versions' diff --git a/.gitignore b/.gitignore index 21b86773..b8470bf2 100644 --- a/.gitignore +++ b/.gitignore @@ -61,3 +61,5 @@ yalc.lock .stylelintcache .DS_Store .pytest_cache + +.qoder diff --git a/.vscode/settings.json b/.vscode/settings.json index 17e2c8cd..a96bd947 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -51,6 +51,5 @@ "editor.defaultFormatter": "esbenp.prettier-vscode" }, "python-envs.defaultEnvManager": "ms-python.python:conda", - "python-envs.defaultPackageManager": "ms-python.python:conda", - "python-envs.pythonProjects": [] + "python-envs.defaultPackageManager": "ms-python.python:conda" } diff --git a/.wiki/en/API Reference/API Reference.md b/.wiki/en/API Reference/API Reference.md new file mode 100644 index 00000000..dd2158e7 --- /dev/null +++ b/.wiki/en/API Reference/API Reference.md @@ -0,0 +1,514 @@ +# API Reference + + +**Files Referenced in This Document** +- [backend/modelscope_studio/__init__.py](file://backend/modelscope_studio/__init__.py) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) +- [backend/modelscope_studio/components/__init__.py](file://backend/modelscope_studio/components/__init__.py) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/table/table.tsx](file://frontend/antd/table/table.tsx) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [frontend/base/application/application.ts](file://frontend/base/application/application.ts) +- [frontend/pro/chatbot/chatbot.ts](file://frontend/pro/chatbot/chatbot.ts) +- [frontend/pro/monaco-editor/monaco-editor.ts](file://frontend/pro/monaco-editor/monaco-editor.ts) +- [frontend/pro/multimodal-input/multimodal-input.ts](file://frontend/pro/multimodal-input/multimodal-input.ts) +- [frontend/pro/web-sandbox/web-sandbox.ts](file://frontend/pro/web-sandbox/web-sandbox.ts) +- [frontend/utils/hooks/useAsyncEffect.ts](file://frontend/utils/hooks/useAsyncEffect.ts) +- [frontend/utils/hooks/useAsyncMemo.ts](file://frontend/utils/hooks/useAsyncMemo.ts) +- [frontend/utils/hooks/useDeepCompareEffect.ts](file://frontend/utils/hooks/useDeepCompareEffect.ts) +- [frontend/utils/hooks/useEvent.ts](file://frontend/utils/hooks/useEvent.ts) +- [frontend/utils/hooks/useMount.ts](file://frontend/utils/hooks/useMount.ts) +- [frontend/utils/hooks/useUnmount.ts](file://frontend/utils/hooks/useUnmount.ts) +- [frontend/utils/hooks/useUpdateEffect.ts](file://frontend/utils/hooks/useUpdateEffect.ts) +- [frontend/utils/createFunction.ts](file://frontend/utils/createFunction.ts) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/patchProps.tsx](file://frontend/utils/patchProps.tsx) +- [frontend/utils/omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) +- [frontend/utils/tick.ts](file://frontend/utils/tick.ts) +- [frontend/utils/upload.ts](file://frontend/utils/upload.ts) +- [frontend/globals/components/index.ts](file://frontend/globals/components/index.ts) +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the complete API reference for ModelScope Studio, covering both the Python backend component system and the frontend JavaScript/Svelte component system. The Python API provides a third-party component library wrapper based on Gradio, the frontend is implemented in Svelte, and the two work together through Gradio's custom component mechanism. This document is intended for developers and covers component import methods, class definitions, method signatures, parameter descriptions, return value types (Python), component props and events (JavaScript/Svelte), lifecycle hooks, public methods, usage examples, and notes, along with supplementary parameter validation rules, error handling mechanisms, and version compatibility information. + +## Project Structure + +ModelScope Studio adopts a multi-package structure with frontend-backend separation: + +- Backend Python Package: `modelscope_studio`, providing component exports and version information +- Frontend Svelte Packages: Multiple sub-packages organized by functional domain (antd, antdx, base, pro), with utility functions and a global component entry +- Build and Release: Custom component builds via the Gradio CLI, with support for disabling auto-generated documentation + +```mermaid +graph TB +subgraph "Backend Python" +PY_PKG["modelscope_studio Package"] +PY_VERSION["Version Information"] +PY_EXPORTS["Component Exports"] +end +subgraph "Frontend Svelte" +FE_ANTD["antd Sub-Package"] +FE_ANTDX["antdx Sub-Package"] +FE_BASE["base Sub-Package"] +FE_PRO["pro Sub-Package"] +FE_UTILS["utils Utility Set"] +FE_GLOBALS["globals Global Components"] +end +PY_PKG --> PY_EXPORTS +PY_EXPORTS --> FE_ANTD +PY_EXPORTS --> FE_ANTDX +PY_EXPORTS --> FE_BASE +PY_EXPORTS --> FE_PRO +FE_ANTD --> FE_UTILS +FE_ANTDX --> FE_UTILS +FE_BASE --> FE_UTILS +FE_PRO --> FE_UTILS +FE_GLOBALS --> FE_UTILS +``` + +Diagram Sources + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [frontend/globals/components/index.ts:1-2](file://frontend/globals/components/index.ts#L1-L2) + +Section Sources + +- [backend/modelscope_studio/**init**.py:1-3](file://backend/modelscope_studio/__init__.py#L1-L3) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [frontend/globals/components/index.ts:1-2](file://frontend/globals/components/index.ts#L1-L2) + +## Core Components + +This section provides an overview of the export and organization of Python and frontend components, helping developers quickly locate target components. + +- Python Imports and Exports + - Root package export: Imports all components from the `components` module and exposes the version number + - Component aggregation: Grouped exports by domain (antd, antdx, base, pro) + - antd sub-package: Exports numerous UI component aliases for direct use + - antdx sub-package: Exports conversation and content-related components +- Frontend Component Organization + - Each component typically corresponds to a Svelte file (e.g., `button.tsx`, `form.tsx`, `table.tsx`) + - Utility functions are centralized in `utils`, including hooks, renderers, prop patching, etc. + - `globals` provides the global component entry point, currently exporting the `markdown` sub-module + +Section Sources + +- [backend/modelscope_studio/**init**.py:1-3](file://backend/modelscope_studio/__init__.py#L1-L3) +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-144](file://backend/modelscope_studio/components/antd/components.py#L1-L144) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [frontend/globals/components/index.ts:1-2](file://frontend/globals/components/index.ts#L1-L2) + +## Architecture Overview + +The diagram below shows the interaction and data flow between the Python backend and frontend components: + +```mermaid +graph TB +PY_API["Python API
modelscope_studio.components.*"] +GRADIO["Gradio Runtime"] +FE_COMP["Frontend Components
Svelte Component Tree"] +UTILS["Frontend Utilities
hooks & renderers"] +PY_API --> GRADIO +GRADIO --> FE_COMP +FE_COMP --> UTILS +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/table/table.tsx](file://frontend/antd/table/table.tsx) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) + +## Detailed Component Analysis + +### Python API Reference (Overview) + +- Version and Dependencies + - Version: 2.0.0 + - Dependencies: Gradio 6.0 ≤ v ≤ 6.8.0 +- Import Methods + - `from modelscope_studio import ComponentName` + - Or `from modelscope_studio.components.antd import ComponentName` + - Or `from modelscope_studio.components.antdx import ComponentName` + - Or `from modelscope_studio.components.pro import Chatbot, MonacoEditor, MultimodalInput, WebSandbox` +- Classes and Aliases + - The antd sub-package exports numerous component aliases such as Button, Form, Table, etc. + - The antdx sub-package exports conversation and content-related components such as Bubble, Chatbot, Sender, etc. + - The pro sub-package exports professional capability components: Chatbot, MonacoEditor (including sub-component MonacoEditorDiffEditor), MultimodalInput, WebSandbox +- Example Paths + - Refer to component examples under `docs/demos` (e.g., the chatbot example) +- Notes + - Ensure the Gradio version meets the range requirements + - Some components may require additional frontend templates or assets (bundled by the build system) + +Section Sources + +- [pyproject.toml:26-26](file://pyproject.toml#L26-L26) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) + +### JavaScript/Svelte API Reference (Overview) + +- Component Organization + - antd: General UI components such as Button, Form, Table, etc. + - antdx: Conversation and content extension components such as Bubble, Sender, ThoughtChain, etc. + - base: Base container and logic components such as Application, Each, Filter, etc. + - pro: Professional capability components such as Chatbot, MonacoEditor, MultimodalInput, WebSandbox +- Props, Events, and Lifecycle + - Props: Passed via `props`, following Svelte conventions + - Events: Via `$on`/`$off` or Svelte event binding + - Lifecycle: mount/unmount/update and other hooks provided by the hooks utilities +- Public Methods + - Callable methods created via tools like `createFunction` + - Upload, slot rendering, prop patching, etc. provided by `utils` + +Section Sources + +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/table/table.tsx](file://frontend/antd/table/table.tsx) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [frontend/base/application/application.ts](file://frontend/base/application/application.ts) +- [frontend/pro/chatbot/chatbot.ts](file://frontend/pro/chatbot/chatbot.ts) +- [frontend/pro/monaco-editor/monaco-editor.ts](file://frontend/pro/monaco-editor/monaco-editor.ts) +- [frontend/pro/multimodal-input/multimodal-input.ts](file://frontend/pro/multimodal-input/multimodal-input.ts) +- [frontend/pro/web-sandbox/web-sandbox.ts](file://frontend/pro/web-sandbox/web-sandbox.ts) + +### Component A: Button + +- Python Import and Alias + - `from modelscope_studio.components.antd import Button` +- Frontend Component + - Path: `frontend/antd/button/button.tsx` + - Props: Refer to the props definition in the component file + - Events: Refer to the event bindings in the component file + - Lifecycle: Managed via hooks (e.g., `useMount`, `useUnmount`) +- Usage Examples + - Refer to example files under `docs/components/antd/button` +- Notes + - Ensure consistency with Gradio interaction patterns + - Use Ant Design icons when icons are required + +Section Sources + +- [backend/modelscope_studio/components/antd/**init**.py:14-14](file://backend/modelscope_studio/components/antd/__init__.py#L14-L14) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) + +### Component B: Form + +- Python Import and Aliases + - `from modelscope_studio.components.antd import Form, FormItem, FormProvider` +- Frontend Component + - Path: `frontend/antd/form/form.tsx` + - Props: Refer to the props definition in the component file + - Events: Refer to the event bindings in the component file + - Form Validation: `FormItem.Rule` supports rule configuration +- Usage Examples + - Refer to example files under `docs/components/antd/form` +- Notes + - Form state must be kept in sync with Gradio data flow + - Rule configuration must conform to Ant Design specifications + +Section Sources + +- [backend/modelscope_studio/components/antd/**init**.py:48-51](file://backend/modelscope_studio/components/antd/__init__.py#L48-L51) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) + +### Component C: Table + +- Python Import and Aliases + - `from modelscope_studio.components.antd import Table, TableColumn, TableRowSelection` +- Frontend Component + - Path: `frontend/antd/table/table.tsx` + - Props: Refer to the props definition in the component file + - Events: Refer to the event bindings in the component file + - Selection Column: `TableRowSelection` provides selection capability +- Usage Examples + - Refer to example files under `docs/components/antd/table` +- Notes + - Column configuration must match the data structure + - Selection behavior must align with Gradio output format + +Section Sources + +- [backend/modelscope_studio/components/antd/**init**.py:116-122](file://backend/modelscope_studio/components/antd/__init__.py#L116-L122) +- [frontend/antd/table/table.tsx](file://frontend/antd/table/table.tsx) + +### Component D: Bubble + +- Python Import and Alias + - `from modelscope_studio.components.antdx import Bubble` +- Frontend Component + - Path: `frontend/antdx/bubble/bubble.tsx` + - Props: Refer to the props definition in the component file + - Events: Refer to the event bindings in the component file +- Usage Examples + - Refer to example files under `docs/components/antdx/bubble` +- Notes + - Message content and styles should be adapted for conversation scenarios + +Section Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:8-13](file://backend/modelscope_studio/components/antdx/__init__.py#L8-L13) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) + +### Component E: Application + +- Frontend Component + - Path: `frontend/base/application/application.ts` + - Purpose: Serves as the application root container, managing context and layout +- Usage Examples + - Refer to example files under `docs/components/base/application` +- Notes + - Used in conjunction with other base components (e.g., Each, Filter) + +Section Sources + +- [frontend/base/application/application.ts](file://frontend/base/application/application.ts) + +### Component F: Chatbot + +- Python Import and Alias + - `from modelscope_studio.components.pro import Chatbot` +- Frontend Component + - Path: `frontend/pro/chatbot/chatbot.ts` + - Props: Refer to the props definition in the component file + - Events: Refer to the event bindings in the component file +- Usage Examples + - Refer to example files under `docs/components/pro/chatbot` +- Notes + - Pay attention to data formats when integrating with backend model services + +Section Sources + +- [backend/modelscope_studio/components/pro/components.py:1-20](file://backend/modelscope_studio/components/pro/components.py#L1-L20) +- [frontend/pro/chatbot/chatbot.ts](file://frontend/pro/chatbot/chatbot.ts) + +### Component G: MonacoEditor + +- Python Import and Alias + - `from modelscope_studio.components.pro import MonacoEditor` +- Frontend Component + - Path: `frontend/pro/monaco-editor/monaco-editor.ts` + - Props: Refer to the props definition in the component file + - Events: Refer to the event bindings in the component file +- Usage Examples + - Refer to example files under `docs/components/pro/monaco_editor` +- Notes + - Editor theme and language configuration must be consistent with Gradio interaction + +Section Sources + +- [backend/modelscope_studio/components/pro/components.py:1-20](file://backend/modelscope_studio/components/pro/components.py#L1-L20) +- [frontend/pro/monaco-editor/monaco-editor.ts](file://frontend/pro/monaco-editor/monaco-editor.ts) + +### Component H: MultimodalInput + +- Python Import and Alias + - `from modelscope_studio.components.pro import MultimodalInput` +- Frontend Component + - Path: `frontend/pro/multimodal-input/multimodal-input.ts` + - Props: Refer to the props definition in the component file + - Events: Refer to the event bindings in the component file +- Usage Examples + - Refer to example files under `docs/components/pro/multimodal_input` +- Notes + - Input types must match the backend model interface + +Section Sources + +- [backend/modelscope_studio/components/pro/components.py:1-20](file://backend/modelscope_studio/components/pro/components.py#L1-L20) +- [frontend/pro/multimodal-input/multimodal-input.ts](file://frontend/pro/multimodal-input/multimodal-input.ts) + +### Component I: WebSandbox + +- Python Import and Alias + - `from modelscope_studio.components.pro import WebSandbox` +- Frontend Component + - Path: `frontend/pro/web-sandbox/web-sandbox.ts` + - Props: Refer to the props definition in the component file + - Events: Refer to the event bindings in the component file +- Usage Examples + - Refer to example files under `docs/components/pro/web_sandbox` +- Notes + - Security policies and cross-origin restrictions must be configured during deployment + +Section Sources + +- [backend/modelscope_studio/components/pro/components.py:1-20](file://backend/modelscope_studio/components/pro/components.py#L1-L20) +- [frontend/pro/web-sandbox/web-sandbox.ts](file://frontend/pro/web-sandbox/web-sandbox.ts) + +### Component J: Global Components (Markdown) + +- Frontend Component + - Path: `frontend/globals/components/index.ts` + - Currently exports the `markdown` sub-module +- Usage Examples + - Refer to example files under `docs/components/base/markdown` +- Notes + - Global components must be uniformly registered at the application entry point + +Section Sources + +- [frontend/globals/components/index.ts:1-2](file://frontend/globals/components/index.ts#L1-L2) + +## Dependency Analysis + +- Python Side + - Dependencies: Gradio 6.0 ≤ v ≤ 6.8.0 + - Version: 2.0.0 +- Frontend Side + - Build scripts: Component builds executed via Gradio CLI + - Dev scripts: Start the documentation site dev server +- Tools and Rendering + - hooks: `useMount`, `useUnmount`, `useUpdateEffect`, `useAsyncEffect`, `useAsyncMemo`, `useDeepCompareEffect`, `useEvent` + - Renderers: `renderSlot`, `renderParamsSlot`, `renderItems` + - Prop handling: `patchProps`, `omitUndefinedProps` + - Others: `createFunction`, `tick`, `upload` + +```mermaid +graph TB +PY_DEPS["Python Dependencies
Gradio 6.0 ≤ v ≤ 6.8.0"] +FE_SCRIPTS["Frontend Scripts
Build/Dev"] +FE_HOOKS["hooks Utility Set"] +FE_RENDER["Renderers"] +FE_PATCH["Prop Handling"] +FE_OTHER["Other Utilities"] +PY_DEPS --> FE_SCRIPTS +FE_SCRIPTS --> FE_HOOKS +FE_SCRIPTS --> FE_RENDER +FE_SCRIPTS --> FE_PATCH +FE_SCRIPTS --> FE_OTHER +``` + +Diagram Sources + +- [pyproject.toml:26-26](file://pyproject.toml#L26-L26) +- [package.json:8-24](file://package.json#L8-L24) +- [frontend/utils/hooks/useMount.ts](file://frontend/utils/hooks/useMount.ts) +- [frontend/utils/hooks/useUnmount.ts](file://frontend/utils/hooks/useUnmount.ts) +- [frontend/utils/hooks/useUpdateEffect.ts](file://frontend/utils/hooks/useUpdateEffect.ts) +- [frontend/utils/hooks/useAsyncEffect.ts](file://frontend/utils/hooks/useAsyncEffect.ts) +- [frontend/utils/hooks/useAsyncMemo.ts](file://frontend/utils/hooks/useAsyncMemo.ts) +- [frontend/utils/hooks/useDeepCompareEffect.ts](file://frontend/utils/hooks/useDeepCompareEffect.ts) +- [frontend/utils/hooks/useEvent.ts](file://frontend/utils/hooks/useEvent.ts) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/patchProps.tsx](file://frontend/utils/patchProps.tsx) +- [frontend/utils/omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) +- [frontend/utils/createFunction.ts](file://frontend/utils/createFunction.ts) +- [frontend/utils/tick.ts](file://frontend/utils/tick.ts) +- [frontend/utils/upload.ts](file://frontend/utils/upload.ts) + +Section Sources + +- [pyproject.toml:26-26](file://pyproject.toml#L26-L26) +- [package.json:8-24](file://package.json#L8-L24) +- [frontend/utils/hooks/useMount.ts](file://frontend/utils/hooks/useMount.ts) +- [frontend/utils/hooks/useUnmount.ts](file://frontend/utils/hooks/useUnmount.ts) +- [frontend/utils/hooks/useUpdateEffect.ts](file://frontend/utils/hooks/useUpdateEffect.ts) +- [frontend/utils/hooks/useAsyncEffect.ts](file://frontend/utils/hooks/useAsyncEffect.ts) +- [frontend/utils/hooks/useAsyncMemo.ts](file://frontend/utils/hooks/useAsyncMemo.ts) +- [frontend/utils/hooks/useDeepCompareEffect.ts](file://frontend/utils/hooks/useDeepCompareEffect.ts) +- [frontend/utils/hooks/useEvent.ts](file://frontend/utils/hooks/useEvent.ts) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/patchProps.tsx](file://frontend/utils/patchProps.tsx) +- [frontend/utils/omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) +- [frontend/utils/createFunction.ts](file://frontend/utils/createFunction.ts) +- [frontend/utils/tick.ts](file://frontend/utils/tick.ts) +- [frontend/utils/upload.ts](file://frontend/utils/upload.ts) + +## Performance Considerations + +- Component Lazy Loading and On-Demand Import: Prefer importing specific components to avoid importing too many modules at once +- Rendering Optimization: Use tools like `renderItems` and `renderParamsSlot` to reduce redundant rendering +- Async Processing: Use `useAsyncEffect`/`useAsyncMemo` to handle async side effects, avoiding blocking the main thread +- Prop Patching: Use `patchProps` to merge props appropriately, reducing unnecessary re-renders +- Upload and Resources: The `upload` utility should be combined with Gradio's upload flow to avoid blocking with large files + +## Troubleshooting Guide + +- Version Incompatibility + - Symptom: Runtime errors or functional anomalies + - Diagnosis: Confirm the Gradio version is within the 6.0 ≤ v ≤ 6.8.0 range +- Component Not Taking Effect + - Symptom: Frontend component not displaying or unresponsive + - Diagnosis: Check that the component is correctly imported; confirm that the build artifacts have been generated; verify props being passed +- Form Validation Failure + - Symptom: Error on submit or no feedback + - Diagnosis: Check `FormItem.Rule` configuration; confirm field names match the data structure +- Upload Anomaly + - Symptom: File upload failure or progress anomaly + - Diagnosis: Check `upload` utility calls; confirm backend interface is consistent with Gradio's upload protocol +- Lifecycle Issues + - Symptom: Side effects persist after component unmount + - Diagnosis: Ensure `useUnmount` is used to register cleanup logic; use `useUpdateEffect` to monitor changes when necessary + +Section Sources + +- [pyproject.toml:26-26](file://pyproject.toml#L26-L26) +- [frontend/utils/hooks/useUnmount.ts](file://frontend/utils/hooks/useUnmount.ts) +- [frontend/utils/hooks/useUpdateEffect.ts](file://frontend/utils/hooks/useUpdateEffect.ts) +- [frontend/utils/upload.ts](file://frontend/utils/upload.ts) + +## Conclusion + +This API reference document outlines ModelScope Studio's Python and frontend component systems, clarifying import methods, component structure, props and events, lifecycle hooks, and utility function usage. It is recommended that developers adhere to version constraints, import components on demand, use utility functions appropriately, and integrate quickly by referencing the example files. + +## Appendix + +- Quick Index + - Python Components: Refer to the export lists of the antd and antdx sub-packages + - Frontend Components: Refer to the Svelte files under each sub-package + - Utility Functions: Refer to hooks and renderers in the `utils` directory +- Version and Compatibility + - Python: 2.0.0 + - Gradio: 6.0 ≤ v ≤ 6.8.0 +- Build and Development + - Build command: `pnpm run build` + - Dev command: `pnpm run dev` + +Section Sources + +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [pyproject.toml:26-26](file://pyproject.toml#L26-L26) +- [package.json:8-24](file://package.json#L8-L24) diff --git a/.wiki/en/API Reference/JavaScript API/JavaScript API.md b/.wiki/en/API Reference/JavaScript API/JavaScript API.md new file mode 100644 index 00000000..723ae230 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/JavaScript API.md @@ -0,0 +1,413 @@ +# JavaScript API + + +**Files referenced in this document** +- [frontend/package.json](file://frontend/package.json) +- [frontend/tsconfig.json](file://frontend/tsconfig.json) +- [frontend/antd/package.json](file://frontend/antd/package.json) +- [frontend/antdx/package.json](file://frontend/antdx/package.json) +- [frontend/base/package.json](file://frontend/base/package.json) +- [frontend/pro/package.json](file://frontend/pro/package.json) +- [frontend/globals/components/index.ts](file://frontend/globals/components/index.ts) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [frontend/antd/form/Index.svelte](file://frontend/antd/form/Index.svelte) +- [frontend/antd/layout/Index.svelte](file://frontend/antd/layout/Index.svelte) +- [frontend/antd/modal/Index.svelte](file://frontend/antd/modal/Index.svelte) +- [frontend/antd/table/Index.svelte](file://frontend/antd/table/Index.svelte) +- [frontend/svelte-preprocess-react/index.ts](file://frontend/svelte-preprocess-react/index.ts) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts](file://frontend/svelte-preprocess-react/sveltify.svelte.ts) +- [frontend/svelte-preprocess-react/inject.ts](file://frontend/svelte-preprocess-react/inject.ts) +- [frontend/svelte-preprocess-react/react-slot.tsx](file://frontend/svelte-preprocess-react/react-slot.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Memory Management](#performance-and-memory-management) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: API Index and Navigation](#appendix-api-index-and-navigation) + +## Introduction + +This document is the JavaScript API reference for ModelScope Studio, focusing on the Svelte component layer and the React component bridging solution. It covers the following topics: + +- Property definitions, event handling, lifecycle, and public methods of Svelte components +- Inter-component communication (props passing, event bubbling, slot system) +- React component bridge implementation (property conversion, event binding, state synchronization) +- Standard instantiation and configuration examples (basic and complex scenarios) +- Style customization, theme configuration, and responsive design support +- TypeScript type definitions, interface specifications, and generic usage +- Performance optimization, memory management, and best practices +- Complete API index and navigation + +## Project Structure + +The frontend adopts a multi-package structure, split by functional domain: + +- Base component library: base +- Ant Design component library: antd +- Ant Design extended component library: antdx +- Pro advanced component library: pro +- Global component entry: globals/components + +All packages use Svelte 5 as the core runtime, and inject React components into Svelte through the in-house `svelte-preprocess-react` bridging solution. + +```mermaid +graph TB +subgraph "Frontend Packages" +BASE["@modelscope-studio/base"] +ANTD["@modelscope-studio/antd"] +ANTHDX["@modelscope-studio/antdx"] +PRO["@modelscope-studio/pro"] +GLOBALS["@globals/components"] +end +subgraph "Bridge Layer" +PRE["@svelte-preprocess-react
index.ts"] +INJ["inject.ts"] +SLOT["react-slot.tsx"] +SVLT["sveltify.svelte.ts"] +end +BASE --> PRE +ANTD --> PRE +ANTHDX --> PRE +PRO --> PRE +GLOBALS --> PRE +PRE --> INJ +PRE --> SLOT +PRE --> SVLT +``` + +Diagram sources + +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) +- [frontend/base/package.json:1-6](file://frontend/base/package.json#L1-L6) +- [frontend/pro/package.json:1-6](file://frontend/pro/package.json#L1-L6) +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) +- [frontend/svelte-preprocess-react/inject.ts:1-103](file://frontend/svelte-preprocess-react/inject.ts#L1-L103) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) + +Section sources + +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) + +## Core Components + +This section provides an overview of common patterns and capability boundaries of Svelte components in the bridge layer, making it easier to quickly locate and reuse them. + +- Property passthrough and filtering + - Props are uniformly retrieved via `getProps`, with visibility flags, internal markers, and element identifiers being filtered or preserved + - `processProps` is used to merge name mappings (e.g., `fields_change` → `fieldsChange`) with additional properties +- Slot system + - Svelte slot content is collected via `getSlots` and injected into the `slots` field of React components + - `ReactSlot` is responsible for cloning or mounting DOM nodes into React components, with support for attribute observation and event cloning +- Async loading and rendering + - `importComponent` dynamically imports React components, combined with Svelte `await` fragments for async rendering +- Event and state synchronization + - Callbacks such as `onValueChange` and `onResetFormAction` are used to write back to parent state + - `updateProps` is used to update mutable properties (e.g., `value`) + +Section sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/modal/Index.svelte:1-63](file://frontend/antd/modal/Index.svelte#L1-L63) +- [frontend/antd/table/Index.svelte:1-61](file://frontend/antd/table/Index.svelte#L1-L61) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) + +## Architecture Overview + +The following diagram shows the bridge path from Svelte to React and key nodes: + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Component
Index.svelte" +participant Bridge as "Bridge Tool
sveltify.ts" +participant Inject as "Global Injection
inject.ts" +participant React as "React Component" +participant Slot as "Slot Bridge
react-slot.tsx" +Svelte->>Bridge : "importComponent + getProps + processProps" +Bridge->>Inject : "Initialize shared root node and context" +Bridge->>React : "Create Portal and mount" +Svelte->>Slot : "getSlots() -> slots.value" +Slot-->>React : "Clone/mount DOM and propagate events" +React-->>Svelte : "onValueChange and other callbacks trigger updateProps" +``` + +Diagram sources + +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) +- [frontend/svelte-preprocess-react/inject.ts:1-103](file://frontend/svelte-preprocess-react/inject.ts#L1-L103) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + +## Component Details + +### Button + +- Property definitions + - `additional_props?: Record` + - `value?: string | undefined` + - `as_item?: string | undefined` + - `_internal: { layout?: boolean }` + - `href_target?: string` + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` +- Events and methods + - Default slot content is injected via `slots` + - Appearance is controlled via `className`, `style`, `id` +- Lifecycle + - After `$props()` initialization, enters async rendering flow immediately +- Complexity and performance + - Dynamic import and derived computation to avoid unnecessary re-renders + +Section sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + +### Form + +- Property definitions + - `value?: Record` + - `form_action?: FormProps['formAction'] | null` + - `form_name?: string` + - `fields_change?: any` + - `finish_failed?: any` + - `values_change?: any` + - Internal and style: `_internal`, `elem_id`, `elem_classes`, `elem_style` +- Events and methods + - `onValueChange` writes back `value` + - `onResetFormAction` clears `form_action` +- Lifecycle + - Async rendering; only displayed when `visible` is true +- Complexity and performance + - Uses derived properties to reduce props computation overhead + +Section sources + +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) + +### Modal + +- Property definitions + - `as_item?: string | undefined` + - `_internal: { layout?: boolean }` + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` +- Events and methods + - Content is injected via `slots` +- Lifecycle + - Conditional rendering; React components are loaded asynchronously + +Section sources + +- [frontend/antd/modal/Index.svelte:1-63](file://frontend/antd/modal/Index.svelte#L1-L63) + +### Table + +- Property definitions + - `as_item?: string | undefined` + - `_internal: {}` + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` +- Events and methods + - Column/row content is injected via `slots` +- Lifecycle + - Async rendering with conditional display + +Section sources + +- [frontend/antd/table/Index.svelte:1-61](file://frontend/antd/table/Index.svelte#L1-L61) + +### Layout + +- Property definitions + - `children: Snippet` + - Other properties are handled by the Base component +- Events and methods + - No explicit event bindings; primarily responsible for structural rendering +- Lifecycle + - Props are passed through directly to the Base component + +Section sources + +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) + +### React Slot Bridge (ReactSlot) + +- Functionality + - Clones and mounts Svelte slots into React components + - Supports event listener cloning, attribute change observation, and application of class names and inline styles +- Key parameters + - `slot: HTMLElement` + - `clone?: boolean` + - `style?: React.CSSProperties` + - `className?: string` + - `observeAttributes?: boolean` +- Behavior + - `MutationObserver` observes subtree changes of the slot and dynamically rebuilds cloned nodes + - React subtrees are mounted to target containers via `createPortal` + +Section sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) + +### Bridge Core (sveltify) + +- Functionality + - Wraps React components as Svelte components with support for slots, styles, class names, and id passthrough + - Maintains shared root nodes and node trees to enable rendering and updates across component trees +- Key points + - Initializes Promise and global shared root node + - Recursively builds node tree and triggers rerender + - Provides the `Sveltified` factory function + +Section sources + +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) + +### Global Injection (inject) + +- Functionality + - Injects global objects required by React ecosystem and the bridge into `window` + - Defines custom elements (`react-portal-target`, `react-child`, `svelte-slot`) + - Initializes global state (`initializePromise`, `sharedRoot`, `autokey`, etc.) +- Impact + - Provides a unified runtime environment for the bridge layer + +Section sources + +- [frontend/svelte-preprocess-react/inject.ts:1-103](file://frontend/svelte-preprocess-react/inject.ts#L1-L103) + +## Dependency Analysis + +```mermaid +graph LR +A["@modelscope-studio/antd"] --> B["@svelte-preprocess-react/index.ts"] +C["@modelscope-studio/antdx"] --> B +D["@modelscope-studio/base"] --> B +E["@modelscope-studio/pro"] --> B +F["@globals/components"] --> B +B --> G["inject.ts"] +B --> H["react-slot.tsx"] +B --> I["sveltify.svelte.ts"] +``` + +Diagram sources + +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) +- [frontend/base/package.json:1-6](file://frontend/base/package.json#L1-L6) +- [frontend/pro/package.json:1-6](file://frontend/pro/package.json#L1-L6) +- [frontend/globals/components/index.ts:1-2](file://frontend/globals/components/index.ts#L1-L2) +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) +- [frontend/svelte-preprocess-react/inject.ts:1-103](file://frontend/svelte-preprocess-react/inject.ts#L1-L103) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) + +Section sources + +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) + +## Performance and Memory Management + +- Async component loading + - Use `importComponent` for dynamic imports to avoid blocking the initial render +- Derived computation and minimized re-renders + - Use `$derived` and `processProps` to reduce redundant renders +- Slot cloning strategy + - `ReactSlot` enables cloning and `MutationObserver` by default to ensure stability during DOM changes; disabling cloning can reduce overhead in high-frequency update scenarios +- Portal management + - `inject.ts` centrally creates and destroys root nodes to avoid memory leaks from repeated mounting +- Styles and themes + - Styles are controlled via `elem_style`, `elem_classes`, and `className`; Ant Design theme variables are injected by `antdCssinjs` to ensure a consistent theme experience + +[This section provides general guidance and does not require specific file sources] + +## Troubleshooting Guide + +- Slot not taking effect + - Check whether `getSlots` is called correctly and `slots.value` is passed to the React component + - Confirm that the `slot` parameter of `ReactSlot` points to a valid DOM element +- Event not triggered + - Ensure event name mapping is correct (e.g., `fields_change` → `fieldsChange`) + - Check the `observeAttributes` and `clone` settings of `ReactSlot` +- Style not applied + - Confirm whether `elem_style` and `elem_classes` are properly passed through + - Check whether theme injection is complete (`inject.ts` initialization) +- Performance issues + - Reduce unnecessary `visible` toggling + - Disable `ReactSlot` cloning or lower observation granularity for high-frequency update scenarios + +Section sources + +- [frontend/antd/form/Index.svelte:60-99](file://frontend/antd/form/Index.svelte#L60-L99) +- [frontend/svelte-preprocess-react/react-slot.tsx:158-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L158-L224) +- [frontend/svelte-preprocess-react/inject.ts:95-103](file://frontend/svelte-preprocess-react/inject.ts#L95-L103) + +## Conclusion + +This API uses Svelte as its core, seamlessly integrating React components through an in-house bridge layer to form a unified component ecosystem. Through standardized property passthrough, event mapping, and slot bridging, developers can use both types of components in a consistent manner. Combined with comprehensive type definitions and performance optimization recommendations, this enables a good development experience and runtime efficiency in complex scenarios. + +[This section is a summary and does not require specific file sources] + +## Appendix: API Index and Navigation + +### Component Categories and Entry Points + +- Base components: base +- Ant Design components: antd +- Ant Design extensions: antdx +- Pro advanced components: pro +- Global component entry: globals/components + +Section sources + +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) +- [frontend/base/package.json:1-6](file://frontend/base/package.json#L1-L6) +- [frontend/pro/package.json:1-6](file://frontend/pro/package.json#L1-L6) +- [frontend/globals/components/index.ts:1-2](file://frontend/globals/components/index.ts#L1-L2) + +### Svelte Component Common Patterns + +- Property retrieval and filtering: `getProps` +- Property mapping and merging: `processProps` +- Slot collection: `getSlots` +- Async rendering: `importComponent` + `{#await ...}` +- Event writeback: `updateProps` + +Section sources + +- [frontend/antd/button/Index.svelte:12-56](file://frontend/antd/button/Index.svelte#L12-L56) +- [frontend/antd/form/Index.svelte:14-71](file://frontend/antd/form/Index.svelte#L14-L71) +- [frontend/antd/modal/Index.svelte:12-47](file://frontend/antd/modal/Index.svelte#L12-L47) +- [frontend/antd/table/Index.svelte:12-45](file://frontend/antd/table/Index.svelte#L12-L45) + +### React Component Bridge + +- `sveltify`: Wraps React components as Svelte components +- `inject`: Global runtime injection and initialization +- `react-slot`: Slot DOM cloning and mounting + +Section sources + +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:30-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L30-L119) +- [frontend/svelte-preprocess-react/inject.ts:20-103](file://frontend/svelte-preprocess-react/inject.ts#L20-L103) +- [frontend/svelte-preprocess-react/react-slot.tsx:109-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L224) + +### TypeScript and Type Definitions + +- The top-level `tsconfig` extends the global tsconfig, enabling ESNext modules and browser types +- Components extensively use generics and read-only array constraints for slot key names + +Section sources + +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:9-39](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L9-L39) diff --git a/.wiki/en/API Reference/JavaScript API/Markdown Component API.md b/.wiki/en/API Reference/JavaScript API/Markdown Component API.md new file mode 100644 index 00000000..3fcbae5e --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Markdown Component API.md @@ -0,0 +1,417 @@ +# Markdown Component API + + +**Files referenced in this document** +- [frontend/globals/components/markdown/index.tsx](file://frontend/globals/components/markdown/index.tsx) +- [frontend/globals/components/markdown/utils.ts](file://frontend/globals/components/markdown/utils.ts) +- [frontend/globals/components/markdown/sanitize.ts](file://frontend/globals/components/markdown/sanitize.ts) +- [frontend/globals/components/markdown/markdown.less](file://frontend/globals/components/markdown/markdown.less) +- [frontend/globals/components/markdown/prism.less](file://frontend/globals/components/markdown/prism.less) +- [frontend/globals/components/markdown/html-tags.ts](file://frontend/globals/components/markdown/html-tags.ts) +- [frontend/base/markdown/Index.svelte](file://frontend/base/markdown/Index.svelte) +- [frontend/base/markdown/markdown.tsx](file://frontend/base/markdown/markdown.tsx) +- [backend/modelscope_studio/components/base/markdown/__init__.py](file://backend/modelscope_studio/components/base/markdown/__init__.py) +- [docs/components/base/markdown/README.md](file://docs/components/base/markdown/README.md) +- [docs/components/base/markdown/demos/basic.py](file://docs/components/base/markdown/demos/basic.py) +- [docs/components/base/markdown/demos/custom_copy_buttons.py](file://docs/components/base/markdown/demos/custom_copy_buttons.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document provides detailed API documentation for the Markdown component in the ModelScope Studio base components, covering the following aspects: + +- Property definitions and default values +- Rendering options (line breaks, header links, math formulas, Mermaid diagrams) +- Code highlighting (Prism.js integration and language support) +- Security filtering (HTML allowlist and external link handling) +- Style customization (CSS class names, inline styles, theme variables) +- Usage examples (basic rendering, copy button, custom buttons) +- Performance optimization recommendations (lazy loading, caching strategies) +- Common issues and debugging methods + +## Project Structure + +The Markdown component is implemented collaboratively by a frontend React component and a backend Gradio component, bridged through a Svelte wrapper. The frontend parsing and rendering logic is centralized in the global components directory, while the backend handles parameter passthrough and event binding. + +```mermaid +graph TB +subgraph "Frontend" +A["Index.svelte
Base Wrapper"] --> B["markdown.tsx
React Component Entry"] +B --> C["utils.ts
Parse/Highlight/Sanitize/Mermaid"] +B --> D["sanitize.ts
HTML Filtering"] +B --> E["markdown.less
General Styles"] +B --> F["prism.less
Code Highlight Theme"] +B --> G["html-tags.ts
Allowlisted Tags"] +end +subgraph "Backend" +H["backend/base/markdown/__init__.py
Gradio Component Definition"] +end +A --> H +H --> B +``` + +**Diagram sources** + +- [frontend/base/markdown/Index.svelte:1-63](file://frontend/base/markdown/Index.svelte#L1-L63) +- [frontend/base/markdown/markdown.tsx:1-34](file://frontend/base/markdown/markdown.tsx#L1-L34) +- [frontend/globals/components/markdown/index.tsx:1-272](file://frontend/globals/components/markdown/index.tsx#L1-L272) +- [frontend/globals/components/markdown/utils.ts:1-411](file://frontend/globals/components/markdown/utils.ts#L1-L411) +- [frontend/globals/components/markdown/sanitize.ts:1-26](file://frontend/globals/components/markdown/sanitize.ts#L1-L26) +- [frontend/globals/components/markdown/markdown.less:1-140](file://frontend/globals/components/markdown/markdown.less#L1-L140) +- [frontend/globals/components/markdown/prism.less:1-185](file://frontend/globals/components/markdown/prism.less#L1-L185) +- [frontend/globals/components/markdown/html-tags.ts:1-210](file://frontend/globals/components/markdown/html-tags.ts#L1-L210) +- [backend/modelscope_studio/components/base/markdown/**init**.py:1-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L1-L174) + +**Section sources** + +- [frontend/base/markdown/Index.svelte:1-63](file://frontend/base/markdown/Index.svelte#L1-L63) +- [frontend/base/markdown/markdown.tsx:1-34](file://frontend/base/markdown/markdown.tsx#L1-L34) +- [frontend/globals/components/markdown/index.tsx:1-272](file://frontend/globals/components/markdown/index.tsx#L1-L272) +- [backend/modelscope_studio/components/base/markdown/**init**.py:1-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L1-L174) + +## Core Components + +- Frontend React component: Responsible for Markdown parsing, code highlighting, math formula rendering, Mermaid diagram rendering, HTML security filtering, and copy button interactions. +- Backend Gradio component: Responsible for parameter passthrough, event binding (such as copy/change/mouse events), default values, and example data. + +Key responsibility division: + +- Parsing and rendering: Marked + marked-highlight (Prism) + custom extensions (LaTeX, Mermaid) +- Security filtering: Amuchina + external link handling +- Math formulas: KaTeX loaded on-demand with auto-rendering +- Diagrams: Mermaid loaded on-demand with error fallback +- Styles: General styles + Prism theme variables + +**Section sources** + +- [frontend/globals/components/markdown/index.tsx:27-48](file://frontend/globals/components/markdown/index.tsx#L27-L48) +- [frontend/globals/components/markdown/utils.ts:286-344](file://frontend/globals/components/markdown/utils.ts#L286-L344) +- [backend/modelscope_studio/components/base/markdown/**init**.py:11-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L11-L174) + +## Architecture Overview + +The Markdown component receives parameters from the backend, and after being wrapped by the frontend, performs parsing and rendering. The parsing phase can enable line breaks, header links, LaTeX, and Mermaid extensions; the rendering phase integrates Prism for code highlighting, KaTeX/Mermaid for math and diagram rendering, and applies security filtering to the output HTML. + +```mermaid +sequenceDiagram +participant Backend as "Backend Component" +participant Wrapper as "Frontend Wrapper (Svelte)" +participant ReactComp as "React Component" +participant Parser as "Marked/Prism/KaTeX/Mermaid" +participant Sanitizer as "HTML Filter" +Backend->>Wrapper : Pass parameters (value, config) +Wrapper->>ReactComp : Render component and inject props +ReactComp->>Parser : Initialize parser (with extensions/highlighting) +ReactComp->>Parser : Parse Markdown +Parser-->>ReactComp : Return HTML fragment +ReactComp->>Sanitizer : Optional security filtering +Sanitizer-->>ReactComp : Return safe HTML +ReactComp-->>Wrapper : Render final content +``` + +**Diagram sources** + +- [frontend/base/markdown/Index.svelte:19-62](file://frontend/base/markdown/Index.svelte#L19-L62) +- [frontend/globals/components/markdown/index.tsx:86-92](file://frontend/globals/components/markdown/index.tsx#L86-L92) +- [frontend/globals/components/markdown/utils.ts:286-344](file://frontend/globals/components/markdown/utils.ts#L286-L344) +- [frontend/globals/components/markdown/sanitize.ts:12-25](file://frontend/globals/components/markdown/sanitize.ts#L12-L25) + +## Detailed Component Analysis + +### Property Definitions and Default Values + +- `value`: String, Markdown content +- `sanitizeHtml`: Boolean, whether to enable HTML security filtering, enabled by default +- `latexDelimiters`: Array, custom LaTeX delimiters, containing left/right/display triplets +- `lineBreaks`: Boolean, whether to convert newlines to `
`, enabled by default +- `headerLinks`: Boolean, whether to generate header anchors and link icons, disabled by default +- `showCopyButton`: Boolean, whether to show the overall copy button +- `rtl`: Boolean, whether to enable right-to-left layout +- `themeMode`: String, theme mode (`light`/`dark`), used for styles and Mermaid theme +- `rootUrl`: String, root path, used for external link detection and resource location +- `allowTags`: Boolean or string array, controls the allowed HTML/SVG tags +- `onCopy`: Callback, triggered on successful copy +- `onChange`: Callback, triggered when rendering is complete +- `copyButtons`: Custom copy button collection (via slots) + +The default LaTeX delimiter set contains multiple common expression groups (inline/block, parenthesis variants, etc.). + +**Section sources** + +- [frontend/globals/components/markdown/index.tsx:27-48](file://frontend/globals/components/markdown/index.tsx#L27-L48) +- [frontend/globals/components/markdown/index.tsx:50-60](file://frontend/globals/components/markdown/index.tsx#L50-L60) +- [backend/modelscope_studio/components/base/markdown/**init**.py:54-141](file://backend/modelscope_studio/components/base/markdown/__init__.py#L54-L141) + +### Rendering Options and Parser Configuration + +- Line breaks: Controlled by the `breaks` option of Marked +- Header links: When `headerLinks` is enabled, IDs are generated for headers and anchor link icons are inserted +- LaTeX: Custom tokenizer supports multiple delimiter groups, rendered as block-level containers +- Mermaid: Custom tokenizer supports marking code blocks as `mermaid`, rendered as diagrams +- Code highlighting: Integrates Prism via `marked-highlight`, renders by language class name +- HTML sanitization: External links get `target`/`rel` attributes, and Amuchina allowlist filtering is applied + +```mermaid +flowchart TD +Start(["Start"]) --> Init["Initialize Marked
Enable GFM/line breaks/highlighting"] +Init --> Header{"Enable header links?"} +Header --> |Yes| AddHeader["Register header extension
Generate ID/anchor"] +Header --> |No| SkipHeader["Skip header extension"] +AddHeader --> Ext +SkipHeader --> Ext +Ext["Register LaTeX/Mermaid extensions"] --> Parse["Parse Markdown"] +Parse --> Math{"LaTeX syntax present?"} +Math --> |Yes| LoadKatex["Load KaTeX on-demand and render"] +Math --> |No| SkipMath["Skip math rendering"] +LoadKatex --> Safe{"HTML filtering enabled?"} +SkipMath --> Safe +Safe --> |Yes| Sanitize["External link handling / allowlist filtering"] +Safe --> |No| NoSanitize["Preserve original HTML"] +Sanitize --> Render["Render result"] +NoSanitize --> Render +Render --> End(["End"]) +``` + +**Diagram sources** + +- [frontend/globals/components/markdown/utils.ts:286-344](file://frontend/globals/components/markdown/utils.ts#L286-L344) +- [frontend/globals/components/markdown/index.tsx:107-138](file://frontend/globals/components/markdown/index.tsx#L107-L138) +- [frontend/globals/components/markdown/sanitize.ts:12-25](file://frontend/globals/components/markdown/sanitize.ts#L12-L25) + +**Section sources** + +- [frontend/globals/components/markdown/utils.ts:286-344](file://frontend/globals/components/markdown/utils.ts#L286-L344) +- [frontend/globals/components/markdown/index.tsx:107-138](file://frontend/globals/components/markdown/index.tsx#L107-L138) + +### Code Highlighting and Language Support + +- Highlighting library: Prism.js (integrated via `marked-highlight`) +- Language support: Built-in loading of commonly used languages including Python, LaTeX, Bash, JSX, TypeScript, and TSX +- Rendering method: Dynamically selects Prism language based on code block language; unrecognized languages are kept as-is +- Theme: Applied via `prism.less` theme variables, with dark color scheme in dark mode + +```mermaid +classDiagram +class Prism { ++highlight(code, lang, alias) ++languages +} +class MarkedHighlight { ++highlight(code, lang) +} +class MarkdownUtils { ++create_marked() +} +MarkdownUtils --> MarkedHighlight : "uses" +MarkedHighlight --> Prism : "calls" +``` + +**Diagram sources** + +- [frontend/globals/components/markdown/utils.ts:9-16](file://frontend/globals/components/markdown/utils.ts#L9-L16) +- [frontend/globals/components/markdown/utils.ts:303-310](file://frontend/globals/components/markdown/utils.ts#L303-L310) + +**Section sources** + +- [frontend/globals/components/markdown/utils.ts:9-16](file://frontend/globals/components/markdown/utils.ts#L9-L16) +- [frontend/globals/components/markdown/utils.ts:303-310](file://frontend/globals/components/markdown/utils.ts#L303-L310) + +### HTML Security Filtering and Allowlist + +- External link handling: Automatically sets `target="_blank"` and `rel="noopener noreferrer"` for external links +- Allowlist filtering: Uses Amuchina to sanitize HTML, retaining only standard HTML and SVG tags +- Allowed tags: Supports boolean toggle or explicit array; tags not in the allowlist are escaped + +```mermaid +flowchart TD +A["Input HTML"] --> B["Traverse nodes (A/IMG, etc.)"] +B --> C{"Is external link?"} +C --> |Yes| D["Set target/_blank + rel"] +C --> |No| E["Keep unchanged"] +D --> F["Amuchina allowlist filtering"] +E --> F +F --> G["Output safe HTML"] +``` + +**Diagram sources** + +- [frontend/globals/components/markdown/sanitize.ts:12-25](file://frontend/globals/components/markdown/sanitize.ts#L12-L25) +- [frontend/globals/components/markdown/html-tags.ts:206-210](file://frontend/globals/components/markdown/html-tags.ts#L206-L210) + +**Section sources** + +- [frontend/globals/components/markdown/sanitize.ts:1-26](file://frontend/globals/components/markdown/sanitize.ts#L1-L26) +- [frontend/globals/components/markdown/html-tags.ts:1-210](file://frontend/globals/components/markdown/html-tags.ts#L1-L210) + +### Style Customization and Theme Variables + +- CSS class names: The component root element includes classes such as `ms-gr-markdown`, `md`, and `prose`, making overrides easy +- Theme variables: CSS variables control colors, spacing, border radius, shadows, etc. +- Code highlighting theme: `prism.less` provides light and dark color schemes, switching with `themeMode` +- Copy button: Absolutely positioned with support for custom button collections (copy/copied states) + +```mermaid +classDiagram +class Styles { ++ms-gr-markdown ++md ++prose ++code_wrap ++copy_code_button +} +class ThemeVars { ++--block-background-fill ++--border-color-primary ++--body-text-color ++--code-background-fill ++... +} +Styles --> ThemeVars : "uses" +``` + +**Diagram sources** + +- [frontend/globals/components/markdown/markdown.less:1-140](file://frontend/globals/components/markdown/markdown.less#L1-L140) +- [frontend/globals/components/markdown/prism.less:1-185](file://frontend/globals/components/markdown/prism.less#L1-L185) + +**Section sources** + +- [frontend/globals/components/markdown/markdown.less:1-140](file://frontend/globals/components/markdown/markdown.less#L1-L140) +- [frontend/globals/components/markdown/prism.less:1-185](file://frontend/globals/components/markdown/prism.less#L1-L185) + +### Usage Examples + +- Basic text rendering: Pass a Markdown string directly +- Show copy button: Enable `showCopyButton` or provide custom buttons via slots +- Custom buttons: Use Slot to inject two buttons (e.g., copy/copied states) + +Reference example scripts and documentation: + +- Basic example: [basic.py:1-10](file://docs/components/base/markdown/demos/basic.py#L1-L10) +- Custom copy buttons: [custom_copy_buttons.py:1-21](file://docs/components/base/markdown/demos/custom_copy_buttons.py#L1-L21) +- Component description: [README.md:1-13](file://docs/components/base/markdown/README.md#L1-L13) + +**Section sources** + +- [docs/components/base/markdown/demos/basic.py:1-10](file://docs/components/base/markdown/demos/basic.py#L1-L10) +- [docs/components/base/markdown/demos/custom_copy_buttons.py:1-21](file://docs/components/base/markdown/demos/custom_copy_buttons.py#L1-L21) +- [docs/components/base/markdown/README.md:1-13](file://docs/components/base/markdown/README.md#L1-L13) + +## Dependency Analysis + +- Frontend dependencies + - Marked: Markdown parsing and rendering + - marked-highlight + Prism: Code highlighting + - KaTeX: Math formula rendering (loaded on-demand) + - Mermaid: Diagram rendering (loaded on-demand) + - Amuchina: HTML allowlist filtering + - github-slugger: Header ID generation +- Backend dependencies + - Gradio event listeners: copy/change/mouse series + - Frontend directory resolution: `resolve_frontend_dir("markdown")` + +```mermaid +graph LR +A["Marked"] --> B["marked-highlight"] +B --> C["Prism"] +A --> D["LaTeX Tokenizer"] +A --> E["Mermaid Tokenizer"] +A --> F["HTML Renderer"] +F --> G["Amuchina"] +A --> H["KaTeX (on-demand)"] +A --> I["Mermaid (on-demand)"] +``` + +**Diagram sources** + +- [frontend/globals/components/markdown/utils.ts:6-18](file://frontend/globals/components/markdown/utils.ts#L6-L18) +- [frontend/globals/components/markdown/utils.ts:286-344](file://frontend/globals/components/markdown/utils.ts#L286-L344) + +**Section sources** + +- [frontend/globals/components/markdown/utils.ts:6-18](file://frontend/globals/components/markdown/utils.ts#L6-L18) +- [backend/modelscope_studio/components/base/markdown/**init**.py:15-46](file://backend/modelscope_studio/components/base/markdown/__init__.py#L15-L46) + +## Performance Considerations + +- Lazy loading + - KaTeX: Styles and auto-render module are only loaded when math formulas first appear + - Mermaid: Loaded asynchronously and executed on the next frame before rendering + - Prism: Highlights on-demand during the parsing phase to avoid unnecessary overhead +- Caching strategy + - Loaded KaTeX modules are globally flagged to avoid duplicate imports + - Mermaid initialization parameters are fixed to reduce repeated initialization costs +- Rendering timing + - `requestAnimationFrame` is used to defer rendering to the browser's idle frame + - Re-parsing and re-rendering only occur when content changes +- Security filtering + - Filtering is only performed when `sanitizeHtml` is enabled, avoiding unnecessary DOM parsing + +**Section sources** + +- [frontend/globals/components/markdown/index.tsx:140-173](file://frontend/globals/components/markdown/index.tsx#L140-L173) +- [frontend/globals/components/markdown/utils.ts:177-223](file://frontend/globals/components/markdown/utils.ts#L177-L223) + +## Troubleshooting Guide + +- Copy button not working + - Check whether the container correctly binds the click event (`bind_copy_event`) + - Confirm whether the `copyButtons` slot is properly injected +- Math formulas not rendering + - Confirm whether `latexDelimiters` is correctly configured + - Check if `sanitizeHtml` is enabled and causing scripts to be removed +- Mermaid diagram errors + - Check the console error log + - Confirm that the mermaid code block is properly closed with correct syntax + - Check whether `themeMode` matches the page theme +- External links not opening in new window + - Confirm that `rootUrl` matches the link's origin + - Check whether `target`/`rel` is correctly set in the sanitize flow +- Code highlighting not working + - Confirm whether the language identifier is in the Prism supported list + - Check whether `prism.less` is correctly imported and theme variables are taking effect + +**Section sources** + +- [frontend/globals/components/markdown/utils.ts:346-380](file://frontend/globals/components/markdown/utils.ts#L346-L380) +- [frontend/globals/components/markdown/sanitize.ts:12-25](file://frontend/globals/components/markdown/sanitize.ts#L12-L25) +- [frontend/globals/components/markdown/utils.ts:177-223](file://frontend/globals/components/markdown/utils.ts#L177-L223) + +## Conclusion + +The Markdown component of ModelScope Studio provides rich rendering capabilities and a flexible customization interface while ensuring security and accessibility. Through the combination of Marked + Prism + KaTeX + Mermaid, it meets diverse needs from basic text to complex formulas and diagrams; allowlist filtering and external link handling ensure safe output; theme variables and style class names achieve consistent visual style and good customizability. + +## Appendix + +### Backend Component Parameter Overview + +- Parameter names: `value`, `rtl`, `latex_delimiters`, `sanitize_html`, `line_breaks`, `header_links`, `allow_tags`, `show_copy_button`, `copy_buttons` +- Events: `change`, `copy`, `click`, `dblclick`, `mousedown`, `mouseup`, `mouseover`, `mouseout`, `mousemove`, `scroll` +- Examples: `example_payload`/`example_value` returns a simple Markdown string + +**Section sources** + +- [backend/modelscope_studio/components/base/markdown/**init**.py:54-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L54-L174) + +### Frontend Component Property Overview + +- `value`, `sanitizeHtml`, `latexDelimiters`, `lineBreaks`, `headerLinks`, `showCopyButton`, `rtl`, `themeMode`, `rootUrl`, `allowTags`, `onCopy`, `onChange`, `copyButtons` +- Default LaTeX delimiter set, copy button icons and feedback, Mermaid error fallback + +**Section sources** + +- [frontend/globals/components/markdown/index.tsx:27-48](file://frontend/globals/components/markdown/index.tsx#L27-L48) +- [frontend/globals/components/markdown/index.tsx:50-60](file://frontend/globals/components/markdown/index.tsx#L50-L60) diff --git a/.wiki/en/API Reference/JavaScript API/React Component Bridge API.md b/.wiki/en/API Reference/JavaScript API/React Component Bridge API.md new file mode 100644 index 00000000..2861584f --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/React Component Bridge API.md @@ -0,0 +1,378 @@ +# React Component Bridge API + + +**Files referenced in this document** +- [frontend/svelte-preprocess-react/index.ts](file://frontend/svelte-preprocess-react/index.ts) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts](file://frontend/svelte-preprocess-react/sveltify.svelte.ts) +- [frontend/svelte-preprocess-react/inject.ts](file://frontend/svelte-preprocess-react/inject.ts) +- [frontend/svelte-preprocess-react/react-slot.tsx](file://frontend/svelte-preprocess-react/reactSlot.tsx) +- [frontend/svelte-preprocess-react/internal/types.ts](file://frontend/svelte-preprocess-react/internal/types.ts) +- [frontend/svelte-preprocess-react/react-contexts/index.ts](file://frontend/svelte-preprocess-react/react-contexts/index.ts) +- [frontend/utils/convertToCamelCase.ts](file://frontend/utils/convertToCamelCase.ts) +- [frontend/utils/createFunction.ts](file://frontend/utils/createFunction.ts) +- [frontend/utils/patchProps.tsx](file://frontend/utils/patchProps.tsx) +- [frontend/utils/hooks/useMemoizedEqualValue.ts](file://frontend/utils/hooks/useMemoizedEqualValue.ts) +- [frontend/utils/style.ts](file://frontend/utils/style.ts) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/base/text/text.tsx](file://frontend/base/text/text.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Standard Usage and Example Paths](#appendix-standard-usage-and-example-paths) + +## Introduction + +This document provides comprehensive API documentation for the React component bridge system in ModelScope Studio, focusing on the following aspects: + +- Conversion mechanism from React components to Svelte components (sveltify) +- Property mapping, event binding, and state synchronization +- Event handling (bubbling, delegation, custom events) +- Corresponding lifecycle hook implementations in Svelte +- Property conversion rules (camelCase, booleans, function properties) +- Context system (React Context and Svelte Context interoperability) +- Performance optimization (lazy loading, caching, memory management) +- Error handling and debugging techniques + +## Project Structure + +The bridge system consists of three main parts: + +- Injection layer: Initializes the global runtime environment and library bridging +- Conversion layer: `sveltify` wraps React components as Svelte components +- Rendering layer: `ReactSlot` renders Svelte slot content as React elements, with support for cloning and property injection + +```mermaid +graph TB +Inject["Injection Layer
inject.ts"] --> Types["Type Definitions
internal/types.ts"] +Inject --> ReactContexts["React Contexts
react-contexts/index.ts"] +Sveltify["Conversion Layer
sveltify.svelte.ts"] --> Bridge["Bridge
Bridge.svelte"] +Sveltify --> ReactWrapper["React Wrapper
ReactWrapper.svelte"] +ReactSlot["Rendering Layer
react-slot.tsx"] --> Portal["DOM Portal
createPortal"] +Utils["Utilities
convertToCamelCase.ts
createFunction.ts
patchProps.tsx
style.ts"] --> Sveltify +Utils --> ReactSlot +DemoBtn["Example Component
antd/button/button.tsx"] --> Sveltify +DemoForm["Example Component
antd/form/form.tsx"] --> Sveltify +DemoText["Example Component
base/text/text.tsx"] --> Sveltify +``` + +Diagram sources + +- [frontend/svelte-preprocess-react/inject.ts:1-103](file://frontend/svelte-preprocess-react/inject.ts#L1-L103) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/svelte-preprocess-react/internal/types.ts:1-79](file://frontend/svelte-preprocess-react/internal/types.ts#L1-L79) +- [frontend/svelte-preprocess-react/react-contexts/index.ts:1-123](file://frontend/svelte-preprocess-react/react-contexts/index.ts#L1-L123) +- [frontend/utils/convertToCamelCase.ts:1-22](file://frontend/utils/convertToCamelCase.ts#L1-L22) +- [frontend/utils/createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) +- [frontend/utils/patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) +- [frontend/utils/style.ts:1-77](file://frontend/utils/style.ts#L1-L77) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/base/text/text.tsx:1-11](file://frontend/base/text/text.tsx#L1-L11) + +Section sources + +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) +- [frontend/svelte-preprocess-react/inject.ts:1-103](file://frontend/svelte-preprocess-react/inject.ts#L1-L103) + +## Core Components + +- `sveltify`: Wraps any React component as a Svelte component; responsible for property passthrough, slot mapping, event bridging, and tree node construction. +- `ReactSlot`: Renders Svelte slot content as React elements, supporting DOM cloning, event listener migration, and style/class name injection. +- Type system: Unified event naming, property exclusion, and Svelte/SvelteKit type adaptation. +- Context system: Bridge and merge strategy between React Context and Svelte. + +Section sources + +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:27-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L27-L119) +- [frontend/svelte-preprocess-react/react-slot.tsx:8-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L8-L224) +- [frontend/svelte-preprocess-react/internal/types.ts:4-79](file://frontend/svelte-preprocess-react/internal/types.ts#L4-L79) +- [frontend/svelte-preprocess-react/react-contexts/index.ts:1-123](file://frontend/svelte-preprocess-react/react-contexts/index.ts#L1-L123) + +## Architecture Overview + +The following diagram shows the complete call chain and data flow from the Svelte consumer to the React component: + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Component" +participant Sveltify as "sveltify Wrapper" +participant Bridge as "Bridge" +participant ReactWrapper as "ReactWrapper" +participant ReactComp as "React Component" +participant DOM as "DOM Portal" +Svelte->>Sveltify : Pass props and slots +Sveltify->>Bridge : Create/update tree node +Bridge->>ReactWrapper : Render ReactWrapper +ReactWrapper->>ReactComp : Pass props/events/slots +ReactComp-->>DOM : Render to target container via createPortal +DOM-->>Svelte : Slot content becomes visible +``` + +Diagram sources + +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:40-104](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L40-L104) +- [frontend/svelte-preprocess-react/react-slot.tsx:109-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L224) + +## Detailed Component Analysis + +### sveltify Function and Conversion Mechanism + +- Functional overview + - Wraps React components as Svelte components, automatically handling property passthrough, slot mapping, event bridging, and tree rendering. + - Supports an optional ignore-render option (`ignore`) to control whether a node participates in rendering. +- Key points + - Initializes shared root node and bridge container to ensure the React root is mounted at the document head. + - Generates a unique key for each Svelte instance and establishes parent-child node relationships. + - Completes rendering and updates through cooperation between `Bridge` and `ReactWrapper`. + - Provides a Promise-based return; can only be used after global initialization is complete. +- Parameters and return value + - First parameter: React component type (can include generic slot declarations). + - Second parameter: Optional configuration object, currently supporting the `ignore` field. + - Returns: `Sveltified` type Svelte component (Promise or already-initialized version). + +```mermaid +flowchart TD +Start(["Call sveltify"]) --> InitRoot["Initialize shared root node and bridge container"] +InitRoot --> BuildNode["Build tree node
Set key/ignore/reactComponent"] +BuildNode --> AttachParent["Attach to parent node
Add to nodes and trigger rerender"] +AttachParent --> Render["Call Bridge to render"] +Render --> Done(["Return Sveltified component"]) +``` + +Diagram sources + +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:40-104](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L40-L104) + +Section sources + +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:27-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L27-L119) +- [frontend/svelte-preprocess-react/index.ts:6-8](file://frontend/svelte-preprocess-react/index.ts#L6-L8) + +### ReactSlot Slot Rendering and Event Handling + +- Functional overview + - Renders Svelte slot content as React elements, supporting DOM cloning, event listener migration, and style/class name injection. + - Optionally observes attribute changes to accommodate dynamic rendering scenarios (such as table column rendering). +- Key points + - Cloning strategy: Traverses child nodes, copies text nodes and element nodes; deep-clones React elements and migrates internally registered side effects. + - Event migration: Reads the event listener list on elements and re-binds them to cloned nodes. + - Property injection: Supports injection of `className` and `style`, converting React style objects to inline styles. + - Observer: Uses a debounced `MutationObserver` to monitor slot changes, ensuring dynamic content is reflected in a timely manner. +- Parameters + - `slot`: The `HTMLElement` corresponding to the slot. + - `clone`: Whether to clone the DOM (default: `false`). + - `className`/`style`: Injected class name and style object. + - `observeAttributes`: Whether to observe attribute changes (default: `false`). + +```mermaid +flowchart TD +Enter(["ReactSlot Render"]) --> CheckSlot{"Does slot exist?"} +CheckSlot --> |No| Exit["Exit"] +CheckSlot --> |Yes| CloneMode{"clone is true?"} +CloneMode --> |Yes| Clone["Clone DOM tree
Migrate event listeners"] +CloneMode --> |No| Mount["Mount directly to container"] +Clone --> Observe{"Observer enabled?"} +Observe --> |Yes| Debounce["Re-render after debounce"] +Observe --> |No| MountProps["Inject className/style and mount"] +Debounce --> Render["Re-clone and render"] +Render --> MountProps +MountProps --> Cleanup["Clean up DOM and observer on unmount"] +Cleanup --> Exit +``` + +Diagram sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:16-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L16-L224) + +Section sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:8-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L8-L224) + +### Type System and Event Mapping + +- Event naming and mapping + - React-side event properties start with uppercase (e.g., `onClick`); Svelte-side event handlers use the `on` prefix (e.g., `onClick` corresponds to `on-click`). + - Type utilities map React event properties to Svelte event handler signatures. +- Property exclusion + - React event properties are excluded from regular properties to avoid conflicts when passed to Svelte components. +- Svelte Props adaptation + - The `children` property is adapted to Svelte's `Snippet` type to support slots and fragments. + +Section sources + +- [frontend/svelte-preprocess-react/internal/types.ts:4-79](file://frontend/svelte-preprocess-react/internal/types.ts#L4-L79) + +### Context System (React Context and Svelte Interoperability) + +- React Context + - Provides contexts such as `IconFont`, `FormItem`, `AutoComplete`, `Suggestion`, and `SuggestionOpen` for sharing state and callbacks between components. +- Svelte-side bridging + - `ContextPropsContext` reads context values inside `ReactSlot`, supporting force-clone and parameter change detection. + - Supports context merge strategy to prevent state loss caused by duplicate Providers. +- Usage recommendations + - In scenarios requiring dynamic rendering or DOM cloning, combine `forceClone` with `observeAttributes` for improved stability. + +Section sources + +- [frontend/svelte-preprocess-react/react-contexts/index.ts:1-123](file://frontend/svelte-preprocess-react/react-contexts/index.ts#L1-L123) + +### Property Conversion Rules and Utilities + +- CamelCase conversion + - Converts underscore-style keys to lowerCamelCase or UpperCamelCase to maintain consistency with React properties. +- Boolean value handling + - Utility functions correctly map boolean values to React properties. +- Function property binding + - Supports function definitions in string form, automatically parsed into executable functions, making it convenient to pass callback logic from the outside. +- Slot property patching + - Special properties like `key` are internally stashed and restored to avoid conflicts with Svelte's internal mechanisms. + +Section sources + +- [frontend/utils/convertToCamelCase.ts:1-22](file://frontend/utils/convertToCamelCase.ts#L1-L22) +- [frontend/utils/createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) +- [frontend/utils/patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) + +### Event Handling Mechanism + +- Event bubbling and delegation + - `ReactSlot` migrates event listeners during cloning to ensure cloned elements can still respond to events. +- Custom events + - Custom callbacks are injected into React components as stable functions through `ContextPropsContext` and the `useFunction` hook. +- Styles and units + - React style objects are converted to inline style strings or objects, with pixel units automatically added (except for unitless properties). + +Section sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:67-96](file://frontend/svelte-preprocess-react/react-slot.tsx#L67-L96) +- [frontend/utils/hooks/useMemoizedEqualValue.ts:1-15](file://frontend/utils/hooks/useMemoizedEqualValue.ts#L1-L15) +- [frontend/utils/style.ts:1-77](file://frontend/utils/style.ts#L1-L77) + +### Lifecycle Hook Implementations in Svelte + +- Initialization + - A global initialization Promise ensures the runtime environment is ready before rendering. +- Update + - Each node change triggers a rerender; Bridge re-renders `ReactWrapper` and the subtree. +- Destruction + - Cleans up DOM nodes and observers, releasing resources. + +Section sources + +- [frontend/svelte-preprocess-react/inject.ts:95-103](file://frontend/svelte-preprocess-react/inject.ts#L95-L103) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:75-82](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L75-L82) +- [frontend/svelte-preprocess-react/react-slot.tsx:204-212](file://frontend/svelte-preprocess-react/react-slot.tsx#L204-L212) + +## Dependency Analysis + +- Runtime dependencies + - Libraries such as React, ReactDOM, `@ant-design/cssinjs`, `@ant-design/icons`, `@ant-design/x`, and `dayjs` are provided via global injection. +- Utility dependencies + - `lodash-es` provides utilities such as `isEqual`, `debounce`, and `noop`. +- Component dependencies + - `sveltify` depends on `Bridge` and `ReactWrapper` to complete rendering; `ReactSlot` depends on `createPortal` and style utilities. + +```mermaid +graph LR +Inject["inject.ts"] --> Libs["Global Library Injection"] +Sveltify["sveltify.svelte.ts"] --> Bridge["Bridge.svelte"] +Sveltify --> ReactWrapper["ReactWrapper.svelte"] +ReactSlot["react-slot.tsx"] --> Portal["createPortal"] +Utils["Utilities"] --> Sveltify +Utils --> ReactSlot +``` + +Diagram sources + +- [frontend/svelte-preprocess-react/inject.ts:20-85](file://frontend/svelte-preprocess-react/inject.ts#L20-L85) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-7](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L7) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-6](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L6) + +Section sources + +- [frontend/svelte-preprocess-react/inject.ts:1-103](file://frontend/svelte-preprocess-react/inject.ts#L1-L103) + +## Performance Considerations + +- Lazy loading and deferred initialization + - The global initialization Promise and shared root node prevent repeated mounting and multiple initializations. +- Caching and deduplication + - `useMemoizedEqualValue` and `ContextPropsContext` change detection reduce unnecessary re-renders. +- Memory management + - On unmount, disconnects `MutationObserver`, removes DOM nodes and bridge containers to prevent memory leaks. +- Rendering optimization + - `ReactSlot`'s cloning and observation use a debounce strategy to reduce performance pressure from frequent changes. + +Section sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:180-198](file://frontend/svelte-preprocess-react/react-slot.tsx#L180-L198) +- [frontend/utils/hooks/useMemoizedEqualValue.ts:1-15](file://frontend/utils/hooks/useMemoizedEqualValue.ts#L1-L15) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:67-82](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L67-L82) + +## Troubleshooting Guide + +- Slot not displaying + - Check whether the slot exists and has not been destroyed; confirm `clone` mode and `observeAttributes` settings. +- Events not working + - Confirm whether event listeners are migrated along with cloning; check if event listeners are overwritten or removed. +- Style anomalies + - Check whether style objects are correctly converted to inline styles; confirm that units are as expected. +- Performance issues + - Use `forceClone` and debounced observers judiciously; avoid re-renders caused by frequent changes. +- Context conflicts + - Use the merge strategy and parameter change detection of `ContextPropsProvider` to prevent state loss from duplicate Providers. + +Section sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:156-212](file://frontend/svelte-preprocess-react/react-slot.tsx#L156-L212) +- [frontend/utils/style.ts:39-77](file://frontend/utils/style.ts#L39-L77) +- [frontend/svelte-preprocess-react/react-contexts/index.ts:67-123](file://frontend/svelte-preprocess-react/react-contexts/index.ts#L67-L123) + +## Conclusion + +ModelScope Studio's React component bridge system achieves seamless collaboration between React and Svelte through `sveltify` and `ReactSlot`. Its design emphasizes: + +- Clear type constraints and event mapping +- Robust slot rendering and event migration +- Extensible context system and performance optimization strategies +- Clear lifecycle management and resource reclamation + +This system provides a unified component bridging solution for complex frontend applications, ensuring both a good development experience and runtime performance and stability. + +## Appendix: Standard Usage and Example Paths + +- Simple component bridging + - Example: Basic text component bridge + - Path: [frontend/base/text/text.tsx:1-11](file://frontend/base/text/text.tsx#L1-L11) +- Complex component bridging (with slots and events) + - Example: Button component bridge (icon and loading state slots) + - Path: [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- Form component bridging (with state synchronization and action dispatch) + - Example: Form component bridge (value synchronization, action reset, event forwarding) + - Path: [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- Key points for using sveltify + - Path: [frontend/svelte-preprocess-react/sveltify.svelte.ts:27-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L27-L119) +- Key points for using ReactSlot + - Path: [frontend/svelte-preprocess-react/react-slot.tsx:8-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L8-L224) +- Type and event mapping + - Path: [frontend/svelte-preprocess-react/internal/types.ts:4-79](file://frontend/svelte-preprocess-react/internal/types.ts#L4-L79) +- Context system + - Path: [frontend/svelte-preprocess-react/react-contexts/index.ts:1-123](file://frontend/svelte-preprocess-react/react-contexts/index.ts#L1-L123) +- Property conversion and function binding + - Path: [frontend/utils/convertToCamelCase.ts:1-22](file://frontend/utils/convertToCamelCase.ts#L1-L22) + - Path: [frontend/utils/createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) + - Path: [frontend/utils/patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) +- Style utilities + - Path: [frontend/utils/style.ts:1-77](file://frontend/utils/style.ts#L1-L77) diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Ant Design Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Ant Design Components API.md new file mode 100644 index 00000000..3134655f --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Ant Design Components API.md @@ -0,0 +1,479 @@ +# Ant Design Components API + + +**Files referenced in this document** +- [frontend/antd/package.json](file://frontend/antd/package.json) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/form/Index.svelte](file://frontend/antd/form/Index.svelte) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/layout/Index.svelte](file://frontend/antd/layout/Index.svelte) +- [frontend/antd/layout/layout.base.tsx](file://frontend/antd/layout/layout.base.tsx) +- [frontend/antd/table/table.tsx](file://frontend/antd/table/table.tsx) +- [frontend/antd/select/select.tsx](file://frontend/antd/select/select.tsx) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/antd/grid/context.ts](file://frontend/antd/grid/context.ts) +- [frontend/antd/table/context.ts](file://frontend/antd/table/context.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for Ant Design Svelte-based components in ModelScope Studio. It systematically covers the encapsulation approach of Ant Design components at the frontend layer, spanning general components, layout components, navigation components, data entry components, data display components, feedback components, and more. It clarifies property definitions, event handling, slot system, style customization, state management, and data binding mechanisms for each component, providing correspondence with native Ant Design components and TypeScript type specifications. It also provides reference paths for instantiation and configuration, as well as performance optimization and best practice recommendations. + +## Project Structure + +ModelScope Studio's Ant Design Svelte components adopt a "Svelte shell + React component bridge" architecture: the Svelte layer handles property passthrough, slots, and visibility control; the React layer bridges Ant Design components into the Svelte ecosystem via `sveltify`. The utility layer provides unified function wrapping, slot rendering, and context injection capabilities. + +```mermaid +graph TB +subgraph "Svelte Shell Layer" +IDX_BTN["button/Index.svelte"] +IDX_FORM["form/Index.svelte"] +IDX_LAYOUT["layout/Index.svelte"] +end +subgraph "React Bridge Layer" +BTN_TSX["button/button.tsx"] +FORM_TSX["form/form.tsx"] +LAYOUT_BASE["layout/layout.base.tsx"] +TABLE_TSX["table/table.tsx"] +SELECT_TSX["select/select.tsx"] +end +subgraph "Utilities and Contexts" +USE_FN["utils/hooks/useFunction.ts"] +RENDER_ITEMS["utils/renderItems.tsx"] +RENDER_SLOT["utils/renderParamsSlot.tsx"] +GRID_CTX["antd/grid/context.ts"] +TABLE_CTX["antd/table/context.ts"] +end +IDX_BTN --> BTN_TSX +IDX_FORM --> FORM_TSX +IDX_LAYOUT --> LAYOUT_BASE +TABLE_TSX --> TABLE_CTX +SELECT_TSX --> GRID_CTX +BTN_TSX --> USE_FN +FORM_TSX --> USE_FN +TABLE_TSX --> USE_FN +SELECT_TSX --> USE_FN +TABLE_TSX --> RENDER_ITEMS +SELECT_TSX --> RENDER_ITEMS +TABLE_TSX --> RENDER_SLOT +SELECT_TSX --> RENDER_SLOT +``` + +Diagram sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [frontend/antd/table/context.ts:1-29](file://frontend/antd/table/context.ts#L1-L29) + +Section sources + +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) + +## Core Components + +This section provides an overview of responsibilities and typical usage highlights for each component layer: + +- General components: Such as Button, responsible for property passthrough, slots (icon, loading state icon), and visibility control. +- Form components: Such as Form, responsible for two-way form value binding, action triggers (reset/submit/validate), and callback merging. +- Layout components: Such as Layout, selecting specific Header/Footer/Content/Layout components on-demand via the Base component and injecting style class names. +- Data display components: Such as Table, supporting complex scenarios including columns, expand, row selection, pagination, sticky headers, summary, title/footer slots, etc. +- Selector components: Such as Select, supporting option lists, filtering, dropdown/popup rendering, tag/tag-item rendering, and other slots. + +Section sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) + +## Architecture Overview + +The Svelte shell collects and transforms properties via `getProps`/`processProps`/`importComponent`, and then the `sveltify`-wrapped React components carry the actual UI logic. The slot system implements parameterized rendering and context injection via `ReactSlot` and `renderItems`/`renderParamsSlot`. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Shell (Index.svelte)" +participant Utils as "Utilities (useFunction/renderItems/renderParamsSlot)" +participant Bridge as "sveltify-wrapped React Component" +participant AntD as "Ant Design Component" +Svelte->>Utils : "Use useFunction to wrap callbacks/function-type props" +Svelte->>Utils : "Use renderItems to render child items/slots" +Svelte->>Utils : "Use renderParamsSlot to render parameterized slots" +Svelte->>Bridge : "Import and await component loading (importComponent)" +Bridge->>AntD : "Pass through props/events/slots" +AntD-->>Bridge : "Return render result" +Bridge-->>Svelte : "Output final UI" +``` + +Diagram sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +## Detailed Component Analysis + +### Button Component + +- Property definitions + - Common properties: Inherits all properties of Ant Design Button. + - Slots: `icon`, `loading.icon`. + - Meta info: `elem_id`, `elem_classes`, `elem_style`, `visible` for visibility and style control. + - Link behavior: `href_target` maps to `target`. +- Event handling + - Passes through events such as `onClick` from Ant Design Button. +- Slot system + - Supports passing icons or loading state icons as slots, rendered internally via `ReactSlot`. +- Style customization + - Injects class names and inline styles via `elem_classes` and `elem_style`. +- State management and data binding + - No two-way binding; visibility can be controlled by updating props externally. +- TypeScript types + - Uses Ant Design Button's `GetProps` type alias for constraints. +- Correspondence + - React component: Ant Design Button. +- Example reference paths + - [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + - [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant Shell as "button/Index.svelte" +participant Btn as "button/button.tsx" +participant AntBtn as "Ant Design Button" +UI->>Shell : "Pass properties and slots" +Shell->>Btn : "Pass through after processProps" +Btn->>AntBtn : "Render Button and inject slots" +AntBtn-->>UI : "Trigger events / display content" +``` + +Diagram sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) + +Section sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) + +### Form Component + +- Property definitions + - `value`: Form initial or controlled value. + - `formAction`: `'reset'` | `'submit'` | `'validate'` | `null`, used to trigger actions. + - Callbacks: `onValueChange`, `onResetFormAction`. + - Others: `requiredMark`, `feedbackIcons`, `as_item`, `visible`, etc. +- Event handling + - `onValuesChange` merges `onValueChange` to implement value change notifications. + - Action execution: Calls `form.resetFields`/`form.submit`/`form.validateFields` based on `formAction`. +- Slot system + - `requiredMark` can be rendered via a slot. +- Style and visibility + - `elem_id`, `elem_classes`, `elem_style`, `visible` control appearance and display. +- State management and data binding + - Two-way binding: `onValueChange` updates the external `value`; external `value` changes sync back to the form. + - Action decoupling: `onResetFormAction` resets `formAction` after an action completes. +- TypeScript types + - `FormProps` extends Ant Design Form's `GetProps`, adding `value`, `onValueChange`, `formAction`, etc. +- Correspondence + - React component: Ant Design Form. +- Example reference paths + - [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) + - [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant Shell as "form/Index.svelte" +participant Form as "form/form.tsx" +participant AntForm as "Ant Design Form" +UI->>Shell : "Set value/formAction" +Shell->>Form : "Pass through properties and callbacks" +Form->>AntForm : "Create and operate Form instance" +AntForm-->>Form : "onValuesChange/value change" +Form-->>Shell : "onValueChange(value)" +Shell-->>UI : "updateProps({ value })" +UI->>Shell : "formAction='reset'/'submit'/'validate'" +Shell->>Form : "Trigger action" +Form-->>Shell : "onResetFormAction()" +``` + +Diagram sources + +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +Section sources + +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +### Layout Component + +- Property definitions + - `component`: `'header'` | `'footer'` | `'content'` | `'layout'`, determines the specific Ant Design component to render. + - Others: `className`, `id`, `style`, etc. are passed through. +- Slot system + - Receives `children` via the Base component and renders them. +- Style customization + - Base injects different class name prefixes for different `component` values to facilitate theming. +- Correspondence + - React component: Ant Design Layout and its Content/Header/Footer. +- Example reference paths + - [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) + - [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +```mermaid +flowchart TD +Start(["Start"]) --> Choose["Select specific component based on 'component'"] +Choose --> |header| Header["Ant Design Layout.Header"] +Choose --> |footer| Footer["Ant Design Layout.Footer"] +Choose --> |content| Content["Ant Design Layout.Content"] +Choose --> |layout| Layout["Ant Design Layout"] +Header --> Render["Render and inject class names"] +Footer --> Render +Content --> Render +Layout --> Render +Render --> End(["End"]) +``` + +Diagram sources + +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +Section sources + +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +### Table Component + +- Property definitions + - `columns`: Column definitions, supporting default columns and extended column constants. + - `rowSelection`, `expandable`: Row selection and expandable configuration, supporting slot injection. + - `pagination`: Pagination configuration, supporting slot injection for quick-jump buttons and page number rendering. + - `loading`: Supports `tip` and `indicator` slots. + - `sticky`, `showSorterTooltip`, `footer`, `title`, `summary`, etc. +- Slot system + - Injects column, row selection, and expandable items via `withColumnItemsContextProvider`/`withRowSelectionItemsContextProvider`/`withExpandableItemsContextProvider`. + - `renderItems` renders columns and child items; `renderParamsSlot` renders parameterized slots (such as pagination buttons, page number rendering, sorter tooltips, etc.). +- Function-type properties + - `useFunction` wraps function-type properties such as `getPopupContainer`, `rowClassName`, `rowKey`, `summary`, and `footer`. +- Performance notes + - Configurations such as columns and row selection are optimized with `useMemo`. +- Correspondence + - React component: Ant Design Table. +- Example reference paths + - [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) + - [frontend/antd/table/context.ts:1-29](file://frontend/antd/table/context.ts#L1-L29) + - [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) + - [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant Shell as "table/Index.svelte" +participant Table as "table/table.tsx" +participant Ctx as "Context (columns/rowSelection/expandable)" +participant AntTable as "Ant Design Table" +UI->>Shell : "Pass columns/rowSelection/expandable/pagination, etc." +Shell->>Table : "processProps and slots" +Table->>Ctx : "Read columns/row selection/expandable items" +Table->>AntTable : "Render and inject slots/function-type properties" +AntTable-->>Table : "Events/render result" +Table-->>Shell : "Output final UI" +``` + +Diagram sources + +- [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [frontend/antd/table/context.ts:1-29](file://frontend/antd/table/context.ts#L1-L29) + +Section sources + +- [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [frontend/antd/table/context.ts:1-29](file://frontend/antd/table/context.ts#L1-L29) + +### Select Component + +- Property definitions + - `options`: Option list, supporting injection via slots. + - `onChange`/`onValueChange`: Value change callbacks. + - `filterOption`/`filterSort`: Filtering and sorting functions. + - `dropdownRender`/`popupRender`/`optionRender`/`tagRender`/`labelRender`: Slot-based rendering. + - `allowClear.prefix`/`removeIcon`/`suffixIcon`/`notFoundContent`/`menuItemSelectedIcon`: Slot-based icons and text. +- Slot system + - `withItemsContextProvider` injects `options`/`default` child items; `renderItems` renders options. + - `renderParamsSlot` renders parameterized slots (such as `maxTagPlaceholder`). +- Function-type properties + - `useFunction` wraps `getPopupContainer`, `dropdownRender`, `popupRender`, `optionRender`, `tagRender`, `labelRender`, `filterOption`, `filterSort`. +- Correspondence + - React component: Ant Design Select. +- Example reference paths + - [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) + - [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) + - [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) + - [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +```mermaid +flowchart TD +Start(["Start"]) --> Options["Resolve options/default slot items"] +Options --> RenderOpts["renderItems renders options"] +RenderOpts --> Hooks["useFunction wraps function-type properties"] +Hooks --> Slots["Slot-based icons/text/renderers"] +Slots --> AntSelect["Render Ant Design Select"] +AntSelect --> End(["End"]) +``` + +Diagram sources + +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) + +Section sources + +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) + +## Dependency Analysis + +- Inter-component dependencies + - Button/Form/Layout/Table/Select all depend on `sveltify` to bridge Ant Design components to Svelte. + - Slots and contexts depend on `renderItems`/`renderParamsSlot` and `createItemsContext`. + - Function-type properties depend on `useFunction` to be wrapped as executable functions. +- External dependencies + - Ant Design: Provides UI foundation capabilities as a React component library. + - Utility libraries: `classnames`, `lodash-es`, etc. assist with styles and object handling. +- Circular dependencies + - No direct circular dependencies found; context injection is exported through independent modules. + +```mermaid +graph LR +Svelte["Svelte Shell"] --> Sveltify["sveltify wrapper"] +Sveltify --> AntD["Ant Design Components"] +Svelte --> Utils["Utility Functions"] +Utils --> RenderItems["renderItems"] +Utils --> RenderSlot["renderParamsSlot"] +Utils --> UseFunction["useFunction"] +Svelte --> Ctx["Context (createItemsContext)"] +``` + +Diagram sources + +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +Section sources + +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +## Performance Considerations + +- Function-type property wrapping + - Use `useFunction` to wrap incoming strings/functions as executable functions, avoiding recreation of closures on each render. +- Slots and contexts + - `renderItems` and `renderParamsSlot` support cloning and parameterized rendering to reduce redundant rendering overhead. +- Computation caching + - Table/Select extensively use `useMemo` to cache computation results (such as columns, row keys, container functions, etc.). +- Async loading + - The Svelte shell asynchronously loads React components via `importComponent` to reduce initial render pressure. +- Best practices + - Prefer using slots over inline JSX to improve reusability and maintainability. + - Use `$derived` or `useMemo` wrappers for frequently changing props to avoid unnecessary re-renders. + - Properly split components to avoid a single component taking on too many responsibilities. + +## Troubleshooting Guide + +- Slot not taking effect + - Check that the slot key is correct (e.g., `'loading.icon'`, `'pagination.showQuickJumper.goButton'`) and ensure the passed value is an `HTMLElement` or an object with `withParams`. + - Confirm the `forceClone` and `clone` settings for `renderParamsSlot`/`renderItems`. +- Function-type properties not working + - Ensure that the passed string expression is correctly wrapped by `useFunction`; pass `plainText=true` when necessary. +- Form action not triggered + - Confirm the `formAction` value is `'reset'` | `'submit'` | `'validate'` | `null`, and reset `formAction` after the action completes. +- Style anomalies + - Check that `elem_classes` and `elem_style` are correctly injected; for Layout components, ensure the `component` parameter matches the actual layout element. + +Section sources + +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +## Conclusion + +ModelScope Studio's Ant Design Svelte components achieve high-fidelity encapsulation of Ant Design components through clear layered design and a powerful slot/context system. Developers can use Ant Design's rich capabilities in Svelte at minimal cost while maintaining good maintainability and performance. It is recommended to prioritize slots and contexts in complex scenarios, combined with function-type property wrapping and `useMemo` caching, for a better development experience and runtime efficiency. + +## Appendix + +- Component inventory (categorized by module) + - General components: Button, Icon, Spin, Space, Typography, etc. + - Layout components: Layout (Header/Footer/Content/Layout), Grid (Row/Col), etc. + - Navigation components: Anchor, Breadcrumb, Dropdown, Menu, Pagination, Steps, Tabs, Tour, etc. + - Data entry components: AutoComplete, Cascader, Checkbox, ColorPicker, DatePicker, Mentions, Radio, Rate, Select, Slider, Switch, TimePicker, TreeSelect, Upload, Input/InputNumber/TextArea/Search/Password/OTP, etc. + - Data display components: Avatar, Badge, Calendar, Card/Card.Grid/Card.Meta, Carousel, Descriptions, Divider, Empty, Image/Image.PreviewGroup, List/List.Item/List.Item.Meta, Masonry/Masonry.Item, Result, Statistical/Countdown/Timer, Table/Table.Column/Table.ColumnGroup/Table.Expandable/Table.RowSelection, etc. + - Feedback components: Alert, Drawer, FloatButton/BackTop/Group, Modal/Static, Message, Notification, Popconfirm, Popover, Progress, QRCode, Result, Tour, Tooltip, Tour/Step, etc. +- Correspondence with native Ant Design + - Each Svelte component wraps the corresponding Ant Design React component via `sveltify`, with consistent properties and events. +- TypeScript type specifications + - Component types are all extended from Ant Design's `GetProps` type alias to ensure type safety. +- Example reference paths + - General components: [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + - Form components: [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) + - Layout components: [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) + - Data display components: [frontend/antd/table/table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) + - Selector components: [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Data Display Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Data Display Components API.md new file mode 100644 index 00000000..04812ea8 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Data Display Components API.md @@ -0,0 +1,578 @@ +# Data Display Components API + + +**Files referenced in this document** +- [avatar.tsx](file://frontend/antd/avatar/avatar.tsx) +- [badge.tsx](file://frontend/antd/badge/badge.tsx) +- [calendar.tsx](file://frontend/antd/calendar/calendar.tsx) +- [card.tsx](file://frontend/antd/card/card.tsx) +- [carousel.tsx](file://frontend/antd/carousel/carousel.tsx) +- [collapse.tsx](file://frontend/antd/collapse/collapse.tsx) +- [descriptions.tsx](file://frontend/antd/descriptions/descriptions.tsx) +- [empty.tsx](file://frontend/antd/empty/empty.tsx) +- [image.tsx](file://frontend/antd/image/image.tsx) +- [list.tsx](file://frontend/antd/list/list.tsx) +- [popover.tsx](file://frontend/antd/popover/popover.tsx) +- [qr-code.tsx](file://frontend/antd/qr-code/qr-code.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [statistic.tsx](file://frontend/antd/statistic/statistic.tsx) +- [table.tsx](file://frontend/antd/table/table.tsx) +- [tabs.tsx](file://frontend/antd/tabs/tabs.tsx) +- [tag.tsx](file://frontend/antd/tag/tag.tsx) +- [timeline.tsx](file://frontend/antd/timeline/timeline.tsx) +- [tooltip.tsx](file://frontend/antd/tooltip/tooltip.tsx) +- [tour.tsx](file://frontend/antd/tour/tour.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for Ant Design-based data display components in ModelScope Studio, covering: Avatar, Badge, Calendar, Card, Carousel, Collapse, Descriptions, Empty, Image, List, Popover, QRCode, Segmented, Statistic, Table, Tabs, Tag, Timeline, Tooltip, Tour, and Tree. It includes: + +- Property definitions and data format requirements +- Display logic and interaction behaviors +- Standard instantiation and configuration examples (provided as paths) +- Data binding, virtual scrolling, lazy loading, and performance optimization mechanisms +- Key TypeScript type definitions, data transformation, and chart library integration ideas +- Visual design principles and user experience optimization recommendations + +## Project Structure + +These components reside in the `antd` submodule of the frontend directory and follow a unified wrapping pattern: bridging Ant Design components into the Svelte ecosystem via `sveltify`, and implementing flexible content slots and function parameter rendering using `slots` and `renderParamsSlot`. + +```mermaid +graph TB +subgraph "Ant Design Component Layer" +AD_Avatar["Avatar"] +AD_Badge["Badge"] +AD_Calendar["Calendar"] +AD_Card["Card"] +AD_Carousel["Carousel"] +AD_Collapse["Collapse"] +AD_Descriptions["Descriptions"] +AD_Empty["Empty"] +AD_Image["Image"] +AD_List["List"] +AD_Popover["Popover"] +AD_QRCode["QRCode"] +AD_Segmented["Segmented"] +AD_Statistic["Statistic"] +AD_Table["Table"] +AD_Tabs["Tabs"] +AD_Tag["Tag"] +AD_Timeline["Timeline"] +AD_Tooltip["Tooltip"] +AD_Tour["Tour"] +AD_Tree["Tree"] +end +subgraph "sveltify Wrapper Layer" +S_Avatar["avatar.tsx"] +S_Badge["badge.tsx"] +S_Calendar["calendar.tsx"] +S_Card["card.tsx"] +S_Carousel["carousel.tsx"] +S_Collapse["collapse.tsx"] +S_Descriptions["descriptions.tsx"] +S_Empty["empty.tsx"] +S_Image["image.tsx"] +S_List["list.tsx"] +S_Popover["popover.tsx"] +S_QRCode["qr-code.tsx"] +S_Segmented["segmented.tsx"] +S_Statistic["statistic.tsx"] +S_Table["table.tsx"] +S_Tabs["tabs.tsx"] +S_Tag["tag.tsx"] +S_Timeline["timeline.tsx"] +S_Tooltip["tooltip.tsx"] +S_Tour["tour.tsx"] +S_Tree["tree.tsx"] +end +S_Avatar --> AD_Avatar +S_Badge --> AD_Badge +S_Calendar --> AD_Calendar +S_Card --> AD_Card +S_Carousel --> AD_Carousel +S_Collapse --> AD_Collapse +S_Descriptions --> AD_Descriptions +S_Empty --> AD_Empty +S_Image --> AD_Image +S_List --> AD_List +S_Popover --> AD_Popover +S_QRCode --> AD_QRCode +S_Segmented --> AD_Segmented +S_Statistic --> AD_Statistic +S_Table --> AD_Table +S_Tabs --> AD_Tabs +S_Tag --> AD_Tag +S_Timeline --> AD_Timeline +S_Tooltip --> AD_Tooltip +S_Tour --> AD_Tour +S_Tree --> AD_Tree +``` + +Diagram sources + +- [avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) +- [badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) +- [calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) +- [carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) +- [image.tsx:1-89](file://frontend/antd/image/image.tsx#L1-L89) +- [list.tsx:1-36](file://frontend/antd/list/list.tsx#L1-L36) +- [popover.tsx:1-37](file://frontend/antd/popover/popover.tsx#L1-L37) +- [qr-code.tsx:1-200](file://frontend/antd/qr-code/qr-code.tsx#L1-L200) +- [segmented.tsx:1-47](file://frontend/antd/segmented/segmented.tsx#L1-L47) +- [statistic.tsx:1-34](file://frontend/antd/statistic/statistic.tsx#L1-L34) +- [table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [tabs.tsx:1-121](file://frontend/antd/tabs/tabs.tsx#L1-L121) +- [tag.tsx:1-200](file://frontend/antd/tag/tag.tsx#L1-L200) +- [timeline.tsx:1-200](file://frontend/antd/timeline/timeline.tsx#L1-L200) +- [tooltip.tsx:1-200](file://frontend/antd/tooltip/tooltip.tsx#L1-L200) +- [tour.tsx:1-200](file://frontend/antd/tour/tour.tsx#L1-L200) +- [tree.tsx:1-200](file://frontend/antd/tree/tree.tsx#L1-L200) + +Section sources + +- [avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) +- [badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) +- [calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) +- [carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) +- [image.tsx:1-89](file://frontend/antd/image/image.tsx#L1-L89) +- [list.tsx:1-36](file://frontend/antd/list/list.tsx#L1-L36) +- [popover.tsx:1-37](file://frontend/antd/popover/popover.tsx#L1-L37) +- [segmented.tsx:1-47](file://frontend/antd/segmented/segmented.tsx#L1-L47) +- [statistic.tsx:1-34](file://frontend/antd/statistic/statistic.tsx#L1-L34) +- [table.tsx:1-279](file://frontend/antd/table/table.tsx#L1-L279) +- [tabs.tsx:1-121](file://frontend/antd/tabs/tabs.tsx#L1-L121) + +## Core Components + +This section provides an overview of each component's responsibility and common wrapping strategy: + +- All components use `sveltify` to wrap Ant Design components, supporting `slots` and `renderParamsSlot` render function parameters. +- Most components support `children` forwarding and various named slots (e.g., `title`, `extra`, `footer`, `header`, `content`, `image`, `description`, `placeholder`, `mask`, `toolbarRender`, `imageRender`, `tabBarExtraContent`, `tabProps.*`, etc.) for flexible appearance and behavior customization. +- Some components wrap event callbacks to ensure correct execution in the Svelte environment. + +Section sources + +- [avatar.tsx:6-25](file://frontend/antd/avatar/avatar.tsx#L6-L25) +- [badge.tsx:6-18](file://frontend/antd/badge/badge.tsx#L6-L18) +- [card.tsx:37-146](file://frontend/antd/card/card.tsx#L37-L146) +- [carousel.tsx:8-28](file://frontend/antd/carousel/carousel.tsx#L8-L28) +- [collapse.tsx:11-49](file://frontend/antd/collapse/collapse.tsx#L11-L49) +- [descriptions.tsx:10-37](file://frontend/antd/descriptions/descriptions.tsx#L10-L37) +- [empty.tsx:6-49](file://frontend/antd/empty/empty.tsx#L6-L49) +- [image.tsx:15-85](file://frontend/antd/image/image.tsx#L15-L85) +- [list.tsx:8-33](file://frontend/antd/list/list.tsx#L8-L33) +- [popover.tsx:7-34](file://frontend/antd/popover/popover.tsx#L7-L34) +- [segmented.tsx:10-43](file://frontend/antd/segmented/segmented.tsx#L10-L43) +- [statistic.tsx:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) +- [table.tsx:28-275](file://frontend/antd/table/table.tsx#L28-L275) +- [tabs.tsx:12-117](file://frontend/antd/tabs/tabs.tsx#L12-L117) + +## Architecture Overview + +The following sequence diagram illustrates the key flow from component wrapping to rendering: Svelte converts props and slots into Ant Design component props via `sveltify`; functional parameters are wrapped with `useFunction` or `createFunction`; complex configuration objects are merged with `omitUndefinedProps` and slots are injected. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Component" +participant Sveltify as "sveltify Wrapper" +participant AntD as "Ant Design Component" +participant Utils as "Utility Functions
useFunction/createFunction/renderParamsSlot" +Svelte->>Sveltify : Passes props and slots +Sveltify->>Utils : Wraps function params / merges config +Utils-->>Sveltify : Returns executable functions or config objects +Sveltify->>AntD : Renders and passes props +AntD-->>Svelte : Fires callbacks / returns render result +``` + +Diagram sources + +- [table.tsx:76-134](file://frontend/antd/table/table.tsx#L76-L134) +- [card.tsx:40-49](file://frontend/antd/card/card.tsx#L40-L49) +- [image.tsx:32-34](file://frontend/antd/image/image.tsx#L32-L34) +- [popover.tsx:10-12](file://frontend/antd/popover/popover.tsx#L10-L12) + +## Component Details + +### Avatar + +- **Purpose**: Displays user avatars or icons; supports `icon` and `src` slots. +- **Key Points**: + - Supports `slots.icon` and `slots.src`; slot content takes priority if present, otherwise falls back to props. + - Slots are rendered via `ReactSlot`. +- **Typical usage path**: + - [Avatar basic usage:6-25](file://frontend/antd/avatar/avatar.tsx#L6-L25) + +Section sources + +- [avatar.tsx:6-25](file://frontend/antd/avatar/avatar.tsx#L6-L25) + +### Badge + +- **Purpose**: Displays a badge count or text on avatars, buttons, and other elements. +- **Key Points**: + - Supports `slots.count` and `slots.text` for dynamic badge content rendering. +- **Typical usage path**: + - [Badge count and text:6-18](file://frontend/antd/badge/badge.tsx#L6-L18) + +Section sources + +- [badge.tsx:6-18](file://frontend/antd/badge/badge.tsx#L6-L18) + +### Calendar + +- **Purpose**: Date selection and schedule display. +- **Key Points**: + - `value`/`defaultValue`/`validRange` are processed with `dayjs` formatting. + - `onChange`/`onPanelChange`/`onSelect` callbacks are uniformly converted to second-level timestamps. + - Supports `slots.cellRender`/`fullCellRender`/`headerRender` function slots. +- **Typical usage path**: + - [Calendar date formatting and callbacks:17-98](file://frontend/antd/calendar/calendar.tsx#L17-L98) + +Section sources + +- [calendar.tsx:17-98](file://frontend/antd/calendar/calendar.tsx#L17-L98) + +### Card + +- **Purpose**: Container component supporting title, extra actions, cover image, action area, and tab pages. +- **Key Points**: + - Supports `slots.title`/`extra`/`cover`/`tabBarExtraContent`/`left`/`right`, etc. + - `actions` are automatically collected from child nodes via `useTargets`. + - `tabList` is resolved from context via `renderItems`. + - `tabProps.indicator.size`, `more.icon`, `tabProps.renderTabBar`, `tabProps.tabBarExtraContent.*`, etc. can all be slotted. +- **Typical usage path**: + - [Card with tab pages and action area:37-146](file://frontend/antd/card/card.tsx#L37-L146) + +Section sources + +- [card.tsx:37-146](file://frontend/antd/card/card.tsx#L37-L146) + +### Carousel + +- **Purpose**: Carousel display of multiple images or content panels. +- **Key Points**: + - Uses `useTargets` to extract child nodes as carousel items. + - `afterChange`/`beforeChange` are wrapped via `useFunction`. +- **Typical usage path**: + - [Carousel item rendering:8-28](file://frontend/antd/carousel/carousel.tsx#L8-L28) + +Section sources + +- [carousel.tsx:8-28](file://frontend/antd/carousel/carousel.tsx#L8-L28) + +### Collapse + +- **Purpose**: Grouping content with collapse/expand behavior. +- **Key Points**: + - Supports `slots.expandIcon` function slot. + - `items` are resolved from context via `renderItems`, supporting `label`/`extra`/`children` structure. +- **Typical usage path**: + - [Collapse items and expand icon:11-49](file://frontend/antd/collapse/collapse.tsx#L11-L49) + +Section sources + +- [collapse.tsx:11-49](file://frontend/antd/collapse/collapse.tsx#L11-L49) + +### Descriptions + +- **Purpose**: Displays information in key-value pairs. +- **Key Points**: + - Supports `slots.title`/`extra`; `items` are resolved via `renderItems` with `label`/`children` fields. +- **Typical usage path**: + - [Descriptions item rendering:10-37](file://frontend/antd/descriptions/descriptions.tsx#L10-L37) + +Section sources + +- [descriptions.tsx:10-37](file://frontend/antd/descriptions/descriptions.tsx#L10-L37) + +### Empty + +- **Purpose**: Placeholder displayed when there is no data. +- **Key Points**: + - Supports `slots.description`/`image`; `image` supports default constant mapping. + - `styles` supports a function that returns a style object. +- **Typical usage path**: + - [Empty with custom image and description:6-49](file://frontend/antd/empty/empty.tsx#L6-L49) + +Section sources + +- [empty.tsx:6-49](file://frontend/antd/empty/empty.tsx#L6-L49) + +### Image + +- **Purpose**: Image display and preview. +- **Key Points**: + - Supports `slots.placeholder`, `preview.mask`, `preview.closeIcon`, `preview.toolbarRender`, `preview.imageRender`. + - `preview` configuration is merged via `getConfig`/`omitUndefinedProps`; `getContainer`/`toolbarRender`/`imageRender` are wrapped via `useFunction`. +- **Typical usage path**: + - [Image preview and toolbar rendering:15-85](file://frontend/antd/image/image.tsx#L15-L85) + +Section sources + +- [image.tsx:15-85](file://frontend/antd/image/image.tsx#L15-L85) + +### List + +- **Purpose**: Long list display with load-more support. +- **Key Points**: + - Supports `slots.footer`/`header`/`loadMore`/`renderItem`; `renderItem` is rendered via `renderParamsSlot` with forced cloning. +- **Typical usage path**: + - [List header, footer, and load more:8-33](file://frontend/antd/list/list.tsx#L8-L33) + +Section sources + +- [list.tsx:8-33](file://frontend/antd/list/list.tsx#L8-L33) + +### Popover + +- **Purpose**: Floating bubble card displaying a title and content. +- **Key Points**: + - Supports `slots.title`/`content`; `title`/`content` are cloned via `ReactSlot`. + - `afterOpenChange`/`getPopupContainer` are wrapped via `useFunction`. +- **Typical usage path**: + - [Popover title and content:7-34](file://frontend/antd/popover/popover.tsx#L7-L34) + +Section sources + +- [popover.tsx:7-34](file://frontend/antd/popover/popover.tsx#L7-L34) + +### QRCode + +- **Purpose**: Generate and display QR codes. +- **Typical usage path**: + - [QRCode component:1-200](file://frontend/antd/qr-code/qr-code.tsx#L1-L200) + +Section sources + +- [qr-code.tsx:1-200](file://frontend/antd/qr-code/qr-code.tsx#L1-L200) + +### Segmented + +- **Purpose**: Switching between multiple options. +- **Key Points**: + - Supports resolving `options`/`default` from context; `onChange` exposes the selected value via `onValueChange`. +- **Typical usage path**: + - [Segmented option rendering:10-43](file://frontend/antd/segmented/segmented.tsx#L10-L43) + +Section sources + +- [segmented.tsx:10-43](file://frontend/antd/segmented/segmented.tsx#L10-L43) + +### Statistic + +- **Purpose**: Displays numeric values with units, prefix, and suffix. +- **Key Points**: + - Supports `slots.prefix`/`suffix`/`title`/`formatter`; `formatter` is rendered via `renderParamsSlot`. +- **Typical usage path**: + - [Statistic value formatting:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) + +Section sources + +- [statistic.tsx:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) + +### Table + +- **Purpose**: Data table display and interaction. +- **Key Points**: + - Supports complex configurations including `columns`, `rowSelection`, `expandable`, `sticky`, `pagination`, `loading`, `footer`, `title`, `summary`, `showSorterTooltip`, etc. + - Injects column, expand, and row-selection contexts via multiple `with*ContextProvider` layers. + - Uses `renderItems` and `renderParamsSlot` to dynamically resolve items and function parameters; uses `createFunction`/`omitUndefinedProps` to wrap and merge configuration. +- **Typical usage path**: + - [Table columns and pagination slots:28-275](file://frontend/antd/table/table.tsx#L28-L275) + +Section sources + +- [table.tsx:28-275](file://frontend/antd/table/table.tsx#L28-L275) + +### Tabs + +- **Purpose**: Tab container and switching. +- **Key Points**: + - Supports `slots.addIcon`/`removeIcon`/`renderTabBar`/`tabBarExtraContent`/`left`/`right`/`more.icon`. + - `indicator.size`, `more.getPopupContainer`, `renderTabBar` are wrapped via `useFunction`; `items` are resolved via `renderItems`. +- **Typical usage path**: + - [Tabs with extra content:12-117](file://frontend/antd/tabs/tabs.tsx#L12-L117) + +Section sources + +- [tabs.tsx:12-117](file://frontend/antd/tabs/tabs.tsx#L12-L117) + +### Tag + +- **Purpose**: Marking and categorization. +- **Typical usage path**: + - [Tag component:1-200](file://frontend/antd/tag/tag.tsx#L1-L200) + +Section sources + +- [tag.tsx:1-200](file://frontend/antd/tag/tag.tsx#L1-L200) + +### Timeline + +- **Purpose**: Displays events in chronological order. +- **Typical usage path**: + - [Timeline component:1-200](file://frontend/antd/timeline/timeline.tsx#L1-L200) + +Section sources + +- [timeline.tsx:1-200](file://frontend/antd/timeline/timeline.tsx#L1-L200) + +### Tooltip + +- **Purpose**: Concise hint text. +- **Typical usage path**: + - [Tooltip component:1-200](file://frontend/antd/tooltip/tooltip.tsx#L1-L200) + +Section sources + +- [tooltip.tsx:1-200](file://frontend/antd/tooltip/tooltip.tsx#L1-L200) + +### Tour + +- **Purpose**: Guided tutorial. +- **Typical usage path**: + - [Tour component:1-200](file://frontend/antd/tour/tour.tsx#L1-L200) + +Section sources + +- [tour.tsx:1-200](file://frontend/antd/tour/tour.tsx#L1-L200) + +### Tree + +- **Purpose**: Hierarchical data display and selection. +- **Typical usage path**: + - [Tree component:1-200](file://frontend/antd/tree/tree.tsx#L1-L200) + +Section sources + +- [tree.tsx:1-200](file://frontend/antd/tree/tree.tsx#L1-L200) + +## Dependency Analysis + +- **Inter-component Coupling**: + - Card and Tabs share context (the `tabList` context is reused when Card embeds Tabs). + - Table injects column, expand, and row-selection contexts via multiple context providers. + - Most components share utilities such as `renderItems`, `renderParamsSlot`, `useFunction`, and `omitUndefinedProps`. +- **External Dependencies**: + - Ant Design component library and `dayjs` (for the Calendar component). + - `lodash-es` (for type checking in the Empty component). + +```mermaid +graph LR +RenderItems["renderItems"] +RenderParam["renderParamsSlot"] +UseFunc["useFunction"] +OmitUndef["omitUndefinedProps"] +Card["card.tsx"] --> RenderItems +Card --> UseFunc +Tabs["tabs.tsx"] --> RenderItems +Tabs --> UseFunc +Collapse["collapse.tsx"] --> RenderItems +Collapse --> UseFunc +Descriptions["descriptions.tsx"] --> RenderItems +Table["table.tsx"] --> RenderItems +Table --> RenderParam +Table --> UseFunc +Table --> OmitUndef +Image["image.tsx"] --> UseFunc +Image --> OmitUndef +Popover["popover.tsx"] --> UseFunc +Statistic["statistic.tsx"] --> UseFunc +Segmented["segmented.tsx"] --> RenderItems +Calendar["calendar.tsx"] --> UseFunc +``` + +Diagram sources + +- [card.tsx:10-14](file://frontend/antd/card/card.tsx#L10-L14) +- [tabs.tsx:6-10](file://frontend/antd/tabs/tabs.tsx#L6-L10) +- [collapse.tsx:4-8](file://frontend/antd/collapse/collapse.tsx#L4-L8) +- [descriptions.tsx:4-7](file://frontend/antd/descriptions/descriptions.tsx#L4-L7) +- [table.tsx:7-18](file://frontend/antd/table/table.tsx#L7-L18) +- [image.tsx:3-6](file://frontend/antd/image/image.tsx#L3-L6) +- [popover.tsx:4-5](file://frontend/antd/popover/popover.tsx#L4-L5) +- [statistic.tsx:4-6](file://frontend/antd/statistic/statistic.tsx#L4-L6) +- [segmented.tsx:3-6](file://frontend/antd/segmented/segmented.tsx#L3-L6) +- [calendar.tsx:3-4](file://frontend/antd/calendar/calendar.tsx#L3-L4) + +Section sources + +- [card.tsx:10-14](file://frontend/antd/card/card.tsx#L10-L14) +- [tabs.tsx:6-10](file://frontend/antd/tabs/tabs.tsx#L6-L10) +- [table.tsx:7-18](file://frontend/antd/table/table.tsx#L7-L18) + +## Performance Considerations + +- **Virtual Scrolling and Lazy Loading** + - List-type components (List, Table) can enable virtual scrolling and lazy loading via external configuration to reduce DOM count and reflow overhead. + - It is recommended to enable virtualization and paginated loading for large data sets. +- **Render Optimization** + - Use `useMemo` to cache computed results (e.g., Table's `columns`, `rowSelection`, `expandable`). + - Split slot rendering appropriately to avoid unnecessary repeated rendering. +- **Event and Function Wrapping** + - Use `useFunction`/`createFunction` to wrap callbacks, ensuring stable execution within the Svelte lifecycle and avoiding closure pitfalls. +- **Image and Preview** + - The Image component supports `placeholder` and preview toolbar customization; set dimensions and lazy loading strategies appropriately to reduce initial page load pressure. + +## Troubleshooting Guide + +- **Slot Not Working** + - Confirm that the slot name is correct (e.g., `preview.mask`, `tabProps.renderTabBar`, `loading.tip`, etc.). + - Check for missing combinations of `slots.*` and props. +- **Callback Not Firing** + - Ensure callbacks are wrapped via `useFunction`; verify event naming and parameter signatures. +- **Date Format Issues (Calendar)** + - The Calendar component internally converts time to second-level timestamps; confirm the input value type and range. +- **Table Columns and Expand Configuration** + - When `columns` is empty, the component attempts to resolve from context; confirm that the context correctly provides `default`/`items`. +- **Style Overrides** + - Empty's `styles` supports functional returns; pay attention to the return object structure and key names. + +Section sources + +- [image.tsx:32-34](file://frontend/antd/image/image.tsx#L32-L34) +- [popover.tsx:10-12](file://frontend/antd/popover/popover.tsx#L10-L12) +- [calendar.tsx:85-94](file://frontend/antd/calendar/calendar.tsx#L85-L94) +- [table.tsx:67-75](file://frontend/antd/table/table.tsx#L67-L75) +- [empty.tsx:34-45](file://frontend/antd/empty/empty.tsx#L34-L45) + +## Conclusion + +ModelScope Studio's data display components achieve seamless integration with Ant Design through a unified `sveltify` wrapper, providing powerful slot and function parameter extension capabilities. With context resolution and utility functions, developers can quickly build card layouts, carousels, collapse panels, description lists, image previews, data tables, tag clouds, and other common data display scenarios. It is recommended to combine virtual scrolling, lazy loading, and style optimization strategies in real-world projects to further improve performance and user experience. + +## Appendix + +- **TypeScript Type Definition Key Points** + - Most components obtain types via `GetProps`, then extend props as needed (e.g., `onValueChange`, `containsGrid`, etc.). + - For complex configuration objects (e.g., `preview`, `loading`, `pagination`, `sticky`, `showSorterTooltip`, `components`), use `getConfig`/`omitUndefinedProps` to merge and inject slots. +- **Data Transformation and Chart Integration** + - The Calendar component internally converts time to `dayjs` and outputs second-level timestamps in callbacks, making it easy to interface with backends or chart libraries. + - The Table component supports mapping business data to columns and rows via `slots` and `renderItems`, making it easy to integrate with visualization libraries (e.g., ECharts, AntV). +- **Visual Design and Experience Optimization** + - Use `Empty` to improve readability in no-data scenarios. + - Use `Tooltip`/`Popover` to provide contextual help information. + - Use `Statistic`/`Segmented`/`Tag` and other components to enhance information density and interaction feedback. diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Data Entry Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Data Entry Components API.md new file mode 100644 index 00000000..e4889737 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Data Entry Components API.md @@ -0,0 +1,523 @@ +# Data Entry Components API + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/auto-complete/auto-complete.tsx](file://frontend/antd/auto-complete/auto-complete.tsx) +- [frontend/antd/cascader/cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [frontend/antd/checkbox/checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [frontend/antd/color-picker/color-picker.tsx](file://frontend/antd/color-picker/color-picker.tsx) +- [frontend/antd/date-picker/date-picker.tsx](file://frontend/antd/date-picker/date-picker.tsx) +- [frontend/antd/input/input.tsx](file://frontend/antd/input/input.tsx) +- [frontend/antd/input-number/input-number.tsx](file://frontend/antd/input-number/input-number.tsx) +- [frontend/antd/mentions/mentions.tsx](file://frontend/antd/mentions/mentions.tsx) +- [frontend/antd/radio/radio.tsx](file://frontend/antd/radio/radio.tsx) +- [frontend/antd/rate/rate.tsx](file://frontend/antd/rate/rate.tsx) +- [frontend/antd/select/select.tsx](file://frontend/antd/select/select.tsx) +- [frontend/antd/slider/slider.tsx](file://frontend/antd/slider/slider.tsx) +- [frontend/antd/switch/switch.tsx](file://frontend/antd/switch/switch.tsx) +- [frontend/antd/time-picker/time-picker.tsx](file://frontend/antd/time-picker/time-picker.tsx) +- [frontend/antd/transfer/transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [frontend/antd/tree-select/tree-select.tsx](file://frontend/antd/tree-select/tree-select.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for Ant Design-based data entry components in ModelScope Studio, covering: AutoComplete, Cascader, Checkbox, ColorPicker, DatePicker, Form, Input, InputNumber, Mentions, Radio, Rate, Select, Slider, Switch, TimePicker, Transfer, TreeSelect, Upload (to be added). It includes: + +- Property definitions and type constraints +- Data validation and formatting strategies +- Event callbacks and data binding mechanisms +- Standard usage example paths (using source code paths instead of inline code) +- Recommendations for interfacing with backend APIs +- Key points for user experience and performance optimization + +## Project Structure + +ModelScope Studio wraps Ant Design components as Svelte components, uniformly using `sveltify` to wrap the React AntD components, and providing a unified `onValueChange` callback, slot rendering, and value change hooks at the frontend layer for two-way data binding with the Python backend. + +```mermaid +graph TB +subgraph "Backend Component Export" +PY["components.py
Exports each AntD component"] +end +subgraph "Frontend Wrapper Layer" +F_FORM["form/form.tsx"] +F_AUTO["auto-complete/auto-complete.tsx"] +F_CASCADE["cascader/cascader.tsx"] +F_CHECK["checkbox/checkbox.tsx"] +F_COLOR["color-picker/color-picker.tsx"] +F_DATE["date-picker/date-picker.tsx"] +F_INPUT["input/input.tsx"] +F_NUM["input-number/input-number.tsx"] +F_MENTIONS["mentions/mentions.tsx"] +F_RADIO["radio/radio.tsx"] +F_RATE["rate/rate.tsx"] +F_SELECT["select/select.tsx"] +F_SLIDER["slider/slider.tsx"] +F_SWITCH["switch/switch.tsx"] +F_TIME["time-picker/time-picker.tsx"] +F_TRANS["transfer/transfer.tsx"] +F_TSELECT["tree-select/tree-select.tsx"] +end +PY --> F_FORM +PY --> F_AUTO +PY --> F_CASCADE +PY --> F_CHECK +PY --> F_COLOR +PY --> F_DATE +PY --> F_INPUT +PY --> F_NUM +PY --> F_MENTIONS +PY --> F_RADIO +PY --> F_RATE +PY --> F_SELECT +PY --> F_SLIDER +PY --> F_SWITCH +PY --> F_TIME +PY --> F_TRANS +PY --> F_TSELECT +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/auto-complete/auto-complete.tsx:1-151](file://frontend/antd/auto-complete/auto-complete.tsx#L1-L151) +- [frontend/antd/cascader/cascader.tsx:1-207](file://frontend/antd/cascader/cascader.tsx#L1-L207) +- [frontend/antd/checkbox/checkbox.tsx:1-22](file://frontend/antd/checkbox/checkbox.tsx#L1-L22) +- [frontend/antd/color-picker/color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) +- [frontend/antd/date-picker/date-picker.tsx:1-234](file://frontend/antd/date-picker/date-picker.tsx#L1-L234) +- [frontend/antd/input/input.tsx:1-119](file://frontend/antd/input/input.tsx#L1-L119) +- [frontend/antd/input-number/input-number.tsx:1-92](file://frontend/antd/input-number/input-number.tsx#L1-L92) +- [frontend/antd/mentions/mentions.tsx:1-80](file://frontend/antd/mentions/mentions.tsx#L1-L80) +- [frontend/antd/radio/radio.tsx:1-32](file://frontend/antd/radio/radio.tsx#L1-L32) +- [frontend/antd/rate/rate.tsx:1-45](file://frontend/antd/rate/rate.tsx#L1-L45) +- [frontend/antd/select/select.tsx:1-181](file://frontend/antd/select/select.tsx#L1-L181) +- [frontend/antd/slider/slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) +- [frontend/antd/switch/switch.tsx:1-42](file://frontend/antd/switch/switch.tsx#L1-L42) +- [frontend/antd/time-picker/time-picker.tsx:1-201](file://frontend/antd/time-picker/time-picker.tsx#L1-L201) +- [frontend/antd/transfer/transfer.tsx:1-112](file://frontend/antd/transfer/transfer.tsx#L1-L112) +- [frontend/antd/tree-select/tree-select.tsx:1-163](file://frontend/antd/tree-select/tree-select.tsx#L1-L163) + +Section sources + +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +## Core Components + +This section provides an overview of the common patterns and key interfaces for all data entry components: + +- **Value binding**: All support `value` and `onValueChange` for controlled/uncontrolled switching and two-way binding. +- **Slot system**: Many components support `slots` (e.g., `allowClear.clearIcon`, `prefix`, `suffix`, `popupRender`, etc.) for custom rendering. +- **Functional props**: Some props support function values (e.g., `formatter`, `parser`, `disabledDate`, etc.), wrapped via `useFunction`. +- **Options/tree data**: Select, Cascader, TreeSelect, AutoComplete, Mentions, etc. support rendering items via `children` or `options`/`treeData`. +- **Form integration**: Form provides global form state management, reset, submit, validate actions, and `requiredMark`/`feedbackIcons` support. + +Section sources + +- [frontend/antd/form/form.tsx:8-76](file://frontend/antd/form/form.tsx#L8-L76) +- [frontend/antd/select/select.tsx:11-178](file://frontend/antd/select/select.tsx#L11-L178) +- [frontend/antd/cascader/cascader.tsx:19-204](file://frontend/antd/cascader/cascader.tsx#L19-L204) +- [frontend/antd/tree-select/tree-select.tsx:14-161](file://frontend/antd/tree-select/tree-select.tsx#L14-L161) +- [frontend/antd/auto-complete/auto-complete.tsx:32-148](file://frontend/antd/auto-complete/auto-complete.tsx#L32-L148) +- [frontend/antd/mentions/mentions.tsx:11-77](file://frontend/antd/mentions/mentions.tsx#L11-L77) + +## Architecture Overview + +The following diagram shows the common call chain for data entry components: frontend components pass values upstream via the `onValueChange` callback; the Form component handles form-level actions (reset/submit/validate) and global `requiredMark`/`feedbackIcons`; some components format values internally (e.g., date/time components). + +```mermaid +sequenceDiagram +participant U as "User" +participant C as "Data Entry Component" +participant F as "Form Component" +participant B as "Backend Service" +U->>C : Input/Select/Change +C->>C : Triggers onChange/onValueChange +C-->>F : onValueChange(value) +F->>F : setFieldsValue / submit / validate +F-->>B : Submits form data +B-->>F : Returns result/error +F-->>U : Displays feedback/error message +``` + +Diagram sources + +- [frontend/antd/form/form.tsx:27-76](file://frontend/antd/form/form.tsx#L27-L76) +- [frontend/antd/date-picker/date-picker.tsx:162-170](file://frontend/antd/date-picker/date-picker.tsx#L162-L170) +- [frontend/antd/time-picker/time-picker.tsx:131-143](file://frontend/antd/time-picker/time-picker.tsx#L131-L143) + +## Component Details + +### Form + +- **Responsibility**: Wraps AntD Form, providing `value`, `onValueChange`, `formAction` (reset/submit/validate), `requiredMark`, and `feedbackIcons` capabilities. +- **Key Points**: + - Creates a form instance via `AForm.useForm`. + - Executes reset/submit/validate when `formAction` changes. + - Syncs upstream value via `onValuesChange` and triggers `onValueChange`. +- **Typical usage path** + - [Form container implementation:15-76](file://frontend/antd/form/form.tsx#L15-L76) + +Section sources + +- [frontend/antd/form/form.tsx:8-76](file://frontend/antd/form/form.tsx#L8-L76) + +### AutoComplete + +- **Capabilities**: Supports options list, filtering, popup rendering, clear icon, empty placeholder, etc. +- **Key Points**: + - Uses `useValueChange` for controlled `value`. + - Supports slots: `allowClear.clearIcon`, `dropdownRender`, `popupRender`, `notFoundContent`. + - Supports `filterOption` function and `getPopupContainer`. +- **Typical usage path** + - [AutoComplete component:32-148](file://frontend/antd/auto-complete/auto-complete.tsx#L32-L148) + +Section sources + +- [frontend/antd/auto-complete/auto-complete.tsx:32-148](file://frontend/antd/auto-complete/auto-complete.tsx#L32-L148) + +### Cascader + +- **Capabilities**: Multi-level cascading selection; supports dynamic loading, search, tag rendering, and custom dropdown panel. +- **Key Points**: + - Supports two data sources: `options` and `children`. + - `showSearch` supports object configuration and `slots['showSearch.render']`. + - Supports `onLoadData` for dynamic loading. +- **Typical usage path** + - [Cascader component:19-204](file://frontend/antd/cascader/cascader.tsx#L19-L204) + +Section sources + +- [frontend/antd/cascader/cascader.tsx:19-204](file://frontend/antd/cascader/cascader.tsx#L19-L204) + +### Checkbox + +- **Capabilities**: Boolean selection; supports `onValueChange`. +- **Key Points**: + - Forwards the native event in `onChange` and triggers `onValueChange(value)`. +- **Typical usage path** + - [Checkbox component:4-19](file://frontend/antd/checkbox/checkbox.tsx#L4-L19) + +Section sources + +- [frontend/antd/checkbox/checkbox.tsx:4-19](file://frontend/antd/checkbox/checkbox.tsx#L4-L19) + +### ColorPicker + +- **Capabilities**: Supports solid color/gradient, preset colors, and multiple output formats (rgb/hex/hsb). +- **Key Points**: + - `onChange` returns different format arrays or a single string depending on whether gradient mode is active. + - Supports `presets` slot and `panelRender`/`showText` customization. +- **Typical usage path** + - [ColorPicker component:11-103](file://frontend/antd/color-picker/color-picker.tsx#L11-L103) + +Section sources + +- [frontend/antd/color-picker/color-picker.tsx:11-103](file://frontend/antd/color-picker/color-picker.tsx#L11-L103) + +### DatePicker + +- **Capabilities**: Single-date/range selection, time selection, preset shortcuts, disabled dates/times, custom cell/panel rendering. +- **Key Points**: + - Internally formats input values as `dayjs` and outputs second-level timestamps in `onChange`/`onPanelChange`. + - Supports `defaultValue` formatting within the `showTime` object. + - Supports slots: `presets`, `cellRender`, `panelRender`, `renderExtraFooter`, etc. +- **Typical usage path** + - [DatePicker component:40-231](file://frontend/antd/date-picker/date-picker.tsx#L40-L231) + +Section sources + +- [frontend/antd/date-picker/date-picker.tsx:40-231](file://frontend/antd/date-picker/date-picker.tsx#L40-L231) + +### Input + +- **Capabilities**: Basic text input; supports prefix/suffix, character counter, clear icon, and slot extensions. +- **Key Points**: + - `useValueChange` for controlled `value`. + - Supports `showCount.formatter` slot and `count`-series functions. + - Supports `addonBefore`/`addonAfter`, `prefix`/`suffix`, `allowClear.clearIcon`. +- **Typical usage path** + - [Input component:10-116](file://frontend/antd/input/input.tsx#L10-L116) + +Section sources + +- [frontend/antd/input/input.tsx:10-116](file://frontend/antd/input/input.tsx#L10-L116) + +### InputNumber + +- **Capabilities**: Numeric input; supports custom step buttons, prefix/suffix, `formatter`/`parser`. +- **Key Points**: + - `useValueChange` for controlled `value`. + - Supports `controls.upIcon`/`downIcon` slots and `addonBefore`/`addonAfter`, `prefix`/`suffix`. +- **Typical usage path** + - [InputNumber component:7-91](file://frontend/antd/input-number/input-number.tsx#L7-L91) + +Section sources + +- [frontend/antd/input-number/input-number.tsx:7-91](file://frontend/antd/input-number/input-number.tsx#L7-L91) + +### Mentions + +- **Capabilities**: `@` mention functionality; supports options list, filtering, and popup rendering. +- **Key Points**: + - `useValueChange` for controlled `value`. + - Supports `options`, `filterOption`, `validateSearch`, `getPopupContainer`. +- **Typical usage path** + - [Mentions component:11-77](file://frontend/antd/mentions/mentions.tsx#L11-L77) + +Section sources + +- [frontend/antd/mentions/mentions.tsx:11-77](file://frontend/antd/mentions/mentions.tsx#L11-L77) + +### Radio + +- **Capabilities**: Single-choice selection; supports `onValueChange`. +- **Key Points**: + - Forwards the native event in `onChange` and triggers `onValueChange(value)`. + - Injects theme tokens to adapt to style variables. +- **Typical usage path** + - [Radio component:6-29](file://frontend/antd/radio/radio.tsx#L6-L29) + +Section sources + +- [frontend/antd/radio/radio.tsx:6-29](file://frontend/antd/radio/radio.tsx#L6-L29) + +### Rate + +- **Capabilities**: Star rating; supports custom characters. +- **Key Points**: + - Supports `character` slot and functional configuration. + - `onChange` triggers `onValueChange`. +- **Typical usage path** + - [Rate component:6-42](file://frontend/antd/rate/rate.tsx#L6-L42) + +Section sources + +- [frontend/antd/rate/rate.tsx:6-42](file://frontend/antd/rate/rate.tsx#L6-L42) + +### Select + +- **Capabilities**: Single/multi-select; supports tag rendering, custom dropdown panel, filtering and sorting. +- **Key Points**: + - Supports two data sources: `options` and `children`. + - Supports `allowClear.clearIcon`, `prefix`/`removeIcon`/`suffixIcon`, `notFoundContent`, `menuItemSelectedIcon`. + - Supports `dropdownRender`/`popupRender`/`optionRender`/`tagRender`/`labelRender`. + - Supports `filterOption`/`filterSort`. +- **Typical usage path** + - [Select component:11-178](file://frontend/antd/select/select.tsx#L11-L178) + +Section sources + +- [frontend/antd/select/select.tsx:11-178](file://frontend/antd/select/select.tsx#L11-L178) + +### Slider + +- **Capabilities**: Single/double sliders; supports tick mark labels and tooltip formatting. +- **Key Points**: + - `marks` are rendered via `children`, supporting a `label` child slot. + - `tooltip` supports a `formatter` slot and function. +- **Typical usage path** + - [Slider component:37-94](file://frontend/antd/slider/slider.tsx#L37-L94) + +Section sources + +- [frontend/antd/slider/slider.tsx:37-94](file://frontend/antd/slider/slider.tsx#L37-L94) + +### Switch + +- **Capabilities**: Boolean toggle; supports custom label slots. +- **Key Points**: + - Supports `checkedChildren`/`unCheckedChildren` slots. + - `onChange` triggers `onValueChange`. +- **Typical usage path** + - [Switch component:6-39](file://frontend/antd/switch/switch.tsx#L6-L39) + +Section sources + +- [frontend/antd/switch/switch.tsx:6-39](file://frontend/antd/switch/switch.tsx#L6-L39) + +### TimePicker + +- **Capabilities**: Time selection, range selection, custom panel, disabled times. +- **Key Points**: + - Internally formats input values as `dayjs` and outputs second-level timestamps in `onChange`/`onPanelChange`/`onCalendarChange`. + - Supports slots: `cellRender`, `panelRender`, `renderExtraFooter`, etc. +- **Typical usage path** + - [TimePicker component:37-198](file://frontend/antd/time-picker/time-picker.tsx#L37-L198) + +Section sources + +- [frontend/antd/time-picker/time-picker.tsx:37-198](file://frontend/antd/time-picker/time-picker.tsx#L37-L198) + +### Transfer + +- **Capabilities**: Left-right list transfer; supports titles, select-all labels, action buttons, custom rendering and filtering. +- **Key Points**: + - `onChange` returns `targetKeys`. + - Supports `titles`/`selectAllLabels`/`actions` slots. + - Supports `render`/`footer`/`locale.notFoundContent`. +- **Typical usage path** + - [Transfer component:9-110](file://frontend/antd/transfer/transfer.tsx#L9-L110) + +Section sources + +- [frontend/antd/transfer/transfer.tsx:9-110](file://frontend/antd/transfer/transfer.tsx#L9-L110) + +### TreeSelect + +- **Capabilities**: Tree-structured selection; supports dynamic loading, filtering, tag rendering, and custom dropdown panel. +- **Key Points**: + - Supports two data sources: `treeData` and `children`. + - Supports `dropdownRender`/`popupRender`/`tagRender`/`treeTitleRender`. + - Supports `allowClear.clearIcon`, `prefix`/`suffix`, `switcherIcon`, `maxTagPlaceholder`, `notFoundContent`. + - `onLoadData` is integrated via a wrapper function. +- **Typical usage path** + - [TreeSelect component:14-161](file://frontend/antd/tree-select/tree-select.tsx#L14-L161) + +Section sources + +- [frontend/antd/tree-select/tree-select.tsx:14-161](file://frontend/antd/tree-select/tree-select.tsx#L14-L161) + +### Upload (pending) + +- The current repository does not provide a frontend wrapper implementation for Upload; API details and example paths are not available. +- It is recommended to refer to the official Ant Design Upload component and add `onValueChange` and slot support following the existing wrapper pattern. + +[No file analysis for this section; no section sources] + +## Dependency Analysis + +- **Inter-component Coupling**: Most components are decoupled via the unified `sveltify` wrapper and hooks (`useValueChange`, `useFunction`, `renderItems`, `renderParamsSlot`). +- **External Dependencies**: Ant Design React component library, `dayjs` (date/time formatting), React Slot/Svelte Preprocess (slot system). +- **Form Integration**: The Form component centrally manages form state and actions; other components collaborate with it via `onValueChange`. + +```mermaid +graph LR +A["AntD React Component Library"] --> B["sveltify wrapper"] +B --> C["Each data entry component"] +C --> D["hooks: useValueChange/useFunction"] +C --> E["renderItems/renderParamsSlot"] +F["Form Component"] --> C +``` + +Diagram sources + +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/input/input.tsx:3-42](file://frontend/antd/input/input.tsx#L3-L42) +- [frontend/antd/select/select.tsx:49-56](file://frontend/antd/select/select.tsx#L49-L56) + +Section sources + +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/input/input.tsx:3-42](file://frontend/antd/input/input.tsx#L3-L42) +- [frontend/antd/select/select.tsx:49-56](file://frontend/antd/select/select.tsx#L49-L56) + +## Performance Considerations + +- **Controlled vs. Uncontrolled**: Prefer controlled components (`value` + `onValueChange`) to avoid redundant rendering and state drift. +- **Slots and Functions**: Externalize complex slot logic as functions where possible to reduce unnecessary re-renders. +- **Option Rendering**: For Select/Cascader/TreeSelect/Mentions etc., it is recommended to pass static `options` to avoid generating new arrays on every render. +- **Date/Time**: DatePicker/TimePicker internally format `dayjs`; avoid redundant conversions in the parent component. +- **Slider and Rate**: Custom characters/labels in Rate/Slider should be kept lightweight to avoid heavy DOM structures. + +[This section provides general guidance; no specific file analysis] + +## Troubleshooting Guide + +- **Form Action Not Working** + - Confirm that Form's `formAction` is set to `reset`/`submit`/`validate` and reset the value after the action completes. + - Reference path: [Form action handling:32-45](file://frontend/antd/form/form.tsx#L32-L45) +- **Value Not Updating** + - Ensure `onValueChange` has been correctly set and triggered. + - Reference path: [Input value change:49-54](file://frontend/antd/input/input.tsx#L49-L54) +- **Date/Time Format Abnormality** + - DatePicker/TimePicker output second-level timestamps; ensure the backend converts them as needed. + - Reference path: [Date formatting:26-38](file://frontend/antd/date-picker/date-picker.tsx#L26-L38) +- **Options Not Displaying or Filter Not Working** + - Check that `options` have been passed or that `children` are rendering correctly. + - Reference path: [Select option rendering:64-77](file://frontend/antd/select/select.tsx#L64-L77) +- **Inconsistent Color Format** + - ColorPicker supports rgb/hex/hsb output; confirm the `value_format` configuration. + - Reference path: [Color formatting:71-95](file://frontend/antd/color-picker/color-picker.tsx#L71-L95) + +Section sources + +- [frontend/antd/form/form.tsx:32-45](file://frontend/antd/form/form.tsx#L32-L45) +- [frontend/antd/input/input.tsx:49-54](file://frontend/antd/input/input.tsx#L49-L54) +- [frontend/antd/date-picker/date-picker.tsx:26-38](file://frontend/antd/date-picker/date-picker.tsx#L26-L38) +- [frontend/antd/select/select.tsx:64-77](file://frontend/antd/select/select.tsx#L64-L77) +- [frontend/antd/color-picker/color-picker.tsx:71-95](file://frontend/antd/color-picker/color-picker.tsx#L71-L95) + +## Conclusion + +ModelScope Studio's data entry components achieve seamless integration with Ant Design through a unified wrapper pattern, providing rich slots and functional props to meet diverse business requirements. In practice, it is recommended to follow the controlled component principle, make good use of slots and functions, pay attention to date/time and color format conversion, and use the Form component to complete the full form interaction loop. + +[This section provides summary content; no specific file analysis] + +## Appendix + +### Component API Overview (by theme) + +- **Text Input** + - **Input**: Supports `value`, `onValueChange`, `addonBefore`/`addonAfter`, `prefix`/`suffix`, `allowClear.clearIcon`, `showCount.formatter` + - Reference path: [Input component:10-116](file://frontend/antd/input/input.tsx#L10-L116) + - **InputNumber**: Supports `value`, `onValueChange`, `formatter`, `parser`, `controls.upIcon`/`downIcon`, `addonBefore`/`addonAfter`, `prefix`/`suffix` + - Reference path: [InputNumber component:7-91](file://frontend/antd/input-number/input-number.tsx#L7-L91) + - **AutoComplete**: Supports `value`, `onValueChange`, `options`, `filterOption`, `dropdownRender`, `popupRender`, `allowClear.clearIcon`, `notFoundContent` + - Reference path: [AutoComplete component:32-148](file://frontend/antd/auto-complete/auto-complete.tsx#L32-L148) + - **Mentions**: Supports `value`, `onValueChange`, `options`, `filterOption`, `validateSearch`, `getPopupContainer`, `notFoundContent` + - Reference path: [Mentions component:11-77](file://frontend/antd/mentions/mentions.tsx#L11-L77) + +- **Selectors** + - **Select**: Supports `value`, `onValueChange`, `options`, `filterOption`, `filterSort`, `allowClear.clearIcon`, `prefix`/`removeIcon`/`suffixIcon`, `notFoundContent`, `menuItemSelectedIcon`, `dropdownRender`/`popupRender`/`optionRender`/`tagRender`/`labelRender` + - Reference path: [Select component:11-178](file://frontend/antd/select/select.tsx#L11-L178) + - **Cascader**: Supports `value`, `onValueChange`, `options`, `showSearch`, `loadData`, `displayRender`/`tagRender`/`optionRender`, `dropdownRender`/`popupRender`, `allowClear.clearIcon`, `prefix`/`suffixIcon`, `expandIcon`, `removeIcon`, `notFoundContent`, `maxTagPlaceholder` + - Reference path: [Cascader component:19-204](file://frontend/antd/cascader/cascader.tsx#L19-L204) + - **TreeSelect**: Supports `value`, `onValueChange`, `treeData`, `filterTreeNode`, `loadData`, `dropdownRender`/`popupRender`/`tagRender`/`treeTitleRender`, `allowClear.clearIcon`, `prefix`/`suffix`, `switcherIcon`, `notFoundContent`, `maxTagPlaceholder` + - Reference path: [TreeSelect component:14-161](file://frontend/antd/tree-select/tree-select.tsx#L14-L161) + +- **Date and Time** + - **DatePicker**: Supports `value`, `onChange`/`onPanelChange`, `pickerValue`/`defaultPickerValue`, `showTime`, `disabledDate`/`disabledTime`, `cellRender`/`panelRender`, `presets`, `renderExtraFooter`, `prevIcon`/`nextIcon`/`suffixIcon`/`superNextIcon`/`superPrevIcon`, `allowClear.clearIcon` + - Reference path: [DatePicker component:40-231](file://frontend/antd/date-picker/date-picker.tsx#L40-L231) + - **TimePicker**: Supports `value`, `onChange`/`onPanelChange`/`onCalendarChange`, `pickerValue`/`defaultPickerValue`, `disabledDate`/`disabledTime`, `cellRender`/`panelRender`, `renderExtraFooter`, `prevIcon`/`nextIcon`/`suffixIcon`/`superNextIcon`/`superPrevIcon`, `allowClear.clearIcon` + - Reference path: [TimePicker component:37-198](file://frontend/antd/time-picker/time-picker.tsx#L37-L198) + +- **Interaction and Rating** + - **Checkbox**: Supports `value`, `onValueChange`, `onChange` + - Reference path: [Checkbox component:4-19](file://frontend/antd/checkbox/checkbox.tsx#L4-L19) + - **Radio**: Supports `value`, `onValueChange`, `onChange`, theme token injection + - Reference path: [Radio component:6-29](file://frontend/antd/radio/radio.tsx#L6-L29) + - **Rate**: Supports `value`, `onValueChange`, `onChange`, `character` slot/function + - Reference path: [Rate component:6-42](file://frontend/antd/rate/rate.tsx#L6-L42) + - **Switch**: Supports `value`, `onChange`, `checkedChildren`/`unCheckedChildren` slots + - Reference path: [Switch component:6-39](file://frontend/antd/switch/switch.tsx#L6-L39) + - **Slider**: Supports `value`, `onChange`, `marks` (children rendering), `tooltip.formatter` slot + - Reference path: [Slider component:37-94](file://frontend/antd/slider/slider.tsx#L37-L94) + +- **Color and Form** + - **ColorPicker**: Supports `value`, `onValueChange`, `onChange`, `value_format` (rgb/hex/hsb), `presets`, `panelRender`, `showText` + - Reference path: [ColorPicker component:11-103](file://frontend/antd/color-picker/color-picker.tsx#L11-L103) + - **Form**: Supports `value`, `onValueChange`, `formAction` (reset/submit/validate), `requiredMark`, `feedbackIcons` + - Reference path: [Form component:8-76](file://frontend/antd/form/form.tsx#L8-L76) + +- **Transfer** + - **Transfer**: Supports `value` (targetKeys), `onChange`, `titles`/`selectAllLabels`/`actions` slots, `render`/`footer`/`locale.notFoundContent`, `selectionsIcon` + - Reference path: [Transfer component:9-110](file://frontend/antd/transfer/transfer.tsx#L9-L110) + +[This section provides a summary overview; no specific file analysis] diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Feedback Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Feedback Components API.md new file mode 100644 index 00000000..58608580 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Feedback Components API.md @@ -0,0 +1,383 @@ +# Feedback Components API + + +**Files referenced in this document** +- [frontend/antd/alert/alert.tsx](file://frontend/antd/alert/alert.tsx) +- [frontend/antd/drawer/drawer.tsx](file://frontend/antd/drawer/drawer.tsx) +- [frontend/antd/message/message.tsx](file://frontend/antd/message/message.tsx) +- [frontend/antd/modal/modal.tsx](file://frontend/antd/modal/modal.tsx) +- [frontend/antd/notification/notification.tsx](file://frontend/antd/notification/notification.tsx) +- [frontend/antd/popconfirm/popconfirm.tsx](file://frontend/antd/popconfirm/popconfirm.tsx) +- [frontend/antd/progress/progress.tsx](file://frontend/antd/progress/progress.tsx) +- [frontend/antd/result/result.tsx](file://frontend/antd/result/result.tsx) +- [frontend/antd/skeleton/skeleton.tsx](file://frontend/antd/skeleton/skeleton.tsx) +- [frontend/antd/spin/spin.tsx](file://frontend/antd/spin/spin.tsx) +- [frontend/antd/watermark/watermark.tsx](file://frontend/antd/watermark/watermark.tsx) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [docs/components/antd/alert/README.md](file://docs/components/antd/alert/README.md) +- [docs/components/antd/drawer/README.md](file://docs/components/antd/drawer/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for Ant Design-based feedback components in ModelScope Studio, covering: Alert, Drawer, Message, Modal, Notification, Popconfirm, Progress, Result, Skeleton, Spin, and Watermark. It includes: + +- Property definitions and type constraints +- State management and lifecycle +- Animation and interaction logic +- Standard instantiation and configuration example paths +- Event callbacks and asynchronous handling +- Accessibility and user experience design principles + +## Project Structure + +Feedback components are implemented on the frontend as Svelte wrappers that bridge Ant Design React components, and are uniformly exported via backend Python modules for on-demand use in applications. + +```mermaid +graph TB +subgraph "Frontend" +A1["alert.tsx"] +A2["drawer.tsx"] +A3["message.tsx"] +A4["modal.tsx"] +A5["notification.tsx"] +A6["popconfirm.tsx"] +A7["progress.tsx"] +A8["result.tsx"] +A9["skeleton.tsx"] +A10["spin.tsx"] +A11["watermark.tsx"] +end +subgraph "Backend" +B1["__init__.py"] +B2["components.py"] +end +A1 --> B1 +A2 --> B1 +A3 --> B1 +A4 --> B1 +A5 --> B1 +A6 --> B1 +A7 --> B1 +A8 --> B1 +A9 --> B1 +A10 --> B1 +A11 --> B1 +B1 --> B2 +``` + +Diagram sources + +- [frontend/antd/alert/alert.tsx:1-46](file://frontend/antd/alert/alert.tsx#L1-L46) +- [frontend/antd/drawer/drawer.tsx:1-60](file://frontend/antd/drawer/drawer.tsx#L1-L60) +- [frontend/antd/message/message.tsx:1-79](file://frontend/antd/message/message.tsx#L1-L79) +- [frontend/antd/modal/modal.tsx:1-107](file://frontend/antd/modal/modal.tsx#L1-L107) +- [frontend/antd/notification/notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) +- [frontend/antd/popconfirm/popconfirm.tsx:1-65](file://frontend/antd/popconfirm/popconfirm.tsx#L1-L65) +- [frontend/antd/progress/progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [frontend/antd/result/result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- [frontend/antd/watermark/watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +Section sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +## Core Components + +- **Alert**: Displays warning information requiring user attention; supports slots for `description`, `icon`, `action`, `closable.closeIcon`, etc. +- **Drawer**: A drawer panel that slides in from the screen edge; supports `title`, `footer`, `extra`, `closeIcon`, and render hooks. +- **Message**: Global hint message; supports visibility control, custom content and icons, and destroy/open operations. +- **Modal**: Modal dialog; supports `title`, `footer`, button icons, render hooks, and container mounting. +- **Notification**: Global notification alert; supports position, actions, close icon, description, and message. +- **Popconfirm**: Bubble confirmation; supports confirm/cancel text and icons, and popup container. +- **Progress**: Progress bar; supports `format` and `rounding` function handling. +- **Result**: Result page; supports `title`, `subTitle`, `icon`, and `extra` slots. +- **Skeleton**: Skeleton screen placeholder. +- **Spin**: Loading indicator; supports `tip` text and `indicator` slots. +- **Watermark**: Watermark overlay. + +Section sources + +- [frontend/antd/alert/alert.tsx:1-46](file://frontend/antd/alert/alert.tsx#L1-L46) +- [frontend/antd/drawer/drawer.tsx:1-60](file://frontend/antd/drawer/drawer.tsx#L1-L60) +- [frontend/antd/message/message.tsx:1-79](file://frontend/antd/message/message.tsx#L1-L79) +- [frontend/antd/modal/modal.tsx:1-107](file://frontend/antd/modal/modal.tsx#L1-L107) +- [frontend/antd/notification/notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) +- [frontend/antd/popconfirm/popconfirm.tsx:1-65](file://frontend/antd/popconfirm/popconfirm.tsx#L1-L65) +- [frontend/antd/progress/progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [frontend/antd/result/result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- [frontend/antd/watermark/watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) + +## Architecture Overview + +Feedback components follow a layered architecture of "Svelte wrapper + Ant Design React component + unified backend export": + +- **Frontend layer**: Each component wraps an Ant Design component with `sveltify`, supporting `slots` and function callback conversion. +- **Interaction layer**: Bridges callbacks and child nodes via utilities like `useFunction`/`useTargets`. +- **Export layer**: Python modules centrally export each component for unified import and aliasing in applications. + +```mermaid +sequenceDiagram +participant App as "Application" +participant Wrapper as "Svelte Wrapper" +participant AD as "Ant Design Component" +participant Util as "Utility Hooks" +App->>Wrapper : Passes props and slots +Wrapper->>Util : useFunction()/useTargets() +Util-->>Wrapper : Converted callbacks/target nodes +Wrapper->>AD : Renders and passes props/slots +AD-->>App : Fires event callbacks/state changes +``` + +Diagram sources + +- [frontend/antd/alert/alert.tsx:12-43](file://frontend/antd/alert/alert.tsx#L12-L43) +- [frontend/antd/drawer/drawer.tsx:24-57](file://frontend/antd/drawer/drawer.tsx#L24-L57) +- [frontend/antd/message/message.tsx:18-76](file://frontend/antd/message/message.tsx#L18-L76) +- [frontend/antd/modal/modal.tsx:22-104](file://frontend/antd/modal/modal.tsx#L22-L104) +- [frontend/antd/notification/notification.tsx:17-103](file://frontend/antd/notification/notification.tsx#L17-L103) + +## Component Details + +### Alert + +- **Key Capabilities** + - Supports slots: `message`, `description`, `icon`, `action`, `closable.closeIcon` + - The `afterClose` callback is converted via `useFunction` +- **Lifecycle** + - Renders based on props after mounting; fires `afterClose` upon dismissal +- **Interaction and Animation** + - Controlled by Ant Design's built-in animation and transitions +- **Example path** + - [docs/components/antd/alert/README.md:1-8](file://docs/components/antd/alert/README.md#L1-L8) + +Section sources + +- [frontend/antd/alert/alert.tsx:7-43](file://frontend/antd/alert/alert.tsx#L7-L43) + +### Drawer + +- **Key Capabilities** + - Supports slots: `title`, `footer`, `extra`, `closeIcon`, `closable.closeIcon`, `drawerRender` + - `afterOpenChange`, `getContainer`, `drawerRender` are handled via `useFunction`/`renderParamsSlot` +- **Lifecycle** + - Fires `afterOpenChange` when open/close state changes +- **Interaction and Animation** + - Ant Design drawer slide-in/slide-out animation +- **Example path** + - [docs/components/antd/drawer/README.md:1-9](file://docs/components/antd/drawer/README.md#L1-L9) + +Section sources + +- [frontend/antd/drawer/drawer.tsx:8-57](file://frontend/antd/drawer/drawer.tsx#L8-L57) + +### Message + +- **Key Capabilities** + - Obtains the API via `message.useMessage` + - Supports `visible` to control show/hide, with `onVisible` callback + - `content` and `icon` slots support customization + - `getContainer` is handled functionally +- **Lifecycle** + - Opens when `visible=true`; destroys when `visible=false` or on unmount +- **Async and Events** + - `onClose` simultaneously triggers `onVisible(false)` and the original `onClose` +- **Example path** + - Refer to demo examples in each component's README + +Section sources + +- [frontend/antd/message/message.tsx:9-76](file://frontend/antd/message/message.tsx#L9-L76) + +### Modal + +- **Key Capabilities** + - Supports `okText`, `okButtonProps.icon`, `cancelText`, `cancelButtonProps.icon`, `footer`, `title`, `modalRender`, `closable.closeIcon`, `closeIcon`, etc. + - `afterOpenChange`, `afterClose`, `getContainer`, `footer`, `modalRender` are handled via `useFunction`/`renderParamsSlot` +- **Lifecycle** + - Fires `afterOpenChange`/`afterClose` when open/close state changes +- **Interaction and Animation** + - Ant Design dialog open/close animation and overlay behavior + +Section sources + +- [frontend/antd/modal/modal.tsx:8-104](file://frontend/antd/modal/modal.tsx#L8-L104) + +### Notification + +- **Key Capabilities** + - Obtains the API via `notification.useNotification` + - Supports `visible` to control show/hide, with `onVisible` callback + - Supports slots: `btn`, `actions`, `closeIcon`, `description`, `icon`, `message` + - Position parameters: `top`, `bottom`, `rtl`, `stack` +- **Lifecycle** + - Opens when `visible=true`; destroys when `visible=false` or on unmount +- **Async and Events** + - `onClose` simultaneously triggers `onVisible(false)` and the original `onClose` + +Section sources + +- [frontend/antd/notification/notification.tsx:8-103](file://frontend/antd/notification/notification.tsx#L8-L103) + +### Popconfirm + +- **Key Capabilities** + - Supports `okText`, `okButtonProps.icon`, `cancelText`, `cancelButtonProps.icon`, `title`, `description` + - `afterOpenChange`, `getPopupContainer` are handled via `useFunction` +- **Lifecycle** + - Fires `afterOpenChange` when the popup opens/closes +- **Interaction and Animation** + - Ant Design bubble confirmation popup behavior + +Section sources + +- [frontend/antd/popconfirm/popconfirm.tsx:7-62](file://frontend/antd/popconfirm/popconfirm.tsx#L7-L62) + +### Progress + +- **Key Capabilities** + - Supports `format` and `rounding` function handling +- **Performance and Complexity** + - Pure display component with no complex computation + +Section sources + +- [frontend/antd/progress/progress.tsx:5-21](file://frontend/antd/progress/progress.tsx#L5-L21) + +### Result + +- **Key Capabilities** + - Supports slots: `title`, `subTitle`, `icon`, `extra` + - Uses `useTargets` to manage child node rendering strategy +- **Lifecycle** + - Renders child nodes when slots are present; hides default children otherwise + +Section sources + +- [frontend/antd/result/result.tsx:7-30](file://frontend/antd/result/result.tsx#L7-L30) + +### Skeleton + +- **Key Capabilities** + - Directly wraps Ant Design Skeleton +- **Usage Recommendations** + - Use as a placeholder display before data loads + +Section sources + +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) + +### Spin + +- **Key Capabilities** + - Supports `tip` and `indicator` slots + - Uses `useTargets` to control child node visibility +- **Lifecycle** + - Shows children when no slots are present; hides children and delegates rendering to Spin when slots exist + +Section sources + +- [frontend/antd/spin/spin.tsx:7-35](file://frontend/antd/spin/spin.tsx#L7-L35) + +### Watermark + +- **Key Capabilities** + - Directly wraps Ant Design Watermark +- **Usage Recommendations** + - Use for content protection and copyright marking + +Section sources + +- [frontend/antd/watermark/watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) + +## Dependency Analysis + +- **Unified Export** + - Backend modules centrally export each component for unified import and alias management on the application side +- **Inter-component Coupling** + - Components are relatively independent; collaboration primarily occurs through the Ant Design ecosystem and common utility hooks + +```mermaid +graph LR +Init["__init__.py"] --> Comp["components.py"] +Init --> |exports| C1["Alert"] +Init --> |exports| C2["Drawer"] +Init --> |exports| C3["Message"] +Init --> |exports| C4["Modal"] +Init --> |exports| C5["Notification"] +Init --> |exports| C6["Popconfirm"] +Init --> |exports| C7["Progress"] +Init --> |exports| C8["Result"] +Init --> |exports| C9["Skeleton"] +Init --> |exports| C10["Spin"] +Init --> |exports| C11["Watermark"] +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +Section sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +## Performance Considerations + +- **Slot and Function Conversion** + - Use `useFunction` to bridge callback functions to the React environment, avoiding re-renders caused by redundant function creation +- **Conditional Rendering** + - Result/Spin precisely control child node rendering via `useTargets`, reducing unnecessary DOM structures +- **Destroy and Cleanup** + - Message/Notification actively `destroy` on unmount or when `visible=false`, preventing memory leaks and duplicate notifications + +## Troubleshooting Guide + +- **Slot Not Working** + - Confirm that the slot name matches the component definition (e.g., `closable.closeIcon`, `okButtonProps.icon`, etc.) +- **Callback Not Firing** + - Check that callbacks are wrapped via `useFunction`; ensure the function signature matches what Ant Design expects +- **Container Mounting Issues** + - `getContainer` supports string selectors or functions; if a string is passed, it is internally converted to a function +- **Notification/Message Not Dismissing** + - Ensure `destroy` is triggered when `visible=false` or the component unmounts; inspect the `onClose` callback chain + +Section sources + +- [frontend/antd/alert/alert.tsx:12-43](file://frontend/antd/alert/alert.tsx#L12-L43) +- [frontend/antd/drawer/drawer.tsx:24-57](file://frontend/antd/drawer/drawer.tsx#L24-L57) +- [frontend/antd/message/message.tsx:35-68](file://frontend/antd/message/message.tsx#L35-L68) +- [frontend/antd/notification/notification.tsx:38-95](file://frontend/antd/notification/notification.tsx#L38-L95) + +## Conclusion + +ModelScope Studio's feedback components achieve flexible extension of Ant Design components and a consistent usage experience through unified Svelte wrappers and utility hooks. Developers can quickly customize interaction and visual presentation via slots and functional callbacks, while simplified module management is enabled by unified backend exports. It is recommended to make appropriate use of each feedback component in real-world scenarios, combining loading strategies, visibility control, and accessibility requirements to enhance the user experience. + +## Appendix + +- **Examples and Demos** + - Refer to the demo examples in each component's README for a quick start: + - [docs/components/antd/alert/README.md:1-8](file://docs/components/antd/alert/README.md#L1-L8) + - [docs/components/antd/drawer/README.md:1-9](file://docs/components/antd/drawer/README.md#L1-L9) diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/General Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/General Components API.md new file mode 100644 index 00000000..4a649ac1 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/General Components API.md @@ -0,0 +1,442 @@ +# General Components API + + +**Files referenced in this document** +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [frontend/antd/float-button/float-button.tsx](file://frontend/antd/float-button/float-button.tsx) +- [frontend/antd/float-button/Index.svelte](file://frontend/antd/float-button/Index.svelte) +- [frontend/antd/icon/icon.tsx](file://frontend/antd/icon/icon.tsx) +- [frontend/antd/icon/Index.svelte](file://frontend/antd/icon/Index.svelte) +- [frontend/antd/typography/typography.base.tsx](file://frontend/antd/typography/typography.base.tsx) +- [frontend/antd/typography/Base.svelte](file://frontend/antd/typography/Base.svelte) +- [frontend/antd/typography/title/Index.svelte](file://frontend/antd/typography/title/Index.svelte) +- [frontend/antd/typography/paragraph/Index.svelte](file://frontend/antd/typography/paragraph/Index.svelte) +- [frontend/antd/typography/text/Index.svelte](file://frontend/antd/typography/text/Index.svelte) +- [frontend/antd/typography/link/Index.svelte](file://frontend/antd/typography/link/Index.svelte) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for general Ant Design-based components in ModelScope Studio, covering Button, FloatButton, Icon, and Typography. It includes: + +- Property definitions and event handling +- Slots and style customization +- Use cases and best practices +- TypeScript types and their correspondence to native Ant Design +- Responsive design, accessibility, and performance optimization recommendations + +## Project Structure + +These components follow a unified "Svelte entry + React wrapper" pattern: the Svelte entry handles prop forwarding, class name composition, and visibility control; the React wrapper interfaces with Ant Design components to implement slot rendering and complex interactions. + +```mermaid +graph TB +subgraph "Button" +B_Index["button/Index.svelte"] +B_Impl["button/button.tsx"] +end +subgraph "FloatButton" +F_Index["float-button/Index.svelte"] +F_Impl["float-button/float-button.tsx"] +end +subgraph "Icon" +I_Index["icon/Index.svelte"] +I_Impl["icon/icon.tsx"] +end +subgraph "Typography" +T_Base["typography/Base.svelte"] +T_Impl["typography/typography.base.tsx"] +T_Title["typography/title/Index.svelte"] +T_Para["typography/paragraph/Index.svelte"] +T_Text["typography/text/Index.svelte"] +T_Link["typography/link/Index.svelte"] +end +B_Index --> B_Impl +F_Index --> F_Impl +I_Index --> I_Impl +T_Title --> T_Base --> T_Impl +T_Para --> T_Base +T_Text --> T_Base +T_Link --> T_Base +``` + +Diagram sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/float-button/Index.svelte:1-70](file://frontend/antd/float-button/Index.svelte#L1-L70) +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) +- [frontend/antd/icon/icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [frontend/antd/typography/Base.svelte:1-85](file://frontend/antd/typography/Base.svelte#L1-L85) +- [frontend/antd/typography/typography.base.tsx:1-170](file://frontend/antd/typography/typography.base.tsx#L1-L170) +- [frontend/antd/typography/title/Index.svelte:1-12](file://frontend/antd/typography/title/Index.svelte#L1-L12) +- [frontend/antd/typography/paragraph/Index.svelte:1-12](file://frontend/antd/typography/paragraph/Index.svelte#L1-L12) +- [frontend/antd/typography/text/Index.svelte:1-12](file://frontend/antd/typography/text/Index.svelte#L1-L12) +- [frontend/antd/typography/link/Index.svelte:1-12](file://frontend/antd/typography/link/Index.svelte#L1-L12) + +Section sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/float-button/Index.svelte:1-70](file://frontend/antd/float-button/Index.svelte#L1-L70) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) +- [frontend/antd/typography/Base.svelte:1-85](file://frontend/antd/typography/Base.svelte#L1-L85) + +## Core Components + +- **Button**: Aligned with Ant Design Button; supports `icon` and `loading.icon` slots, with priority logic between `value` and child nodes. +- **FloatButton**: Aligned with Ant Design FloatButton; supports `icon`, `description`, `tooltip`, `tooltip.title`, and `badge.count` slots, with function bridging for tooltip configuration. +- **Icon**: Supports built-in Ant Design icon name mapping and IconFont; supports a custom `component` slot. +- **Typography**: A unified typography base supporting `title`, `paragraph`, `text`, and `link` variants, with slot-based configuration for `copyable`, `editable`, and `ellipsis`. + +Section sources + +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/icon/icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [frontend/antd/typography/typography.base.tsx:1-170](file://frontend/antd/typography/typography.base.tsx#L1-L170) + +## Architecture Overview + +All components are unified through the Svelte entry, which handles: + +- Prop forwarding and extra prop merging +- Visibility control and class name composition +- Slot context injection +- Lazy loading and async component rendering + +The React wrapper layer handles: + +- Interfacing with Ant Design components +- Mapping slots to ReactSlot +- Conditional rendering and function bridging for complex configuration objects (e.g., `tooltip`, `ellipsis`) + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Entry (Index.svelte)" +participant Loader as "importComponent" +participant ReactImpl as "React Wrapper (button.tsx/float-button.tsx/icon.tsx/typography.base.tsx)" +participant AntD as "Ant Design Component" +Svelte->>Loader : Dynamically imports component module +Loader-->>Svelte : Returns renderable component +Svelte->>ReactImpl : Passes props + slots + value +ReactImpl->>AntD : Renders and injects slots/config +AntD-->>ReactImpl : Render result +ReactImpl-->>Svelte : Render result +``` + +Diagram sources + +- [frontend/antd/button/Index.svelte:10-73](file://frontend/antd/button/Index.svelte#L10-L73) +- [frontend/antd/button/button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) +- [frontend/antd/float-button/Index.svelte:10-69](file://frontend/antd/float-button/Index.svelte#L10-L69) +- [frontend/antd/float-button/float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) +- [frontend/antd/icon/Index.svelte:10-66](file://frontend/antd/icon/Index.svelte#L10-L66) +- [frontend/antd/icon/icon.tsx:12-52](file://frontend/antd/icon/icon.tsx#L12-L52) +- [frontend/antd/typography/Base.svelte:11-83](file://frontend/antd/typography/Base.svelte#L11-L83) +- [frontend/antd/typography/typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) + +## Component Details + +### Button + +- **Capability Overview** + - Supports all Ant Design Button props and events + - Slots: `icon`, `loading.icon` + - Content priority: renders child nodes when present, otherwise falls back to `value` +- **Key Behaviors** + - Injects `slots.icon` into Ant Design Button's `icon` + - Injects `slots.loading.icon` into `loading.icon`, preserving `loading.delay` if `loading` is an object +- **Use Cases** + - Basic buttons, buttons with icons, loading buttons +- **Examples (paths)** + - Basic usage: [frontend/antd/button/Index.svelte:59-73](file://frontend/antd/button/Index.svelte#L59-L73) + - Slot icons: [frontend/antd/button/button.tsx:18-30](file://frontend/antd/button/button.tsx#L18-L30) +- **Types and Native Correspondence** + - Wraps Ant Design Button's `GetProps` type via `sveltify`, maintaining a consistent prop signature +- **Styles and Accessibility** + - Controlled via `elem_classes`/`elem_id`/`elem_style`; accessibility provided by Ant Design +- **Performance** + - Child node detection with conditional rendering avoids unnecessary DOM updates + +```mermaid +flowchart TD +Start(["Enter Button Render"]) --> HasChildren{"Does child node exist?"} +HasChildren --> |Yes| RenderChild["Render child node"] +HasChildren --> |No| RenderValue["Render value"] +RenderChild --> InjectIcon["Inject slots.icon into AntD Button"] +RenderValue --> InjectIcon +InjectIcon --> LoadingCfg{"Is loading.icon configured?"} +LoadingCfg --> |Yes| MergeLoading["Merge loading with loading.icon.delay"] +LoadingCfg --> |No| PassThrough["Pass through loading directly"] +MergeLoading --> End(["Done"]) +PassThrough --> End +``` + +Diagram sources + +- [frontend/antd/button/button.tsx:11-36](file://frontend/antd/button/button.tsx#L11-L36) + +Section sources + +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + +### FloatButton + +- **Capability Overview** + - Supports all Ant Design FloatButton props and events + - Slots: `icon`, `description`, `tooltip`, `tooltip.title`, `badge.count` + - `tooltip` supports object configuration; internally bridges `afterOpenChange`, `getPopupContainer`, and other functions via `useFunction` +- **Key Behaviors** + - Enables tooltip configuration when `slots.tooltip` exists or `tooltip` is an object + - Maps `slots.icon`/`description`/`badge.count` to their corresponding props +- **Use Cases** + - Back-to-top, floating action panels, floating entry points with description and badge +- **Examples (paths)** + - Basic usage: [frontend/antd/float-button/Index.svelte:56-69](file://frontend/antd/float-button/Index.svelte#L56-L69) + - Slots and tooltip configuration: [frontend/antd/float-button/float-button.tsx:19-72](file://frontend/antd/float-button/float-button.tsx#L19-L72) +- **Types and Native Correspondence** + - Wraps Ant Design FloatButton's `GetProps` type via `sveltify`, with an additional `id` field +- **Styles and Accessibility** + - Controlled via `elem_classes`/`elem_id`/`elem_style`; accessibility provided by Ant Design +- **Performance** + - Conditional rendering of tooltip and slots reduces unnecessary overhead + +```mermaid +sequenceDiagram +participant S as "Svelte Entry" +participant R as "React Wrapper" +participant T as "tooltip config" +participant A as "AntD FloatButton" +S->>R : Passes props + slots +R->>T : Checks if tooltip is an object or slots.tooltip.title exists +alt Tooltip enabled +T-->>R : Merges config and bridges functions +else Not enabled +T-->>R : Passes through tooltip directly +end +R->>A : Renders and injects icon/description/badge/count +A-->>R : Render result +``` + +Diagram sources + +- [frontend/antd/float-button/float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) +- [frontend/antd/float-button/Index.svelte:1-70](file://frontend/antd/float-button/Index.svelte#L1-L70) + +Section sources + +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/float-button/Index.svelte:1-70](file://frontend/antd/float-button/Index.svelte#L1-L70) + +### Icon + +- **Capability Overview** + - Supports Ant Design built-in icon name mapping + - Supports font icons provided by `IconFontProvider` + - Slot: `component` (for custom SVG components) +- **Key Behaviors** + - If `slots.component` is provided, renders the custom component with Ant Design `IconWrapper` + - Otherwise, looks up the built-in icon by `value` or uses `IconFont.type` +- **Use Cases** + - Inline text icons, button icons, custom vector icons +- **Examples (paths)** + - Basic usage: [frontend/antd/icon/Index.svelte:52-66](file://frontend/antd/icon/Index.svelte#L52-L66) + - Custom component and IconFont: [frontend/antd/icon/icon.tsx:12-52](file://frontend/antd/icon/icon.tsx#L12-L52) +- **Types and Native Correspondence** + - Wraps Ant Design Icons' `GetProps` type via `sveltify`, with an additional `value` field +- **Styles and Accessibility** + - Controlled via `elem_classes`/`elem_id`/`elem_style`; accessibility provided by Ant Design +- **Performance** + - `useMemo` caches custom components to avoid redundant creation + +```mermaid +flowchart TD +Start(["Enter Icon Render"]) --> HasCustom{"Does slots.component exist?"} +HasCustom --> |Yes| WrapCustom["Wrap custom component with Ant Design IconWrapper"] +HasCustom --> |No| LookupIcon{"Is value a built-in icon name?"} +LookupIcon --> |Yes| RenderBuiltin["Render built-in icon"] +LookupIcon --> |No| UseIconFont{"Does IconFont context exist?"} +UseIconFont --> |Yes| RenderIconFont["Use IconFont(type=value)"] +UseIconFont --> |No| Noop["Not rendered"] +WrapCustom --> End(["Done"]) +RenderBuiltin --> End +RenderIconFont --> End +Noop --> End +``` + +Diagram sources + +- [frontend/antd/icon/icon.tsx:12-52](file://frontend/antd/icon/icon.tsx#L12-L52) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) + +Section sources + +- [frontend/antd/icon/icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) + +### Typography + +- **Capability Overview** + - Unified base: four variants — `title`, `paragraph`, `text`, `link` + - Supports slot-based configuration for `copyable`, `editable`, and `ellipsis` + - Slots: `copyable.icon`, `copyable.tooltips`, `editable.icon`, `editable.tooltip`, `editable.enterIcon`, `ellipsis.symbol`, `ellipsis.tooltip`, `ellipsis.tooltip.title` +- **Key Behaviors** + - Selects the corresponding Ant Design Typography component based on `component` + - Conditionally injects `copyable`, `editable`, and `ellipsis` configuration + - `ellipsis` enablement conditions differ for the `link` component +- **Use Cases** + - Unified typography and interaction for headings, paragraphs, text, and links +- **Examples (paths)** + - Basic usage: [frontend/antd/typography/Base.svelte:65-84](file://frontend/antd/typography/Base.svelte#L65-L84) + - Sub-component aliases: [frontend/antd/typography/title/Index.svelte:9-11](file://frontend/antd/typography/title/Index.svelte#L9-L11) + - Slot and config merging: [frontend/antd/typography/typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) +- **Types and Native Correspondence** + - Wraps multiple Ant Design Typography types via `sveltify`, with additional `component` and `value` fields +- **Styles and Accessibility** + - Controlled via `elem_classes`/`elem_id`/`elem_style`; accessibility provided by Ant Design +- **Performance** + - Conditional rendering with slot target collection reduces unnecessary overhead + +```mermaid +sequenceDiagram +participant S as "Base.svelte" +participant R as "typography.base.tsx" +participant T as "Typography Component" +participant C as "copyable/editable/ellipsis" +S->>R : Passes component/value + slots +R->>R : Parses copyable/editable/ellipsis config +alt Capability supported +R->>C : Injects slots.icon/tooltip/symbol/... and merges config +else Not supported +R->>C : No injection, keeps undefined +end +R->>T : Renders corresponding Typography component +T-->>R : Render result +``` + +Diagram sources + +- [frontend/antd/typography/Base.svelte:11-83](file://frontend/antd/typography/Base.svelte#L11-L83) +- [frontend/antd/typography/typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) + +Section sources + +- [frontend/antd/typography/typography.base.tsx:1-170](file://frontend/antd/typography/typography.base.tsx#L1-L170) +- [frontend/antd/typography/Base.svelte:1-85](file://frontend/antd/typography/Base.svelte#L1-L85) +- [frontend/antd/typography/title/Index.svelte:1-12](file://frontend/antd/typography/title/Index.svelte#L1-L12) +- [frontend/antd/typography/paragraph/Index.svelte:1-12](file://frontend/antd/typography/paragraph/Index.svelte#L1-L12) +- [frontend/antd/typography/text/Index.svelte:1-12](file://frontend/antd/typography/text/Index.svelte#L1-L12) +- [frontend/antd/typography/link/Index.svelte:1-12](file://frontend/antd/typography/link/Index.svelte#L1-L12) + +## Dependency Analysis + +- **Inter-component Coupling** + - The four Typography sub-components are merely aliases for Base, reducing duplication and coupling + - Button/FloatButton/Icon separate entry from implementation for ease of maintenance and extension +- **External Dependencies** + - Ant Design component library (Button, FloatButton, Typography, Icon, etc.) + - `@svelte-preprocess-react` (sveltify, ReactSlot, useFunction, etc.) + - Utility functions: `useTargets`, `useSlotsChildren`, `omitUndefinedProps`, `renderParamsSlot`, etc. +- **Potential Circular Dependencies** + - No direct circular dependencies found; all components follow a unidirectional dependency: entry → implementation → Ant Design + +```mermaid +graph LR +S_Button["button/Index.svelte"] --> R_Button["button/button.tsx"] +S_Float["float-button/Index.svelte"] --> R_Float["float-button/float-button.tsx"] +S_Icon["icon/Index.svelte"] --> R_Icon["icon/icon.tsx"] +S_TBase["typography/Base.svelte"] --> R_TBase["typography/typography.base.tsx"] +R_TBase --> AntD["Ant Design Components"] +R_Button --> AntD +R_Float --> AntD +R_Icon --> AntD +``` + +Diagram sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/float-button/Index.svelte:1-70](file://frontend/antd/float-button/Index.svelte#L1-L70) +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) +- [frontend/antd/icon/icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [frontend/antd/typography/Base.svelte:1-85](file://frontend/antd/typography/Base.svelte#L1-L85) +- [frontend/antd/typography/typography.base.tsx:1-170](file://frontend/antd/typography/typography.base.tsx#L1-L170) + +Section sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/float-button/Index.svelte:1-70](file://frontend/antd/float-button/Index.svelte#L1-L70) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) +- [frontend/antd/typography/Base.svelte:1-85](file://frontend/antd/typography/Base.svelte#L1-L85) + +## Performance Considerations + +- **On-demand Rendering** + - Conditional checks and slot detection inject configuration and slots only when needed, reducing rendering cost +- **Function Bridging** + - Callbacks in configurations like `tooltip` are bridged via `useFunction`, avoiding new function creation on every render +- **Computed Caching** + - `Icon` uses `useMemo` to cache custom components, avoiding redundant creation +- **Async Loading** + - Lazy loading via `importComponent` reduces initial page load pressure + +## Troubleshooting Guide + +- **Slot Not Working** + - Verify that the slot name matches the component's supported list (e.g., Button: `icon`, `loading.icon`; FloatButton: `icon`/`description`/`tooltip`/`badge.count`; Typography: `copyable.*`, `editable.*`, `ellipsis.*`) +- **Tooltip Callback Not Working** + - When `tooltip` is an object, ensure related callbacks have been bridged via `useFunction` +- **Custom Icon Not Displayed** + - Ensure `value` is a valid icon name or that the IconFont context is available +- **`ellipsis` Not Working on `link`** + - Ensure `ellipsis` configuration is present or the slot has been provided +- **Visibility Issues** + - Ensure the `visible` prop is correctly passed to the entry component + +Section sources + +- [frontend/antd/button/button.tsx:11-36](file://frontend/antd/button/button.tsx#L11-L36) +- [frontend/antd/float-button/float-button.tsx:19-72](file://frontend/antd/float-button/float-button.tsx#L19-L72) +- [frontend/antd/icon/icon.tsx:12-52](file://frontend/antd/icon/icon.tsx#L12-L52) +- [frontend/antd/typography/typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) +- [frontend/antd/button/Index.svelte:59-73](file://frontend/antd/button/Index.svelte#L59-L73) +- [frontend/antd/float-button/Index.svelte:56-69](file://frontend/antd/float-button/Index.svelte#L56-L69) +- [frontend/antd/icon/Index.svelte:52-66](file://frontend/antd/icon/Index.svelte#L52-L66) +- [frontend/antd/typography/Base.svelte:65-84](file://frontend/antd/typography/Base.svelte#L65-L84) + +## Conclusion + +The above components implement deep alignment with and flexible extension of Ant Design through a unified Svelte + React wrapper pattern. Using the slot system and utility functions, developers can achieve rich interaction and style customization while maintaining type safety. It is recommended to follow the prop and slot conventions documented here, combined with the performance and accessibility recommendations, to achieve a more stable and maintainable user experience. + +## Appendix + +- **Props and Slots Summary** + - **Button** + - Props: inherits all Ant Design Button props + - Slots: `icon`, `loading.icon` + - **FloatButton** + - Props: inherits all Ant Design FloatButton props + - Slots: `icon`, `description`, `tooltip`, `tooltip.title`, `badge.count` + - **Icon** + - Props: `value` (string), inherits all Ant Design Icon props + - Slots: `component` (custom SVG component) + - **Typography** + - Props: `component` (`'title'|'paragraph'|'text'|'link'`), `value` (string) + - Slots: `copyable.icon`, `copyable.tooltips`; `editable.icon`, `editable.tooltip`, `editable.enterIcon`; `ellipsis.symbol`, `ellipsis.tooltip`, `ellipsis.tooltip.title` diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Layout Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Layout Components API.md new file mode 100644 index 00000000..83606490 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Layout Components API.md @@ -0,0 +1,398 @@ +# Layout Components API + + +**Files referenced in this document** +- [divider.tsx](file://frontend/antd/divider/divider.tsx) +- [flex.tsx](file://frontend/antd/flex/flex.tsx) +- [grid/context.ts](file://frontend/antd/grid/context.ts) +- [grid/row/row.tsx](file://frontend/antd/grid/row/row.tsx) +- [grid/col/col.tsx](file://frontend/antd/grid/col/col.tsx) +- [layout/layout.base.tsx](file://frontend/antd/layout/layout.base.tsx) +- [layout/Base.svelte](file://frontend/antd/layout/Base.svelte) +- [layout.sider/layout.sider.tsx](file://frontend/antd/layout/sider/layout.sider.tsx) +- [space/space.tsx](file://frontend/antd/space/space.tsx) +- [splitter/splitter.tsx](file://frontend/antd/splitter/splitter.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for Ant Design-based layout components in ModelScope Studio, covering Divider, Flex, Grid (Row/Col), Layout (Header/Footer/Sider/Content), Space, and Splitter. It includes: + +- Property definitions and type sources for each component +- Layout algorithms and nesting rules +- Responsive behavior and key points of size calculation +- Correspondence with CSS Grid/Flexbox +- Standard usage paths and best practices +- Performance optimization and mobile adaptation recommendations + +## Project Structure + +These layout components expose Ant Design's React components as Svelte components through a unified Svelte preprocessing bridge. The core patterns are: + +- Using `sveltify` to wrap Ant Design components as Svelte components +- Collecting and rendering child items via context and Slot mechanisms +- Dynamically selecting specific Ant Design sub-components (e.g., Header/Footer/Content/Layout) via a Base component as needed + +```mermaid +graph TB +subgraph "Antd Wrapper Layer" +D["Divider
divider.tsx"] +F["Flex
flex.tsx"] +G["Grid.Row/Col
row.tsx / col.tsx"] +L["Layout.Base
layout.base.tsx"] +S["Space
space.tsx"] +SP["Splitter
splitter.tsx"] +end +subgraph "Context and Slots" +Ctx["Grid Context
grid/context.ts"] +Slots["ReactSlot / useTargets
Space Rendering"] +end +D --> |"sveltify"| AntD_D["antd.Divider"] +F --> |"sveltify"| AntD_F["antd.Flex"] +G --> |"useItems context"| Ctx +G --> |"ReactSlot"| Slots +L --> |"Dynamic component selection"| AntD_L["antd.Layout.*"] +S --> |"ReactSlot / useTargets"| Slots +SP --> |"withItemsContextProvider"| Ctx +SP --> |"ReactSlot"| Slots +``` + +Diagram sources + +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) +- [flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) +- [grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [space/space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter/splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) + +Section sources + +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) +- [flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) +- [grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [space/space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter/splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) + +## Core Components + +- **Divider**: A dividing line supporting child nodes as custom content or empty content. +- **Flex**: A flexbox layout container that forwards all Ant Design Flex props. +- **Grid**: A Row/Col combination implementing a grid system; Col registers itself to Row via context. +- **Layout**: The Base component dynamically maps to Header/Footer/Content/Layout based on the `component` prop. +- **Space**: Enhances slot rendering and separator slots on top of Ant Design Space. +- **Splitter**: A split-panel container that collects Panel children via context and renders them. + +Section sources + +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) +- [flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) +- [grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [space/space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter/splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) + +## Architecture Overview + +The following diagram shows how layout components organize child items through context and Slot mechanisms, ultimately rendering as an Ant Design component tree. + +```mermaid +sequenceDiagram +participant App as "Application" +participant Row as "Grid.Row
row.tsx" +participant Ctx as "Grid Context
context.ts" +participant Col as "Grid.Col
col.tsx" +participant Base as "Layout.Base
layout.base.tsx" +App->>Row : Renders Row and provides children +Row->>Ctx : withItemsContextProvider registers default list +Col->>Ctx : ItemHandler registers column item +Row->>Row : useItems retrieves default list +Row->>App : Renders ARow + ACol*ReactSlot rendering +App->>Base : Renders Base and specifies component +Base->>Base : Selects ALayout.Header/Footer/Content/Layout based on component +Base-->>App : Returns Ant Design component +``` + +Diagram sources + +- [grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) +- [layout/layout.base.tsx:13-37](file://frontend/antd/layout/layout.base.tsx#L13-L37) + +## Component Details + +### Divider + +- **Function**: Provides horizontal or vertical dividing lines, with optional custom child nodes (e.g., icons, text). +- **Key Points**: + - When child nodes are present, they are passed to Ant Design Divider; otherwise, an empty divider is rendered. + - Types come from Ant Design Divider Props. +- **Typical usage path** + - [divider.tsx:5-12](file://frontend/antd/divider/divider.tsx#L5-L12) + +Section sources + +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) + +### Flex + +- **Function**: An Ant Design Flex container supporting main-axis/cross-axis alignment, wrapping, and other layout props. +- **Key Points**: + - Directly forwards all Ant Design Flex Props. + - Suitable for complex flexbox layout scenarios. +- **Typical usage path** + - [flex.tsx:4-8](file://frontend/antd/flex/flex.tsx#L4-L8) + +Section sources + +- [flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) + +### Grid + +- **Row/Col Combination** + - **Row**: Collects Col children via context, renders as Ant Design Row, and renders Col content via Slot. + - **Col**: Registers itself into Row's context via `ItemHandler`. +- **Context** + - Provides `withItemsContextProvider`, `useItems`, and `ItemHandler` for collecting and distributing child items. +- **Responsive and Nesting** + - Supports responsive breakpoint props (controlled by Ant Design Row/Col Props); Col can be nested within Row. +- **Typical usage paths** + - [grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) + - [grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) + - [grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) + +```mermaid +classDiagram +class GridContext { ++withItemsContextProvider(slots) ++useItems() ++ItemHandler +} +class Row { ++props : RowProps ++children : Col* ++render() : ARow + ACol* +} +class Col { ++props : ColProps ++register() : ItemHandler +} +Row --> GridContext : "Registers/consumes default list" +Col --> GridContext : "Registers into default list" +``` + +Diagram sources + +- [grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) +- [grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) + +Section sources + +- [grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) + +### Layout + +- **Base Component** + - Dynamically maps to Header/Footer/Content/Layout based on the `component` prop. + - Supports extra class names and style forwarding. +- **Sider Sub-component** + - Exported via a separate file; used with Layout to implement sidebars. +- **Typical usage paths** + - [layout/layout.base.tsx:13-37](file://frontend/antd/layout/layout.base.tsx#L13-L37) + - [layout/Base.svelte:53-67](file://frontend/antd/layout/Base.svelte#L53-L67) + - [layout.sider/layout.sider.tsx](file://frontend/antd/layout/sider/layout.sider.tsx) + +```mermaid +sequenceDiagram +participant Svelte as "Base.svelte" +participant Base as "layout.base.tsx" +participant AD as "antd.Layout.*" +Svelte->>Base : Passes component and props +Base->>Base : Selects Header/Footer/Content/Layout based on component +Base->>AD : Renders corresponding component and forwards props +AD-->>Svelte : Returns DOM +``` + +Diagram sources + +- [layout/Base.svelte:53-67](file://frontend/antd/layout/Base.svelte#L53-L67) +- [layout/layout.base.tsx:13-37](file://frontend/antd/layout/layout.base.tsx#L13-L37) + +Section sources + +- [layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [layout.sider/layout.sider.tsx](file://frontend/antd/layout/sider/layout.sider.tsx) + +### Space + +- **Function**: Inserts spacing between elements, supporting a custom separator slot. +- **Key Points**: + - Uses `useTargets` to parse children, hides the real DOM, and renders via Ant Design Space. + - Supports a `split` slot for custom separators. +- **Typical usage path** + - [space/space.tsx:7-26](file://frontend/antd/space/space.tsx#L7-L26) + +```mermaid +flowchart TD +Start(["Start"]) --> Parse["Parse children into target list"] +Parse --> Hide["Hide real DOM"] +Hide --> Render["Render Ant Design Space"] +Render --> Split{"Is split slot provided?"} +Split --> |Yes| UseSplit["Use split slot"] +Split --> |No| UseProp["Use props.split"] +UseSplit --> Done(["Done"]) +UseProp --> Done +``` + +Diagram sources + +- [space/space.tsx:8-26](file://frontend/antd/space/space.tsx#L8-L26) + +Section sources + +- [space/space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) + +### Splitter + +- **Function**: Splits an area into multiple panels with draggable size adjustment. +- **Key Points**: + - Collects Panel children from the default slot via `withItemsContextProvider`. + - Uses `ReactSlot` to render each Panel's content. +- **Typical usage path** + - [splitter/splitter.tsx:7-35](file://frontend/antd/splitter/splitter.tsx#L7-L35) + +```mermaid +sequenceDiagram +participant App as "Application" +participant Splitter as "Splitter
splitter.tsx" +participant Ctx as "Context
context.ts" +participant Panel as "Panel" +App->>Splitter : Renders Splitter and provides children +Splitter->>Ctx : withItemsContextProvider registers default panel list +Splitter->>Splitter : useItems retrieves default panels +Splitter->>Panel : Renders each Panel and injects content +Panel-->>App : Returns draggable panel +``` + +Diagram sources + +- [splitter/splitter.tsx:7-35](file://frontend/antd/splitter/splitter.tsx#L7-L35) +- [grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) + +Section sources + +- [splitter/splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) + +## Dependency Analysis + +- **Inter-component Coupling** + - Grid.Row/Col depends on Grid context for child item collection and distribution. + - Space/Splitter depends on the common Slot mechanism and target resolution utilities. + - Layout.Base implements multi-form layouts through dynamic component selection. +- **External Dependencies** + - Ant Design component library (Divider, Flex, Grid, Layout, Space, Splitter). + - Svelte preprocessing toolchain (sveltify, ReactSlot, useTargets). + - Style utilities (classnames) for conditional class name composition. + +```mermaid +graph LR +Row["Grid.Row"] --> Ctx["Grid Context"] +Col["Grid.Col"] --> Ctx +Space["Space"] --> Slot["ReactSlot / useTargets"] +Splitter["Splitter"] --> Ctx +Splitter --> Slot +LayoutBase["Layout.Base"] --> AD["antd.Layout.*"] +``` + +Diagram sources + +- [grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) +- [grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) +- [space/space.tsx:8-26](file://frontend/antd/space/space.tsx#L8-L26) +- [splitter/splitter.tsx:7-35](file://frontend/antd/splitter/splitter.tsx#L7-L35) +- [layout/layout.base.tsx:13-37](file://frontend/antd/layout/layout.base.tsx#L13-L37) + +Section sources + +- [grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [space/space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter/splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +## Performance Considerations + +- **Virtualization and Lazy Loading** + - For Grid/Space/Splitter with long lists or many children, prefer virtualization or pagination strategies to reduce upfront rendering overhead. +- **Slot Rendering Optimization** + - Space hides the real DOM and only renders Ant Design Space, avoiding redundant rendering and style jitter. +- **Conditional Rendering** + - Layout.Base dynamically selects components based on `component`, avoiding unnecessary DOM structure. +- **Responsive Breakpoints** + - Grid uses Ant Design breakpoint params; set responsive thresholds appropriately to avoid frequent reflows. +- **Mobile Adaptation** + - On small screens, prefer Flex or Space's compact mode to reduce overflow issues from fixed-width layouts. + - For Splitter on mobile, it is recommended to limit minimum panel size and disable dragging to improve interaction stability. + +## Troubleshooting Guide + +- **Grid Children Not Displayed** + - Check that Row correctly wraps Col and that Col has registered to the context via `ItemHandler`. + - Confirm that Row's children include Col and that Col's `el` is valid. +- **Space Separator Not Working** + - Confirm that the `split` slot or `props.split` has been provided, and that the slot content can be correctly rendered by ReactSlot. +- **Splitter Panel Empty** + - Confirm that Panel has been registered in the default slot and that Panel's `el` is valid. +- **Layout Style Abnormalities** + - Check that the `component` passed to the Base component matches expectations, and confirm that the class name composition logic has not been overridden. + +Section sources + +- [grid/row/row.tsx:12-29](file://frontend/antd/grid/row/row.tsx#L12-L29) +- [grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) +- [space/space.tsx:13-22](file://frontend/antd/space/space.tsx#L13-L22) +- [splitter/splitter.tsx:9-31](file://frontend/antd/splitter/splitter.tsx#L9-L31) +- [layout/layout.base.tsx:31-35](file://frontend/antd/layout/layout.base.tsx#L31-L35) + +## Conclusion + +ModelScope Studio's layout components present Ant Design's layout capabilities in a more ergonomic way through a unified Svelte preprocessing bridge. Grid, Layout, Space, Splitter, and other components maintain consistency with the Ant Design API while enhancing slot and context capabilities, making them suitable for composing and reusing complex layout scenarios. Following the property definitions, nesting rules, and performance recommendations in this document will deliver a stable and efficient layout experience on both desktop and mobile. + +## Appendix + +- **Correspondence with CSS Grid/Flexbox** + - Grid.Row/Col corresponds to row/column division in CSS Grid; Flex corresponds to CSS Flexbox. + - Space corresponds to flex gap distribution; Splitter corresponds to draggable area partitioning. +- **Common Layout Scenarios** + - **Grid system**: Row + Col combination, controlling column width and wrapping by breakpoint. + - **Flexbox layout**: Flex container with multiple children, controlling main-axis and cross-axis alignment. + - **Split panels**: Splitter with multiple Panels, supporting draggable size adjustment. + - **Page layout**: Layout.Base selecting Header/Footer/Content/Sider combinations as needed. diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Navigation Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Navigation Components API.md new file mode 100644 index 00000000..b66562ca --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Navigation Components API.md @@ -0,0 +1,462 @@ +# Navigation Components API + + +**Files referenced in this document** +- [frontend/antd/anchor/Index.svelte](file://frontend/antd/anchor/Index.svelte) +- [frontend/antd/anchor/anchor.tsx](file://frontend/antd/anchor/anchor.tsx) +- [frontend/antd/anchor/context.ts](file://frontend/antd/anchor/context.ts) +- [frontend/antd/breadcrumb/Index.svelte](file://frontend/antd/breadcrumb/Index.svelte) +- [frontend/antd/breadcrumb/breadcrumb.tsx](file://frontend/antd/breadcrumb/breadcrumb.tsx) +- [frontend/antd/breadcrumb/context.ts](file://frontend/antd/breadcrumb/context.ts) +- [frontend/antd/breadcrumb/item/Index.svelte](file://frontend/antd/breadcrumb/item/Index.svelte) +- [frontend/antd/dropdown/Index.svelte](file://frontend/antd/dropdown/Index.svelte) +- [frontend/antd/dropdown/dropdown.tsx](file://frontend/antd/dropdown/dropdown.tsx) +- [frontend/antd/menu/Index.svelte](file://frontend/antd/menu/Index.svelte) +- [frontend/antd/menu/menu.tsx](file://frontend/antd/menu/menu.tsx) +- [frontend/antd/menu/context.ts](file://frontend/antd/menu/context.ts) +- [frontend/antd/menu/item/Index.svelte](file://frontend/antd/menu/item/Index.svelte) +- [frontend/antd/pagination/Index.svelte](file://frontend/antd/pagination/Index.svelte) +- [frontend/antd/pagination/pagination.tsx](file://frontend/antd/pagination/pagination.tsx) +- [frontend/antd/steps/Index.svelte](file://frontend/antd/steps/Index.svelte) +- [frontend/antd/steps/steps.tsx](file://frontend/antd/steps/steps.tsx) +- [frontend/antd/steps/context.ts](file://frontend/antd/steps/context.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for Ant Design-based navigation components in ModelScope Studio, covering: Anchor, Breadcrumb, Dropdown, Menu, Pagination, and Steps. It provides a systematic overview of architecture design, data flow, processing logic, type definitions, event binding, routing integration, permission control, and dynamic loading, along with reusable usage patterns and best practices. + +## Project Structure + +Navigation components use a unified "Svelte wrapper layer + React component bridge" pattern on the frontend: + +- The Svelte layer handles prop forwarding, visibility control, style injection, slot rendering, and lazy loading. +- The React layer bridges native Ant Design components into the Svelte ecosystem via `sveltify`, while providing slot rendering, function hooks, and context injection capabilities. + +```mermaid +graph TB +subgraph "Svelte Wrapper Layer" +A_Index["anchor/Index.svelte"] +B_Index["breadcrumb/Index.svelte"] +C_Index["dropdown/Index.svelte"] +D_Index["menu/Index.svelte"] +E_Index["pagination/Index.svelte"] +F_Index["steps/Index.svelte"] +end +subgraph "React Bridge Layer" +A_Core["anchor.tsx"] +B_Core["breadcrumb.tsx"] +C_Core["dropdown.tsx"] +D_Core["menu.tsx"] +E_Core["pagination.tsx"] +F_Core["steps.tsx"] +end +A_Index --> A_Core +B_Index --> B_Core +C_Index --> C_Core +D_Index --> D_Core +E_Index --> E_Core +F_Index --> F_Core +``` + +Diagram sources + +- [frontend/antd/anchor/Index.svelte:1-66](file://frontend/antd/anchor/Index.svelte#L1-L66) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/dropdown/Index.svelte:1-70](file://frontend/antd/dropdown/Index.svelte#L1-L70) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/menu/Index.svelte:1-75](file://frontend/antd/menu/Index.svelte#L1-L75) +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/pagination/Index.svelte:1-68](file://frontend/antd/pagination/Index.svelte#L1-L68) +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) +- [frontend/antd/steps/Index.svelte:1-63](file://frontend/antd/steps/Index.svelte#L1-L63) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) + +Section sources + +- [frontend/antd/anchor/Index.svelte:1-66](file://frontend/antd/anchor/Index.svelte#L1-L66) +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/dropdown/Index.svelte:1-70](file://frontend/antd/dropdown/Index.svelte#L1-L70) +- [frontend/antd/menu/Index.svelte:1-75](file://frontend/antd/menu/Index.svelte#L1-L75) +- [frontend/antd/pagination/Index.svelte:1-68](file://frontend/antd/pagination/Index.svelte#L1-L68) +- [frontend/antd/steps/Index.svelte:1-63](file://frontend/antd/steps/Index.svelte#L1-L63) + +## Core Components + +This section provides an overview of the responsibilities and common characteristics of the six navigation components: + +- **Anchor**: In-page anchor navigation supporting container selection and current anchor callbacks. +- **Breadcrumb**: Displays the current page's position in the hierarchy; supports custom separators, item rendering, and dropdown icons. +- **Dropdown**: Wraps a trigger element and renders a dropdown menu; supports custom popup rendering and menu item injection. +- **Menu**: Side or top navigation menu; supports themes, expand icons, overflow indicators, and select/expand events. +- **Pagination**: Data pagination control; supports quick-jump buttons and custom page item rendering. +- **Steps**: Step flow indicator; supports step item lists and custom progress dot rendering. + +Section sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) + +## Architecture Overview + +Component bridging follows a unified pattern of "lazy loading + slot rendering + function hooks": + +- **Prop forwarding**: The wrapper layer forwards common props such as `visible`, `elem_id`, `elem_classes`, `elem_style`, `_internal`, and `as_item` to the React component. +- **Slot rendering**: Slot name mapping and parameterized rendering are supported via `ReactSlot` and `renderParamsSlot`. +- **Dynamic injection**: `items` lists are injected via `withItemsContextProvider`, supporting both default slots and explicit `items` params. +- **Event binding**: Events such as `onOpenChange`, `onSelect`, `onDeselect`, and `onChange` are ensured to be reactive through the `useFunction` hook. + +```mermaid +sequenceDiagram +participant S as "Svelte Wrapper Layer (Index.svelte)" +participant P as "Prop Processor (processProps)" +participant R as "React Component (sveltify)" +participant C as "Context/Slots (Items/Slots)" +S->>P : Parses component props and extra props +P-->>S : Returns normalized prop set +S->>R : Renders Antd component and passes props +R->>C : Reads items context and slots +C-->>R : Provides items list and slot functions +R-->>S : Fires event callbacks (onChange/onSelect, etc.) +S-->>S : Processes result via Gradio/routing callback +``` + +Diagram sources + +- [frontend/antd/anchor/Index.svelte:22-44](file://frontend/antd/anchor/Index.svelte#L22-L44) +- [frontend/antd/anchor/anchor.tsx:10-43](file://frontend/antd/anchor/anchor.tsx#L10-L43) +- [frontend/antd/breadcrumb/breadcrumb.tsx:15-63](file://frontend/antd/breadcrumb/breadcrumb.tsx#L15-L63) +- [frontend/antd/dropdown/dropdown.tsx:26-108](file://frontend/antd/dropdown/dropdown.tsx#L26-L108) +- [frontend/antd/menu/menu.tsx:18-92](file://frontend/antd/menu/menu.tsx#L18-L92) +- [frontend/antd/pagination/pagination.tsx:14-52](file://frontend/antd/pagination/pagination.tsx#L14-L52) +- [frontend/antd/steps/steps.tsx:16-49](file://frontend/antd/steps/steps.tsx#L16-L49) + +## Component Details + +### Anchor + +- **Responsibility**: Provides in-page anchor navigation; supports container selection and current anchor callbacks. +- **Key Props and Behaviors** + - Container selection: `getContainer` specifies the scroll container. + - Current anchor: `getCurrentAnchor` retrieves the currently active anchor. + - Items injection: `items` are injected via context, supporting default slot and explicit `items`. +- **Events and State** + - No explicit event callbacks; scroll positioning and highlight sync are achieved via callback functions. +- **Usage Notes** + - Use with anchor items on long pages; ensure the container is set correctly. + - Use slots to render custom anchor titles. + +```mermaid +flowchart TD +Start(["Enter Anchor"]) --> Items["Parse items context"] +Items --> Render["Render Antd Anchor"] +Render --> Events{"Scroll/Click event"} +Events --> |Positioning| SetActive["Set current anchor"] +Events --> |Switch| Callback["Execute callback function"] +SetActive --> End(["Done"]) +Callback --> End +``` + +Diagram sources + +- [frontend/antd/anchor/anchor.tsx:10-43](file://frontend/antd/anchor/anchor.tsx#L10-L43) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) + +Section sources + +- [frontend/antd/anchor/Index.svelte:1-66](file://frontend/antd/anchor/Index.svelte#L1-L66) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) + +### Breadcrumb + +- **Responsibility**: Displays the current page's path in the hierarchy; supports custom separators, item rendering, and dropdown icons. +- **Key Props and Behaviors** + - Separator: `separator` supports slots and functions. + - Item rendering: `itemRender` supports slots and functions. + - Dropdown icon: `dropdownIcon` supports slots. + - Items injection: supports `default` and `items` slots. +- **Events and State** + - Rendering is controlled via props and slots; no direct event callbacks. +- **Usage Notes** + - Generate a hierarchical structure in combination with a routing system; use `itemRender` to customize link styles when necessary. + +```mermaid +sequenceDiagram +participant B as "Breadcrumb" +participant S as "Slots" +participant I as "Items Context" +B->>I : Reads items/default +B->>S : Renders separator/itemRender/dropdownIcon +B-->>B : Renders Antd Breadcrumb +``` + +Diagram sources + +- [frontend/antd/breadcrumb/breadcrumb.tsx:15-63](file://frontend/antd/breadcrumb/breadcrumb.tsx#L15-L63) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) + +Section sources + +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) +- [frontend/antd/breadcrumb/item/Index.svelte:1-72](file://frontend/antd/breadcrumb/item/Index.svelte#L1-L72) + +### Dropdown + +- **Responsibility**: Wraps a trigger element and renders a dropdown menu; supports custom popup rendering and menu item injection. +- **Key Props and Behaviors** + - Popup container: `getPopupContainer`. + - Dropdown rendering: `dropdownRender`, `popupRender` support slots and functions. + - Menu expand icon: `menu.expandIcon` supports slots. + - Overflow indicator: `menu.overflowedIndicator` supports slots. + - Menu item injection: items are injected via the menu context. +- **Events and State** + - Rendering is controlled via props and slots; no direct event callbacks. +- **Usage Notes** + - Place the trigger element inside the component to avoid style occlusion. + - Use slots to implement complex dropdown panel layouts. + +```mermaid +classDiagram +class Dropdown { ++props : GetProps ++slots : dropdownRender,popupRender,menu.expandIcon,menu.overflowedIndicator ++getPopupContainer() ++render() +} +class MenuItems { ++items : ItemType[] ++expandIcon() ++overflowedIndicator() +} +Dropdown --> MenuItems : "Injects menu items" +``` + +Diagram sources + +- [frontend/antd/dropdown/dropdown.tsx:15-108](file://frontend/antd/dropdown/dropdown.tsx#L15-L108) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) + +Section sources + +- [frontend/antd/dropdown/Index.svelte:1-70](file://frontend/antd/dropdown/Index.svelte#L1-L70) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) + +### Menu + +- **Responsibility**: Side or top navigation menu; supports themes, expand icons, overflow indicators, and select/expand events. +- **Key Props and Behaviors** + - Theme: `theme` supports external injection. + - Expand icon: `expandIcon` supports slots. + - Overflow indicator: `overflowedIndicator` supports slots. + - Popup rendering: `popupRender` supports slots. + - Events: `onOpenChange`, `onSelect`, `onDeselect`. + - Items injection: supports `default` and `items` slots. +- **Events and State** + - State management and routing integration are achieved via `onOpenChange`, `onSelect`, and `onDeselect`. +- **Usage Notes** + - When integrating with a routing library, handle routing navigation and selection state sync inside `onSelect`. + +```mermaid +sequenceDiagram +participant M as "Menu" +participant E as "Event Callbacks" +participant R as "Router/Gradio" +M->>E : onSelect/onDeselect/onOpenChange +E->>R : Update route/state +R-->>M : Sync selected/expanded state +``` + +Diagram sources + +- [frontend/antd/menu/menu.tsx:18-92](file://frontend/antd/menu/menu.tsx#L18-L92) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) + +Section sources + +- [frontend/antd/menu/Index.svelte:1-75](file://frontend/antd/menu/Index.svelte#L1-L75) +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) +- [frontend/antd/menu/item/Index.svelte:1-84](file://frontend/antd/menu/item/Index.svelte#L1-L84) + +### Pagination + +- **Responsibility**: Data pagination control; supports quick-jump buttons and custom page item rendering. +- **Key Props and Behaviors** + - Quick jump: `showQuickJumper` supports the `goButton` slot. + - Total display: `showTotal` supports functions. + - Page item rendering: `itemRender` supports slots and functions. + - Events: `onChange(page, pageSize)`. +- **Events and State** + - Handle pagination logic and data refresh inside `onChange`. +- **Usage Notes** + - When interfacing with backend pagination APIs, pay attention to `page`/`pageSize` conversion and boundary handling. + +```mermaid +flowchart TD +Start(["User action"]) --> Jump["Click page number / quick jump"] +Jump --> Call["Call onChange(page,pageSize)"] +Call --> Fetch["Request new page data"] +Fetch --> Update["Update list and total count"] +Update --> End(["Done"]) +``` + +Diagram sources + +- [frontend/antd/pagination/pagination.tsx:14-52](file://frontend/antd/pagination/pagination.tsx#L14-L52) + +Section sources + +- [frontend/antd/pagination/Index.svelte:1-68](file://frontend/antd/pagination/Index.svelte#L1-L68) +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) + +### Steps + +- **Responsibility**: Step flow indicator; supports step item lists and custom progress dot rendering. +- **Key Props and Behaviors** + - Step items: `items` injection, supporting `default` and `items` slots. + - Progress dot: `progressDot` supports slots and functions. + - Events: step switching is implemented via callback functions. +- **Events and State** + - No direct event callbacks; step state management is achieved via function hooks. +- **Usage Notes** + - When combined with form wizards, control the availability of the next step based on the current step. + +```mermaid +sequenceDiagram +participant S as "Steps" +participant P as "progressDot slot" +participant I as "items context" +S->>I : Reads items/default +S->>P : Renders progress dot +S-->>S : Renders Antd Steps +``` + +Diagram sources + +- [frontend/antd/steps/steps.tsx:16-49](file://frontend/antd/steps/steps.tsx#L16-L49) +- [frontend/antd/steps/context.ts:1-7](file://frontend/antd/steps/context.ts#L1-L7) + +Section sources + +- [frontend/antd/steps/Index.svelte:1-63](file://frontend/antd/steps/Index.svelte#L1-L63) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/steps/context.ts:1-7](file://frontend/antd/steps/context.ts#L1-L7) + +## Dependency Analysis + +- **Inter-component Coupling** + - Dropdown depends on Menu's context injection for unified menu item management. + - All components with `items` depend on the context and rendering utilities provided by `createItemsContext`. +- **External Dependencies** + - Native Ant Design components as the rendering foundation. + - `@svelte-preprocess-react` provides tools such as `sveltify`, `ReactSlot`, `renderItems`, and `renderParamsSlot`. +- **Potential Circular Dependencies** + - Direct circular imports are avoided via context injection; each component independently maintains its own context. + +```mermaid +graph LR +Ctx["createItemsContext"] --> A["Anchor Items"] +Ctx --> B["Breadcrumb Items"] +Ctx --> M["Menu Items"] +Ctx --> S["Steps Items"] +D["Dropdown"] --> M +A --> Antd["Antd Anchor"] +B --> Antd2["Antd Breadcrumb"] +D --> Antd3["Antd Dropdown"] +M --> Antd4["Antd Menu"] +P["Pagination"] --> Antd5["Antd Pagination"] +S --> Antd6["Antd Steps"] +``` + +Diagram sources + +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) +- [frontend/antd/steps/context.ts:1-7](file://frontend/antd/steps/context.ts#L1-L7) +- [frontend/antd/dropdown/dropdown.tsx:10-13](file://frontend/antd/dropdown/dropdown.tsx#L10-L13) + +Section sources + +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) +- [frontend/antd/steps/context.ts:1-7](file://frontend/antd/steps/context.ts#L1-L7) +- [frontend/antd/dropdown/dropdown.tsx:10-13](file://frontend/antd/dropdown/dropdown.tsx#L10-L13) + +## Performance Considerations + +- **Lazy Loading**: The Svelte wrapper layer lazy-loads React components to reduce the initial page load burden. +- **Computed Caching**: The React layer uses `useMemo` to stabilize `items`, avoiding unnecessary re-renders. +- **Slot Cloning**: Slot rendering enables cloning by default to ensure independence, but be mindful of cloning overhead. +- **Event Hooks**: The `useFunction` hook ensures stable callback references, preventing re-renders caused by function reference changes. + +## Troubleshooting Guide + +- **Event Not Triggered** + - Check that `onOpenChange`/`onSelect`/`onDeselect`/`onChange` callbacks have been correctly passed. + - Confirm that the callback functions are wrapped with the `useFunction` hook. +- **Slot Not Working** + - Confirm that the slot name matches the mapping (e.g., `menu.expandIcon`, `itemRender`, etc.). + - Check that the slot has cloning enabled (`clone: true`). +- **Items Not Displayed** + - Confirm that `items` have been injected via context or passed explicitly. + - Check the priority and naming of the default slot vs. the `items` slot. +- **Style Conflicts** + - Check whether `elem_id`/`elem_classes` conflict with global styles. + - Ensure the component style class prefix `ms-gr-antd-*` has not been overridden. + +Section sources + +- [frontend/antd/anchor/anchor.tsx:10-43](file://frontend/antd/anchor/anchor.tsx#L10-L43) +- [frontend/antd/breadcrumb/breadcrumb.tsx:15-63](file://frontend/antd/breadcrumb/breadcrumb.tsx#L15-L63) +- [frontend/antd/dropdown/dropdown.tsx:26-108](file://frontend/antd/dropdown/dropdown.tsx#L26-L108) +- [frontend/antd/menu/menu.tsx:18-92](file://frontend/antd/menu/menu.tsx#L18-L92) +- [frontend/antd/pagination/pagination.tsx:14-52](file://frontend/antd/pagination/pagination.tsx#L14-L52) +- [frontend/antd/steps/steps.tsx:16-49](file://frontend/antd/steps/steps.tsx#L16-L49) + +## Conclusion + +ModelScope Studio's navigation components achieve seamless integration of Ant Design components in the frontend ecosystem through a unified Svelte wrapper layer and React bridge layer. The design emphasizes: + +- **Ease of use**: Unified prop forwarding and slot mapping. +- **Extensibility**: Context injection and function hooks for greater flexibility. +- **Maintainability**: Clear separation of responsibilities and dependencies. + +It is recommended to normalize event callbacks and state management in combination with routing systems and permission frameworks in real-world projects to achieve a better user experience and development efficiency. + +## Appendix + +- **Routing Integration Recommendations** + - Handle routing navigation and state sync uniformly in Menu/Pagination/Steps callbacks. + - Handle scroll positioning and highlight sync uniformly in Anchor and Steps callbacks. +- **Permission Control Recommendations** + - Filter invisible items at the items injection stage, or hide them based on permission conditions at the rendering layer. +- **Dynamic Loading Recommendations** + - Use lazy loading and `useMemo` caching strategies to avoid frequent re-renders. +- **Accessibility Recommendations** + - Provide keyboard accessibility and screen-reader-friendly labels for clickable items. + - Provide clear ARIA attributes and state hints for step indicators and pagination controls. diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Other Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Other Components API.md new file mode 100644 index 00000000..4162672a --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design Components API/Other Components API.md @@ -0,0 +1,278 @@ +# Other Components API + + +**Files referenced in this document** +- [frontend/antd/affix/Index.svelte](file://frontend/antd/affix/Index.svelte) +- [frontend/antd/affix/affix.tsx](file://frontend/antd/affix/affix.tsx) +- [frontend/antd/affix/package.json](file://frontend/antd/affix/package.json) +- [frontend/antd/config-provider/Index.svelte](file://frontend/antd/config-provider/Index.svelte) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts](file://frontend/antd/config-provider/locales.ts) +- [frontend/antd/config-provider/package.json](file://frontend/antd/config-provider/package.json) +- [docs/components/antd/affix/README.md](file://docs/components/antd/affix/README.md) +- [docs/components/antd/config_provider/README.md](file://docs/components/antd/config_provider/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document provides a systematic overview of special-function Ant Design components in ModelScope Studio: Affix (sticky positioning) and ConfigProvider (global configuration). It covers their APIs, type definitions, context provision, theme and internationalization mechanisms, and how they integrate into the component system. The document also presents standard usage workflows, typical scenarios, and best practices to help developers quickly understand and correctly use these components. + +## Project Structure + +- Components are organized as Svelte packages; each component directory contains: + - `Index.svelte`: The Gradio/Svelte wrapper layer, responsible for prop forwarding, slot rendering, visibility control, and lazy loading. + - Component implementation files (e.g., `affix.tsx`, `config-provider.tsx`): Bridge React components into a Svelte-usable form via `@svelte-preprocess-react`, extending necessary types and behaviors. + - `package.json`: The export entry, supporting both Gradio and default modes. +- Documentation is located under `docs/components/antd`, providing examples and explanations. + +```mermaid +graph TB +subgraph "Ant Design Components" +A["affix/Index.svelte"] +B["affix/affix.tsx"] +C["config-provider/Index.svelte"] +D["config-provider/config-provider.tsx"] +E["config-provider/locales.ts"] +end +A --> B +C --> D +D --> E +``` + +Diagram sources + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) + +Section sources + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [frontend/antd/affix/package.json:1-15](file://frontend/antd/affix/package.json#L1-L15) +- [frontend/antd/config-provider/package.json:1-15](file://frontend/antd/config-provider/package.json#L1-L15) +- [docs/components/antd/affix/README.md:1-9](file://docs/components/antd/affix/README.md#L1-L9) +- [docs/components/antd/config_provider/README.md:1-8](file://docs/components/antd/config_provider/README.md#L1-L8) + +## Core Components + +- **Affix** + - **Responsibility**: Fixes child elements to the viewport or container boundaries; commonly used for sidebars, back-to-top buttons, etc. + - **Key Points**: Dynamically determines the scroll container via the `target` function; supports `visible` to control rendering; supports extra prop forwarding and slot rendering. +- **ConfigProvider** + - **Responsibility**: Provides unified global configuration for Ant Design components, including themes, locales, popup containers, and empty state rendering. + - **Key Points**: Supports theme algorithm toggles (dark/compact), internationalization locale switching, style injection, and container function callbacks; can be used as the context root node. + +Section sources + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) + +## Architecture Overview + +The following diagram illustrates the call chain from the Svelte wrapper layer to React components, as well as the theme and internationalization processing flow for ConfigProvider. + +```mermaid +sequenceDiagram +participant UI as "Page/Application" +participant Wrap as "Svelte Wrapper Layer (Index.svelte)" +participant Impl as "Component Implementation (.tsx)" +participant AD as "Ant Design Component Library" +participant CSS as "Style Injection (StyleProvider)" +UI->>Wrap : Renders component and passes props/slots +Wrap->>Impl : Lazy-imports and forwards props +Impl->>AD : Instantiates target component (e.g., Affix/ConfigProvider) +Impl->>CSS : Injects style prefix and hash strategy +AD-->>UI : Render result +``` + +Diagram sources + +- [frontend/antd/affix/Index.svelte:55-68](file://frontend/antd/affix/Index.svelte#L55-L68) +- [frontend/antd/affix/affix.tsx:6-11](file://frontend/antd/affix/affix.tsx#L6-L11) +- [frontend/antd/config-provider/Index.svelte:54-71](file://frontend/antd/config-provider/Index.svelte#L54-L71) +- [frontend/antd/config-provider/config-provider.tsx:108-149](file://frontend/antd/config-provider/config-provider.tsx#L108-L149) + +## Component Details + +### Affix + +- **Responsibility** + - Fixes child content to the viewport or a specified container boundary, showing/hiding as the user scrolls. +- **Props and Behaviors** + - Supports a `target` container function for dynamically selecting the scroll container. + - Supports `visible` to control whether to render. + - Supports extra prop forwarding and slot rendering. +- **Use Cases** + - Sidebar toolbars, back-to-top buttons, floating action areas, etc. +- **Types and Implementation Notes** + - Bridges Ant Design's `Affix` as a Svelte component via `sveltify` from `@svelte-preprocess-react`. + - `target` is wrapped via `useFunction` to ensure reactive updates. +- **Examples and Documentation** + - Documentation provides two examples: "Basic" and "Container scroll" for quick onboarding. + +```mermaid +sequenceDiagram +participant P as "Parent Component" +participant W as "affix/Index.svelte" +participant T as "affix.tsx (Antd Affix)" +participant R as "React/Antd" +P->>W : Passes props (including target/visible/slots) +W->>T : Forwards after processProps +T->>R : Wraps target via useFunction and renders +R-->>P : DOM result with sticky positioning applied +``` + +Diagram sources + +- [frontend/antd/affix/Index.svelte:23-49](file://frontend/antd/affix/Index.svelte#L23-L49) +- [frontend/antd/affix/affix.tsx:6-11](file://frontend/antd/affix/affix.tsx#L6-L11) + +Section sources + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [docs/components/antd/affix/README.md:1-9](file://docs/components/antd/affix/README.md#L1-L9) + +### ConfigProvider + +- **Responsibility** + - Provides unified global configuration covering theme, locale, popup container, empty state rendering, and more. +- **Theme and Algorithms** + - `theme.algorithm` supports automatic detection: dark/compact algorithms can be enabled based on `themeMode` or explicit configuration. +- **Internationalization** + - `locale` supports multi-language mapping, switching based on browser language or explicit input; also synchronizes `dayjs` locale settings. +- **Slots and Prop Composition** + - Supports converting slots into a prop tree for declarative passing of complex configuration items. +- **Context and Containers** + - Marks the context as `antd` type via `setConfigType`, affecting behaviors like shared theming. + - Supports `getPopupContainer`/`getTargetContainer` for customizing popup and mount containers. + +```mermaid +flowchart TD +Start(["Enter ConfigProvider"]) --> Locale["Parse locale
Load corresponding Antd and dayjs language pack"] +Locale --> Theme["Merge theme.algorithm
Generate final algorithm array based on themeMode and props"] +Theme --> Slots["Convert slots to prop tree
Functionalize slots like renderEmpty"] +Slots --> Style["Inject style prefix and hash strategy"] +Style --> Render["Render subtree"] +Render --> End(["Done"]) +``` + +Diagram sources + +- [frontend/antd/config-provider/config-provider.tsx:85-105](file://frontend/antd/config-provider/config-provider.tsx#L85-L105) +- [frontend/antd/config-provider/config-provider.tsx:127-143](file://frontend/antd/config-provider/config-provider.tsx#L127-L143) +- [frontend/antd/config-provider/config-provider.tsx:29-49](file://frontend/antd/config-provider/config-provider.tsx#L29-L49) +- [frontend/antd/config-provider/locales.ts:15-27](file://frontend/antd/config-provider/locales.ts#L15-L27) + +Section sources + +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [docs/components/antd/config_provider/README.md:1-8](file://docs/components/antd/config_provider/README.md#L1-L8) + +## Dependency Analysis + +- **Component Export** + - Both components provide Gradio and default entry points via the `exports` field in `package.json`, making them usable across different runtime environments. +- **Runtime Dependencies** + - ConfigProvider depends on Ant Design's `ConfigProvider`, theme algorithms, and style injection; it also depends on `dayjs` and the locales mapping. + - Affix depends on Ant Design's `Affix` and the `useFunction` utility to wrap callback functions. +- **Wrapper Layer Coupling** + - Both components use lazy imports and prop forwarding to reduce initial load pressure and improve rendering controllability. + +```mermaid +graph LR +PkgA["@modelscope-studio/antd-affix/package.json"] --> IA["affix/Index.svelte"] +PkgB["@modelscope-studio/antd-config-provider/package.json"] --> IC["config-provider/Index.svelte"] +IA --> TA["affix.tsx"] +IC --> TC["config-provider.tsx"] +TC --> L["locales.ts"] +``` + +Diagram sources + +- [frontend/antd/affix/package.json:1-15](file://frontend/antd/affix/package.json#L1-L15) +- [frontend/antd/config-provider/package.json:1-15](file://frontend/antd/config-provider/package.json#L1-L15) +- [frontend/antd/affix/Index.svelte:10-13](file://frontend/antd/affix/Index.svelte#L10-L13) +- [frontend/antd/config-provider/Index.svelte:11-13](file://frontend/antd/config-provider/Index.svelte#L11-L13) + +Section sources + +- [frontend/antd/affix/package.json:1-15](file://frontend/antd/affix/package.json#L1-L15) +- [frontend/antd/config-provider/package.json:1-15](file://frontend/antd/config-provider/package.json#L1-L15) + +## Performance Considerations + +- **Lazy Loading** + - Components are loaded on demand via `importComponent` and the `{#await}` pattern, avoiding initial page blocking. +- **Prop Forwarding and Derived Computation** + - Using `processProps` and `$derived` avoids unnecessary re-renders, only updating when essential props change. +- **Style Injection Strategy** + - Using `StyleProvider` with a high-priority hash reduces style conflicts and repaint costs. +- **Callback Function Wrapping** + - Using `useFunction` to wrap callbacks like `target`/`getPopupContainer` ensures stable function references, reducing unnecessary updates. + +## Troubleshooting Guide + +- **Sticky Positioning Not Working** + - Check that `target` returns the correct scroll container; confirm that `visible` is `true` and the container has a scrollbar. + - Reference paths: [frontend/antd/affix/Index.svelte:47-49](file://frontend/antd/affix/Index.svelte#L47-L49), [frontend/antd/affix/affix.tsx:7-10](file://frontend/antd/affix/affix.tsx#L7-L10) +- **Popup/Float Position Abnormal** + - Check that `getPopupContainer` returns the correct container; confirm the `getTargetContainer` setting in ConfigProvider. + - Reference path: [frontend/antd/config-provider/config-provider.tsx:93-95](file://frontend/antd/config-provider/config-provider.tsx#L93-L95) +- **Theme Not Switching or Algorithm Not Taking Effect** + - Confirm the combination of `themeMode` and `theme.algorithm`; note that the algorithm array is composed of multiple algorithm functions. + - Reference paths: [frontend/antd/config-provider/config-provider.tsx:88-91](file://frontend/antd/config-provider/config-provider.tsx#L88-L91), [frontend/antd/config-provider/config-provider.tsx:127-143](file://frontend/antd/config-provider/config-provider.tsx#L127-L143) +- **Locale Not Taking Effect** + - Check the `locale` parameter format and the locales mapping; confirm that the `dayjs` locale has been synchronized. + - Reference paths: [frontend/antd/config-provider/config-provider.tsx:85-105](file://frontend/antd/config-provider/config-provider.tsx#L85-L105), [frontend/antd/config-provider/locales.ts:15-27](file://frontend/antd/config-provider/locales.ts#L15-L27) + +Section sources + +- [frontend/antd/affix/Index.svelte:47-49](file://frontend/antd/affix/Index.svelte#L47-L49) +- [frontend/antd/affix/affix.tsx:7-10](file://frontend/antd/affix/affix.tsx#L7-L10) +- [frontend/antd/config-provider/config-provider.tsx:85-105](file://frontend/antd/config-provider/config-provider.tsx#L85-L105) +- [frontend/antd/config-provider/config-provider.tsx:88-91](file://frontend/antd/config-provider/config-provider.tsx#L88-L91) +- [frontend/antd/config-provider/config-provider.tsx:127-143](file://frontend/antd/config-provider/config-provider.tsx#L127-L143) +- [frontend/antd/config-provider/locales.ts:15-27](file://frontend/antd/config-provider/locales.ts#L15-L27) + +## Conclusion + +- Affix and ConfigProvider in ModelScope Studio are seamlessly integrated with the Ant Design component library through a unified Svelte wrapper layer and `@svelte-preprocess-react` bridging. +- ConfigProvider provides powerful global configuration capabilities covering themes, internationalization, and container strategies; Affix focuses on sticky positioning scenarios with good configurability and performance. +- It is recommended to place ConfigProvider at the application root to unify style and locale; use Affix for areas requiring sticky positioning, and set `target` and `visible` appropriately. + +## Appendix + +- **Examples and Demos** + - Affix examples: Basic, Container scroll + - ConfigProvider examples: Basic +- **Reference Documentation** + - Ant Design official Affix and ConfigProvider documentation links are in each component's README. + +Section sources + +- [docs/components/antd/affix/README.md:1-9](file://docs/components/antd/affix/README.md#L1-L9) +- [docs/components/antd/config_provider/README.md:1-8](file://docs/components/antd/config_provider/README.md#L1-L8) diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Ant Design X Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Ant Design X Components API.md new file mode 100644 index 00000000..84e46c54 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Ant Design X Components API.md @@ -0,0 +1,436 @@ +# Ant Design X Components API + + +**Files referenced in this document** +- [backend/modelscope_studio/components/__init__.py](file://backend/modelscope_studio/components/__init__.py) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/components/pro/__init__.py](file://backend/modelscope_studio/components/pro/__init__.py) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [frontend/antdx/conversations/conversations.tsx](file://frontend/antdx/conversations/conversations.tsx) +- [frontend/antdx/sender/sender.tsx](file://frontend/antdx/sender/sender.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for Ant Design X-based Svelte components in ModelScope Studio, covering the following component families: + +- **General Components**: Common UI component wrappers from Ant Design (antd) +- **Awakening Components**: Components for guiding user interaction, hints, or triggering flows +- **Expression Components**: Components for content display, rich text, chat bubbles, and other expressive uses +- **Confirmation Components**: Interaction components for secondary confirmation and popup confirmation +- **Feedback Components**: Feedback components for messages, notifications, progress, and results +- **Tool Components**: Auxiliary capabilities including forms, layouts, toolbars, and contexts + +The document focuses on property definitions, event handlers, slot systems, state management, message passing, conversation flow control mechanisms, and provides usage patterns and best practices for AI/ML scenarios. + +## Project Structure + +ModelScope Studio's frontend uses a combination of Svelte + Ant Design X, bridging React components into the Svelte ecosystem through a unified adapter layer. The backend Python layer is responsible for exporting component collections for on-demand use in applications. + +```mermaid +graph TB +subgraph "Backend Component Export" +A_init["backend/modelscope_studio/components/__init__.py"] +A_antd_init["backend/modelscope_studio/components/antd/__init__.py"] +A_antdx_init["backend/modelscope_studio/components/antdx/__init__.py"] +A_base_init["backend/modelscope_studio/components/base/__init__.py"] +A_pro_init["backend/modelscope_studio/components/pro/__init__.py"] +end +subgraph "Frontend Adapter Layer" +F_button["frontend/antd/button/button.tsx"] +F_form["frontend/antd/form/form.tsx"] +F_actions["frontend/antdx/actions/actions.tsx"] +F_bubble["frontend/antdx/bubble/bubble.tsx"] +F_conversations["frontend/antdx/conversations/conversations.tsx"] +F_sender["frontend/antdx/sender/sender.tsx"] +end +A_init --> A_antd_init +A_init --> A_antdx_init +A_init --> A_base_init +A_init --> A_pro_init +A_antd_init --> F_button +A_antd_init --> F_form +A_antdx_init --> F_actions +A_antdx_init --> F_bubble +A_antdx_init --> F_conversations +A_antdx_init --> F_sender +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [frontend/antdx/conversations/conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +**Section sources** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) + +## Core Components + +This section provides a quick overview of each component family's key responsibilities and typical use cases for rapid identification and selection. + +- **General Components (Antd)** + - Responsibility: Provide basic UI capabilities such as buttons, inputs, forms, layouts, messages, notifications, etc. + - Typical components: Button, Form, Input, Modal, Message, Notification, etc. + - Feature: Bridges Ant Design's React components as Svelte components via an adapter; supports slots and functional props. + +- **Awakening Components (AntdX)** + - Responsibility: Guide users to their next action, such as action menus, hints, skill toggles, etc. + - Typical components: Actions, Sender, Suggestion, Welcome, etc. + - Feature: Supports complex slots, context injection, event forwarding, and value change integration. + +- **Expression Components (AntdX)** + - Responsibility: For content expression and conversational display, such as bubbles, thought chains, file cards, attachments, etc. + - Typical components: Bubble, ThoughtChain, FileCard, Attachments, Prompts, etc. + - Feature: Supports render functions, editable configuration, header/footer, and extra area slots. + +- **Confirmation Components (AntdX)** + - Responsibility: For secondary confirmation, popup confirmation, and similar interactions. + - Typical components: Popconfirm, Modal (static), Tour, etc. + - Feature: Consistent interaction semantics with AntdX, maintaining a uniform slot and event model. + +- **Feedback Components (AntdX)** + - Responsibility: Messages, notifications, progress, results, and other feedback. + - Typical components: Message, Notification, Progress, Result, etc. + - Feature: Supports slot-based rendering, functional callbacks, and state-driven updates. + +- **Tool Components (AntdX)** + - Responsibility: Auxiliary capabilities for forms, layouts, contexts, and application containers. + - Typical components: Form, Layout, XProvider, Markdown, Slot, etc. + - Feature: Provides contexts, rendering utility functions, and the slot system. + +**Section sources** + +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [frontend/antdx/conversations/conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +## Architecture Overview + +The following diagram shows the mapping from backend component exports to the frontend adapter layer to specific components, as well as the processing paths for slots and functional props. + +```mermaid +graph TB +subgraph "Backend Export" +B1["antd/__init__.py
Exports Button/Form etc."] +B2["antdx/__init__.py
Exports Actions/Bubble etc."] +B3["base/__init__.py
Exports Application/Slot etc."] +B4["pro/__init__.py
Exports Chatbot/Monaco etc."] +end +subgraph "Frontend Adapter" +F1["sveltify
Bridges React components"] +F2["Slot System
ReactSlot/renderParamsSlot"] +F3["Functional Props
useFunction/createFunction"] +F4["Context and Menu Items
withItemsContextProvider/useItems"] +end +subgraph "Component Instances" +C1["Button"] +C2["Form"] +C3["Actions"] +C4["Bubble"] +C5["Conversations"] +C6["Sender"] +end +B1 --> F1 --> C1 +B1 --> F1 --> C2 +B2 --> F1 --> C3 +B2 --> F1 --> C4 +B2 --> F1 --> C5 +B2 --> F1 --> C6 +F1 --> F2 +F1 --> F3 +F1 --> F4 +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [frontend/antdx/conversations/conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +## Component Details + +### General Components API (Antd) + +#### Button + +- **Purpose**: Bridges Ant Design's Button as a Svelte component; supports slots and loading icon slots. +- **Key Points** + - Slots: `icon`, `loading.icon` + - Value binding: Intelligent selection between `value` and `children` + - Loading state: `loading` supports object input with configurable delay +- **Usage Notes** + - When slots exist, slot rendering takes priority; otherwise falls back to prop values. + - Uses `useTargets` to handle target nodes in `children`. + +**Section sources** + +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) + +#### Form + +- **Purpose**: Bridges Ant Design's Form as a Svelte component; provides controlled value and action sync. +- **Key Points** + - Controlled value: `value` and `onValueChange` + - Action sync: `formAction` (reset/submit/validate) and `onResetFormAction` + - Slots: `requiredMark` + - Callbacks: `onValuesChange` +- **Usage Notes** + - Uses `useEffect` to execute reset/submit/validate based on `formAction`. + - Syncs external `value` to the internal form instance. + +**Section sources** + +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +### Awakening Components API (AntdX) + +#### Actions + +- **Purpose**: Bridges AntdX's Actions as a Svelte component; supports menu items and dropdown render slots. +- **Key Points** + - Slots: `dropdownProps.menu.items`, `dropdownProps.menu.expandIcon`, `dropdownProps.menu.overflowedIndicator`, `dropdownProps.dropdownRender`, `dropdownProps.popupRender` + - Context: Integrates with menu item context, supporting `items`/`default` slots + - Rendering: `renderItems`, `renderParamsSlot`, `createFunction` +- **Usage Notes** + - Prioritizes `items` from slots; falls back to prop `items` if absent. + - Conditionally replaces dropdown render and menu items. + +**Section sources** + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) + +#### Sender + +- **Purpose**: Svelte adapter for AntdX Sender; supports file upload, paste, suggestion context, and slotted header/footer. +- **Key Points** + - Slots: `suffix`, `header`, `prefix`, `footer`, `skill.*` series + - Events: `onSubmit` (fires when suggestion is not open), `onChange`, `onPasteFile` + - Value change: `onValueChange` and `useValueChange` + - Upload: The `upload` function returns an array of file data +- **Usage Notes** + - Calls `upload` when pasting files and returns the path. + - Formats results and customizes rendering via `slotConfig`. + +**Section sources** + +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +### Expression Components API (AntdX) + +#### Bubble + +- **Purpose**: Svelte adapter for AntdX Bubble; supports header/body/footer/extra areas and editable configuration. +- **Key Points** + - Slots: `avatar`, `editable.okText`, `editable.cancelText`, `content`, `footer`, `header`, `extra`, `loadingRender`, `contentRender` + - Functions: `typing`, `contentRender`, `header`/`footer`/`avatar`/`extra`, `editable` +- **Usage Notes** + - Supports boolean `editable` or object configuration; slot content takes priority when slots exist. + - Converts props to functional rendering via `useFunction`. + +**Section sources** + +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) + +#### Conversations + +- **Purpose**: Svelte adapter for AntdX Conversations; supports grouping, menus, and slotted labels. +- **Key Points** + - Slots: `menu.trigger`, `menu.expandIcon`, `menu.overflowedIndicator`, `groupable.label` + - Context: Menu item context and conversation item context + - Rendering: `renderItems`, `patchMenuEvents` (event forwarding) +- **Usage Notes** + - Supports string or object form for `menu` configuration; auto-falls back when no `items`. + - Injects style class names via `classNames`. + +**Section sources** + +- [frontend/antdx/conversations/conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) + +### Confirmation Components API (AntdX) + +- **Popconfirm**: Secondary confirmation popup; supports slotted title and description. +- **Modal (static)**: Static modal dialog; suitable for fixed content display. +- **Tour**: Guided tour; supports steps and slotted rendering. + +[This section is conceptual; no specific file analysis] + +### Feedback Components API (AntdX) + +- **Message**: Message hint; supports slotted content and functional rendering. +- **Notification**: Notification alert; supports slotted rendering and close callbacks. +- **Progress**: Progress bar; supports slotted formatting. +- **Result**: Result page; supports slotted action areas. + +[This section is conceptual; no specific file analysis] + +### Tool Components API (AntdX) + +- **Form**: See "General Components" section. +- **Layout**: Layout container supporting Content/Footer/Header/Sider. +- **XProvider**: Context provider supplying global configuration for AntdX components. +- **Markdown**: Markdown rendering component. +- **Slot**: Slot container for dynamic content mounting. + +**Section sources** + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +## Dependency Analysis + +```mermaid +graph TB +subgraph "Backend Export" +A["components/__init__.py"] +A_antd["antd/__init__.py"] +A_antdx["antdx/__init__.py"] +A_base["base/__init__.py"] +A_pro["pro/__init__.py"] +end +subgraph "Frontend Adapter" +U_render["renderItems/renderParamsSlot"] +U_func["useFunction/createFunction"] +U_slot["ReactSlot"] +U_ctx["withItemsContextProvider/useItems"] +end +subgraph "Components" +C_btn["Button"] +C_form["Form"] +C_act["Actions"] +C_bub["Bubble"] +C_conv["Conversations"] +C_snd["Sender"] +end +A --> A_antd --> C_btn +A --> A_antd --> C_form +A --> A_antdx --> C_act +A --> A_antdx --> C_bub +A --> A_antdx --> C_conv +A --> A_antdx --> C_snd +C_btn -.-> U_render +C_form -.-> U_func +C_act -.-> U_render +C_act -.-> U_ctx +C_bub -.-> U_func +C_bub -.-> U_slot +C_conv -.-> U_render +C_conv -.-> U_ctx +C_snd -.-> U_func +C_snd -.-> U_slot +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [frontend/antdx/conversations/conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +**Section sources** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [frontend/antdx/conversations/conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +## Performance Considerations + +- **Lazy Rendering of Slots and Functional Props** + - Corresponding content is only rendered when slots exist, avoiding unnecessary computation. + - `useMemo` wraps menu and rendering logic to reduce repeated renders. +- **Controlled Value and Action Sync** + - Uses `useEffect` to trigger reset/submit/validate based on `formAction`, avoiding frequent redraws. + - Uses `useValueChange` to manage input value changes, reducing upstream jitter. +- **Event Forwarding and Debouncing** + - Stops DOM event bubbling on `onClick` in menu events to avoid unexpected triggers. + - Uses `useMemoizedFn` to cache callbacks for functional props. + +[This section provides general guidance; no specific file analysis] + +## Troubleshooting Guide + +- **Slot Not Working** + - Check that slot key names match the component's convention (e.g., `menu.items`, `dropdownRender`, etc.). + - Confirm that the slot is not hidden by `children` or not passed correctly. +- **Value Not Synced** + - For Form: Confirm that `value` is correctly passed in and `onValueChange` is being fired. + - For Sender: Confirm the binding of `onValueChange` and `useValueChange`. +- **Dropdown Menu Not Showing** + - Check that `dropdownProps` and `menu.items` are correctly configured. + - Confirm that `withItemsContextProvider` wraps the component. +- **Upload Failing** + - Confirm that the return value of the `upload` function contains a `path` field. + - Check that the path returned by `onPasteFile` is correct. + +**Section sources** + +- [frontend/antd/form/form.tsx:32-53](file://frontend/antd/form/form.tsx#L32-L53) +- [frontend/antdx/sender/sender.tsx:135-138](file://frontend/antdx/sender/sender.tsx#L135-L138) +- [frontend/antdx/actions/actions.tsx:39-96](file://frontend/antdx/actions/actions.tsx#L39-L96) + +## Conclusion + +This document covers the APIs and usage patterns of Ant Design X Svelte components in ModelScope Studio, focusing on key mechanisms such as the slot system, functional props, context and menu item integration, value change and action sync. For AI/ML scenarios, it is recommended to prioritize Sender, Bubble, Conversations, and Actions for building conversation and expression flows, using slots and functional props to achieve highly customized content rendering and interaction behaviors. + +## Appendix + +### Component Instantiation and Configuration (AI/ML Scenario Recommendations) + +- **Conversation Flow** + - Use Sender as the input entry; configure `upload` to support multimodal input. + - Use Bubble to render response content; enable `editable` when secondary editing is needed. + - Use Conversations to manage the conversation list; combine `menu` and `groupable` for grouping and operations. +- **Form and Validation** + - Use Form for controlled value and action sync; combine reset/submit/validate for flow control. +- **Actions and Guidance** + - Use Actions for context menus and guidance items; combine slots for custom rendering. + +[This section is conceptual; no specific file analysis] diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Awakening Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Awakening Components API.md new file mode 100644 index 00000000..1c62f5ae --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Awakening Components API.md @@ -0,0 +1,348 @@ +# Awakening Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/welcome/__init__.py](file://backend/modelscope_studio/components/antdx/welcome/__init__.py) +- [backend/modelscope_studio/components/antdx/prompts/__init__.py](file://backend/modelscope_studio/components/antdx/prompts/__init__.py) +- [frontend/antdx/welcome/Index.svelte](file://frontend/antdx/welcome/Index.svelte) +- [frontend/antdx/welcome/welcome.tsx](file://frontend/antdx/welcome/welcome.tsx) +- [frontend/antdx/prompts/Index.svelte](file://frontend/antdx/prompts/Index.svelte) +- [frontend/antdx/prompts/prompts.tsx](file://frontend/antdx/prompts/prompts.tsx) +- [frontend/antdx/prompts/context.ts](file://frontend/antdx/prompts/context.ts) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Ant Design X Awakening Components API reference for ModelScope Studio, focusing on the following two components: + +- Welcome Component (AntdXWelcome): Used to display welcome messages on the first load or in specific scenarios, supporting slot-based configuration for title, description, icon, and extra content. +- Prompts Component (AntdXPrompts): Used to display a set of clickable prompt cards, supporting configuration for title, vertical layout, fade-in animation, line wrapping, etc., and providing an item click event callback. + +This document provides an in-depth analysis of system architecture, component relationships, data flow, processing logic, integration points, error handling, and performance characteristics, as well as lifecycle hooks, event handling, state management mechanisms, TypeScript type definitions, and interface specifications, helping developers build smooth first-time experiences and prompt guidance in AI applications. + +## Project Structure + +ModelScope Studio's frontend adopts the Svelte + Ant Design X component system, with the backend bridging frontend components via Python components. The Welcome and Prompts components are located in the `antdx` module; backend components handle property passing and event binding, while frontend components handle rendering and interaction. + +```mermaid +graph TB +subgraph "Backend" +B_Welcome["AntdXWelcome
Python Component"] +B_Prompts["AntdXPrompts
Python Component"] +end +subgraph "Frontend" +F_Welcome["welcome/Index.svelte
Renderer"] +F_Welcome_TSX["welcome/welcome.tsx
Component Implementation"] +F_Prompts["prompts/Index.svelte
Renderer"] +F_Prompts_TSX["prompts/prompts.tsx
Component Implementation"] +F_Prompts_Context["prompts/context.ts
Context"] +end +B_Welcome --> F_Welcome +F_Welcome --> F_Welcome_TSX +B_Prompts --> F_Prompts +F_Prompts --> F_Prompts_TSX +F_Prompts_TSX --> F_Prompts_Context +``` + +**Chart Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) +- [frontend/antdx/welcome/Index.svelte:1-72](file://frontend/antdx/welcome/Index.svelte#L1-L72) +- [frontend/antdx/welcome/welcome.tsx](file://frontend/antdx/welcome/welcome.tsx) +- [frontend/antdx/prompts/Index.svelte:1-71](file://frontend/antdx/prompts/Index.svelte#L1-L71) +- [frontend/antdx/prompts/prompts.tsx](file://frontend/antdx/prompts/prompts.tsx) +- [frontend/antdx/prompts/context.ts](file://frontend/antdx/prompts/context.ts) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:1-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L1-L73) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:1-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L1-L88) +- [frontend/antdx/welcome/Index.svelte:1-72](file://frontend/antdx/welcome/Index.svelte#L1-L72) +- [frontend/antdx/prompts/Index.svelte:1-71](file://frontend/antdx/prompts/Index.svelte#L1-L71) + +## Core Components + +This section provides an overview of the key responsibilities and capability boundaries of the two components: + +- Welcome Component (AntdXWelcome) + - Responsibility: Display welcome messages, supporting multiple slots (title, description, icon, extra content) with optional styles and variants. + - Key Points: Does not expose standard API (`skip_api` is true); implemented via slots and static resource path injection. +- Prompts Component (AntdXPrompts) + - Responsibility: Display a set of prompt cards, supporting title, vertical layout, fade-in animation, line wrapping, etc.; provides an item click event callback. + - Key Points: Internally nested item components; event binding is configured via `EventListener`. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) + +## Architecture Overview + +The diagram below shows the call chain from backend components to frontend renderers to specific component implementations, as well as the event binding and slot passing mechanism. + +```mermaid +sequenceDiagram +participant Py as "Python Backend Component" +participant Svelte as "Svelte Renderer" +participant TSX as "TSX Component Implementation" +Py->>Py : "Initialize component properties and events" +Py->>Svelte : "Pass props and visibility control" +Svelte->>TSX : "Dynamically import and render component" +TSX-->>Svelte : "Render complete, await slot content" +Svelte-->>Py : "Event callback binding (e.g., item_click)" +``` + +**Chart Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:55-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L55-L73) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:70-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L70-L88) +- [frontend/antdx/welcome/Index.svelte:10-72](file://frontend/antdx/welcome/Index.svelte#L10-L72) +- [frontend/antdx/prompts/Index.svelte:10-71](file://frontend/antdx/prompts/Index.svelte#L10-L71) + +## Detailed Component Analysis + +### Welcome Component (AntdXWelcome) + +- Component Purpose: Used for first-time experience or onboarding scenarios, carrying title, description, icon, and extra content. +- Slot Support: `extra`, `icon`, `description`, `title`. +- Properties and Behavior: + - Supports additional properties `additional_props`, styles `styles`/`class_names`, and root class name `root_class_name`. + - The `icon` parameter is processed through static asset service (`serve_static_file`). + - Does not expose standard API (`skip_api` is true); suitable for use through slot and static resource combinations. +- Lifecycle and Hooks: + - `preprocess`/`postprocess`/`example_payload`/`example_value` all return null, indicating this component does not participate in regular data flow transformation. +- Typical Use Cases: + - Welcome pages after app startup, new user onboarding, feature entry hints, etc. + +```mermaid +classDiagram +class AntdXWelcome { ++EVENTS : list ++SLOTS : list ++additional_props : dict|None ++extra : str|None ++icon : str|None ++styles : dict|str|None ++class_names : dict|str|None ++description : str|None ++variant : "filled"| "borderless"| None ++title : str|None ++root_class_name : str|None ++skip_api() : bool ++preprocess(payload) : None ++postprocess(value) : None ++example_payload() : None ++example_value() : None +} +``` + +**Chart Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) +- [frontend/antdx/welcome/Index.svelte:1-72](file://frontend/antdx/welcome/Index.svelte#L1-L72) +- [frontend/antdx/welcome/welcome.tsx](file://frontend/antdx/welcome/welcome.tsx) + +### Prompts Component (AntdXPrompts) + +- Component Purpose: Display a set of prompt cards, supporting title, vertical layout, fade-in animation, line wrapping, etc. +- Internal Structure: + - Nested item component: `AntdXPrompts.Item`. + - Events: `item_click` (triggered when a prompt item is clicked). +- Properties and Behavior: + - `items`: List of prompt items (array of dicts). + - Styles and layout: `prefix_cls`, `vertical`, `fade_in`, `fade_in_left`, `wrap`. + - Supports `additional_props`, `styles`, `class_names`, `root_class_name`. + - Does not expose standard API (`skip_api` is true). +- Event Handling: + - Maps click events to internal state updates (`bind_itemClick_event`) via `EventListener("item_click")`. + +```mermaid +classDiagram +class AntdXPrompts { ++Item : AntdXPromptsItem ++EVENTS : list ++SLOTS : list ++items : list[dict]|None ++prefix_cls : str|None ++title : str|None ++vertical : bool|None ++fade_in : bool|None ++fade_in_left : bool|None ++wrap : bool|None ++styles : dict|str|None ++class_names : dict|str|None ++root_class_name : str|None ++skip_api() : bool ++preprocess(payload) : None ++postprocess(value) : None ++example_payload() : Any ++example_value() : Any +} +class AntdXPromptsItem { ++... item-level properties and behavior ... +} +AntdXPrompts --> AntdXPromptsItem : "contains" +``` + +**Chart Sources** + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) +- [frontend/antdx/prompts/Index.svelte:1-71](file://frontend/antdx/prompts/Index.svelte#L1-L71) +- [frontend/antdx/prompts/prompts.tsx](file://frontend/antdx/prompts/prompts.tsx) +- [frontend/antdx/prompts/context.ts](file://frontend/antdx/prompts/context.ts) + +### Component Rendering and Event Binding Flow + +The following sequence diagram shows how backend components bind events and render components through frontend renderers. + +```mermaid +sequenceDiagram +participant Backend as "Backend Component" +participant Renderer as "Svelte Renderer" +participant Frontend as "TSX Component" +Backend->>Renderer : "Pass component properties and event configuration" +Renderer->>Frontend : "Dynamically import and render" +Frontend-->>Renderer : "Register event listeners (e.g., item_click)" +Renderer-->>Backend : "Event callbacks take effect" +``` + +**Chart Sources** + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-23](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L23) +- [frontend/antdx/prompts/Index.svelte:10-71](file://frontend/antdx/prompts/Index.svelte#L10-L71) + +## Dependency Analysis + +- Component Base Class and Utilities: + - All components inherit from `ModelScopeLayoutComponent`, uniformly handling visibility, element ID/classes, styles, and render switches. + - Frontend directory resolution is done via `resolve_frontend_dir`, ensuring correct mapping between Python backend and Svelte frontend. +- Inter-component Coupling: + - The Welcome and Prompts components are independent UI components with no direct dependency on each other. + - The Prompts component's internal item component interacts with the context, but is still exposed externally as a whole component. + +```mermaid +graph LR +Base["ModelScopeLayoutComponent
Component Base Class"] --> Welcome["AntdXWelcome"] +Base --> Prompts["AntdXPrompts"] +Resolve["resolve_frontend_dir
Frontend Directory Resolution"] --> Welcome +Resolve --> Prompts +``` + +**Chart Sources** + +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:55-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L55-L55) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:70-70](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L70-L70) + +**Section Sources** + +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:55-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L55-L55) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:70-70](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L70-L70) + +## Performance Considerations + +- Rendering Strategy + - Components are rendered via dynamic import, avoiding first-screen blocking and improving initial load performance. +- Event Binding + - Events are only bound when needed, and unnecessary re-renders are reduced through internal state updates. +- Resource Handling + - Static resources such as icons are handled via `serve_static_file`; caching and preloading are recommended for optimizing user experience. + +[This section provides general guidance and requires no specific file sources] + +## Troubleshooting Guide + +- Component Not Displaying + - Check whether `visible`, `elem_id`, `elem_classes`, `elem_style` are correctly set. + - Confirm the render switch `render` is true. +- Slot Content Not Taking Effect + - Confirm slot names match the component's supported `SLOTS` list (Welcome: `extra`, `icon`, `description`, `title`; Prompts: `title`, `items`). +- Event Not Firing + - Confirm event listeners are correctly configured (Prompts component's `item_click`). +- Icon or Static Resources Cannot Load + - Confirm the `icon` path is valid and `serve_static_file` is working properly. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:14-15](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L14-L15) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:25-26](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L25-L26) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-23](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L23) + +## Conclusion + +AntdXWelcome and AntdXPrompts serve as the core components for "welcome onboarding" and "prompt guidance" respectively in ModelScope Studio. The former achieves flexible welcome page display through slots and static resources; the latter provides efficient prompt word guidance through item click events and layout configuration. Both use dynamic rendering and event binding mechanisms, with good extensibility and maintainability. Combined with the type definitions, interface specifications, and best practices provided in this document, developers can quickly build consistent and smooth first-time experience and prompt guidance flows in AI applications. + +[This section is a summary and requires no specific file sources] + +## Appendix + +### TypeScript Type Definitions and Interface Specifications + +- Welcome Component (AntdXWelcome) + - Supported Properties: `additional_props`, `extra`, `icon`, `styles`, `class_names`, `description`, `variant`, `title`, `root_class_name`, `as_item`, `visible`, `elem_id`, `elem_classes`, `elem_style`, `render`. + - Slots: `extra`, `icon`, `description`, `title`. + - Events: None. + - Lifecycle Hooks: `preprocess`/`postprocess`/`example_payload`/`example_value` return null. +- Prompts Component (AntdXPrompts) + - Supported Properties: `items`, `prefix_cls`, `title`, `vertical`, `fade_in`, `fade_in_left`, `wrap`, `styles`, `class_names`, `root_class_name`, `additional_props`, `as_item`, `visible`, `elem_id`, `elem_classes`, `elem_style`, `render`. + - Slots: `title`, `items`. + - Events: `item_click` (triggered when a prompt item is clicked). + - Lifecycle Hooks: `preprocess`/`postprocess`/`example_payload`/`example_value` return null. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:17-54](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L17-L54) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:14-15](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L14-L15) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:61-69](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L61-L69) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:28-68](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L28-L68) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:25-26](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L25-L26) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:76-87](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L76-L87) + +### Integration with Conversation Systems + +- The Prompts component can serve as a guidance layer before conversation input; after the user clicks a prompt item, the upper-level business logic injects the prompt content into the conversation input field or directly initiates a conversation request. +- The Welcome component can serve as the entry point hint for a conversation session, deciding whether to display it based on context state. + +[This section is a conceptual explanation and requires no specific file sources] + +### Best Practices + +- Welcome Component + - Use slots to organize title, description, and icon for clear visual hierarchy. + - For multilingual scenarios, pass `title` and `description` through an external copy management module. +- Prompts Component + - Set `vertical`, `fade_in`, `fade_in_left`, `wrap` appropriately to adapt to different screen sizes and interaction paces. + - Provide clear semantic labels for each prompt item to facilitate accessibility and SEO. +- Event Handling + - Perform the minimum necessary operations in the `item_click` callback (such as writing the prompt content to the input field) to avoid blocking the UI. +- State Management + - Decouple the visibility of the Prompts collection from the current conversation state, allowing reuse across different pages or views. + +[This section provides general guidance and requires no specific file sources] diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Confirmation Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Confirmation Components API.md new file mode 100644 index 00000000..2fb63a41 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Confirmation Components API.md @@ -0,0 +1,331 @@ +# Confirmation Components API + + +**Files Referenced in This Document** +- [thought_chain/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py) +- [think/__init__.py](file://backend/modelscope_studio/components/antdx/think/__init__.py) +- [thought-chain.tsx](file://frontend/antdx/thought-chain/thought-chain.tsx) +- [think.tsx](file://frontend/antdx/think/think.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Ant Design X Confirmation Components API reference for ModelScope Studio, focusing on the complete interface and behavioral specifications of the ThoughtChain component and the Think component. Content includes: + +- Component property, event, and slot definitions +- Visualization and node management mechanisms for the thinking process +- Confirmation flow control and state management +- Integration recommendations for AI reasoning processes and decision display scenarios +- TypeScript type and interface specifications +- Best practices and common issue troubleshooting + +## Project Structure + +Ant Design X components are wrapped by Python component packages on the backend and bridged to the native `@ant-design/x` implementation on the frontend via Svelte/React hybrid bridging. Core file organization: + +- Backend Python wrapper: Located under `backend/modelscope_studio/components/antdx`, providing Python component classes for ThoughtChain and Think respectively +- Frontend implementation: Located under `frontend/antdx`, providing TSX implementations for `thought-chain` and `think` respectively + +```mermaid +graph TB +subgraph "Backend" +PY_TC["AntdXThoughtChain
Python Component"] +PY_TH["AntdXThink
Python Component"] +end +subgraph "Frontend" +FE_TC["ThoughtChain
TSX Implementation"] +FE_TH["Think
TSX Implementation"] +end +subgraph "Third-Party Libraries" +ADX["@ant-design/x
Native Component Library"] +end +PY_TC --> FE_TC +PY_TH --> FE_TH +FE_TC --> ADX +FE_TH --> ADX +``` + +Chart Sources + +- [thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +Section Sources + +- [thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +## Core Components + +This section provides an overview of the responsibilities and capability boundaries of the two core components: + +- ThoughtChain: Used to visually display a sequence of reasoning or decision-making nodes in tree/list form, supporting expand/collapse, connector styles, and node collection management +- Think: Used to encapsulate a single thought unit, supporting title, icon, loading state, and expandable state, with slot extension points + +Section Sources + +- [thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) + +## Architecture Overview + +The diagram below shows the call chain from backend Python components to frontend TSX implementations to `@ant-design/x` native components. + +```mermaid +sequenceDiagram +participant PyTC as "Backend : AntdXThoughtChain" +participant PyTH as "Backend : AntdXThink" +participant FETC as "Frontend : ThoughtChain" +participant FETH as "Frontend : Think" +participant ADX as "@ant-design/x" +PyTC->>FETC : Render ThoughtChain component +FETC->>ADX : Render using XThoughtChain +PyTH->>FETH : Render Think component +FETH->>ADX : Render using XThink +``` + +Chart Sources + +- [thought_chain/**init**.py:68-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L68-L86) +- [think/**init**.py:61-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L61-L79) +- [thought-chain.tsx:11-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L43) +- [think.tsx:6-24](file://frontend/antdx/think/think.tsx#L6-L24) + +## Detailed Component Analysis + +### ThoughtChain Component + +- Component Purpose: Used to present "thought chain"-style data flows or decision sequences, supporting node collections (`items`), expanded keys (`expanded_keys`), default expanded keys (`default_expanded_keys`), connector styles (`line`), etc. +- Slots: Supports `items` slot for injecting node collections +- Events: `expand` event, triggered when expanded keys change +- Property Notes: + - `expanded_keys` / `default_expanded_keys`: Control node expand state + - `items`: Node data collection, can be passed via slot or property + - `line`: Connector style, supports boolean values and specific string enumerations + - `prefix_cls` / `styles` / `class_names` / `root_class_name`: Style and class name customization + - Other general properties: `visible`, `elem_id`, `elem_classes`, `elem_style`, `render`, etc. + +```mermaid +classDiagram +class AntdXThoughtChain { ++expanded_keys : list[str] | None ++default_expanded_keys : list[str] | None ++items : list[dict] | None ++line : bool | "solid" | "dashed" | "dotted" | None ++prefix_cls : str | None ++additional_props : dict | None ++styles : dict | str | None ++class_names : dict | str | None ++root_class_name : str | None ++EVENTS : ["expand"] ++SLOTS : ["items"] ++FRONTEND_DIR ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +``` + +Chart Sources + +- [thought_chain/**init**.py:30-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L30-L86) + +Section Sources + +- [thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [thought-chain.tsx:11-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L43) + +### Think Component + +- Component Purpose: Used to encapsulate a single thought unit, supporting title (`title`), icon (`icon`), loading state (`loading`), default expanded (`default_expanded`), current expanded (`expanded`), and blink (`blink`), etc. +- Slots: Supports `loading`, `icon`, and `title` slots for custom rendering +- Events: `expand` event, for expanded state change notifications +- Property Notes: + - `icon` / `title` / `loading`: Basic display properties + - `default_expanded` / `expanded`: Expand state control + - `blink`: Visual indicator + - Other general properties: `visible`, `elem_id`, `elem_classes`, `elem_style`, `render`, etc. + +```mermaid +classDiagram +class AntdXThink { ++additional_props : dict | None ++icon : str | None ++styles : dict | str | None ++class_names : dict | str | None ++loading : str | bool | None ++title : str | None ++root_class_name : str | None ++default_expanded : bool | None ++expanded : bool | None ++blink : bool | None ++EVENTS : ["expand"] ++SLOTS : ["loading","icon","title"] ++FRONTEND_DIR ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +``` + +Chart Sources + +- [think/**init**.py:21-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L21-L79) + +Section Sources + +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [think.tsx:6-24](file://frontend/antdx/think/think.tsx#L6-L24) + +### Frontend Implementation and Slot Mechanism + +- The ThoughtChain frontend implementation reads slot `items`/`default` via context and clones nodes when necessary to avoid side effects; finally passes the parsed `items` to `@ant-design/x`'s `XThoughtChain` +- The Think frontend implementation injects `slots.loading`/`icon`/`title` into `@ant-design/x`'s `XThink` via `ReactSlot`; falls back to property values if no slot is provided + +```mermaid +flowchart TD +Start(["Enter ThoughtChain Render"]) --> ReadSlot["Read slots items/default"] +ReadSlot --> HasItems{"Does slot items exist and is non-empty?"} +HasItems -- Yes --> UseItems["Use slot items"] +HasItems -- No --> UseDefault["Use slot default"] +UseItems --> Clone["Optional: clone nodes"] +UseDefault --> Clone +Clone --> RenderADX["Render XThoughtChain with items"] +RenderADX --> End(["Done"]) +``` + +Chart Sources + +- [thought-chain.tsx:14-39](file://frontend/antdx/thought-chain/thought-chain.tsx#L14-L39) + +Section Sources + +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [think.tsx:6-24](file://frontend/antdx/think/think.tsx#L6-L24) + +## Dependency Analysis + +- Backend Python components are only responsible for declaring properties, events, slots, and frontend directory mappings; they do not directly handle business logic +- Frontend TSX components are responsible for: + - Parsing slots and properties, merging them into the props required by `@ant-design/x` + - Bridging to the React ecosystem via `sveltify` +- Third-party library `@ant-design/x` provides the actual UI behavior and styles + +```mermaid +graph LR +PY["Backend Python Component"] --> FE["Frontend TSX Component"] +FE --> ADX["@ant-design/x"] +``` + +Chart Sources + +- [thought_chain/**init**.py:68-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L68-L86) +- [think/**init**.py:61-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L61-L79) +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +Section Sources + +- [thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +## Performance Considerations + +- Node Cloning: The frontend clones slot nodes when necessary to avoid side effects from shared references, but this increases memory and computation overhead. Use with caution when the number of nodes is large +- Slot Parsing: Prioritize using the `items` slot, falling back to the `default` slot, to reduce unnecessary property passing +- Expand State: Set `expanded_keys`/`default_expanded_keys` appropriately to avoid expanding too many nodes at once, which causes rendering pressure +- Loading State: The Think component's `loading` slot/property should be enabled on demand to avoid redundant animations and DOM structure + +## Troubleshooting Guide + +- Slot Not Taking Effect + - Check whether the `items`/`default` slot is used correctly; confirm slot name casing and ordering + - If using the `items` property, ensure the type matches `@ant-design/x`'s expectations +- Expand Event Not Working + - Confirm the `expand` event is bound; check whether `bind_expand_event` or related state is updated in the callback +- Loading State and Slot Conflict + - When a `loading` slot is provided, the slot takes priority over the property; if no slot is provided, it falls back to the property value +- Styles and Class Names + - To override styles, prefer using `styles`/`class_names`/`root_class_name`; watch for conflicts with the third-party library's default styles + +Section Sources + +- [thought-chain.tsx:14-39](file://frontend/antdx/thought-chain/thought-chain.tsx#L14-L39) +- [think.tsx:10-17](file://frontend/antdx/think/think.tsx#L10-L17) +- [thought_chain/**init**.py:20-25](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L20-L25) +- [think/**init**.py:12-16](file://backend/modelscope_studio/components/antdx/think/__init__.py#L12-L16) + +## Conclusion + +- ThoughtChain and Think components provide a stable foundation for visualizing AI reasoning and decision-making processes through their clear property, event, and slot design +- For large-scale node scenarios, it is recommended to optimize slot usage and expand strategies, combining loading states and style customization to enhance the user experience +- Through `expand` events and expand state control, interactive confirmation flows and step-by-step displays can be implemented + +## Appendix + +### API Specifications and Type Definitions (Based on Source Code) + +- AntdXThoughtChain + - Properties + - `expanded_keys`: List, node expand keys + - `default_expanded_keys`: List, initial expand keys + - `items`: List, node data + - `line`: Boolean or specific string, connector style + - `prefix_cls`: String, prefix class name + - `additional_props`/`styles`/`class_names`/`root_class_name`: Style and class name customization + - `visible`/`elem_id`/`elem_classes`/`elem_style`/`render`: General properties + - Events + - `expand`: Expand key change callback + - Slots + - `items`: Node collection +- AntdXThink + - Properties + - `icon`/`title`/`loading`: Icon, title, loading state + - `default_expanded`/`expanded`: Default/current expand state + - `blink`: Blink effect + - `styles`/`class_names`/`root_class_name`: Style and class name customization + - `visible`/`elem_id`/`elem_classes`/`elem_style`/`render`: General properties + - Events + - `expand`: Expand state change callback + - Slots + - `loading`/`icon`/`title`: Slot alternatives to the corresponding properties + +Section Sources + +- [thought_chain/**init**.py:30-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L30-L86) +- [think/**init**.py:21-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L21-L79) + +### Integration and Best Practices + +- Reasoning Process Visualization + - Use ThoughtChain to display multi-step reasoning/decision sequences; each Think represents a single thought unit + - Control step-by-step display via `expand`, combined with the `loading` slot to indicate thinking in progress +- User Understanding Optimization + - Use the `line` connector style and `prefix_cls` appropriately to enhance hierarchical sense + - Use `icon`/`title` in Think to clarify roles and intent; use `blink` when attention is needed +- State Management and Flow Control + - Manage node expansion via `expanded_keys`/`default_expanded_keys`; drive subsequent steps via `expand` events + - For long chains, consider pagination/segmented loading to avoid rendering too many nodes at once diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Expression Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Expression Components API.md new file mode 100644 index 00000000..0c2f2b76 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Expression Components API.md @@ -0,0 +1,344 @@ +# Expression Components API + + +**Files Referenced in This Document** +- [frontend/antdx/attachments/Index.svelte](file://frontend/antdx/attachments/Index.svelte) +- [frontend/antdx/attachments/attachments.tsx](file://frontend/antdx/attachments/attachments.tsx) +- [frontend/antdx/sender/Index.svelte](file://frontend/antdx/sender/Index.svelte) +- [frontend/antdx/sender/sender.tsx](file://frontend/antdx/sender/sender.tsx) +- [frontend/antdx/suggestion/Index.svelte](file://frontend/antdx/suggestion/Index.svelte) +- [frontend/antdx/suggestion/suggestion.tsx](file://frontend/antdx/suggestion/suggestion.tsx) +- [frontend/antdx/suggestion/context.ts](file://frontend/antdx/suggestion/context.ts) +- [frontend/antdx/file-card/base.tsx](file://frontend/antdx/file-card/base.tsx) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/utils/hooks/useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [docs/components/antdx/attachments/README.md](file://docs/components/antdx/attachments/README.md) +- [docs/components/antdx/sender/README.md](file://docs/components/antdx/sender/README.md) +- [docs/components/antdx/suggestion/README.md](file://docs/components/antdx/suggestion/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for Ant Design X Expression Components in ModelScope Studio, focusing on the following three components: + +- Attachments Component: For displaying and uploading files/images and other attachments in multimodal input +- Sender Component: For chat message input, quick command triggering, and paste upload +- Suggestion Component: For providing selectable suggestion items within an input field + +The document covers component property interfaces, event callbacks, data binding, state synchronization, TypeScript type definitions, integration with the chat system, and best practices for multimodal data processing and user input optimization. + +## Project Structure + +- Components are organized with a Svelte wrapper layer (`Index.svelte`) + React implementation layer (`*.tsx`), bridging Ant Design X React components as Svelte components via `svelte-preprocess-react`. +- The Attachments component supports custom placeholder images, preview containers, icon rendering, list item rendering, and other slot extensions; the Sender component supports prefix/suffix/header/footer slots, skill panels, and paste upload; the Suggestion component supports dynamic item rendering and keyboard trigger control. + +```mermaid +graph TB +subgraph "Svelte Wrapper Layer" +A_Index["attachments/Index.svelte"] +B_Index["sender/Index.svelte"] +C_Index["suggestion/Index.svelte"] +end +subgraph "React Implementation Layer" +A_Impl["attachments.tsx"] +B_Impl["sender.tsx"] +C_Impl["suggestion.tsx"] +end +A_Index --> A_Impl +B_Index --> B_Impl +C_Index --> C_Impl +``` + +Chart Sources + +- [frontend/antdx/attachments/Index.svelte:1-98](file://frontend/antdx/attachments/Index.svelte#L1-L98) +- [frontend/antdx/sender/Index.svelte:1-102](file://frontend/antdx/sender/Index.svelte#L1-L102) +- [frontend/antdx/suggestion/Index.svelte:1-75](file://frontend/antdx/suggestion/Index.svelte#L1-L75) +- [frontend/antdx/attachments/attachments.tsx:1-413](file://frontend/antdx/attachments/attachments.tsx#L1-L413) +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) +- [frontend/antdx/suggestion/suggestion.tsx:1-165](file://frontend/antdx/suggestion/suggestion.tsx#L1-L165) + +Section Sources + +- [frontend/antdx/attachments/Index.svelte:1-98](file://frontend/antdx/attachments/Index.svelte#L1-L98) +- [frontend/antdx/sender/Index.svelte:1-102](file://frontend/antdx/sender/Index.svelte#L1-L102) +- [frontend/antdx/suggestion/Index.svelte:1-75](file://frontend/antdx/suggestion/Index.svelte#L1-L75) + +## Core Components + +- Attachments Component + - Responsibility: Display and manage attachment lists, supporting drag-and-drop/click upload, count limits, placeholder images, preview configuration, custom rendering, and icon slots. + - Key Properties: `items`, `maxCount`, `placeholder`, `imageProps`, `showUploadList`, `beforeUpload`, `customRequest`, `isImageUrl`, `itemRender`, `iconRender`, `getDropContainer`, `progress`, `onChange`/`onValueChange`, `upload`. + - Data Flow: Receives `items` and maintains a local `fileList`; `onChange`/`onValueChange` syncs external values; the `upload` callback handles file uploading and backfills `uid`. +- Sender Component + - Responsibility: Chat input field supporting text input, paste upload, quick command panel, prefix/suffix and header/footer slots, submission interception, and coordination. + - Key Properties: `value`, `onValueChange`, `onChange`, `onSubmit`, `suffix`/`header`/`prefix`/`footer`, `skill`, `slotConfig`, `onPasteFile`, `upload`. + - Data Flow: Uses `useValueChange` to sync external `value`; when the quick command panel is open, `onSubmit` is not triggered; when pasting files, file path arrays are obtained via `upload`. +- Suggestion Component + - Responsibility: Provides selectable suggestion items within an input field, supporting dynamic `items` rendering, slot extensions, keyboard trigger control, and popup container configuration. + - Key Properties: `items`, `open`, `onOpenChange`, `getPopupContainer`, `shouldTrigger`, `children` slot. + - Data Flow: Maintains `open` state internally; merges `items` from slots and props; shares state with subtree via `SuggestionOpenContext`. + +Section Sources + +- [frontend/antdx/attachments/attachments.tsx:36-410](file://frontend/antdx/attachments/attachments.tsx#L36-L410) +- [frontend/antdx/sender/sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) +- [frontend/antdx/suggestion/suggestion.tsx:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) + +## Architecture Overview + +The diagram below shows the bridging relationship and data flow between the three components across Svelte and React layers. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Wrapper Layer" +participant ReactImpl as "React Implementation Layer" +participant Gradio as "Gradio Client" +Svelte->>ReactImpl : Pass props/slots/callbacks +ReactImpl->>ReactImpl : useFunction/useValueChange handles function and value sync +ReactImpl->>Gradio : upload callback for file upload +Gradio-->>ReactImpl : Returns FileData list +ReactImpl-->>Svelte : Triggers onValueChange/onChange +Svelte-->>Svelte : updateProps updates value +``` + +Chart Sources + +- [frontend/antdx/attachments/Index.svelte:77-92](file://frontend/antdx/attachments/Index.svelte#L77-L92) +- [frontend/antdx/sender/Index.svelte:71-78](file://frontend/antdx/sender/Index.svelte#L71-L78) +- [frontend/antdx/attachments/attachments.tsx:329-348](file://frontend/antdx/attachments/attachments.tsx#L329-L348) +- [frontend/antdx/sender/sender.tsx:135-138](file://frontend/antdx/sender/sender.tsx#L135-L138) + +## Detailed Component Analysis + +### Attachments Component + +- Types and Interfaces + - Exported types: Based on `@ant-design/x`'s `AttachmentsProps`, with additional declarations for `onValueChange`, `onChange`, `upload`, `items`, etc. + - Supported slot keys: `showUploadList.extra`, `showUploadList.previewIcon`, `showUploadList.removeIcon`, `showUploadList.downloadIcon`, `iconRender`, `itemRender`, `placeholder`, `placeholder.title`, `placeholder.description`, `placeholder.icon`, `imageProps.placeholder`, `imageProps.preview.mask`, `imageProps.preview.closeIcon`, `imageProps.preview.toolbarRender`, `imageProps.preview.imageRender`. +- Upload Flow + - In `onChange`, distinguishes between add/remove operations: on add, executes `beforeUpload` first, then calls `upload` to get `FileData`, merges into `fileList`, and finally triggers `onValueChange`. + - On remove, if not currently uploading, triggers `onRemove` and updates the value. +- Configuration Notes + - `maxCount` controls single/multi-file upload strategy. + - `imageProps.preview` supports custom `mask`/`closeIcon`/`toolbarRender`/`imageRender`, or completely disables preview. + - `placeholder` supports object-based configuration combined with slots. + - `showUploadList` supports object-based configuration combined with slots, injecting `downloadIcon`/`removeIcon`/`previewIcon`/`extra` separately. +- Events and State + - `onValueChange`: Returns `FileData[]`, for external value binding. + - `onChange`: Returns string path arrays, for downstream processing by path. + - `upload`: `Promise<(FileData|null)[]>`, must preserve the original file `uid` for subsequent matching. + +```mermaid +flowchart TD +Start(["Start"]) --> Change["Listen to onChange event"] +Change --> IsRemove{"Is this a remove operation?"} +IsRemove --> |Yes| RemoveLogic["Trigger onRemove
Update fileList
Trigger onValueChange/onChange"] +IsRemove --> |No| AddLogic["Execute beforeUpload
Check maxCount and upload status
Call upload to get FileData
Merge into fileList
Trigger onValueChange/onChange"] +RemoveLogic --> End(["End"]) +AddLogic --> End +``` + +Chart Sources + +- [frontend/antdx/attachments/attachments.tsx:275-354](file://frontend/antdx/attachments/attachments.tsx#L275-L354) + +Section Sources + +- [frontend/antdx/attachments/attachments.tsx:36-410](file://frontend/antdx/attachments/attachments.tsx#L36-L410) +- [frontend/antdx/attachments/Index.svelte:72-92](file://frontend/antdx/attachments/Index.svelte#L72-L92) + +### Sender Component + +- Types and Interfaces + - Exported types: Based on `@ant-design/x`'s `SenderProps`, with additional declarations for `onValueChange`, `upload`, `onPasteFile`, etc. + - Slot keys: `suffix`, `header`, `prefix`, `footer`, `skill.title`, `skill.toolTip.title`, `skill.closable.closeIcon`. + - `slotConfig`: Supports `formatResult`/`customRender` function wrapping. +- Submission Flow + - `onSubmit` is intercepted: when the quick command panel is open, submission is blocked to avoid accidental triggers. + - `onChange` syncs the internal `value` and triggers the external `onChange`. +- Paste Upload + - `onPasteFile`: Reads clipboard files, calls `upload` to get a `FileData` array, and passes the path array back to `onPasteFile`. +- Events and State + - `onValueChange`: When the external `value` changes, `useValueChange` syncs the internal state. + - `onChange`: Real-time change notification. + - `upload`: `Promise`, used for paste upload and external extensions. + +```mermaid +sequenceDiagram +participant User as "User" +participant Sender as "Sender" +participant Sugg as "Suggestion" +participant Gradio as "Gradio Client" +User->>Sender : Input / paste file +Sender->>Sugg : Check open state +alt Quick command panel is open +Sender-->>User : Block onSubmit +else Quick command panel is closed +Sender->>Gradio : Call upload(files) +Gradio-->>Sender : Returns FileData[] +Sender-->>User : Trigger onPasteFile(paths) +end +``` + +Chart Sources + +- [frontend/antdx/sender/sender.tsx:126-138](file://frontend/antdx/sender/sender.tsx#L126-L138) +- [frontend/antdx/suggestion/suggestion.tsx:135-140](file://frontend/antdx/suggestion/suggestion.tsx#L135-L140) + +Section Sources + +- [frontend/antdx/sender/sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) +- [frontend/antdx/sender/Index.svelte:71-78](file://frontend/antdx/sender/Index.svelte#L71-L78) + +### Suggestion Component + +- Types and Interfaces + - Exported types: Based on `@ant-design/x`'s `SuggestionProps`, with additional `shouldTrigger` and `children` slot declarations. + - Internal context: `SuggestionContext`/`SuggestionOpenContext`, passes trigger logic and `open` state to the subtree. + - Context items: `withItemsContextProvider` injects `items`/`default`, supporting merging of slots and props. +- Trigger Mechanism + - `shouldTrigger`: Allows custom keyboard event trigger logic, combined with `onTrigger`/`onKeyDown`. + - `open`/`onOpenChange`: Controlled/uncontrolled mode switching, defaults to `false` internally. +- Slots and Rendering + - `children` slot: Acts as the render container, rendered with `ReactSlot`. + - `items`: Supports functional and static arrays; internally extends sub-item `extra`/`icon`/`label`, etc. via `renderItems`/`patchSlots`. + +```mermaid +classDiagram +class SuggestionContext { ++onKeyDown(e) ++onTrigger(...) ++elRef +} +class SuggestionOpenContext { ++open : boolean +} +class ItemsContext { ++items : SuggestionItem[] +} +SuggestionContext --> ItemsContext : "shared items/default" +SuggestionOpenContext --> SuggestionContext : "influences trigger behavior" +``` + +Chart Sources + +- [frontend/antdx/suggestion/suggestion.tsx:22-62](file://frontend/antdx/suggestion/suggestion.tsx#L22-L62) +- [frontend/antdx/suggestion/suggestion.tsx:131-160](file://frontend/antdx/suggestion/suggestion.tsx#L131-L160) +- [frontend/antdx/suggestion/context.ts:1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) + +Section Sources + +- [frontend/antdx/suggestion/suggestion.tsx:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) +- [frontend/antdx/suggestion/context.ts:1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) + +## Dependency Analysis + +- Component Bridging + - The Svelte wrapper layer dynamically loads the React implementation layer via `importComponent`, uniformly handling props, slots, and callbacks. + - Uses `processProps` to map camelCase names to React-expected property names (e.g., `keyPress` → `keyPress`). +- Utilities and Hooks + - `useFunction`: Converts incoming functions/slots to stable functions, avoiding re-renders. + - `useValueChange`: Maintains value synchronization between controlled and uncontrolled modes, ensuring external `value` changes correctly reflect in internal state. +- File Processing + - `BaseFileCard`: Uniformly parses file `src`, supporting strings and `FileData`, and automatically concatenates accessible URLs. + - The Attachments component internally handles compatibility between `FileData` and `UploadFile`, ensuring `uid` consistency. + +```mermaid +graph LR +Svelte["Svelte Wrapper Layer"] --> Hooks["Utility Hooks
useFunction/useValueChange"] +Svelte --> Impl["React Implementation Layer"] +Impl --> ADX["@ant-design/x Components"] +Impl --> Utils["BaseFileCard/Upload Utilities"] +Hooks --> Impl +``` + +Chart Sources + +- [frontend/antdx/attachments/Index.svelte:28-56](file://frontend/antdx/attachments/Index.svelte#L28-L56) +- [frontend/antdx/sender/Index.svelte:35-66](file://frontend/antdx/sender/Index.svelte#L35-L66) +- [frontend/antdx/suggestion/Index.svelte:26-54](file://frontend/antdx/suggestion/Index.svelte#L26-L54) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [frontend/utils/hooks/useValueChange.ts:9-29](file://frontend/utils/hooks/useValueChange.ts#L9-L29) +- [frontend/antdx/file-card/base.tsx:15-41](file://frontend/antdx/file-card/base.tsx#L15-L41) + +Section Sources + +- [frontend/antdx/attachments/Index.svelte:28-56](file://frontend/antdx/attachments/Index.svelte#L28-L56) +- [frontend/antdx/sender/Index.svelte:35-66](file://frontend/antdx/sender/Index.svelte#L35-L66) +- [frontend/antdx/suggestion/Index.svelte:26-54](file://frontend/antdx/suggestion/Index.svelte#L26-L54) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [frontend/utils/hooks/useValueChange.ts:9-29](file://frontend/utils/hooks/useValueChange.ts#L9-L29) +- [frontend/antdx/file-card/base.tsx:15-41](file://frontend/antdx/file-card/base.tsx#L15-L41) + +## Performance Considerations + +- Slot and Functionalization + - Use `useFunction` to wrap props and slots, reducing unnecessary re-renders. + - Use `useMemo` and `useMemoizedEqualValue` to cache results for complex computations (such as `items` rendering). +- Upload State + - The Attachments component sets the `uploading` state during upload to prevent concurrent uploads and accidental deletions. + - Use `maxCount` and a temporary `fileList` to avoid excess uploads and UI jitter. +- Value Synchronization + - `useValueChange` only updates internal state when the external `value` changes, preventing circular updates. + +Section Sources + +- [frontend/antdx/attachments/attachments.tsx:122-132](file://frontend/antdx/attachments/attachments.tsx#L122-L132) +- [frontend/antdx/attachments/attachments.tsx:304-312](file://frontend/antdx/attachments/attachments.tsx#L304-L312) +- [frontend/antdx/sender/sender.tsx:68-72](file://frontend/antdx/sender/sender.tsx#L68-L72) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [frontend/utils/hooks/useValueChange.ts:9-29](file://frontend/utils/hooks/useValueChange.ts#L9-L29) + +## Troubleshooting Guide + +- Attachment Upload Failure + - Check whether the `upload` callback correctly returns `FileData[]` with `uid` matching the original files. + - Confirm the Gradio client upload path is consistent with the `rootUrl`/`apiPrefix` configuration. +- Quick Command Not Triggering + - Confirm `shouldTrigger` is set and works in coordination with the input field's `onKeyDown`/`onTrigger`. + - Check whether the `open` state is being overridden externally, or whether `SuggestionOpenContext` is being correctly passed. +- Sender Submission Intercepted + - If the quick command panel is open, `onSubmit` will be intercepted; close the panel or wait for it to close before submitting. +- Preview and Icons Not Displaying + - Check whether the slot keys for `imageProps.preview` and `showUploadList` are correctly configured. + - Ensure slot content is correctly rendered; use `ReactSlot` wrapping if necessary. + +Section Sources + +- [frontend/antdx/attachments/attachments.tsx:329-348](file://frontend/antdx/attachments/attachments.tsx#L329-L348) +- [frontend/antdx/suggestion/suggestion.tsx:135-140](file://frontend/antdx/suggestion/suggestion.tsx#L135-L140) +- [frontend/antdx/sender/sender.tsx:126-130](file://frontend/antdx/sender/sender.tsx#L126-L130) + +## Conclusion + +- The Attachments component provides comprehensive multimodal upload capabilities and flexible slot extensions, suitable for handling image/file multimedia input in chat scenarios. +- The Sender component integrates input, paste upload, and the quick command panel, offering good interaction consistency and controllability. +- The Suggestion component achieves a highly customizable suggestion experience through the context and slot system, adapting to various triggering and rendering requirements. +- It is recommended to use the Gradio client and `BaseFileCard` together in real applications to uniformly handle file paths, ensuring cross-module consistency and maintainability. + +## Appendix + +- Example and Documentation Entry Points + - Attachments component examples: see demo tab in the documentation directory + - Sender component examples: see demo tab in the documentation directory + - Suggestion component examples: see demo tab in the documentation directory + +Section Sources + +- [docs/components/antdx/attachments/README.md:1-9](file://docs/components/antdx/attachments/README.md#L1-L9) +- [docs/components/antdx/sender/README.md:1-10](file://docs/components/antdx/sender/README.md#L1-L10) +- [docs/components/antdx/suggestion/README.md:1-10](file://docs/components/antdx/suggestion/README.md#L1-L10) diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Feedback Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Feedback Components API.md new file mode 100644 index 00000000..eec901af --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Feedback Components API.md @@ -0,0 +1,395 @@ +# Feedback Components API + + +**Files Referenced in This Document** +- [frontend/antd/notification/notification.tsx](file://frontend/antd/notification/notification.tsx) +- [frontend/antd/notification/Index.svelte](file://frontend/antd/notification/Index.svelte) +- [frontend/antdx/notification/notification.tsx](file://frontend/antdx/notification/notification.tsx) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) +- [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- [frontend/antdx/actions/item/actions.item.tsx](file://frontend/antdx/actions/item/actions.item.tsx) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Ant Design X Feedback Components API reference for ModelScope Studio, focusing on two types of feedback capabilities: + +- Actions Component: Provides a set of clickable action items in conversations or workflows, supporting dropdown menus, sub-items, icons, and other extensions. +- Notification Component: For global notification messages and browser native notification permission management, covering both Ant Design and Ant Design X implementations. + +This document systematically covers interface definitions, data structures, event and state management, user interaction mechanisms, type specifications and best practices, and provides typical use cases and configuration recommendations for AI applications. + +## Project Structure + +Feedback components are primarily distributed in the following paths: + +- Frontend Ant Design implementation: `frontend/antd/notification` +- Frontend Ant Design X implementation: `frontend/antdx/notification` and `frontend/antdx/actions` +- Common utilities: `frontend/utils` — items context and rendering utilities + +```mermaid +graph TB +subgraph "Ant Design Implementation" +A1["antd/notification/notification.tsx"] +A2["antd/notification/Index.svelte"] +end +subgraph "Ant Design X Implementation" +B1["antdx/notification/notification.tsx"] +B2["antdx/actions/actions.tsx"] +B3["antdx/actions/context.ts"] +B4["antdx/actions/feedback/actions.feedback.tsx"] +B5["antdx/actions/action-item/actions.action-item.tsx"] +B6["antdx/actions/item/actions.item.tsx"] +end +subgraph "Common Utilities" +C1["utils/createItemsContext.tsx"] +C2["utils/renderItems.tsx"] +C3["utils/renderParamsSlot.tsx"] +C4["utils/renderSlot.tsx"] +end +A2 --> A1 +B2 --> B3 +B2 --> C1 +B2 --> C2 +B2 --> C3 +B2 --> C4 +B4 --> B2 +B5 --> B3 +B6 --> B2 +``` + +Chart Sources + +- [frontend/antd/notification/notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) +- [frontend/antd/notification/Index.svelte:56-79](file://frontend/antd/notification/Index.svelte#L56-L79) +- [frontend/antdx/notification/notification.tsx:1-51](file://frontend/antdx/notification/notification.tsx#L1-L51) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:1-16](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L1-L16) +- [frontend/antdx/actions/action-item/actions.action-item.tsx:1-23](file://frontend/antdx/actions/action-item/actions.action-item.tsx#L1-L23) +- [frontend/antdx/actions/item/actions.item.tsx:1-34](file://frontend/antdx/actions/item/actions.item.tsx#L1-L34) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) + +Section Sources + +- [frontend/antd/notification/notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) +- [frontend/antd/notification/Index.svelte:56-79](file://frontend/antd/notification/Index.svelte#L56-L79) +- [frontend/antdx/notification/notification.tsx:1-51](file://frontend/antdx/notification/notification.tsx#L1-L51) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:1-16](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L1-L16) +- [frontend/antdx/actions/action-item/actions.action-item.tsx:1-23](file://frontend/antdx/actions/action-item/actions.action-item.tsx#L1-L23) +- [frontend/antdx/actions/item/actions.item.tsx:1-34](file://frontend/antdx/actions/item/actions.item.tsx#L1-L34) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) + +## Core Components + +- Actions Component + - Responsible for rendering a set of interactive action items, supporting dropdown menus, sub-items, icon slots, and menu item context injection. + - Provides the `Actions.Feedback` sub-component to adapt to specific feedback scenarios. +- Notification Component + - Ant Design version: Based on `antd.notification.useNotification`, supports visibility control and slot rendering. + - Ant Design X version: Based on `@ant-design/x/notification`, with built-in browser notification permission requests and the ability to close by tag. + +Section Sources + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:1-16](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L1-L16) +- [frontend/antd/notification/notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) +- [frontend/antdx/notification/notification.tsx:1-51](file://frontend/antdx/notification/notification.tsx#L1-L51) + +## Architecture Overview + +The runtime architecture of feedback components consists of a "component bridge layer + notification/action library + rendering pipeline": + +- Component Bridge Layer: Wraps Svelte components as React components via `sveltify`, uniformly exposing properties and slots externally. +- Notification/Action Library: Connects to notification and action capabilities from both `antd` and `@ant-design/x`. +- Rendering Pipeline: Uses utilities such as `createItemsContext` and `renderItems` to convert DOM nodes from slots into a React component tree, supporting parameterized slots and cloning strategies. + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant Actions as "Actions Component" +participant ItemsCtx as "ItemsContext" +participant Renderer as "Rendering Pipeline" +participant XActions as "@ant-design/x Actions" +UI->>Actions : Pass items/dropdownProps/slots +Actions->>ItemsCtx : Inject context and collect slot items +Actions->>Renderer : Parse slots into React components +Renderer-->>Actions : Return renderable items +Actions->>XActions : Render as Ant Design X action list +XActions-->>UI : User interaction callbacks (onClick, etc.) +``` + +Chart Sources + +- [frontend/antdx/actions/actions.tsx:17-120](file://frontend/antdx/actions/actions.tsx#L17-L120) +- [frontend/utils/createItemsContext.tsx:97-274](file://frontend/utils/createItemsContext.tsx#L97-L274) +- [frontend/utils/renderItems.tsx:8-114](file://frontend/utils/renderItems.tsx#L8-L114) + +## Detailed Component Analysis + +### Actions Component API + +- Component Name: Actions +- Appearance: Ant Design X Actions component, supporting dropdown menus and multi-level sub-items. +- Key Properties (partial): + - `items`: Action item array, supporting default slot and sub-item slots. + - `dropdownProps`: Configuration passed through to the dropdown menu, including `dropdownRender`, `popupRender`, `menu`, etc. + - `slots`: Slot mapping, supporting `menu.expandIcon`, `menu.overflowedIndicator`, `menu.items`, etc. +- Slots and Context: + - Uses `createItemsContext` to maintain `default` and `items` slot item collections. + - Writes child nodes to the context via `ItemHandler`, supporting dynamic calculation of `itemProps`, `itemChildren`, etc. +- Rendering Flow: + - Merges external `items` with slot parsing results to generate the final menu items. + - Performs parameterized slot rendering for `dropdownRender`/`popupRender` and menu items. +- Typical Sub-components: + - `Actions.Feedback`: Directly forwards `@ant-design/x`'s `Actions.Feedback`. + - `Actions.Item`: Encapsulates slots for default icon and running icon. + - `ActionsActionItem`: A convenience wrapper for `ItemHandler`, restricting allowed slot keys. + +```mermaid +classDiagram +class Actions { ++props : ActionsProps ++slots : Record ++dropdownProps ++items +} +class ActionsItem { ++props : ActionsItemProps ++slots : defaultIcon, runningIcon +} +class ActionsFeedback { ++props : ActionsFeedbackProps +} +class ItemsContext { ++items : Record ++setItem() ++useItems() +} +class ItemHandler { ++itemIndex ++itemSlotKey ++allowedSlots ++itemChildrenKey +} +Actions --> ItemsContext : "collect/read" +Actions --> ItemHandler : "sub-item injection" +ActionsItem --> Actions : "as sub-item" +ActionsFeedback --> Actions : "sub-component" +``` + +Chart Sources + +- [frontend/antdx/actions/actions.tsx:17-120](file://frontend/antdx/actions/actions.tsx#L17-L120) +- [frontend/antdx/actions/item/actions.item.tsx:6-34](file://frontend/antdx/actions/item/actions.item.tsx#L6-L34) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:5-16](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L5-L16) +- [frontend/antdx/actions/context.ts:3-4](file://frontend/antdx/actions/context.ts#L3-L4) +- [frontend/antdx/actions/action-item/actions.action-item.tsx:7-20](file://frontend/antdx/actions/action-item/actions.action-item.tsx#L7-L20) + +Section Sources + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:1-16](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L1-L16) +- [frontend/antdx/actions/action-item/actions.action-item.tsx:1-23](file://frontend/antdx/actions/action-item/actions.action-item.tsx#L1-L23) +- [frontend/antdx/actions/item/actions.item.tsx:1-34](file://frontend/antdx/actions/item/actions.item.tsx#L1-L34) +- [frontend/utils/createItemsContext.tsx:20-95](file://frontend/utils/createItemsContext.tsx#L20-L95) +- [frontend/utils/renderItems.tsx:8-114](file://frontend/utils/renderItems.tsx#L8-L114) +- [frontend/utils/renderParamsSlot.tsx:5-51](file://frontend/utils/renderParamsSlot.tsx#L5-L51) +- [frontend/utils/renderSlot.tsx:13-29](file://frontend/utils/renderSlot.tsx#L13-L29) + +### Notification Component API + +- Ant Design Version (antd/notification) + - Property Notes: + - `visible`: Whether to show the notification. + - `onVisible`: Callback when closed, used to sync `visible` state. + - `notificationKey`: Unique identifier, used for `destroy`/`open`. + - Supported slots: `btn`, `actions`, `closeIcon`, `description`, `icon`, `message`. + - Behavior Mechanism: + - When `visible` is true, calls `open`; otherwise, `destroy`. + - In the `onClose` callback, triggers `onVisible(false)` first, then executes the user's custom `onClose`. +- Ant Design X Version (@ant-design/x/notification) + - Property Notes: + - `visible`: Whether to show the notification. + - `onVisible`: Callback when closed. + - `onPermission`: Browser notification permission change callback. + - `tag`: Notification tag, used for closing by tag. + - Behavior Mechanism: + - If not yet authorized before the first display, requests permission; only `open` when `granted`. + - When `visible` is true, `open`; otherwise, `close(tag)`. + - Automatically closes notifications with the corresponding `tag` when the component unmounts. + +```mermaid +sequenceDiagram +participant Caller as "Caller" +participant ANTD as "antd Notification" +participant XNOTI as "X Notification" +Caller->>ANTD : Set visible=true, pass message/description etc. +ANTD->>ANTD : useNotification initialization +ANTD->>ANTD : open({ key, message, description, ... }) +ANTD-->>Caller : onClose callback triggers onVisible(false) +Caller->>XNOTI : Set visible=true, pass tag/message +XNOTI->>XNOTI : useNotification gets permission +alt Not authorized +XNOTI->>XNOTI : requestPermission() +end +XNOTI->>XNOTI : open({ tag, message, onClose }) +XNOTI-->>Caller : onClose callback triggers onVisible(false) +``` + +Chart Sources + +- [frontend/antd/notification/notification.tsx:38-95](file://frontend/antd/notification/notification.tsx#L38-L95) +- [frontend/antdx/notification/notification.tsx:17-46](file://frontend/antdx/notification/notification.tsx#L17-L46) + +Section Sources + +- [frontend/antd/notification/notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) +- [frontend/antd/notification/Index.svelte:56-79](file://frontend/antd/notification/Index.svelte#L56-L79) +- [frontend/antdx/notification/notification.tsx:1-51](file://frontend/antdx/notification/notification.tsx#L1-L51) + +## Dependency Analysis + +- Actions and Rendering Toolchain + - Actions depends on `createItemsContext` to maintain the slot item collection. + - Uses `renderItems` to convert slot items into a React component tree, supporting the `children` key and `itemPropsTransformer`. + - `renderParamsSlot` and `renderSlot` support parameterized slots and cloning strategies. +- Actions and Menu Context + - Works with the `antd/menu` context; prioritizes `dropdownProps.menu.items` provided by the menu context. +- Notification and Permissions + - The X version has built-in permission requests and callbacks, avoiding duplicate requests. + - The ANTD version does not involve browser permissions; local notifications only. + +```mermaid +graph LR +Actions["Actions"] --> Ctx["createItemsContext"] +Actions --> RItems["renderItems"] +Actions --> RPSlot["renderParamsSlot"] +Actions --> RSlot["renderSlot"] +Actions --> MenuCtx["antd/menu context"] +XNoti["X Notification"] --> Perm["requestPermission/onPermission"] +ANoti["antd Notification"] --> Local["Local Notifications"] +``` + +Chart Sources + +- [frontend/antdx/actions/actions.tsx:10-15](file://frontend/antdx/actions/actions.tsx#L10-L15) +- [frontend/utils/createItemsContext.tsx:97-274](file://frontend/utils/createItemsContext.tsx#L97-L274) +- [frontend/utils/renderItems.tsx:8-114](file://frontend/utils/renderItems.tsx#L8-L114) +- [frontend/utils/renderParamsSlot.tsx:5-51](file://frontend/utils/renderParamsSlot.tsx#L5-L51) +- [frontend/utils/renderSlot.tsx:13-29](file://frontend/utils/renderSlot.tsx#L13-L29) +- [frontend/antdx/notification/notification.tsx:13-19](file://frontend/antdx/notification/notification.tsx#L13-L19) + +Section Sources + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/antdx/notification/notification.tsx:1-51](file://frontend/antdx/notification/notification.tsx#L1-L51) + +## Performance Considerations + +- Slot Rendering Optimization + - Use `useMemo` to wrap `dropdownProps` modifications, reducing unnecessary re-renders. + - `renderItems` supports `clone`/`forceClone` controls to avoid unnecessary React node rebuilding. +- Notification Lifecycle + - ANTD: Destroys the corresponding key when `visible` toggles, and also destroys on unmount to avoid memory leaks. + - X: Closes by tag when `visible=false` or on unmount, ensuring resource cleanup. +- Permission Request Debouncing + - The X version checks permissions before first open, avoiding duplicate requests. + +Section Sources + +- [frontend/antdx/actions/actions.tsx:39-96](file://frontend/antdx/actions/actions.tsx#L39-L96) +- [frontend/antd/notification/notification.tsx:74-95](file://frontend/antd/notification/notification.tsx#L74-L95) +- [frontend/antdx/notification/notification.tsx:17-46](file://frontend/antdx/notification/notification.tsx#L17-L46) + +## Troubleshooting Guide + +- Actions Sub-items Not Displaying + - Check slot keys: verify `default` and `subItems` match the `ItemHandler`'s `itemChildrenKey`. + - Confirm the return value logic of `allowedSlots` and `itemChildren` is consistent. +- Slot Not Taking Effect + - Confirm elements in `slots` have been correctly passed to `ItemHandler` or Actions's `slots`. + - For parameterized slots, confirm `renderParamsSlot`'s `targets` and `withParams` configuration. +- Notification Not Displaying + - ANTD: Confirm `visible` is true and `notificationKey` is unique; check whether `onVisible(false)` is called in `onClose`. + - X: Confirm browser notification permission is `granted`; check whether `tag` is correctly passed; check whether `onVisible(false)` is called in `onClose`. +- Performance Issues + - Check whether `dropdownProps` changes frequently; reuse object references or use `useMemo` as much as possible. + - Reduce unnecessary cloning; only enable `forceClone` when necessary. + +Section Sources + +- [frontend/antdx/actions/action-item/actions.action-item.tsx:11-19](file://frontend/antdx/actions/action-item/actions.action-item.tsx#L11-L19) +- [frontend/antdx/actions/context.ts:3-4](file://frontend/antdx/actions/context.ts#L3-L4) +- [frontend/utils/renderParamsSlot.tsx:23-49](file://frontend/utils/renderParamsSlot.tsx#L23-L49) +- [frontend/antd/notification/notification.tsx:38-95](file://frontend/antd/notification/notification.tsx#L38-L95) +- [frontend/antdx/notification/notification.tsx:17-46](file://frontend/antdx/notification/notification.tsx#L17-L46) + +## Conclusion + +- Actions transforms complex UI structures into composable and extensible action lists through slot and context mechanisms, suitable for carrying multi-step task and multi-turn conversation action feedback in AI applications. +- Notification provides unified visibility and lifecycle management on both the ANTD and X sides; the X version additionally supports browser notification permissions, meeting richer user feedback needs. +- It is recommended to choose the appropriate implementation version based on business semantics in real applications, and to follow slot and context best practices for stable and high-performance feedback experiences. + +## Appendix + +### Type and Interface Summary + +- Actions + - `ActionsProps`: From `@ant-design/x`, includes `items`, `dropdownProps`, etc. + - `ActionsItemProps`: Property collection for `Actions.Item`. + - `ActionsFeedbackProps`: Property collection for `Actions.Feedback`. +- Notification + - ANTD: `ArgsProps` and `NotificationConfig`, supporting `visible`, `onVisible`, slots, etc. + - X: `XNotificationOpenArgs`, supporting `visible`, `onVisible`, `onPermission`, `tag`, etc. + +Section Sources + +- [frontend/antdx/actions/actions.tsx:3-8](file://frontend/antdx/actions/actions.tsx#L3-L8) +- [frontend/antd/notification/notification.tsx:8-16](file://frontend/antd/notification/notification.tsx#L8-L16) +- [frontend/antdx/notification/notification.tsx:6-11](file://frontend/antdx/notification/notification.tsx#L6-L11) + +### Usage Scenarios and Best Practices + +- Action Feedback in AI Applications + - Use `Actions.Feedback` to quickly mount feedback-type actions. + - Use `Actions.Item` to customize icons and text, combined with slots for dynamic text and status indicators. + - For multi-level menus, use `subItems` and `allowedSlots` to manage hierarchy. +- Notification Timing Control + - ANTD: Use `visible` for precise show/hide control; use brief notifications for critical errors or success states. + - X: Enable for system-level alerts; note that permission requests only trigger on the first use, avoiding frequent interruptions. +- State Synchronization + - Uniformly set `onVisible(false)` in `onClose` to ensure UI and state consistency. + - For batch closures, use `tag` or `key` for precise targeting. diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/General Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/General Components API.md new file mode 100644 index 00000000..4ee600b7 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/General Components API.md @@ -0,0 +1,518 @@ +# General Components API + + +**Files Referenced in This Document** +- [bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [conversations.tsx](file://frontend/antdx/conversations/conversations.tsx) +- [prompts.tsx](file://frontend/antdx/prompts/prompts.tsx) +- [suggestion.tsx](file://frontend/antdx/suggestion/suggestion.tsx) +- [sender.tsx](file://frontend/antdx/sender/sender.tsx) +- [context.ts (suggestion item context)](file://frontend/antdx/suggestion/context.ts) +- [context.ts (conversation item context)](file://frontend/antdx/conversations/context.ts) +- [context.ts (prompt item context)](file://frontend/antdx/prompts/context.ts) +- [renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [createFunction.ts](file://frontend/utils/createFunction.ts) +- [patchSlots.ts](file://frontend/utils/patchSlots.ts) +- [useMemoizedEqualValue.ts](file://frontend/utils/hooks/useMemoizedEqualValue.ts) +- [react-slot.tsx](file://frontend/svelte-preprocess-react/react-slot.tsx) +- [react-contexts.ts](file://frontend/svelte-preprocess-react/react-contexts.ts) +- [sveltify.svelte.ts](file://frontend/svelte-preprocess-react/sveltify.svelte.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Ant Design X General Components API reference for ModelScope Studio. It focuses on the complete interface specifications and usage guides for the following core general components: + +- Bubble: Conversation bubble component, supports avatar, content, footer, extra actions, and other slots and render functions +- Conversations: Conversation list/group management, supports menus, group labels, overflow indicators, and other extensions +- Prompts: Prompt card collection, supports title slots and dynamic item rendering +- Suggestion: Quick commands/suggestion input, supports popup containers, trigger strategies, and sub-item slot patching +- Sender: Sender component, supports paste upload, skill panel, prefix/suffix/header/footer slots + +This document covers property definitions, event handling, slot systems, state management, message passing, and conversation flow control mechanisms. It also provides instantiation and configuration example paths for AI chat and conversation scenarios, TypeScript types and integration with Ant Design components, as well as performance optimization and best practices. + +## Project Structure + +Ant Design X general components are located in the `antdx` submodule of the frontend directory. They adopt a "Svelte wrapper + React component bridge" architecture: using `svelte-preprocess-react` to use `@ant-design/x` React components in a Svelte-compatible way, while providing a unified slot system and context injection capability. + +```mermaid +graph TB +subgraph "Ant Design X General Components" +B["Bubble
Bubble Component"] +C["Conversations
Conversation List/Groups"] +P["Prompts
Prompt Cards"] +S["Suggestion
Quick Commands/Suggestions"] +SD["Sender
Sender"] +end +subgraph "Utilities and Context" +U1["renderItems.tsx
Render Items Utility"] +U2["renderParamsSlot.tsx
Parameterized Slot Renderer"] +U3["useFunction.ts
Function Wrapper Hook"] +U4["useValueChange.ts
Value Change Hook"] +U5["createFunction.ts
Function Factory"] +U6["patchSlots.ts
Slot Patching"] +U7["react-slot.tsx
React Slot"] +U8["react-contexts.ts
React Contexts"] +U9["sveltify.svelte.ts
Svelte Wrapper"] +end +B --> U1 +B --> U2 +B --> U3 +B --> U7 +C --> U1 +C --> U2 +C --> U3 +C --> U8 +P --> U1 +P --> U2 +S --> U1 +S --> U2 +S --> U3 +S --> U6 +SD --> U1 +SD --> U2 +SD --> U3 +SD --> U4 +SD --> U5 +SD --> U7 +SD --> U8 +``` + +Chart Sources + +- [bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [suggestion.tsx:1-165](file://frontend/antdx/suggestion/suggestion.tsx#L1-L165) +- [sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) +- [renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [createFunction.ts](file://frontend/utils/createFunction.ts) +- [patchSlots.ts](file://frontend/utils/patchSlots.ts) +- [react-slot.tsx](file://frontend/svelte-preprocess-react/react-slot.tsx) +- [react-contexts.ts](file://frontend/svelte-preprocess-react/react-contexts.ts) +- [sveltify.svelte.ts](file://frontend/svelte-preprocess-react/sveltify.svelte.ts) + +Section Sources + +- [bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [suggestion.tsx:1-165](file://frontend/antdx/suggestion/suggestion.tsx#L1-L165) +- [sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +## Core Components + +This section provides an overview of the five core general components, their responsibilities and typical use cases, to help quickly locate specific implementations and example paths. + +- Bubble (Conversation Bubble) + - Supports avatar, content, header, footer, extra actions, editable text, loading state, and custom content rendering + - Slot keys: `avatar`, `content`, `header`, `footer`, `extra`, `editable.okText`, `editable.cancelText`, `loadingRender`, `contentRender` + - Typical use cases: User/system message display, editable replies, async loading states + +- Conversations (Conversation Management) + - Supports conversation item lists, grouping, menus, overflow indicators, expand icons, and triggers + - Slot keys: `menu.items`, `menu.trigger`, `menu.expandIcon`, `menu.overflowedIndicator`, `groupable.label` + - Typical use cases: Historical conversation browsing, group collapsing, right-click menu operations + +- Prompts (Prompt Collection) + - Supports prompt card title slots and dynamic item rendering + - Slot keys: `title` + - Typical use cases: Chat guidance, quick prompts, templated input + +- Suggestion (Quick Commands) + - Supports suggestion item lists, sub-item slot patching, popup containers, open state, and keyboard trigger strategies + - Slot keys: `children` + - Typical use cases: @mentions, /commands, quick suggestions + +- Sender (Sender) + - Supports paste upload, skill panel, prefix/suffix/header/footer slots, value change, and submission interception + - Slot keys: `suffix`, `header`, `prefix`, `footer`, `skill.title`, `skill.toolTip.title`, `skill.closable.closeIcon` + - Typical use cases: Text input, file paste upload, skill toggles + +Section Sources + +- [bubble.tsx:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) +- [conversations.tsx:59-175](file://frontend/antdx/conversations/conversations.tsx#L59-L175) +- [prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) +- [suggestion.tsx:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) +- [sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) + +## Architecture Overview + +The diagram below shows the call relationships and data flow between general components and the utility library, reflecting the overall flow of "slot parsing → function wrapping → render item generation → React component bridging". + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Comp as "Svelte Wrapper Component" +participant Utils as "Utility Library" +participant X as "@ant-design/x Component" +Dev->>Comp : Pass props and slots +Comp->>Utils : Parse slots / wrap functions / handle value changes +Utils-->>Comp : Return render results / function handles +Comp->>X : Pass through props and bridge React component +X-->>Dev : Render UI and trigger callbacks +``` + +Chart Sources + +- [bubble.tsx:27-115](file://frontend/antdx/bubble/bubble.tsx#L27-L115) +- [conversations.tsx:72-171](file://frontend/antdx/conversations/conversations.tsx#L72-L171) +- [prompts.tsx:16-37](file://frontend/antdx/prompts/prompts.tsx#L16-L37) +- [suggestion.tsx:77-159](file://frontend/antdx/suggestion/suggestion.tsx#L77-L159) +- [sender.tsx:35-169](file://frontend/antdx/sender/sender.tsx#L35-L169) +- [renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [createFunction.ts](file://frontend/utils/createFunction.ts) +- [patchSlots.ts](file://frontend/utils/patchSlots.ts) +- [react-slot.tsx](file://frontend/svelte-preprocess-react/react-slot.tsx) + +## Detailed Component Analysis + +### Bubble Component API + +- Component Responsibilities + - Wraps `@ant-design/x`'s Bubble in Svelte form, providing slot and function wrapping capabilities + - Supports editable text, loading state, custom content rendering, and avatar/header/footer/extra action slots +- Key Properties and Slots + - Props: Inherits from `BubbleProps`, supports `editable`, `typing`, `content`, `avatar`, `extra`, `footer`, `header`, `loadingRender`, `contentRender`, etc. + - Slots: `avatar`, `content`, `header`, `footer`, `extra`, `editable.okText`, `editable.cancelText`, `loadingRender`, `contentRender` +- Events and State + - Callbacks are wrapped via `useFunction` to ensure reactive updates; `editable` supports boolean or config objects +- Usage Notes + - Edit mode is enabled when `editable` config exists or slots are present; `loadingRender`/`contentRender` support parameterized slots +- Example Path + - [Bubble Implementation:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) + +```mermaid +classDiagram +class Bubble { ++props : BubbleProps ++slots : slot collection ++useFunction() ++ReactSlot ++renderParamsSlot() +} +class XBubble { ++Inherits from @ant-design/x +} +Bubble --> XBubble : "bridge" +``` + +Chart Sources + +- [bubble.tsx:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) + +Section Sources + +- [bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) + +### Conversations Component API + +- Component Responsibilities + - Wraps `@ant-design/x`'s Conversations in Svelte form, providing menu and grouping capabilities +- Key Properties and Slots + - Props: Inherits from `ConversationsProps`, supports `items`, `menu`, `groupable`, `classNames`, etc. + - Slots: `menu.items`, `menu.trigger`, `menu.expandIcon`, `menu.overflowedIndicator`, `groupable.label` +- Events and State + - Menu callbacks are wrapped via `useFunction`; menu events are wrapped to pass the current conversation context + - Group labels support both slot and function configuration +- Usage Notes + - `menu` supports strings or objects; when `items` is not provided, they can be injected from context + - `classNames.item` injects style class names for improved consistency +- Example Path + - [Conversations Implementation:59-175](file://frontend/antdx/conversations/conversations.tsx#L59-L175) + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Conv as "Conversations" +participant Ctx as "Context/Slots" +participant XConv as "X Conversations" +Dev->>Conv : Pass items/menu/groupable +Conv->>Ctx : Read slots/context items +Conv->>Conv : Wrap menu callbacks via useFunction +Conv->>XConv : Pass through props and render +XConv-->>Dev : Render conversation list/groups +``` + +Chart Sources + +- [conversations.tsx:59-175](file://frontend/antdx/conversations/conversations.tsx#L59-L175) +- [context.ts (conversation item context):1-7](file://frontend/antdx/conversations/context.ts#L1-L7) + +Section Sources + +- [conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [context.ts (conversation item context):1-7](file://frontend/antdx/conversations/context.ts#L1-L7) + +### Prompts Component API + +- Component Responsibilities + - Wraps `@ant-design/x`'s Prompts in Svelte form, providing title slots and dynamic item rendering +- Key Properties and Slots + - Props: Inherits from `PromptsProps`, supports `items`, `title`, etc. + - Slots: `title` +- Events and State + - Item lists are dynamically generated via `renderItems`; slot `items`/`default` takes priority +- Usage Notes + - Suitable for "quick prompts", "templated input", and similar scenarios +- Example Path + - [Prompts Implementation:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) + +```mermaid +flowchart TD +Start(["Start"]) --> Read["Read slot items/default"] +Read --> HasItems{"Has items?"} +HasItems --> |Yes| Render["renderItems render"] +HasItems --> |No| UseProps["Use props.items"] +Render --> SetTitle["Set title slot"] +UseProps --> SetTitle +SetTitle --> End(["End"]) +``` + +Chart Sources + +- [prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) +- [context.ts (prompt item context):1-7](file://frontend/antdx/prompts/context.ts#L1-L7) + +Section Sources + +- [prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [context.ts (prompt item context):1-7](file://frontend/antdx/prompts/context.ts#L1-L7) + +### Suggestion Component API + +- Component Responsibilities + - Wraps `@ant-design/x`'s Suggestion in Svelte form, providing suggestion item slot patching, popup containers, open state, and keyboard trigger strategies +- Key Properties and Slots + - Props: Inherits from `SuggestionProps`, adds `children` slot and `shouldTrigger` callback + - Slots: `children` +- Events and State + - `SuggestionOpenContext` and `useSuggestionOpenContext` control and observe the open state + - `patchSlots` patches suggestion item `icon`/`label`/`extra`/`children` slots + - `useMemoizedEqualValue` optimizes rendering overhead +- Usage Notes + - Supports injecting context into `children` render function to customize `onTrigger`/`onKeyDown` + - Supports controlled/uncontrolled `open` state switching +- Example Path + - [Suggestion Implementation:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Sug as "Suggestion" +participant Ctx as "SuggestionContext/SuggestionOpenContext" +participant Patch as "patchSlots" +participant XSug as "X Suggestion" +Dev->>Sug : Pass items/children/shouldTrigger +Sug->>Patch : Patch suggestion item slots +Sug->>Ctx : Provider injects context +Sug->>XSug : Pass through props and render +XSug-->>Dev : Popup and suggestion items +``` + +Chart Sources + +- [suggestion.tsx:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) +- [context.ts (suggestion item context):1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) +- [react-contexts.ts](file://frontend/svelte-preprocess-react/react-contexts.ts) + +Section Sources + +- [suggestion.tsx:1-165](file://frontend/antdx/suggestion/suggestion.tsx#L1-L165) +- [context.ts (suggestion item context):1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) + +### Sender Component API + +- Component Responsibilities + - Wraps `@ant-design/x`'s Sender in Svelte form, providing paste upload, skill panel, slots, and value change hooks +- Key Properties and Slots + - Props: Inherits from `SenderProps`, adds `upload`, `onPasteFile`, `onValueChange`, etc. + - Slots: `suffix`, `header`, `prefix`, `footer`, `skill.title`, `skill.toolTip.title`, `skill.closable.closeIcon` +- Events and State + - `useValueChange` manages controlled/uncontrolled `value` + - `useSuggestionOpenContext` intercepts submission when Suggestion is open + - `createFunction`/`formatResult`/`customRender` customize `slotConfig` +- Usage Notes + - When pasting files, calls `upload` and backfills the path array + - Skill panel supports combinations of slots and configuration for tooltip/closable +- Example Path + - [Sender Implementation:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) + +```mermaid +flowchart TD +A["onPasteFile triggered"] --> B["Call upload(files)"] +B --> C["Backfill path array to onPasteFile"] +D["onSubmit triggered"] --> E{"Is Suggestion open?"} +E --> |Yes| F["Intercept submission"] +E --> |No| G["Normal submission"] +H["onChange triggered"] --> I["useValueChange updates value"] +``` + +Chart Sources + +- [sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) + +Section Sources + +- [sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +## Dependency Analysis + +There is a clear dependency relationship between general components and the utility library: components consume utility library capabilities through the context and slot systems, ultimately bridging to `@ant-design/x` React components. + +```mermaid +graph LR +subgraph "Components" +B["Bubble"] +C["Conversations"] +P["Prompts"] +S["Suggestion"] +SD["Sender"] +end +subgraph "Utilities" +R1["renderItems"] +R2["renderParamsSlot"] +H1["useFunction"] +H2["useValueChange"] +H3["useMemoizedEqualValue"] +F1["createFunction"] +F2["patchSlots"] +RS["ReactSlot"] +RC["ReactContexts"] +end +B --> R1 +B --> R2 +B --> H1 +B --> RS +C --> R1 +C --> R2 +C --> H1 +C --> RC +P --> R1 +P --> R2 +S --> R1 +S --> R2 +S --> H1 +S --> F2 +S --> H3 +SD --> R1 +SD --> R2 +SD --> H1 +SD --> H2 +SD --> F1 +SD --> RS +SD --> RC +``` + +Chart Sources + +- [bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [suggestion.tsx:1-165](file://frontend/antdx/suggestion/suggestion.tsx#L1-L165) +- [sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) +- [renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [createFunction.ts](file://frontend/utils/createFunction.ts) +- [patchSlots.ts](file://frontend/utils/patchSlots.ts) +- [react-slot.tsx](file://frontend/svelte-preprocess-react/react-slot.tsx) +- [react-contexts.ts](file://frontend/svelte-preprocess-react/react-contexts.ts) + +Section Sources + +- [bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [suggestion.tsx:1-165](file://frontend/antdx/suggestion/suggestion.tsx#L1-L165) +- [sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +## Performance Considerations + +- Slot and Function Wrapping + - Use `useMemoizedEqualValue` and `useMemo` to reduce render jitter and redundant computation + - Wrap callbacks via `useFunction` to prevent child component re-renders caused by new function instances on every render +- Render Items and Slots + - `renderItems` and `renderParamsSlot` execute only when necessary, reducing unnecessary cloning and rendering + - `patchSlots` patches suggestion items on demand, avoiding full replacement +- Value Change and Event Interception + - `useValueChange` unifies value management to prevent external state inconsistencies + - Sender intercepts submission when Suggestion is open, reducing invalid requests +- Best Practices + - Properly split slots and functions, avoid heavy logic inside slots + - Use stable references for high-frequency update data, combined with `useMemo`/`useCallback` + - Reuse already-parsed `items` in Conversations/Prompts as much as possible to reduce duplicate rendering + +[This section provides general performance guidance and requires no specific file sources] + +## Troubleshooting Guide + +- Slot Not Taking Effect + - Check if slot key names match the component declarations (e.g., `bubble`'s `editable.okText`, `conversations`'s `menu.items`, etc.) + - Confirm that slot content is properly wrapped in `ReactSlot` or `renderParamsSlot` +- Event Not Firing + - Confirm that the callback wrapped by `useFunction` is correctly passed to the underlying component + - For Conversations menu events, check if `patchMenuEvents` correctly wraps the original event +- Suggestion Item Slot Not Displaying + - Confirm that `patchSlots` has patched `icon`/`label`/`extra`/`children` + - Check if the Suggestion `children` render function returns the correct nodes +- Sender Submission Intercepted + - Confirm whether `SuggestionOpenContext` state is `true` + - Check if `shouldTrigger` correctly fires on keyboard events +- Value Not Updating + - Confirm that `useValueChange`'s `onValueChange` is being called + - Check the synchronization logic between `props.value` and internal state + +Section Sources + +- [bubble.tsx:27-115](file://frontend/antdx/bubble/bubble.tsx#L27-L115) +- [conversations.tsx:35-122](file://frontend/antdx/conversations/conversations.tsx#L35-L122) +- [suggestion.tsx:100-159](file://frontend/antdx/suggestion/suggestion.tsx#L100-L159) +- [sender.tsx:126-138](file://frontend/antdx/sender/sender.tsx#L126-L138) + +## Conclusion + +ModelScope Studio's Ant Design X general components achieve seamless bridging with `@ant-design/x` components through a unified slot system and function wrapping mechanism. Bubble, Conversations, Prompts, Suggestion, and Sender provide powerful extensibility and ease of use for AI chat and conversation scenarios. Following this document's property definitions, event handling, slot system, and state management recommendations, you can efficiently build high-quality conversational interfaces and interaction flows. + +[This section is a summary and requires no specific file sources] + +## Appendix + +- TypeScript Types and Interfaces + - All components extend or trim the corresponding `Props` types from `@ant-design/x` to ensure type safety + - Slots and function wrapping leverage generics and utility functions to guarantee type inference +- Integration with Ant Design Components + - Svelte-to-React bridging is achieved via `sveltify` and `ReactSlot` from `svelte-preprocess-react` + - Property and callback functionalization is achieved via utility tools such as `createFunction`/`useFunction` +- Example Path Index + - Bubble: [bubble.tsx:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) + - Conversations: [conversations.tsx:59-175](file://frontend/antdx/conversations/conversations.tsx#L59-L175) + - Prompts: [prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) + - Suggestion: [suggestion.tsx:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) + - Sender: [sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) + +[This section is supplementary information and requires no specific file sources] diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Tool Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Tool Components API.md new file mode 100644 index 00000000..652751cf --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Ant Design X Components API/Tool Components API.md @@ -0,0 +1,377 @@ +# Tool Components API + + +**Files Referenced in This Document** +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antdx/code-highlighter/code-highlighter.tsx](file://frontend/antdx/code-highlighter/code-highlighter.tsx) +- [frontend/antdx/file-card/file-card.tsx](file://frontend/antdx/file-card/file-card.tsx) +- [frontend/antdx/file-card/base.tsx](file://frontend/antdx/file-card/base.tsx) +- [frontend/antdx/folder/folder.tsx](file://frontend/antdx/folder/folder.tsx) +- [frontend/antdx/folder/context.ts](file://frontend/antdx/folder/context.ts) +- [frontend/antdx/mermaid/mermaid.tsx](file://frontend/antdx/mermaid/mermaid.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [docs/components/antdx/x_provider/README.md](file://docs/components/antdx/x_provider/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document covers the Ant Design X Tool Components API for ModelScope Studio, focusing on the complete interface and usage of the following components: + +- XProvider Global Configuration Component (based on antd's ConfigProvider extension) +- CodeHighlighter Code Highlighting Component +- FileCard File Card Component +- Folder Directory Component +- Mermaid Flowchart Component + +The document covers global configuration approaches, code highlighting language and theme support, file management interactions, flowchart drawing and action integration, and integration with the Gradio ecosystem. It also provides key type definition notes, context provision and state management mechanisms, performance optimization, and best extension practices. + +## Project Structure + +Key directories and files around tool components: + +- Frontend component implementations are in `frontend/antdx` and `frontend/antd`, corresponding to Ant Design X components and the antd configuration layer respectively +- Each component is wrapped via `sveltify` as a React component usable in Svelte, bridged through slots and parameters +- Shared context between components is provided via `createItemsContext`, used for tree nodes, directory icons, and action items, etc. + +```mermaid +graph TB +subgraph "Antd Configuration Layer" +CP["ConfigProvider
frontend/antd/config-provider/config-provider.tsx"] +end +subgraph "Ant Design X Tool Components" +CH["CodeHighlighter
frontend/antdx/code-highlighter/code-highlighter.tsx"] +FC["FileCard
frontend/antdx/file-card/file-card.tsx"] +FCB["BaseFileCard
frontend/antdx/file-card/base.tsx"] +FD["Folder
frontend/antdx/folder/folder.tsx"] +FDCtx["Folder Context
frontend/antdx/folder/context.ts"] +MM["Mermaid
frontend/antdx/mermaid/mermaid.tsx"] +ActCtx["Actions Context
frontend/antdx/actions/context.ts"] +end +CP --> CH +CP --> FC +FC --> FCB +CP --> FD +FD --> FDCtx +CP --> MM +MM --> ActCtx +``` + +Chart Sources + +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) +- [frontend/antdx/folder/folder.tsx:1-123](file://frontend/antdx/folder/folder.tsx#L1-L123) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) + +Section Sources + +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) +- [frontend/antdx/folder/folder.tsx:1-123](file://frontend/antdx/folder/folder.tsx#L1-L123) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) + +## Core Components + +This section provides an overview of each component's responsibilities and key capabilities: + +- XProvider: Replaces antd's ConfigProvider in Gradio Blocks scenarios, uniformly providing global configuration for Ant Design X components (theme, localization, popup containers, etc.), and compatible with slot injection +- CodeHighlighter: Encapsulates `@ant-design/x`'s code highlighting component, supporting custom `header` slots and syntax highlighting styles in light/dark themes +- FileCard: File card component, supporting slot-based configuration for image placeholders, preview masks, close icons, toolbar rendering, indicators, and description text +- Folder: Directory tree component, supporting slot injection for tree node data, directory icon mapping, empty state rendering, and title/preview rendering, and can connect to file content services +- Mermaid: Flowchart component, supporting theme switching, highlight styles, action item context injection, and custom actions + +Section Sources + +- [docs/components/antdx/x_provider/README.md:1-19](file://docs/components/antdx/x_provider/README.md#L1-L19) +- [frontend/antd/config-provider/config-provider.tsx:51-151](file://frontend/antd/config-provider/config-provider.tsx#L51-L151) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:29-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L29-L51) +- [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) +- [frontend/antdx/folder/folder.tsx:16-120](file://frontend/antdx/folder/folder.tsx#L16-L120) +- [frontend/antdx/mermaid/mermaid.tsx:33-84](file://frontend/antdx/mermaid/mermaid.tsx#L33-L84) + +## Architecture Overview + +XProvider serves as the top-level configuration container, providing unified theme, localization, and popup container strategies to tool components below; tool components use slot and parameter bridging, combined with context providers for flexible slot-based and dynamic rendering. + +```mermaid +sequenceDiagram +participant App as "Application" +participant XProv as "XProvider (ConfigProvider)" +participant Comp as "Tool Component" +participant Slots as "Slot System" +App->>XProv : "Wrap application and pass configuration" +XProv->>Comp : "Provide theme/localization/container strategy" +Comp->>Slots : "Read slots (e.g., header, mask, previewRender)" +Slots-->>Comp : "Return React nodes" +Comp-->>App : "Render final UI" +``` + +Chart Sources + +- [frontend/antd/config-provider/config-provider.tsx:108-149](file://frontend/antd/config-provider/config-provider.tsx#L108-L149) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:35-49](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L35-L49) +- [frontend/antdx/file-card/file-card.tsx:46-123](file://frontend/antdx/file-card/file-card.tsx#L46-L123) +- [frontend/antdx/folder/folder.tsx:48-116](file://frontend/antdx/folder/folder.tsx#L48-L116) +- [frontend/antdx/mermaid/mermaid.tsx:47-81](file://frontend/antdx/mermaid/mermaid.tsx#L47-L81) + +## Component Details + +### XProvider Global Configuration Component + +- Role: Replaces antd's ConfigProvider, providing unified global configuration for `@ant-design/x` components +- Key Capabilities + - Theme Mode: Supports `themeMode` to control dark/compact algorithms + - Localization: Automatically parses and loads the corresponding `antd`/`dayjs` locale resources based on the browser language + - Popup Containers: Supports `getPopupContainer`/`getTargetContainer` function injection + - Slot-based: Injects slots into component properties via `combinePropsAndSlots` + - Custom Rendering: `renderEmpty` supports both slot and function forms +- Usage Recommendations + - Use `antdx.XProvider` instead of `antd.ConfigProvider` in Gradio Blocks + - Switch light/dark themes via `themeMode`, avoiding re-render issues caused by duplicate keys + - Set `getPopupContainer` appropriately to ensure floating layers render in the correct container + +Section Sources + +- [docs/components/antdx/x_provider/README.md:1-19](file://docs/components/antdx/x_provider/README.md#L1-L19) +- [frontend/antd/config-provider/config-provider.tsx:51-151](file://frontend/antd/config-provider/config-provider.tsx#L51-L151) + +### CodeHighlighter Code Highlighting Component + +- Role: Renders code with syntax highlighting, supporting `header` slots and light/dark theme styles +- Key Capabilities + - Language Support: Relies on `react-syntax-highlighter`'s Prism style, can directly render multiple languages + - Light/Dark Theme: Switches `materialDark`/`materialLight` styles based on `themeMode`, uniformly removing the code block outer margin + - Slot-based: Supports `header` slot for custom header injection + - Value Binding: Both the `value` property and child node content can serve as code input +- Usage Recommendations + - In AI applications, prefer consistent light/dark theme styles for a better reading experience + - Add copy, download, and other action buttons via the `header` slot + +Section Sources + +- [frontend/antdx/code-highlighter/code-highlighter.tsx:29-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L29-L51) + +### FileCard File Card Component + +- Role: Displays file information, supporting slot-based configuration for image placeholders, preview masks, toolbars, indicators, and description text +- Key Capabilities + - Image Processing: Supports slot-based placeholders, preview containers, close icons, toolbars, and image rendering + - Loading State: `spinProps` supports `size`, `icon`, `description`, `indicator` slots + - Description and Icons: `description` and `icon` slots allow custom display content + - Resource Resolution: Resolves relative paths and `FileData` via `BaseFileCard`'s `resolveFileSrc` +- Usage Recommendations + - For remote images, ensure `rootUrl` and `apiPrefix` are correctly concatenated for an accessible URL + - Enable preview functionality on demand to avoid unnecessary DOM rendering + +```mermaid +flowchart TD +Start(["Enter FileCard"]) --> CheckImg["Check if imageProps.preview is enabled"] +CheckImg --> |Enabled| BuildPreview["Build preview config (with slots)"] +CheckImg --> |Disabled| NoPreview["Disable preview"] +BuildPreview --> ResolveSrc["Resolve src to accessible URL"] +NoPreview --> ResolveSrc +ResolveSrc --> Render["Render BaseFileCard"] +Render --> End(["Done"]) +``` + +Chart Sources + +- [frontend/antdx/file-card/file-card.tsx:34-123](file://frontend/antdx/file-card/file-card.tsx#L34-L123) +- [frontend/antdx/file-card/base.tsx:15-41](file://frontend/antdx/file-card/base.tsx#L15-L41) + +Section Sources + +- [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) +- [frontend/antdx/file-card/base.tsx:9-41](file://frontend/antdx/file-card/base.tsx#L9-L41) + +### Folder Directory Component + +- Role: Directory tree component, supporting tree node data, directory icon mapping, empty state and title rendering, preview rendering, and file content services +- Key Capabilities + - Tree Node Context: Provides two data sources `treeData`/`default` via `withTreeNodeItemsContextProvider` + - Directory Icon Context: Provides extension-to-icon mapping via `withDirectoryIconItemsContextProvider` + - Preview Service: `fileContentService` can inject a callback for loading file content + - Slot-based: `emptyRender`, `directoryTitle`, `previewTitle`, `previewRender` all support slots +- Usage Recommendations + - When `treeData` is empty, fall back to the default node list to ensure stable initial rendering + - Directory icon mappings are collected via slots and then converted to a dictionary for fast lookup + +```mermaid +sequenceDiagram +participant FD as "Folder" +participant Ctx as "Context Provider" +participant XFD as "@ant-design/x Folder" +participant FS as "File Content Service" +FD->>Ctx : "Read tree nodes and directory icons" +FD->>FD : "Merge treeData/default" +FD->>FD : "Build directory icon mapping" +FD->>XFD : "Pass treeData, directoryIcons, emptyRender..." +alt fileContentService exists +FD->>FS : "Call onLoadFileContent(filePath)" +FS-->>FD : "Return file content" +end +XFD-->>FD : "Render tree and preview" +``` + +Chart Sources + +- [frontend/antdx/folder/folder.tsx:24-120](file://frontend/antdx/folder/folder.tsx#L24-L120) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) + +Section Sources + +- [frontend/antdx/folder/folder.tsx:16-120](file://frontend/antdx/folder/folder.tsx#L16-L120) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) + +### Mermaid Flowchart Component + +- Role: Flowchart drawing component, supporting theme switching, highlight styles, and action item context +- Key Capabilities + - Theme and Highlight: Switches `dark`/`base` theme based on `themeMode`, and applies Prism-style highlighting + - Actions Context: Injects custom action items via `withActionItemsContextProvider` + - Slot-based: `header` and `actions.customActions` support slots + - Config Merging: `theme` in `config` will be overridden by `themeMode` +- Usage Recommendations + - In AI applications, inject copy, download, full-screen, and other actions via `actions.customActions` + - Maintain theme consistency to avoid visual breaks caused by light/dark switching + +Section Sources + +- [frontend/antdx/mermaid/mermaid.tsx:33-84](file://frontend/antdx/mermaid/mermaid.tsx#L33-L84) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) + +## Dependency Analysis + +- Component Coupling + - FileCard depends on BaseFileCard for resource resolution, reducing duplicate logic + - Folder injects tree nodes and directory icons via context providers, decoupling external data sources + - Mermaid injects custom actions via the actions context provider, enhancing extensibility +- External Dependencies + - `react-syntax-highlighter`: Provides Prism-style highlighting + - `@ant-design/x`: Provides underlying component capabilities (CodeHighlighter, Folder, Mermaid, FileCard, etc.) + - `antd`: ConfigProvider extension and theme algorithms +- Circular Dependencies + - No circular dependencies detected in the current structure; context providers are abstracted via `createItemsContext`, avoiding direct mutual references + +```mermaid +graph LR +CH["CodeHighlighter"] --> XCH["@ant-design/x CodeHighlighter"] +FC["FileCard"] --> FCB["BaseFileCard"] +FCB --> XFC["@ant-design/x FileCard"] +FD["Folder"] --> XFD["@ant-design/x Folder"] +FD --> FDCtx["Folder Context"] +MM["Mermaid"] --> XMM["@ant-design/x Mermaid"] +MM --> ActCtx["Actions Context"] +CP["ConfigProvider (XProvider)"] --> CH +CP --> FC +CP --> FD +CP --> MM +``` + +Chart Sources + +- [frontend/antdx/code-highlighter/code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) +- [frontend/antdx/folder/folder.tsx:1-123](file://frontend/antdx/folder/folder.tsx#L1-L123) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) + +Section Sources + +- [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) +- [frontend/antdx/folder/folder.tsx:16-120](file://frontend/antdx/folder/folder.tsx#L16-L120) +- [frontend/antdx/mermaid/mermaid.tsx:33-84](file://frontend/antdx/mermaid/mermaid.tsx#L33-L84) +- [frontend/antd/config-provider/config-provider.tsx:51-151](file://frontend/antd/config-provider/config-provider.tsx#L51-L151) + +## Performance Considerations + +- Rendering Strategy + - Use `useMemo` to cache computed results like `treeData`, `directoryIcons`, `actions.customActions`, etc., to avoid duplicate renders + - Enable preview containers and toolbars only when needed to reduce DOM structure complexity +- Theme Switching + - When `themeMode` changes, combine light/dark algorithms and reuse style objects to avoid frequent style rebuilding +- Slot Rendering + - When using `renderParamsSlot` and `renderItems`, pass `clone: true` as much as possible to ensure independent slot node updates +- Resource Resolution + - `BaseFileCard`'s `resolveFileSrc` only recalculates when `src`/`rootUrl`/`apiPrefix` changes, avoiding unnecessary URL concatenation + +[This section provides general guidance and requires no specific file sources] + +## Troubleshooting Guide + +- Localization Not Taking Effect + - Check whether the `locale` parameter format is as expected; confirm the `locales` map has the corresponding language pack + - Confirm `dayjs.locale` has been correctly set +- Popup Layer Position Anomaly + - Check whether the container returned by `getPopupContainer`/`getTargetContainer` is visible and at the correct z-index level +- Preview Not Available + - Confirm `imageProps.preview` has not been explicitly set to `false`, and at least one of the `mask`/`closeIcon`/`toolbarRender`/`imageRender` slots is available +- Files Inaccessible + - Confirm `resolveFileSrc`'s `rootUrl` and `apiPrefix` are correctly concatenated; use `FileData.url` field if necessary +- Action Items Not Displaying + - Confirm that action items injected via `withActionItemsContextProvider` have been correctly collected and passed to `actions.customActions` + +Section Sources + +- [frontend/antd/config-provider/config-provider.tsx:96-105](file://frontend/antd/config-provider/config-provider.tsx#L96-L105) +- [frontend/antdx/file-card/file-card.tsx:34-123](file://frontend/antdx/file-card/file-card.tsx#L34-L123) +- [frontend/antdx/file-card/base.tsx:15-41](file://frontend/antdx/file-card/base.tsx#L15-L41) +- [frontend/antdx/mermaid/mermaid.tsx:40-84](file://frontend/antdx/mermaid/mermaid.tsx#L40-L84) + +## Conclusion + +This document systematically covers the API and usage of Ant Design X Tool Components in ModelScope Studio, with a focus on the interface highlights and best practices of XProvider global configuration, CodeHighlighter, FileCard, Folder, and Mermaid. Through slot-based design and context providers, the components achieve highly customizable and extensible capabilities within the Gradio ecosystem, suitable for tool integration and content display scenarios in AI applications. + +[This section is a summary and requires no specific file sources] + +## Appendix + +### Component API Quick Reference + +- XProvider + - Main Properties: `themeMode`, `locale`, `getPopupContainer`, `getTargetContainer`, `renderEmpty`, `component`, `className`, `style`, `id` + - Slots: None (injected via parameters and functions) +- CodeHighlighter + - Main Properties: `value`, `themeMode`, `highlightProps`, `header` + - Slots: `header` +- FileCard + - Main Properties: `rootUrl`, `apiPrefix`, `src`, `imageProps`, `spinProps`, `description`, `icon`, `mask` + - Slots: `imageProps.placeholder`, `imageProps.preview.mask`, `imageProps.preview.closeIcon`, `imageProps.preview.toolbarRender`, `imageProps.preview.imageRender`, `description`, `icon`, `mask`, `spinProps.icon`, `spinProps.description`, `spinProps.indicator` +- Folder + - Main Properties: `treeData`, `directoryIcons`, `emptyRender`, `directoryTitle`, `previewTitle`, `previewRender`, `fileContentService` + - Slots: `emptyRender`, `previewRender`, `directoryTitle`, `previewTitle` +- Mermaid + - Main Properties: `value`, `themeMode`, `config`, `actions`, `header` + - Slots: `header`, `actions.customActions` + +Section Sources + +- [frontend/antd/config-provider/config-provider.tsx:51-151](file://frontend/antd/config-provider/config-provider.tsx#L51-L151) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:29-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L29-L51) +- [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) +- [frontend/antdx/folder/folder.tsx:16-120](file://frontend/antdx/folder/folder.tsx#L16-L120) +- [frontend/antdx/mermaid/mermaid.tsx:33-84](file://frontend/antdx/mermaid/mermaid.tsx#L33-L84) diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Basic Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Basic Components API.md new file mode 100644 index 00000000..17bbd1ec --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Basic Components API.md @@ -0,0 +1,570 @@ +# Basic Components API + + +**Files referenced in this document** +- [frontend/base/application/Index.svelte](file://frontend/base/application/Index.svelte) +- [frontend/base/auto-loading/Index.svelte](file://frontend/base/auto-loading/Index.svelte) +- [frontend/base/slot/Index.svelte](file://frontend/base/slot/Index.svelte) +- [frontend/base/fragment/Index.svelte](file://frontend/base/fragment/Index.svelte) +- [frontend/base/div/Index.svelte](file://frontend/base/div/Index.svelte) +- [frontend/base/span/Index.svelte](file://frontend/base/span/Index.svelte) +- [frontend/base/text/Index.svelte](file://frontend/base/text/Index.svelte) +- [frontend/base/markdown/Index.svelte](file://frontend/base/markdown/Index.svelte) +- [frontend/base/each/Index.svelte](file://frontend/base/each/Index.svelte) +- [frontend/base/filter/Index.svelte](file://frontend/base/filter/Index.svelte) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the authoritative reference for ModelScope Studio's basic Svelte components, covering the complete API specifications and usage instructions for the following components: Application, AutoLoading, Slot, Fragment, Div, Span, Text, Markdown, Each, and Filter. Content includes: + +- Property definitions and default values +- Event and callback conventions +- Slot system and parameter mapping +- Lifecycle and rendering control (visibility, lazy loading) +- Inter-component communication mechanisms (contexts, slot keys, loading states) +- TypeScript type constraints and interface specifications +- Instantiation and configuration example paths +- Performance optimization and best practices + +## Project Structure + +Base components are located in the `base` directory of the frontend workspace, organized with a "one directory per component" structure. Each component contains an entry `Index.svelte` and corresponding implementation files (`.tsx` or `.svelte`). Components use a unified preprocessing toolchain for property extraction, additional property injection, and lazy loading. + +```mermaid +graph TB +subgraph "Base Components" +APP["application/Index.svelte"] +AL["auto-loading/Index.svelte"] +SLOT["slot/Index.svelte"] +FRAG["fragment/Index.svelte"] +DIV["div/Index.svelte"] +SPAN["span/Index.svelte"] +TEXT["text/Index.svelte"] +MD["markdown/Index.svelte"] +EACH["each/Index.svelte"] +FILT["filter/Index.svelte"] +end +subgraph "Common Utilities" +PREACT["@svelte-preprocess-react/*"] +CLS["classnames"] +end +APP --> PREACT +AL --> PREACT +SLOT --> PREACT +FRAG --> PREACT +DIV --> PREACT +SPAN --> PREACT +TEXT --> PREACT +MD --> PREACT +EACH --> PREACT +FILT --> PREACT +DIV --> CLS +SPAN --> CLS +MD --> CLS +AL --> CLS +``` + +Diagram sources + +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) +- [frontend/base/div/Index.svelte:1-65](file://frontend/base/div/Index.svelte#L1-L65) +- [frontend/base/span/Index.svelte:1-64](file://frontend/base/span/Index.svelte#L1-L64) +- [frontend/base/text/Index.svelte:1-42](file://frontend/base/text/Index.svelte#L1-L42) +- [frontend/base/markdown/Index.svelte:1-64](file://frontend/base/markdown/Index.svelte#L1-L64) +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) +- [frontend/base/filter/Index.svelte:1-52](file://frontend/base/filter/Index.svelte#L1-L52) + +Section sources + +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) +- [frontend/base/div/Index.svelte:1-65](file://frontend/base/div/Index.svelte#L1-L65) +- [frontend/base/span/Index.svelte:1-64](file://frontend/base/span/Index.svelte#L1-L64) +- [frontend/base/text/Index.svelte:1-42](file://frontend/base/text/Index.svelte#L1-L42) +- [frontend/base/markdown/Index.svelte:1-64](file://frontend/base/markdown/Index.svelte#L1-L64) +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) +- [frontend/base/filter/Index.svelte:1-52](file://frontend/base/filter/Index.svelte#L1-L52) + +## Core Components + +This section systematically covers the key properties, events, slots, and lifecycle of each component, along with type constraints and usage notes. + +- **Application** + - Purpose: Dynamically imports and renders application-level components, with support for lazy loading and `children` rendering. + - Key properties + - `children`: Optional render function for passing child nodes. + - Other properties are extracted by `getProps` and passed through to internal components. + - Lifecycle + - Uses `{#await}` for async rendering, ensuring the component mounts only after the import completes. + - Example path + - [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) + +- **AutoLoading** + - Purpose: Wraps any component, providing visibility, generating state, error state, and style passthrough capabilities. + - Key properties + - `visible`: Controls whether to render. + - `generating`: Indicates the generating state, affecting the loading status. + - `showError`: Whether to display the error state. + - `elem_id`/`elem_classes`/`elem_style`: DOM attribute passthrough. + - `as_item`/`_internal`: Internal flags and container identifiers. + - Other properties are passed through after processing by `getComponentProps`/`processProps`. + - Context + - Reads config type, slot collection, and loading status. + - Example path + - [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) + +- **Slot** + - Purpose: Registers and updates named slots, supporting parameter mapping and visibility control. + - Key properties + - `value`: Slot key value. + - `params_mapping`: Parameter mapping expression string, converted to a function at runtime. + - `visible`/`as_item`/`_internal`: Controls visibility and containerization. + - Behavior + - Detects `value` changes in `effect` and calls `setSlot` to update the context. + - Sets the current slot key and parameter mapping. + - Example path + - [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) + +- **Fragment** + - Purpose: Lightweight container that wraps multiple child nodes without introducing extra DOM. + - Key properties + - `visible`/`_internal`/`as_item`: Controls visibility and containerization. + - Other properties are passed through to the internal Fragment. + - Note + - `shouldResetSlotKey`: Slot key reset is disabled in the configuration. + - Example path + - [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) + +- **Div** + - Purpose: Block-level container supporting styles, class names, IDs, and internal layout flags. + - Key properties + - `value`: Text or content value. + - `elem_style`: Inline style object. + - `additional_props`: Additional properties object. + - `_internal.layout`: Marks whether this is a layout-related internal element. + - `visible`/`as_item`/`elem_id`/`elem_classes`: Controls visibility and DOM attributes. + - Example path + - [frontend/base/div/Index.svelte:1-65](file://frontend/base/div/Index.svelte#L1-L65) + +- **Span** + - Purpose: Inline container; behaves similarly to Div but with inline semantics. + - Key properties + - `value`: Text or content value. + - `additional_props`: Additional properties object. + - `_internal.layout`: Marks whether this is a layout-related internal element. + - `visible`/`as_item`/`elem_id`/`elem_classes`/`elem_style`: Controls visibility and DOM attributes. + - Example path + - [frontend/base/span/Index.svelte:1-64](file://frontend/base/span/Index.svelte#L1-L64) + +- **Text** + - Purpose: Text display component with value and common property passthrough. + - Key properties + - `value`: Text value. + - `visible`/`as_item`/`_internal`: Controls visibility and containerization. + - Example path + - [frontend/base/text/Index.svelte:1-42](file://frontend/base/text/Index.svelte#L1-L42) + +- **Markdown** + - Purpose: Markdown rendering component with support for themes, root paths, and slots. + - Key properties + - `value`: Markdown text. + - `elem_id`/`elem_classes`/`elem_style`: DOM attribute passthrough. + - `visible`/`as_item`/`_internal`: Controls visibility and containerization. + - Context + - Reads `root` and `theme` from the shared configuration. + - Reads the slot collection for custom component embedding. + - Example path + - [frontend/base/markdown/Index.svelte:1-64](file://frontend/base/markdown/Index.svelte#L1-L64) + +- **Each** + - Purpose: List rendering component supporting context merging, index calculation, and placeholders. + - Key properties + - `value`: Array to be rendered. + - `context_value`: Context object. + - `_internal.index`: Internal start index. + - `visible`/`as_item`/`elem_id`/`elem_classes`/`elem_style`: Controls visibility and DOM attributes. + - Behavior + - Uses `EachPlaceholder` to merge external changes and determines whether to force-clone rendering. + - Supports nested Each, calculating sub-indices and slot keys via `getSubIndex` and `getSlotKey`. + - Example path + - [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + +- **Filter** + - Purpose: Conditional filter component that wraps `children` into a fragment filterable by parameter mapping. + - Key properties + - `params_mapping`: Parameter mapping expression string. + - `visible`/`as_item`/`_internal`: Controls visibility and containerization. + - Example path + - [frontend/base/filter/Index.svelte:1-52](file://frontend/base/filter/Index.svelte#L1-L52) + +Section sources + +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) +- [frontend/base/div/Index.svelte:1-65](file://frontend/base/div/Index.svelte#L1-L65) +- [frontend/base/span/Index.svelte:1-64](file://frontend/base/span/Index.svelte#L1-L64) +- [frontend/base/text/Index.svelte:1-42](file://frontend/base/text/Index.svelte#L1-L42) +- [frontend/base/markdown/Index.svelte:1-64](file://frontend/base/markdown/Index.svelte#L1-L64) +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) +- [frontend/base/filter/Index.svelte:1-52](file://frontend/base/filter/Index.svelte#L1-L52) + +## Architecture Overview + +Base components complete property resolution, additional property injection, and lazy loading through a unified preprocessing pipeline, while leveraging the context system for slot registration, loading state, and config type management. Components collaborate through props and contexts, forming clear responsibility boundaries and composability. + +```mermaid +sequenceDiagram +participant U as "User Code" +participant IDX as "Index.svelte" +participant PRE as "@svelte-preprocess-react/*" +participant CMP as "Internal Component" +participant CTX as "Context (slots/config/loading)" +U->>IDX : Pass props and children +IDX->>PRE : getProps()/processProps() +PRE-->>IDX : Normalized props and additional properties +IDX->>CTX : Read/set slots/config/loading state +IDX->>CMP : Async import and render component +CMP-->>U : Render result +``` + +Diagram sources + +- [frontend/base/auto-loading/Index.svelte:15-52](file://frontend/base/auto-loading/Index.svelte#L15-L52) +- [frontend/base/slot/Index.svelte:16-54](file://frontend/base/slot/Index.svelte#L16-L54) +- [frontend/base/markdown/Index.svelte:19-44](file://frontend/base/markdown/Index.svelte#L19-L44) + +## Detailed Component Analysis + +### Application Component + +- Design highlights + - Uses `importComponent` to dynamically import internal `Application.svelte`. + - Renders `children` as slot content. +- API summary + - Properties + - `children`: Optional render function + - Other properties are extracted by `getProps` and passed through + - Slots + - Default slot: `children()` + - Lifecycle + - `{#await}` async rendering prevents mounting before import completes + +Example path + +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) + +Section sources + +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) + +### AutoLoading Component + +- Design highlights + - Wraps any component, providing visibility, generating state, error state, and style passthrough. + - Integrates with `getLoadingStatus` and config type linkage. +- API summary + - Properties + - `visible`/`generating`/`showError` + - `elem_id`/`elem_classes`/`elem_style` + - `as_item`/`_internal` + - Other properties processed by `processProps` + - Context + - Reads config type, slot collection, and loading status + - Slots + - Default slot: `children()` + +Example path + +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) + +Section sources + +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) + +### Slot Component + +- Design highlights + - Registers named slots with support for parameter mapping and visibility control. + - Detects `value` changes in `effect` and updates the context. +- API summary + - Properties + - `value`: Slot key + - `params_mapping`: Parameter mapping expression + - `visible`/`as_item`/`_internal` + - Behavior + - `setSlotKey`/`setSlotParamsMapping` + - Obtains the host element via `svelte-slot bind:this` + +Example path + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) + +Section sources + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) + +### Fragment Component + +- Design highlights + - Lightweight container that does not introduce extra DOM. + - Slot key reset is disabled to maintain context stability. +- API summary + - Properties + - `visible`/`_internal`/`as_item` + - Other properties are passed through + - Slots + - Default slot: `children()` + +Example path + +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) + +Section sources + +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) + +### Div Component + +- Design highlights + - Block-level container supporting styles, class names, IDs, and internal layout flags. +- API summary + - Properties + - `value`/`additional_props`/`_internal.layout` + - `elem_id`/`elem_classes`/`elem_style` + - `visible`/`as_item`/`_internal` + - Slots + - Default slot: `children()` + +Example path + +- [frontend/base/div/Index.svelte:1-65](file://frontend/base/div/Index.svelte#L1-L65) + +Section sources + +- [frontend/base/div/Index.svelte:1-65](file://frontend/base/div/Index.svelte#L1-L65) + +### Span Component + +- Design highlights + - Inline container; behaves similarly to Div. +- API summary + - Properties + - `value`/`additional_props`/`_internal.layout` + - `elem_id`/`elem_classes`/`elem_style` + - `visible`/`as_item`/`_internal` + - Slots + - Default slot: `children()` + +Example path + +- [frontend/base/span/Index.svelte:1-64](file://frontend/base/span/Index.svelte#L1-L64) + +Section sources + +- [frontend/base/span/Index.svelte:1-64](file://frontend/base/span/Index.svelte#L1-L64) + +### Text Component + +- Design highlights + - Text display component with minimal overhead. +- API summary + - Properties + - `value` + - `visible`/`as_item`/`_internal` + +Example path + +- [frontend/base/text/Index.svelte:1-42](file://frontend/base/text/Index.svelte#L1-L42) + +Section sources + +- [frontend/base/text/Index.svelte:1-42](file://frontend/base/text/Index.svelte#L1-L42) + +### Markdown Component + +- Design highlights + - Supports themes and root paths, combining with slots for extensible rendering. +- API summary + - Properties + - `value` + - `elem_id`/`elem_classes`/`elem_style` + - `visible`/`as_item`/`_internal` + - Context + - Reads `shared.root` and `theme` + - Reads the slot collection + +Example path + +- [frontend/base/markdown/Index.svelte:1-64](file://frontend/base/markdown/Index.svelte#L1-L64) + +Section sources + +- [frontend/base/markdown/Index.svelte:1-64](file://frontend/base/markdown/Index.svelte#L1-L64) + +### Each Component + +- Design highlights + - List rendering with support for context merging, index calculation, and placeholders. + - Nested Each calculates sub-indices and slot keys via `getSubIndex` and `getSlotKey`. +- API summary + - Properties + - `value`/`context_value`/`_internal.index` + - `elem_id`/`elem_classes`/`elem_style` + - `visible`/`as_item`/`_internal` + - Slots + - Default slot: `children()` + - Events + - `EachPlaceholder.onChange`: Receives merged `value` and `contextValue` + +Example path + +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + +Section sources + +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + +### Filter Component + +- Design highlights + - Conditional filter container that wraps `children` into a fragment filterable by parameter mapping. +- API summary + - Properties + - `params_mapping` + - `visible`/`as_item`/`_internal` + - Slots + - Default slot: `children()` + +Example path + +- [frontend/base/filter/Index.svelte:1-52](file://frontend/base/filter/Index.svelte#L1-L52) + +Section sources + +- [frontend/base/filter/Index.svelte:1-52](file://frontend/base/filter/Index.svelte#L1-L52) + +## Dependency Analysis + +Base components generally depend on the `@svelte-preprocess-react` toolkit and styling libraries, forming a unified property processing and lazy loading mechanism. Some components also depend on the context system for slot registration and loading state management. + +```mermaid +graph LR +subgraph "Utilities" +PRE["@svelte-preprocess-react/*"] +CLS["classnames"] +end +subgraph "Components" +AL["AutoLoading"] +SLOT["Slot"] +MD["Markdown"] +DIV["Div"] +SPAN["Span"] +FRAG["Fragment"] +EACH["Each"] +FILT["Filter"] +end +AL --> PRE +SLOT --> PRE +MD --> PRE +DIV --> PRE +SPAN --> PRE +FRAG --> PRE +EACH --> PRE +FILT --> PRE +DIV -.-> CLS +SPAN -.-> CLS +MD -.-> CLS +AL -.-> CLS +``` + +Diagram sources + +- [frontend/base/auto-loading/Index.svelte:1-10](file://frontend/base/auto-loading/Index.svelte#L1-L10) +- [frontend/base/slot/Index.svelte:1-8](file://frontend/base/slot/Index.svelte#L1-L8) +- [frontend/base/markdown/Index.svelte:1-8](file://frontend/base/markdown/Index.svelte#L1-L8) +- [frontend/base/div/Index.svelte:1-8](file://frontend/base/div/Index.svelte#L1-L8) +- [frontend/base/span/Index.svelte:1-7](file://frontend/base/span/Index.svelte#L1-L7) + +Section sources + +- [frontend/base/auto-loading/Index.svelte:1-10](file://frontend/base/auto-loading/Index.svelte#L1-L10) +- [frontend/base/slot/Index.svelte:1-8](file://frontend/base/slot/Index.svelte#L1-L8) +- [frontend/base/markdown/Index.svelte:1-8](file://frontend/base/markdown/Index.svelte#L1-L8) +- [frontend/base/div/Index.svelte:1-8](file://frontend/base/div/Index.svelte#L1-L8) +- [frontend/base/span/Index.svelte:1-7](file://frontend/base/span/Index.svelte#L1-L7) + +## Performance Considerations + +- Lazy loading + - Use `importComponent` and `{#await}` to load components only when needed, reducing the initial load. +- Visibility control + - Use the `visible` property to quickly show/hide without triggering unnecessary rendering and context updates. +- Slot keys and contexts + - Set slot keys and parameter mappings appropriately to avoid duplicate registration and invalid updates. +- Style passthrough + - Prefer `elem_classes` and `elem_style` to reduce frequent inline style changes. +- List rendering + - The Each component supports placeholder and force-clone strategies; choose as needed to balance performance and consistency. +- Loading state + - AutoLoading combines `generating` and `showError` states to avoid duplicate requests and flickering. + +## Troubleshooting Guide + +- Component not rendering + - Check if the `visible` property is `true`. + - Confirm that the `{#await}` import flow succeeded. +- Slot not taking effect + - Confirm that `Slot`'s `value` and `params_mapping` are correctly set. + - Check that the parent component has correctly registered the slot key. +- Each rendering abnormalities + - Check that `value` is an array and `context_value` is an object. + - For nested Each, confirm the index and slot key calculation logic. +- Markdown theme or resource path issues + - Confirm that `shared.root` and `theme` configurations are correct. +- AutoLoading state out of sync + - Check that `generating` and `showError` are consistent with the business state. + +Section sources + +- [frontend/base/each/Index.svelte:66-104](file://frontend/base/each/Index.svelte#L66-L104) +- [frontend/base/markdown/Index.svelte:47-63](file://frontend/base/markdown/Index.svelte#L47-L63) +- [frontend/base/auto-loading/Index.svelte:65-80](file://frontend/base/auto-loading/Index.svelte#L65-L80) +- [frontend/base/slot/Index.svelte:57-61](file://frontend/base/slot/Index.svelte#L57-L61) + +## Conclusion + +ModelScope Studio's base components achieve a highly cohesive, loosely coupled, and easily composable UI infrastructure through a unified preprocessing pipeline and context system. By following the property specifications, slot conventions, and performance recommendations in this document, stable runtime performance can be achieved while maintaining development efficiency. + +## Appendix + +- TypeScript type constraints and interface specifications + - `getProps()`: Extracts and normalizes component properties from `$props()`, where T is the component property interface. + - `processProps(fn, ..., options)`: Performs secondary processing on component properties, returning derived values. + - Context access: `getConfigType()`/`getSlots()`/`getLoadingStatus()`/`getSetSlot()`, etc. + - Style handling: `classnames` for class name concatenation. +- Best practices + - Prefer using `visible` to control rendering and avoid expensive operations in invisible states. + - Properly separate `value` and `context_value` in Each to improve diff efficiency. + - Use `params_mapping` to encapsulate complex logic as string expressions for easier maintenance. + - For heavy components, combine with AutoLoading and lazy loading to optimize the initial load experience. diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Pro Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Pro Components API.md new file mode 100644 index 00000000..ed47eceb --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Pro Components API.md @@ -0,0 +1,413 @@ +# Pro Components API + + +**Files referenced in this document** +- [frontend/pro/package.json](file://frontend/pro/package.json) +- [frontend/pro/chatbot/package.json](file://frontend/pro/chatbot/package.json) +- [frontend/pro/monaco-editor/package.json](file://frontend/pro/monaco-editor/package.json) +- [frontend/pro/multimodal-input/package.json](file://frontend/pro/multimodal-input/package.json) +- [frontend/pro/web-sandbox/package.json](file://frontend/pro/web-sandbox/package.json) +- [frontend/pro/chatbot/Index.svelte](file://frontend/pro/chatbot/Index.svelte) +- [frontend/pro/monaco-editor/Index.svelte](file://frontend/pro/monaco-editor/Index.svelte) +- [frontend/pro/multimodal-input/Index.svelte](file://frontend/pro/multimodal-input/Index.svelte) +- [frontend/pro/web-sandbox/Index.svelte](file://frontend/pro/web-sandbox/Index.svelte) +- [frontend/pro/chatbot/type.ts](file://frontend/pro/chatbot/type.ts) +- [frontend/pro/monaco-editor/loader.ts](file://frontend/pro/monaco-editor/loader.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the authoritative reference for ModelScope Studio Pro Svelte components, covering the complete API for the following professional components: Chatbot, MultimodalInput, WebSandbox, and MonacoEditor. Content includes: + +- Property definitions and default behaviors +- Event handling and callbacks +- Slot system and rendering extensions +- Advanced capabilities and integration points (such as Gradio shared context) +- Real-time communication and state update mechanisms +- TypeScript types and interface specifications +- Performance optimization and best practices (especially for AI applications) + +## Project Structure + +Pro components are located in the `pro` directory of the frontend workspace. Each component is exported as an independent package, bridged to the underlying React/TSX implementation through Svelte components, and leverages the `getProps`/`processProps`/`importComponent` capabilities provided by `@svelte-preprocess-react` for property passthrough, event writeback, and dynamic loading. + +```mermaid +graph TB +subgraph "Pro Component Packages" +P["@modelscope-studio/pro
Package Info"] +C["@modelscope-studio/pro-chatbot
Package Info"] +M["@modelscope-studio/pro-monaco-editor
Package Info"] +U["@modelscope-studio/pro-multimodal-input
Package Info"] +W["@modelscope-studio/pro-web-sandbox
Package Info"] +end +subgraph "Svelte Bridge Layer" +CI["chatbot/Index.svelte"] +MI["monaco-editor/Index.svelte"] +UI["multimodal-input/Index.svelte"] +WI["web-sandbox/Index.svelte"] +end +subgraph "Runtime Shared Context" +G["gradio.shared.*
root/api_prefix/theme"] +end +P --> CI +P --> MI +P --> UI +P --> WI +C --> CI +M --> MI +U --> UI +W --> WI +CI --> G +MI --> G +UI --> G +WI --> G +``` + +Diagram sources + +- [frontend/pro/package.json:1-6](file://frontend/pro/package.json#L1-L6) +- [frontend/pro/chatbot/package.json:1-15](file://frontend/pro/chatbot/package.json#L1-L15) +- [frontend/pro/monaco-editor/package.json:1-15](file://frontend/pro/monaco-editor/package.json#L1-L15) +- [frontend/pro/multimodal-input/package.json:1-15](file://frontend/pro/multimodal-input/package.json#L1-L15) +- [frontend/pro/web-sandbox/package.json:1-15](file://frontend/pro/web-sandbox/package.json#L1-L15) +- [frontend/pro/chatbot/Index.svelte:1-90](file://frontend/pro/chatbot/Index.svelte#L1-L90) +- [frontend/pro/monaco-editor/Index.svelte:1-101](file://frontend/pro/monaco-editor/Index.svelte#L1-L101) +- [frontend/pro/multimodal-input/Index.svelte:1-99](file://frontend/pro/multimodal-input/Index.svelte#L1-L99) +- [frontend/pro/web-sandbox/Index.svelte:1-76](file://frontend/pro/web-sandbox/Index.svelte#L1-L76) + +Section sources + +- [frontend/pro/package.json:1-6](file://frontend/pro/package.json#L1-L6) +- [frontend/pro/chatbot/package.json:1-15](file://frontend/pro/chatbot/package.json#L1-L15) +- [frontend/pro/monaco-editor/package.json:1-15](file://frontend/pro/monaco-editor/package.json#L1-L15) +- [frontend/pro/multimodal-input/package.json:1-15](file://frontend/pro/multimodal-input/package.json#L1-L15) +- [frontend/pro/web-sandbox/package.json:1-15](file://frontend/pro/web-sandbox/package.json#L1-L15) + +## Core Components + +This section provides an overview of the responsibilities and common capabilities of the four professional components: + +- **Chatbot**: Displays and interacts with conversational message streams. Supports composite content including text, tool calls, files, welcome messages, and suggested prompts. Features user/assistant actions (copy, edit, delete, like/dislike, retry) and theme adaptation. +- **MultimodalInput**: Multimodal input entry supporting text and file uploads, with upload hooks and event callbacks for easy integration with Gradio clients. +- **WebSandbox**: A compilable and renderable web sandbox providing compile error/success and render error events, with support for theme mode and slot extensions. +- **MonacoEditor**: A code editor based on Monaco, supporting initialization with local or CDN loaders, with value change events and theme mode. + +Section sources + +- [frontend/pro/chatbot/Index.svelte:1-90](file://frontend/pro/chatbot/Index.svelte#L1-L90) +- [frontend/pro/multimodal-input/Index.svelte:1-99](file://frontend/pro/multimodal-input/Index.svelte#L1-L99) +- [frontend/pro/web-sandbox/Index.svelte:1-76](file://frontend/pro/web-sandbox/Index.svelte#L1-L76) +- [frontend/pro/monaco-editor/Index.svelte:1-101](file://frontend/pro/monaco-editor/Index.svelte#L1-L101) + +## Architecture Overview + +All four components adopt a unified bridging pattern: the Svelte layer handles property resolution, event writeback, dynamic imports, and slot rendering; the underlying TSX components carry the specific UI logic; the runtime shared context (`gradio.shared`) provides global configurations such as `root`, `api_prefix`, and `theme`. + +```mermaid +sequenceDiagram +participant App as "Application" +participant S as "Svelte Bridge Layer" +participant R as "React/TSX Component" +participant G as "Gradio Shared Context" +App->>S : Pass properties and slots +S->>G : Read root/api_prefix/theme +S->>R : Dynamic import and pass properties/events +R-->>S : Value change callback +S->>App : updateProps writes back value +S-->>App : Render slot content +``` + +Diagram sources + +- [frontend/pro/chatbot/Index.svelte:14-64](file://frontend/pro/chatbot/Index.svelte#L14-L64) +- [frontend/pro/monaco-editor/Index.svelte:14-89](file://frontend/pro/monaco-editor/Index.svelte#L14-L89) +- [frontend/pro/multimodal-input/Index.svelte:17-66](file://frontend/pro/multimodal-input/Index.svelte#L17-L66) +- [frontend/pro/web-sandbox/Index.svelte:14-57](file://frontend/pro/web-sandbox/Index.svelte#L14-L57) + +## Detailed Component Analysis + +### Chatbot Component API + +- Package exports and entry point + - Package name and export mapping follow the standard; the main entry points to `Index.svelte`. +- Property definitions + - `additional_props`: Additional property passthrough + - `as_item`: Element identifier + - `_internal`: Internal layout flag + - `value`: Message array, type see `ChatbotMessages` + - `suggestion_select` / `welcome_prompt_select`: Event callback alias mappings + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` + - Runtime shared: `gradio.shared.root`, `gradio.shared.api_prefix`, `gradio.shared.theme` +- Events and callbacks + - `onValueChange`: Value change writeback to parent component +- Slot system + - Supports `children` slot and `slots` mapping +- Data model and types + - `ChatbotMessages`, `ChatbotMessage`, `ChatbotMessageContentObject`, action types (`like`/`dislike`/`retry`/`copy`/`edit`/`delete`), etc. +- Advanced features + - Theme mode inherited from `gradio.shared.theme` + - Built-in composite display of welcome messages, suggested prompts, files/tools/text content +- Usage examples (paths) + - Basic usage and value binding: [frontend/pro/chatbot/Index.svelte:76-84](file://frontend/pro/chatbot/Index.svelte#L76-L84) + - Event writeback: [frontend/pro/chatbot/Index.svelte:76-80](file://frontend/pro/chatbot/Index.svelte#L76-L80) + - Type definition reference: [frontend/pro/chatbot/type.ts:160-197](file://frontend/pro/chatbot/type.ts#L160-L197) + +```mermaid +classDiagram +class ChatbotMessage { ++role ++content ++status ++meta ++key +} +class ChatbotMessages { +} +class ChatbotMessageContentObject { ++type ++content ++options +} +ChatbotMessages --> ChatbotMessage +ChatbotMessage --> ChatbotMessageContentObject +``` + +Diagram sources + +- [frontend/pro/chatbot/type.ts:137-158](file://frontend/pro/chatbot/type.ts#L137-L158) +- [frontend/pro/chatbot/type.ts:121-135](file://frontend/pro/chatbot/type.ts#L121-L135) + +Section sources + +- [frontend/pro/chatbot/package.json:1-15](file://frontend/pro/chatbot/package.json#L1-L15) +- [frontend/pro/chatbot/Index.svelte:14-64](file://frontend/pro/chatbot/Index.svelte#L14-L64) +- [frontend/pro/chatbot/Index.svelte:76-84](file://frontend/pro/chatbot/Index.svelte#L76-L84) +- [frontend/pro/chatbot/type.ts:160-197](file://frontend/pro/chatbot/type.ts#L160-L197) + +### MultimodalInput Component API + +- Package exports and entry point + - Package name and export mapping follow the standard; the main entry points to `Index.svelte`. +- Property definitions + - `additional_props`: Additional property passthrough + - `_internal`: Internal flag + - `value`: Multimodal input value, type from the underlying component + - `key_press` / `paste_file` / `key_down`: Event callback alias mappings + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` + - Runtime shared: `gradio.shared.theme` +- Events and callbacks + - `onValueChange`: Value change writeback +- Slot system + - Supports `children` slot and `slots` mapping +- File upload + - Upload hook: Uploads files via `gradio.shared.client.upload`, returns `FileData[]` +- Usage examples (paths) + - Value binding and event writeback: [frontend/pro/multimodal-input/Index.svelte:88-92](file://frontend/pro/multimodal-input/Index.svelte#L88-L92) + - Upload flow: [frontend/pro/multimodal-input/Index.svelte:68-75](file://frontend/pro/multimodal-input/Index.svelte#L68-L75) + +```mermaid +sequenceDiagram +participant UI as "MultimodalInput" +participant GR as "Gradio Client" +participant SV as "Svelte Bridge Layer" +UI->>GR : upload(prepare_files(files)) +GR-->>UI : FileData[] +UI->>SV : updateProps({ value }) +``` + +Diagram sources + +- [frontend/pro/multimodal-input/Index.svelte:68-75](file://frontend/pro/multimodal-input/Index.svelte#L68-L75) +- [frontend/pro/multimodal-input/Index.svelte:88-92](file://frontend/pro/multimodal-input/Index.svelte#L88-L92) + +Section sources + +- [frontend/pro/multimodal-input/package.json:1-15](file://frontend/pro/multimodal-input/package.json#L1-L15) +- [frontend/pro/multimodal-input/Index.svelte:17-66](file://frontend/pro/multimodal-input/Index.svelte#L17-L66) +- [frontend/pro/multimodal-input/Index.svelte:68-75](file://frontend/pro/multimodal-input/Index.svelte#L68-L75) + +### WebSandbox Component API + +- Package exports and entry point + - Package name and export mapping follow the standard; the main entry points to `Index.svelte`. +- Property definitions + - `additional_props`: Additional property passthrough + - `_internal`: Internal flag + - `value`: Sandbox value, type from the underlying component + - `compile_error` / `compile_success` / `render_error`: Event callback alias mappings + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` + - Runtime shared: `gradio.shared.theme` +- Slot system + - Supports `children` slot and `slots` mapping +- Usage examples (paths) + - Value binding and theme: [frontend/pro/web-sandbox/Index.svelte:62-70](file://frontend/pro/web-sandbox/Index.svelte#L62-L70) + +```mermaid +flowchart TD +Start(["Start"]) --> CheckVisible["Check visible"] +CheckVisible --> |No| End(["End"]) +CheckVisible --> |Yes| Load["Dynamically load WebSandbox"] +Load --> Render["Render and pass value/slots/theme"] +Render --> End +``` + +Diagram sources + +- [frontend/pro/web-sandbox/Index.svelte:60-75](file://frontend/pro/web-sandbox/Index.svelte#L60-L75) + +Section sources + +- [frontend/pro/web-sandbox/package.json:1-15](file://frontend/pro/web-sandbox/package.json#L1-L15) +- [frontend/pro/web-sandbox/Index.svelte:14-57](file://frontend/pro/web-sandbox/Index.svelte#L14-L57) +- [frontend/pro/web-sandbox/Index.svelte:62-70](file://frontend/pro/web-sandbox/Index.svelte#L62-L70) + +### MonacoEditor Component API + +- Package exports and entry point + - Package name and export mapping follow the standard; the main entry points to `Index.svelte`. +- Property definitions + - `additional_props`: Additional property passthrough + - `_internal`: Internal flag + - `value`: Editor initial value + - `_loader`: Loader configuration + - `mode`: `'cdn'` | `'local'` + - `cdn_url`: CDN path + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` + - Runtime shared: `gradio.shared.theme` +- Events and callbacks + - `onValueChange`: Value change writeback +- Slot system + - Supports `children` slot and `slots` mapping +- Loader mechanism + - Local loading: Initializes Monaco and registers Workers by language + - CDN loading: Sets the `vs` path +- Usage examples (paths) + - Value binding and theme: [frontend/pro/monaco-editor/Index.svelte:79-89](file://frontend/pro/monaco-editor/Index.svelte#L79-L89) + - Loader selection and initialization: [frontend/pro/monaco-editor/Index.svelte:61-70](file://frontend/pro/monaco-editor/Index.svelte#L61-L70) + - Loader implementation: [frontend/pro/monaco-editor/loader.ts:27-94](file://frontend/pro/monaco-editor/loader.ts#L27-L94) + +```mermaid +flowchart TD +A["Select Loader"] --> B{"mode=local?"} +B --> |Yes| C["initLocalLoader()
Register Monaco and Workers"] +B --> |No| D{"cdn_url present?"} +D --> |Yes| E["initCDNLoader(cdn_url)
Set vs path"] +D --> |No| F["Use default configuration"] +C --> G["Done"] +E --> G +F --> G +``` + +Diagram sources + +- [frontend/pro/monaco-editor/Index.svelte:61-70](file://frontend/pro/monaco-editor/Index.svelte#L61-L70) +- [frontend/pro/monaco-editor/loader.ts:27-94](file://frontend/pro/monaco-editor/loader.ts#L27-L94) + +Section sources + +- [frontend/pro/monaco-editor/package.json:1-15](file://frontend/pro/monaco-editor/package.json#L1-L15) +- [frontend/pro/monaco-editor/Index.svelte:14-89](file://frontend/pro/monaco-editor/Index.svelte#L14-L89) +- [frontend/pro/monaco-editor/loader.ts:27-94](file://frontend/pro/monaco-editor/loader.ts#L27-L94) + +## Dependency Analysis + +- Unified dependency chain + - The Svelte bridge layer depends on `getProps`/`processProps`/`importComponent` and slot utilities from `@svelte-preprocess-react` + - Each component obtains shared configuration (`root`, `api_prefix`, `theme`) through `gradio.shared` + - File upload capability comes from `prepare_files` and `client.upload` of `@gradio/client` +- Inter-component coupling + - Low coupling: Each component independently maintains its own properties and events + - High cohesion: The bridge layer handles property processing and dynamic loading; underlying components focus on UI logic + +```mermaid +graph LR +SP["@svelte-preprocess-react/*"] --> BR["Svelte Bridge Layer"] +BR --> CH["Chatbot"] +BR --> ME["MonacoEditor"] +BR --> MU["MultimodalInput"] +BR --> WS["WebSandbox"] +GC["@gradio/client"] --> MU +GS["gradio.shared.*"] --> BR +``` + +Diagram sources + +- [frontend/pro/chatbot/Index.svelte:1-12](file://frontend/pro/chatbot/Index.svelte#L1-L12) +- [frontend/pro/monaco-editor/Index.svelte:1-12](file://frontend/pro/monaco-editor/Index.svelte#L1-L12) +- [frontend/pro/multimodal-input/Index.svelte:1-9](file://frontend/pro/multimodal-input/Index.svelte#L1-L9) +- [frontend/pro/web-sandbox/Index.svelte:1-8](file://frontend/pro/web-sandbox/Index.svelte#L1-L8) + +Section sources + +- [frontend/pro/chatbot/Index.svelte:1-12](file://frontend/pro/chatbot/Index.svelte#L1-L12) +- [frontend/pro/monaco-editor/Index.svelte:1-12](file://frontend/pro/monaco-editor/Index.svelte#L1-L12) +- [frontend/pro/multimodal-input/Index.svelte:1-9](file://frontend/pro/multimodal-input/Index.svelte#L1-L9) +- [frontend/pro/web-sandbox/Index.svelte:1-8](file://frontend/pro/web-sandbox/Index.svelte#L1-L8) + +## Performance Considerations + +- Dynamic imports and lazy loading + - Use `importComponent` to dynamically import underlying components to avoid blocking the initial render +- Computed properties and derived values + - Use `$derived` to reuse derived computations and reduce unnecessary re-renders +- Loader strategy + - MonacoEditor supports both local and CDN loaders; choose as needed to balance bundle size and network overhead +- Event writeback + - Trigger `updateProps` only when values change to avoid frequent writebacks +- File upload + - Use `prepare_files` and the Gradio client for uploads to reduce manual serialization costs + +## Troubleshooting Guide + +- Editor not loading + - Check that `_loader.mode` and `cdn_url` configurations are correct + - Confirm that `initCDNLoader`/`initLocalLoader` has completed initialization + - Reference: [frontend/pro/monaco-editor/Index.svelte:61-70](file://frontend/pro/monaco-editor/Index.svelte#L61-L70), [frontend/pro/monaco-editor/loader.ts:27-94](file://frontend/pro/monaco-editor/loader.ts#L27-L94) +- Upload failing + - Confirm that `gradio.shared.client` is available and `root` is correct + - Check `prepare_files` and the returned `FileData[]` + - Reference: [frontend/pro/multimodal-input/Index.svelte:68-75](file://frontend/pro/multimodal-input/Index.svelte#L68-L75) +- Theme not applied + - Confirm that `gradio.shared.theme` is set to `light`/`dark` + - Reference: [frontend/pro/chatbot/Index.svelte:83](file://frontend/pro/chatbot/Index.svelte#L83), [frontend/pro/web-sandbox/Index.svelte:70](file://frontend/pro/web-sandbox/Index.svelte#L70), [frontend/pro/monaco-editor/Index.svelte:88](file://frontend/pro/monaco-editor/Index.svelte#L88) + +Section sources + +- [frontend/pro/monaco-editor/Index.svelte:61-70](file://frontend/pro/monaco-editor/Index.svelte#L61-L70) +- [frontend/pro/monaco-editor/loader.ts:27-94](file://frontend/pro/monaco-editor/loader.ts#L27-L94) +- [frontend/pro/multimodal-input/Index.svelte:68-75](file://frontend/pro/multimodal-input/Index.svelte#L68-L75) +- [frontend/pro/chatbot/Index.svelte:83](file://frontend/pro/chatbot/Index.svelte#L83) +- [frontend/pro/web-sandbox/Index.svelte:70](file://frontend/pro/web-sandbox/Index.svelte#L70) +- [frontend/pro/monaco-editor/Index.svelte:88](file://frontend/pro/monaco-editor/Index.svelte#L88) + +## Conclusion + +This reference document systematically covers the API and implementation details of ModelScope Studio's Pro Svelte components, emphasizing the unified pattern of the bridge layer, the use of the runtime shared context, and deep integration with the Gradio ecosystem. Through well-designed properties, event writeback, and dynamic loading strategies, these components efficiently support core AI application scenarios such as conversation, code editing, multimodal input, and sandbox rendering. + +## Appendix + +- TypeScript types and interfaces + - Chatbot types: [frontend/pro/chatbot/type.ts:1-197](file://frontend/pro/chatbot/type.ts#L1-L197) +- Package exports and entry points + - Chatbot: [frontend/pro/chatbot/package.json:1-15](file://frontend/pro/chatbot/package.json#L1-L15) + - MonacoEditor: [frontend/pro/monaco-editor/package.json:1-15](file://frontend/pro/monaco-editor/package.json#L1-L15) + - MultimodalInput: [frontend/pro/multimodal-input/package.json:1-15](file://frontend/pro/multimodal-input/package.json#L1-L15) + - WebSandbox: [frontend/pro/web-sandbox/package.json:1-15](file://frontend/pro/web-sandbox/package.json#L1-L15) +- Component bridge implementations + - Chatbot: [frontend/pro/chatbot/Index.svelte:1-90](file://frontend/pro/chatbot/Index.svelte#L1-L90) + - MonacoEditor: [frontend/pro/monaco-editor/Index.svelte:1-101](file://frontend/pro/monaco-editor/Index.svelte#L1-L101) + - MultimodalInput: [frontend/pro/multimodal-input/Index.svelte:1-99](file://frontend/pro/multimodal-input/Index.svelte#L1-L99) + - WebSandbox: [frontend/pro/web-sandbox/Index.svelte:1-76](file://frontend/pro/web-sandbox/Index.svelte#L1-L76) diff --git a/.wiki/en/API Reference/JavaScript API/Svelte Component API/Svelte Components API.md b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Svelte Components API.md new file mode 100644 index 00000000..9784d1f0 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Svelte Component API/Svelte Components API.md @@ -0,0 +1,415 @@ +# Svelte Components API + + +**Files referenced in this document** +- [frontend/package.json](file://frontend/package.json) +- [frontend/tsconfig.json](file://frontend/tsconfig.json) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/form/Index.svelte](file://frontend/antd/form/Index.svelte) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/layout/Index.svelte](file://frontend/antd/layout/Index.svelte) +- [frontend/antd/modal/Index.svelte](file://frontend/antd/modal/Index.svelte) +- [frontend/antd/table/Index.svelte](file://frontend/antd/table/Index.svelte) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [frontend/utils/createFunction.ts](file://frontend/utils/createFunction.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Best Practices](#performance-and-best-practices) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference for ModelScope Studio frontend Svelte components, focusing on the Svelte component encapsulation system based on the Ant Design (Antd) ecosystem. The document covers: + +- Component property definitions: props interfaces, default values, and type constraints +- Event system: user interaction events, state change events, and custom events +- Slot system: usage of default slots, named slots, and scoped slots +- Lifecycle and rendering: component instantiation, async loading, and conditional rendering +- Inter-component communication: parent-child, sibling, and cross-level communication patterns +- Style customization: CSS class names, theme variables, and inline styles +- TypeScript types: interface specifications, generic usage, and type inference +- Performance optimization: on-demand loading, derived computation, and event throttling recommendations + +## Project Structure + +The frontend uses a multi-package organization, with core components in `frontend/antd` and `frontend/antdx`, implementing Antd components in Svelte through the Svelte 5 and React component bridging solution. + +```mermaid +graph TB +subgraph "Frontend Packages" +A["frontend/package.json"] +B["frontend/tsconfig.json"] +end +subgraph "Antd Component Layer" +BTN["antd/button/Index.svelte"] +BTN_TS["antd/button/button.tsx"] +FORM["antd/form/Index.svelte"] +FORM_TS["antd/form/form.tsx"] +LYT["antd/layout/Index.svelte"] +MODAL["antd/modal/Index.svelte"] +TAB["antd/table/Index.svelte"] +end +subgraph "Common Utilities" +RS["utils/renderSlot.tsx"] +CF["utils/createFunction.ts"] +end +A --> BTN +A --> FORM +A --> LYT +A --> MODAL +A --> TAB +BTN --> BTN_TS +FORM --> FORM_TS +BTN_TS --> RS +FORM_TS --> RS +BTN_TS --> CF +FORM_TS --> CF +``` + +**Diagram sources** + +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/modal/Index.svelte:1-63](file://frontend/antd/modal/Index.svelte#L1-L63) +- [frontend/antd/table/Index.svelte:1-61](file://frontend/antd/table/Index.svelte#L1-L61) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) + +**Section sources** + +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) + +## Core Components + +This section provides an overview of the responsibilities and common characteristics of the main components: + +- **Button**: Wraps Antd Button, supports icon and loading state slots, with visibility control and class name concatenation. +- **Form**: Wraps Antd Form, provides value synchronization, action triggers (reset/submit/validate), required mark, and feedback icon slots. +- **Layout**: Basic layout container that passes through children and component identifiers. +- **Modal**: Wraps Antd Modal, supports visibility control and slots. +- **Table**: Wraps Antd Table, supports visibility control and slots. + +**Section sources** + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/modal/Index.svelte:1-63](file://frontend/antd/modal/Index.svelte#L1-L63) +- [frontend/antd/table/Index.svelte:1-61](file://frontend/antd/table/Index.svelte#L1-L61) + +## Architecture Overview + +Components adopt a three-layer architecture of "Svelte layer + React wrapping layer + utility functions": + +- Svelte layer: Responsible for property collection, slot resolution, conditional rendering, and async loading. +- React wrapping layer: Uses `sveltify` to bridge Antd components for use in Svelte, handling slots and callbacks. +- Utility functions: Provides slot rendering, function-string-to-function conversion, and other capabilities. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Component Layer (Index.svelte)" +participant Utils as "Utilities (renderSlot.tsx/createFunction.ts)" +participant ReactComp as "React Wrapping Layer (button.tsx/form.tsx)" +participant Antd as "Antd Component" +Svelte->>Svelte : Collect props and slots +Svelte->>ReactComp : Async import and pass props +ReactComp->>Utils : Render slots / wrap functions +ReactComp->>Antd : Render Antd component +Antd-->>ReactComp : Callback events +ReactComp-->>Svelte : Trigger update/action +``` + +**Diagram sources** + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) + +## Component Details + +### Button + +- Responsibility: Exposes Antd Button as a Svelte component, supports icon and loading state slots; conditionally renders based on visibility; concatenates style class names. +- Key props + - `additional_props?: Record`: Additional property passthrough + - `value?: string | undefined`: Button text or value + - `as_item?: string | undefined`: Used as item identifier + - `_internal: { layout?: boolean }`: Internal layout flag + - `href_target?: string`: Link target attribute mapping + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` +- Event system + - Events triggered by the underlying Antd Button are passed through via `{...props}` +- Slot system + - `icon`: Icon slot + - `loading.icon`: Loading state icon slot +- Lifecycle and rendering + - Uses `importComponent` to asynchronously load the wrapper component + - Conditional rendering: only renders when `visible` is true +- Style customization + - Inline `style` and `className` passthrough + - Fixed class name: `ms-gr-antd-button` +- TypeScript types + - Wraps Antd Button's `GetProps` type via `sveltify` + - Slot allowlist: `['icon', 'loading.icon']` + +```mermaid +classDiagram +class ButtonWrapper { ++props : AdditionalProps ++value : string|undefined ++as_item : string|undefined ++_internal : Internal ++href_target : string ++visible : boolean ++elem_id : string ++elem_classes : string[] ++elem_style : Record +} +class AntdButton { ++props : AntdButtonProps ++slots : Slots ++value : string +} +ButtonWrapper --> AntdButton : "sveltify wrapper" +``` + +**Diagram sources** + +- [frontend/antd/button/Index.svelte:12-56](file://frontend/antd/button/Index.svelte#L12-L56) +- [frontend/antd/button/button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) + +**Section sources** + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) + +### Form + +- Responsibility: Wraps Antd Form to provide value synchronization, action triggering, and slot extensions. +- Key props + - `additional_props?: Record` + - `_internal: { layout?: boolean }` + - `value?: Record`: Form initial values + - `form_action?: FormProps['formAction'] | null`: Action command (`reset`/`submit`/`validate`/`null`) + - `form_name?: string`: Form name mapping + - `fields_change?: any`, `finish_failed?: any`, `values_change?: any`: Event mapping + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` +- Event system + - `onValueChange(value: Record)`: Value change callback + - `onResetFormAction()`: Resets `form_action` after action execution +- Slot system + - `requiredMark`: Required mark slot +- Lifecycle and rendering + - Uses `importComponent` to asynchronously load the wrapper component + - Conditional rendering: only renders when `visible` is true +- Style customization + - Inline `style` and `className` passthrough + - Fixed class name: `ms-gr-antd-form` +- TypeScript types + - `FormProps` extends Antd Form Props, adding `value`, `onValueChange`, `formAction`, `onResetFormAction` + - Slot allowlist: `['requiredMark']` + +```mermaid +sequenceDiagram +participant S as "Svelte Form (Index.svelte)" +participant R as "React Form (form.tsx)" +participant F as "Antd Form" +participant U as "Utilities (createFunction.ts)" +S->>R : Pass props and slots +R->>U : Required mark / feedback icon function wrapping +R->>F : Render Antd Form and bind onValuesChange +F-->>R : Trigger onValuesChange(changedValues, values) +R-->>S : onValueChange(values) +S->>S : updateProps({ value }) +``` + +**Diagram sources** + +- [frontend/antd/form/Index.svelte:14-98](file://frontend/antd/form/Index.svelte#L14-L98) +- [frontend/antd/form/form.tsx:8-76](file://frontend/antd/form/form.tsx#L8-L76) +- [frontend/utils/createFunction.ts:10-37](file://frontend/utils/createFunction.ts#L10-L37) + +**Section sources** + +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +### Layout + +- Responsibility: Basic layout container that passes through children and component identifiers. +- Key props + - `children: Snippet`: Default slot content +- Lifecycle and rendering + - Directly renders the Base container component as a layout +- Style customization + - Styles and class names are handled by the Base component + +**Section sources** + +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) + +### Modal + +- Responsibility: Wraps Antd Modal, supports visibility control and slots. +- Key props + - `additional_props?: Record` + - `as_item?: string | undefined` + - `_internal: { layout?: boolean }` + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` +- Slot system + - Default slot: Content area +- Style customization + - Fixed class name: `ms-gr-antd-modal` + +**Section sources** + +- [frontend/antd/modal/Index.svelte:1-63](file://frontend/antd/modal/Index.svelte#L1-L63) + +### Table + +- Responsibility: Wraps Antd Table, supports visibility control and slots. +- Key props + - `additional_props?: Record` + - `as_item?: string | undefined` + - `_internal: {}` + - Visibility and style: `visible`, `elem_id`, `elem_classes`, `elem_style` +- Slot system + - Default slot: Content area +- Style customization + - Fixed class name: `ms-gr-antd-table` + +**Section sources** + +- [frontend/antd/table/Index.svelte:1-61](file://frontend/antd/table/Index.svelte#L1-L61) + +## Dependency Analysis + +- Component dependencies + - The Svelte layer depends on `getProps`/`importComponent`/`processProps`/`getSlots` provided by `@svelte-preprocess-react` + - The React wrapping layer depends on the Ant Design component library and `sveltify`/`ReactSlot` from `@svelte-preprocess-react` + - The utility layer provides slot rendering and function-string parsing capabilities +- External dependencies + - Svelte 5, Antd, classnames, dayjs, immer, lodash-es, marked, mermaid, monaco-editor, etc. + +```mermaid +graph LR +IDX_BTN["button/Index.svelte"] --> WRAP_BTN["button/button.tsx"] +IDX_FORM["form/Index.svelte"] --> WRAP_FORM["form/form.tsx"] +WRAP_BTN --> SLOT["utils/renderSlot.tsx"] +WRAP_FORM --> SLOT +WRAP_BTN --> CF["utils/createFunction.ts"] +WRAP_FORM --> CF +``` + +**Diagram sources** + +- [frontend/antd/button/Index.svelte:6-7](file://frontend/antd/button/Index.svelte#L6-L7) +- [frontend/antd/button/button.tsx:1-6](file://frontend/antd/button/button.tsx#L1-L6) +- [frontend/antd/form/Index.svelte:6-7](file://frontend/antd/form/Index.svelte#L6-L7) +- [frontend/antd/form/form.tsx:1-6](file://frontend/antd/form/form.tsx#L1-L6) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) + +**Section sources** + +- [frontend/package.json:8-39](file://frontend/package.json#L8-L39) + +## Performance and Best Practices + +- On-demand loading + - Use `importComponent` to asynchronously import React wrapper components to avoid blocking the initial render +- Derived computation + - Use `$derived` to derive from props and reduce redundant computation +- Event throttling and debouncing + - For frequently-triggered callbacks (such as `onValuesChange`), throttle/debounce can be combined with utility functions +- Slot rendering optimization + - Use `forceClone` and `params` judiciously to avoid unnecessary cloning overhead +- Styles and themes + - Prefer combining `className` with inline styles; introduce Antd theme variables when necessary to ensure consistency + +[This section provides general guidance and does not require specific file references] + +## Troubleshooting Guide + +- Slot not taking effect + - Check if the slot name matches the wrapper layer allowlist (e.g., `icon`, `loading.icon`, `requiredMark`) + - Confirm that slot elements are properly passed to `slots` +- Function string cannot execute + - Use `createFunction` to convert the string to a function; ensure the format is valid +- Action not triggered + - Confirm the `form_action` value matches the wrapper layer switch branch (`reset`/`submit`/`validate`/`null`) + - Call `onResetFormAction` promptly after action execution to reset the state +- Visibility issues + - Ensure the component is only rendered when `visible` is truthy to avoid empty rendering + +**Section sources** + +- [frontend/antd/button/button.tsx:10-36](file://frontend/antd/button/button.tsx#L10-L36) +- [frontend/antd/form/form.tsx:32-45](file://frontend/antd/form/form.tsx#L32-L45) +- [frontend/utils/createFunction.ts:10-37](file://frontend/utils/createFunction.ts#L10-L37) + +## Conclusion + +ModelScope Studio's Svelte Component API achieves stable use of Antd components in Svelte through a unified bridge layer and utility functions. Its design emphasizes: + +- Clear props interfaces and type constraints +- Rich slot system and event mapping +- Controllable rendering and style strategies +- Extensible toolchain to support complex scenarios + +[This section is a summary and does not require specific file references] + +## Appendix + +### Component Properties and Events Quick Reference (Summary) + +- **Button** + - Properties: `additional_props`, `value`, `as_item`, `_internal`, `href_target`, `visible`, `elem_id`, `elem_classes`, `elem_style` + - Events: Passed through from Antd Button + - Slots: `icon`, `loading.icon` + - Class name: Fixed `ms-gr-antd-button` +- **Form** + - Properties: `additional_props`, `_internal`, `value`, `form_action`, `form_name`, `fields_change`, `finish_failed`, `values_change`, `visible`, `elem_id`, `elem_classes`, `elem_style` + - Events: `onValueChange`, `onResetFormAction` + - Slots: `requiredMark` + - Class name: Fixed `ms-gr-antd-form` +- **Layout** + - Properties: `children` (default slot) +- **Modal** + - Properties: `additional_props`, `as_item`, `_internal`, `visible`, `elem_id`, `elem_classes`, `elem_style` + - Class name: Fixed `ms-gr-antd-modal` +- **Table** + - Properties: `additional_props`, `as_item`, `_internal`, `visible`, `elem_id`, `elem_classes`, `elem_style` + - Class name: Fixed `ms-gr-antd-table` + +**Section sources** + +- [frontend/antd/button/Index.svelte:12-56](file://frontend/antd/button/Index.svelte#L12-L56) +- [frontend/antd/button/button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) +- [frontend/antd/form/Index.svelte:14-98](file://frontend/antd/form/Index.svelte#L14-L98) +- [frontend/antd/form/form.tsx:8-76](file://frontend/antd/form/form.tsx#L8-L76) +- [frontend/antd/layout/Index.svelte:6-14](file://frontend/antd/layout/Index.svelte#L6-L14) +- [frontend/antd/modal/Index.svelte:22-44](file://frontend/antd/modal/Index.svelte#L22-L44) +- [frontend/antd/table/Index.svelte:20-42](file://frontend/antd/table/Index.svelte#L20-L42) diff --git a/.wiki/en/API Reference/JavaScript API/Utility Functions API.md b/.wiki/en/API Reference/JavaScript API/Utility Functions API.md new file mode 100644 index 00000000..48260000 --- /dev/null +++ b/.wiki/en/API Reference/JavaScript API/Utility Functions API.md @@ -0,0 +1,582 @@ +# Utility Functions API + + +**Files referenced in this document** +- [convertToCamelCase.ts](file://frontend/utils/convertToCamelCase.ts) +- [patchProps.tsx](file://frontend/utils/patchProps.tsx) +- [omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) +- [renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [patchSlots.ts](file://frontend/utils/patchSlots.ts) +- [style.ts](file://frontend/utils/style.ts) +- [upload.ts](file://frontend/utils/upload.ts) +- [walkHtmlNodes.ts](file://frontend/utils/walkHtmlNodes.ts) +- [createFunction.ts](file://frontend/utils/createFunction.ts) +- [tick.ts](file://frontend/utils/tick.ts) +- [renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [useMemoizedEqualValue.ts](file://frontend/utils/hooks/useMemoizedEqualValue.ts) +- [useMemoizedFn.ts](file://frontend/utils/hooks/useMemoizedFn.ts) +- [useSlotsChildren.ts](file://frontend/utils/hooks/useSlotsChildren.ts) +- [useTargets.ts](file://frontend/utils/hooks/useTargets.ts) +- [useUpdate.ts](file://frontend/utils/hooks/useUpdate.ts) +- [useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the API reference and usage guide for the ModelScope Studio frontend utility function system, covering the following topics: + +- Property handling: `convertToCamelCase`, `patchProps`, `omitUndefinedProps`, etc. +- Slot handling: `renderSlot`, `renderItems`, `patchSlots`, `renderParamsSlot` +- Style handling: Style computation and application in `style.ts` +- Upload handling: URL resolution and file address conversion in `upload.ts` +- HTML traversal: Node finding and callbacks in `walkHtmlNodes` +- Functions and hooks: `createFunction`, hooks series (`useFunction`, `useMemoizedFn`, `useMemoizedEqualValue`, `useSlotsChildren`, `useTargets`, `useUpdate`, `useValueChange`) +- Practical usage examples, performance characteristics and best practices, error handling and edge cases + +## Project Structure + +Utility functions are centralized in the `frontend/utils` directory, organized by functional layers; the `hooks` subdirectory provides React Hooks wrappers. + +```mermaid +graph TB +subgraph "Utility Functions (utils)" +A["convertToCamelCase.ts"] +B["patchProps.tsx"] +C["omitUndefinedProps.ts"] +D["renderSlot.tsx"] +E["renderItems.tsx"] +F["patchSlots.ts"] +G["style.ts"] +H["upload.ts"] +I["walkHtmlNodes.ts"] +J["createFunction.ts"] +K["tick.ts"] +L["renderParamsSlot.tsx"] +end +subgraph "Hooks" +H1["useFunction.ts"] +H2["useMemoizedFn.ts"] +H3["useMemoizedEqualValue.ts"] +H4["useSlotsChildren.ts"] +H5["useTargets.ts"] +H6["useUpdate.ts"] +H7["useValueChange.ts"] +end +D --> B +E --> B +L --> D +H1 --> J +``` + +Diagram sources + +- [renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) +- [patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [style.ts:1-77](file://frontend/utils/style.ts#L1-L77) +- [upload.ts:1-45](file://frontend/utils/upload.ts#L1-L45) +- [walkHtmlNodes.ts:1-19](file://frontend/utils/walkHtmlNodes.ts#L1-L19) +- [createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) +- [tick.ts:1-13](file://frontend/utils/tick.ts#L1-L13) +- [renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useMemoizedFn.ts:1-11](file://frontend/utils/hooks/useMemoizedFn.ts#L1-L11) +- [useMemoizedEqualValue.ts:1-15](file://frontend/utils/hooks/useMemoizedEqualValue.ts#L1-L15) +- [useSlotsChildren.ts:1-24](file://frontend/utils/hooks/useSlotsChildren.ts#L1-L24) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [useUpdate.ts:1-7](file://frontend/utils/hooks/useUpdate.ts#L1-L7) +- [useValueChange.ts:1-30](file://frontend/utils/hooks/useValueChange.ts#L1-L30) + +Section sources + +- [convertToCamelCase.ts:1-22](file://frontend/utils/convertToCamelCase.ts#L1-L22) +- [patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) +- [omitUndefinedProps.ts:1-17](file://frontend/utils/omitUndefinedProps.ts#L1-L17) +- [renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [style.ts:1-77](file://frontend/utils/style.ts#L1-L77) +- [upload.ts:1-45](file://frontend/utils/upload.ts#L1-L45) +- [walkHtmlNodes.ts:1-19](file://frontend/utils/walkHtmlNodes.ts#L1-L19) +- [createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) +- [tick.ts:1-13](file://frontend/utils/tick.ts#L1-L13) +- [renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useMemoizedFn.ts:1-11](file://frontend/utils/hooks/useMemoizedFn.ts#L1-L11) +- [useMemoizedEqualValue.ts:1-15](file://frontend/utils/hooks/useMemoizedEqualValue.ts#L1-L15) +- [useSlotsChildren.ts:1-24](file://frontend/utils/hooks/useSlotsChildren.ts#L1-L24) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [useUpdate.ts:1-7](file://frontend/utils/hooks/useUpdate.ts#L1-L7) +- [useValueChange.ts:1-30](file://frontend/utils/hooks/useValueChange.ts#L1-L30) + +## Core Components + +- Property handling + - `convertToCamelCase`: Converts underscore-style strings to camelCase; `convertObjectKeyToCamelCase`: Batch converts object key names + - `patchProps`/`applyPatchToProps`: Internal marking and restoration for key conflicts + - `omitUndefinedProps`: Filters out undefined (optionally also null) properties +- Slot handling + - `renderSlot`: Renders an HTMLElement slot as a React component, supporting cloning, force-cloning, and parameter passing + - `renderItems`: Renders structured items as React structures, automatically injecting slots, contexts, and keys + - `patchSlots`: Injects additional parameters (prepended or appended) into slot rendering functions + - `renderParamsSlot`: Renders parameterized slots based on multiple target nodes +- Style handling + - `styleObject2String`: Converts `CSSProperties` to a string + - `styleObject2HtmlStyle`: Converts `CSSProperties` to an HTML-compatible style object (with unit handling) + - `cssUnits`: Maps numeric values to unit-bearing strings (with no units for specific properties) +- Upload handling + - `getFetchableUrl`: Generates a URL for fetching a file + - `getFileUrl`: Uniformly resolves `FileData`, URL strings, and relative paths +- HTML traversal + - `walkHtmlNodes`: Depth-first node traversal, executing callbacks on matches by name, collection, or predicate +- Functions and hooks + - `createFunction`: Creates a callable function from a string or function + - hooks: `useFunction`, `useMemoizedFn`, `useMemoizedEqualValue`, `useSlotsChildren`, `useTargets`, `useUpdate`, `useValueChange` + +Section sources + +- [convertToCamelCase.ts:1-22](file://frontend/utils/convertToCamelCase.ts#L1-L22) +- [patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) +- [omitUndefinedProps.ts:1-17](file://frontend/utils/omitUndefinedProps.ts#L1-L17) +- [renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [style.ts:1-77](file://frontend/utils/style.ts#L1-L77) +- [upload.ts:1-45](file://frontend/utils/upload.ts#L1-L45) +- [walkHtmlNodes.ts:1-19](file://frontend/utils/walkHtmlNodes.ts#L1-L19) +- [createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useMemoizedFn.ts:1-11](file://frontend/utils/hooks/useMemoizedFn.ts#L1-L11) +- [useMemoizedEqualValue.ts:1-15](file://frontend/utils/hooks/useMemoizedEqualValue.ts#L1-L15) +- [useSlotsChildren.ts:1-24](file://frontend/utils/hooks/useSlotsChildren.ts#L1-L24) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [useUpdate.ts:1-7](file://frontend/utils/hooks/useUpdate.ts#L1-L7) +- [useValueChange.ts:1-30](file://frontend/utils/hooks/useValueChange.ts#L1-L30) + +## Architecture Overview + +The utility functions work together across six major domains — "properties/slots/styles/uploads/traversal/functions & hooks" — forming a complete pipeline from data structures to React rendering. + +```mermaid +graph TB +subgraph "Input Layer" +IN1["Raw Properties / Objects"] +IN2["DOM Slots / HTML Nodes"] +IN3["File Data / URLs / Paths"] +end +subgraph "Processing Layer" +P1["convertToCamelCase
omitUndefinedProps"] +P2["patchProps/applyPatchToProps"] +P3["renderSlot/renderItems/patchSlots"] +P4["style.ts computation"] +P5["upload.ts resolution"] +P6["walkHtmlNodes traversal"] +P7["createFunction / function factory"] +end +subgraph "Output Layer" +OUT1["React Component Tree"] +OUT2["Inline Style String / Object"] +OUT3["Accessible File URL"] +end +IN1 --> P1 --> P2 --> P3 --> OUT1 +IN2 --> P3 --> OUT1 +IN2 --> P6 --> OUT1 +IN3 --> P5 --> OUT3 +IN1 --> P4 --> OUT2 +IN1 --> P7 --> P3 +``` + +Diagram sources + +- [convertToCamelCase.ts:1-22](file://frontend/utils/convertToCamelCase.ts#L1-L22) +- [patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) +- [omitUndefinedProps.ts:1-17](file://frontend/utils/omitUndefinedProps.ts#L1-L17) +- [renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [style.ts:1-77](file://frontend/utils/style.ts#L1-L77) +- [upload.ts:1-45](file://frontend/utils/upload.ts#L1-L45) +- [walkHtmlNodes.ts:1-19](file://frontend/utils/walkHtmlNodes.ts#L1-L19) +- [createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) + +## Detailed Component Analysis + +### Property Handling Functions + +#### convertToCamelCase and convertObjectKeyToCamelCase + +- Functionality: Converts underscore-style naming to camelCase; batch converts object key names +- Parameters and return values: + - `convertToCamelCase(str: string): string` + - `convertObjectKeyToCamelCase(obj: T): T` +- Use case: Backend fields are often `snake_case`; use when frontend needs camelCase key names +- Complexity: O(n) character processing; O(k) key iteration for object conversion +- Edge cases: Non-objects are returned as-is + +Section sources + +- [convertToCamelCase.ts:1-22](file://frontend/utils/convertToCamelCase.ts#L1-L22) + +#### patchProps and applyPatchToProps + +- Functionality: Resolves React `key` conflicts; internally stashes `key` and restores it at the consumer side +- Parameters and return values: + - `patchProps(props: Record): Record` + - `applyPatchToProps(props: Record): Record` +- Use case: When incoming props contain `key` and need to be passed through to child components +- Complexity: O(n) shallow copy and conditional checks +- Edge cases: No modification when no `key` is present + +Section sources + +- [patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) + +#### omitUndefinedProps + +- Functionality: Filters out undefined (optionally also null) properties +- Parameters and return values: + - `omitUndefinedProps(props: T, options?: { omitNull?: boolean }): T` +- Use case: Reduces invalid property passing and avoids rendering anomalies +- Complexity: O(n) key iteration +- Edge cases: Safe with empty objects + +Section sources + +- [omitUndefinedProps.ts:1-17](file://frontend/utils/omitUndefinedProps.ts#L1-L17) + +### Slot Handling Functions + +#### renderSlot + +- Functionality: Renders an `HTMLElement` slot as a React component, supporting cloning, force-cloning, and parameter passing +- Parameters and return values: + - `renderSlot(el?: HTMLElement, options?: { clone?: boolean; forceClone?: boolean; params?: any[] }): ReactElement | null` +- Use case: Bridges Svelte/Gradio slot nodes to React +- Complexity: O(1) rendering overhead depends on slot content +- Edge cases: Returns `null` when `el` is empty; `forceClone` and `params` require context + +Section sources + +- [renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) + +#### renderItems + +- Functionality: Renders structured items as React structures, automatically injecting slots, contexts, and keys; supports recursive children +- Parameters and return values: + - `renderItems(items: Item[], options?: { children?: string; fallback?: (item) => R; clone?: boolean; forceClone?: boolean; itemPropsTransformer?: (props) => props }, key?: React.Key): R[] | undefined` +- Use case: Multi-slot and nested rendering for complex container components +- Complexity: O(m) where m is the number of valid items; slot injection is O(s) where s is the number of slots +- Edge cases: Non-object items can fall back; the `children` key is customizable + +Section sources + +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) + +#### patchSlots + +- Functionality: Injects additional parameters (prepended or appended) into slot rendering functions to uniformly pass context to slots +- Parameters and return values: + - `patchSlots(params: any[], transform: (patch) => Record): ReturnType` +- Use case: Uniformly injecting parameters into slot functions for improved reusability +- Complexity: O(p) where p is the length of params; function wrapping is O(1) +- Edge cases: Non-function slots are not processed + +Section sources + +- [patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) + +#### renderParamsSlot + +- Functionality: Renders parameterized slots based on multiple target nodes, supporting force-cloning +- Parameters and return values: + - `renderParamsSlot({ key, slots, targets }, options?: { forceClone?: boolean } & RenderSlotOptions)` +- Use case: Multiple target nodes sharing the same slot template with parameter passing +- Complexity: O(t) where t is the number of targets +- Edge cases: Returns `undefined` when no corresponding slot exists + +Section sources + +- [renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +### Style Handling Utilities + +#### style.ts + +- Functionality: Bidirectional conversion between style objects and strings / HTML style objects, with numeric unit handling +- Key functions: + - `styleObject2String(styleObj: React.CSSProperties): string` + - `styleObject2HtmlStyle(styleObj: React.CSSProperties): Record` + - `cssUnits(prop: T, value: number | string | undefined): string | number` +- Use case: Inline style concatenation, DOM attribute setting +- Complexity: O(n) where n is the number of style keys +- Edge cases: Numeric types automatically get `px` appended; specific properties remain unitless + +Section sources + +- [style.ts:1-77](file://frontend/utils/style.ts#L1-L77) + +### Upload Handling Functions + +#### upload.ts + +- Functionality: Uniformly resolves file sources and generates accessible URLs +- Key functions: + - `getFetchableUrl(path: string, rootUrl: string, apiPrefix: string): string` + - `getFileUrl(file: T, rootUrl: string, apiPrefix: string): string | Exclude | undefined` +- Use case: Uniform handling of local files, remote URLs, and `FileData` +- Complexity: O(1) +- Edge cases: Empty input returns `undefined`; non-http(s) strings are treated as relative paths + +Section sources + +- [upload.ts:1-45](file://frontend/utils/upload.ts#L1-L45) + +### HTML Node Traversal Utilities + +#### walkHtmlNodes + +- Functionality: Depth-first node traversal, executing callbacks on matches by name, collection, or predicate +- Parameters and return values: + - `walkHtmlNodes(node: Node | HTMLElement | null, test: string | string[] | ((node) => boolean), callback: (node) => void): void` +- Use case: Finding specific tags, batch node operations +- Complexity: O(n) where n is the total number of nodes +- Edge cases: Safe with null nodes; array and function forms allow flexible matching + +Section sources + +- [walkHtmlNodes.ts:1-19](file://frontend/utils/walkHtmlNodes.ts#L1-L19) + +### Functions and Hooks + +#### createFunction + +- Functionality: Creates a callable function from a string or function, with support for plain-text mode validation +- Parameters and return values: + - `createFunction(target: any, plainText?: boolean): T | undefined` +- Use case: Dynamic function creation, runtime code injection +- Complexity: O(1) for creation; execution depends on the function body +- Edge cases: Invalid strings return `undefined`; exceptions are caught + +Section sources + +- [createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) + +#### Hooks Series + +- `useFunction`: Memoizes the result of `createFunction` +- `useMemoizedFn`: Stabilizes function references to avoid closure traps +- `useMemoizedEqualValue`: Equal-value caching to avoid unnecessary re-renders +- `useSlotsChildren`: Distinguishes slot children from regular children +- `useTargets`: Extracts portal target nodes sorted by `slotKey` +- `useUpdate`: Triggers a state update to force a refresh +- `useValueChange`: Synchronizes external values with internal state changes + +Section sources + +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useMemoizedFn.ts:1-11](file://frontend/utils/hooks/useMemoizedFn.ts#L1-L11) +- [useMemoizedEqualValue.ts:1-15](file://frontend/utils/hooks/useMemoizedEqualValue.ts#L1-L15) +- [useSlotsChildren.ts:1-24](file://frontend/utils/hooks/useSlotsChildren.ts#L1-L24) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [useUpdate.ts:1-7](file://frontend/utils/hooks/useUpdate.ts#L1-L7) +- [useValueChange.ts:1-30](file://frontend/utils/hooks/useValueChange.ts#L1-L30) + +## Dependency Analysis + +```mermaid +graph LR +CF["createFunction.ts"] --> UF["useFunction.ts"] +PP["patchProps.tsx"] --> RS["renderSlot.tsx"] +PP --> RI["renderItems.tsx"] +PS["patchSlots.ts"] --> RI +ST["style.ts"] --> OUT1["Inline Style Output"] +UP["upload.ts"] --> OUT2["File URL Output"] +WH["walkHtmlNodes.ts"] --> RS +WH --> RI +``` + +Diagram sources + +- [createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) +- [renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [style.ts:1-77](file://frontend/utils/style.ts#L1-L77) +- [upload.ts:1-45](file://frontend/utils/upload.ts#L1-L45) +- [walkHtmlNodes.ts:1-19](file://frontend/utils/walkHtmlNodes.ts#L1-L19) + +## Performance Considerations + +- Batch object key conversion and property filtering: O(k) and O(n); recommended to call only when necessary +- Slot rendering: `clone` and `forceClone` increase rendering cost; enable on-demand when possible +- Style conversion: Numeric-to-string and unit concatenation are O(n); cache results for large style objects +- Upload URL resolution: O(1), but involves string concatenation and regex; validate path correctness +- HTML traversal: O(n); recommended to limit traversal scope or use more precise match conditions +- Function factory: `new Function` has compilation overhead; cache results with `useFunction` + +## Troubleshooting Guide + +- Slot not displayed + - Check whether `el` exists; confirm if `clone` or `forceClone` is needed + - If using parameterized slots, ensure `params` is provided and `targets` are correct +- Key conflicts or duplicates + - Use `patchProps`/`applyPatchToProps` for internal key mapping +- Style not applied + - Check `cssUnits` handling for specific properties; confirm whether numeric values need units +- Uploaded file not accessible + - Verify `rootUrl` and `apiPrefix` configuration; relative paths will be converted to fetchable URLs +- Nodes not found during traversal + - Check the `test` type (string/array/function) and the case sensitivity of node names +- Dynamic function not available + - In `plainText` mode, invalid strings return `undefined`; check syntax + +Section sources + +- [renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) +- [style.ts:1-77](file://frontend/utils/style.ts#L1-L77) +- [upload.ts:1-45](file://frontend/utils/upload.ts#L1-L45) +- [walkHtmlNodes.ts:1-19](file://frontend/utils/walkHtmlNodes.ts#L1-L19) +- [createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) + +## Conclusion + +This utility function system provides full-stack capabilities from properties/slots/styles/uploads/traversal to functions and hooks, bridging the Svelte/Gradio ecosystem while accommodating the flexibility and performance of React rendering. Through proper parameter configuration and edge case handling, a consistent and maintainable development experience can be achieved in complex component scenarios. + +## Appendix + +### API Definitions and Key Usage Points + +- `convertToCamelCase` + - Input: underscore-style string + - Output: camelCase string + - Example path: [convertToCamelCase.ts:3-11](file://frontend/utils/convertToCamelCase.ts#L3-L11) + +- `convertObjectKeyToCamelCase` + - Input: object + - Output: new object with camelCase keys + - Example path: [convertToCamelCase.ts:13-21](file://frontend/utils/convertToCamelCase.ts#L13-L21) + +- `patchProps` / `applyPatchToProps` + - Input: props (possibly containing `key`) + - Output: props with internal `key` marked or restored + - Example path: [patchProps.tsx:3-22](file://frontend/utils/patchProps.tsx#L3-L22) + +- `omitUndefinedProps` + - Input: props, optional `omitNull` + - Output: filtered props + - Example path: [omitUndefinedProps.ts:1-16](file://frontend/utils/omitUndefinedProps.ts#L1-L16) + +- `renderSlot` + - Input: `HTMLElement`, optional `clone`/`forceClone`/`params` + - Output: `ReactElement` or `null` + - Example path: [renderSlot.tsx:13-28](file://frontend/utils/renderSlot.tsx#L13-L28) + +- `renderItems` + - Input: `Item[]`, optional `children`/`fallback`/`clone`/`forceClone`/`itemPropsTransformer` + - Output: `R[]` or `undefined` + - Example path: [renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +- `patchSlots` + - Input: `params[]`, `transform` function + - Output: enhanced return object + - Example path: [patchSlots.ts:4-31](file://frontend/utils/patchSlots.ts#L4-L31) + +- `renderParamsSlot` + - Input: `{ key, slots, targets }`, optional `options` + - Output: parameterized slot function or `undefined` + - Example path: [renderParamsSlot.tsx:5-49](file://frontend/utils/renderParamsSlot.tsx#L5-L49) + +- `style.ts` + - Input: `React.CSSProperties` + - Output: style string or HTML-compatible style object + - Example path: [style.ts:39-76](file://frontend/utils/style.ts#L39-L76) + +- `upload.ts` + - Input: `file` (`FileData | string | any`), `rootUrl`, `apiPrefix` + - Output: accessible URL or original value + - Example path: [upload.ts:27-44](file://frontend/utils/upload.ts#L27-L44) + +- `walkHtmlNodes` + - Input: `node`, `test` (string/array/function), `callback` + - Output: `void` + - Example path: [walkHtmlNodes.ts:1-18](file://frontend/utils/walkHtmlNodes.ts#L1-L18) + +- `createFunction` + - Input: `target` (function/string), `plainText` + - Output: callable function or `undefined` + - Example path: [createFunction.ts:10-37](file://frontend/utils/createFunction.ts#L10-L37) + +- hooks + - `useFunction`: [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) + - `useMemoizedFn`: [useMemoizedFn.ts:3-10](file://frontend/utils/hooks/useMemoizedFn.ts#L3-L10) + - `useMemoizedEqualValue`: [useMemoizedEqualValue.ts:4-14](file://frontend/utils/hooks/useMemoizedEqualValue.ts#L4-L14) + - `useSlotsChildren`: [useSlotsChildren.ts:4-23](file://frontend/utils/hooks/useSlotsChildren.ts#L4-L23) + - `useTargets`: [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) + - `useUpdate`: [useUpdate.ts:3-6](file://frontend/utils/hooks/useUpdate.ts#L3-L6) + - `useValueChange`: [useValueChange.ts:9-29](file://frontend/utils/hooks/useValueChange.ts#L9-L29) + +### Usage Flow Diagrams + +#### renderItems Data Flow + +```mermaid +flowchart TD +Start(["Start"]) --> Filter["Filter empty items"] +Filter --> Loop{"Iterate over each item"} +Loop --> |Is object| Merge["Merge props and set key"] +Merge --> Slots["Resolve slots mapping"] +Slots --> Children{"children key present?"} +Children --> |Yes| Recur["Recursively render children"] +Children --> |No| Push["Return current result"] +Recur --> Push +Push --> Next["Next item"] +Next --> Loop +Loop --> |End| End(["End"]) +``` + +Diagram sources + +- [renderItems.tsx:18-113](file://frontend/utils/renderItems.tsx#L18-L113) + +#### renderSlot Rendering Sequence + +```mermaid +sequenceDiagram +participant Caller as "Caller" +participant RS as "renderSlot" +participant CPS as "patchSlotProps" +participant RSP as "ReactSlot" +Caller->>RS : Pass el and options +alt Params required or force clone +RS->>CPS : Wrap children +CPS->>RSP : Pass slot/clone/params +else +RS->>RSP : Pass slot/clone directly +end +RSP-->>Caller : Return ReactElement +``` + +Diagram sources + +- [renderSlot.tsx:13-28](file://frontend/utils/renderSlot.tsx#L13-L28) +- [patchProps.tsx:31-38](file://frontend/utils/patchProps.tsx#L31-L38) diff --git a/.wiki/en/API Reference/Python API/Antd Components API/Antd Components API.md b/.wiki/en/API Reference/Python API/Antd Components API/Antd Components API.md new file mode 100644 index 00000000..f581ba60 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antd Components API/Antd Components API.md @@ -0,0 +1,371 @@ +# Antd Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/components/antd/button/__init__.py](file://backend/modelscope_studio/components/antd/button/__init__.py) +- [backend/modelscope_studio/components/antd/form/__init__.py](file://backend/modelscope_studio/components/antd/form/__init__.py) +- [backend/modelscope_studio/components/antd/table/__init__.py](file://backend/modelscope_studio/components/antd/table/__init__.py) +- [backend/modelscope_studio/components/antd/input/__init__.py](file://backend/modelscope_studio/components/antd/input/__init__.py) +- [backend/modelscope_studio/components/antd/select/__init__.py](file://backend/modelscope_studio/components/antd/select/__init__.py) +- [backend/modelscope_studio/components/antd/form/item/__init__.py](file://backend/modelscope_studio/components/antd/form/item/__init__.py) +- [backend/modelscope_studio/components/antd/table/column/__init__.py](file://backend/modelscope_studio/components/antd/table/column/__init__.py) +- [backend/modelscope_studio/components/antd/layout/__init__.py](file://backend/modelscope_studio/components/antd/layout/__init__.py) +- [backend/modelscope_studio/components/antd/menu/__init__.py](file://backend/modelscope_studio/components/antd/menu/__init__.py) +- [backend/modelscope_studio/components/antd/modal/__init__.py](file://backend/modelscope_studio/components/antd/modal/__init__.py) +- [backend/modelscope_studio/components/antd/message/__init__.py](file://backend/modelscope_studio/components/antd/message/__init__.py) +- [backend/modelscope_studio/components/antd/notification/__init__.py](file://backend/modelscope_studio/components/antd/notification/__init__.py) +- [backend/modelscope_studio/components/antd/card/__init__.py](file://backend/modelscope_studio/components/antd/card/__init__.py) +- [backend/modelscope_studio/components/antd/breadcrumb/__init__.py](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: API Index by Category](#appendix-api-index-by-category) + +## Introduction + +This document is the Python API reference for the Antd component library, covering 150+ components under `modelscope_studio.components.antd.*`. The documentation is designed for both developers and non-technical readers, providing: + +- Complete import paths and class names +- Constructor parameters, property definitions, method signatures, and return types +- Standard instantiation examples (given as code snippet paths) +- Event handling mechanisms, data binding patterns, and state management interfaces +- Parameter validation rules, exception handling strategies, and inter-component communication patterns +- API index organized by category (general, layout, navigation, data entry, data display, feedback, etc.) + +## Project Structure + +Antd components wrap frontend Svelte components as Python classes, all inheriting from base component classes, supporting event binding, slots, and Gradio data flows. + +```mermaid +graph TB +subgraph "Python Layer" +A["ModelScopeComponent
ModelScopeLayoutComponent
ModelScopeDataLayoutComponent"] +B["AntdButton"] +C["AntdForm / AntdFormItem"] +D["AntdTable / AntdTableColumn"] +E["AntdInput / AntdSelect"] +F["AntdLayout / AntdMenu / AntdModal"] +G["AntdMessage / AntdNotification"] +H["AntdCard / AntdBreadcrumb"] +end +subgraph "Frontend Layer (Svelte)" +P["button/*"] +Q["form/*"] +R["table/*"] +S["input/*"] +T["select/*"] +U["layout/*"] +V["menu/*"] +W["modal/*"] +X["message/*"] +Y["notification/*"] +Z["card/*"] +AA["breadcrumb/*"] +end +A --> B +A --> C +A --> D +A --> E +A --> F +A --> G +A --> H +B --> P +C --> Q +D --> R +E --> S +E --> T +F --> U +F --> V +F --> W +G --> X +G --> Y +H --> Z +H --> AA +``` + +Diagram sources + +- [backend/modelscope_studio/utils/dev/component.py:54-169](file://backend/modelscope_studio/utils/dev/component.py#L54-L169) +- [backend/modelscope_studio/components/antd/button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) +- [backend/modelscope_studio/components/antd/form/**init**.py:17-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L17-L133) +- [backend/modelscope_studio/components/antd/table/**init**.py:16-153](file://backend/modelscope_studio/components/antd/table/__init__.py#L16-L153) +- [backend/modelscope_studio/components/antd/input/**init**.py:16-127](file://backend/modelscope_studio/components/antd/input/__init__.py#L16-L127) +- [backend/modelscope_studio/components/antd/select/**init**.py:12-231](file://backend/modelscope_studio/components/antd/select/__init__.py#L12-L231) +- [backend/modelscope_studio/components/antd/layout/**init**.py:14-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L14-L91) +- [backend/modelscope_studio/components/antd/menu/**init**.py:12-123](file://backend/modelscope_studio/components/antd/menu/__init__.py#L12-L123) +- [backend/modelscope_studio/components/antd/modal/**init**.py:11-136](file://backend/modelscope_studio/components/antd/modal/__init__.py#L11-L136) +- [backend/modelscope_studio/components/antd/message/**init**.py:10-91](file://backend/modelscope_studio/components/antd/message/__init__.py#L10-L91) +- [backend/modelscope_studio/components/antd/notification/**init**.py:10-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L10-L109) +- [backend/modelscope_studio/components/antd/card/**init**.py:12-149](file://backend/modelscope_studio/components/antd/card/__init__.py#L12-L149) +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:9-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L9-L73) + +Section sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [backend/modelscope_studio/utils/dev/component.py:1-169](file://backend/modelscope_studio/utils/dev/component.py#L1-L169) + +## Core Components + +- Base component classes + - `ModelScopeComponent`: General component base class; supports Gradio properties such as `value`, `visible`, `elem_*`, `key`, `inputs`, `load_fn`, `render`; provides `skip_api` to control API exposure. + - `ModelScopeLayoutComponent`: Layout component base class; supports `__enter__`/`__exit__` context management for nested layouts. + - `ModelScopeDataLayoutComponent`: Data-layout component base class; combines data component capabilities with layout capabilities. +- Events and slots + - `EVENTS`: List of events supported by the component; binds callbacks via `EventListener`. + - `SLOTS`: Set of slot names supported by the component; used for rendering child content or custom nodes. +- Frontend directory resolution + - `FRONTEND_DIR`: Points to the corresponding Svelte component directory via `resolve_frontend_dir(...)`. + +Section sources + +- [backend/modelscope_studio/utils/dev/component.py:54-169](file://backend/modelscope_studio/utils/dev/component.py#L54-L169) +- [backend/modelscope_studio/components/antd/button/**init**.py:41-49](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L49) +- [backend/modelscope_studio/components/antd/table/**init**.py:32-53](file://backend/modelscope_studio/components/antd/table/__init__.py#L32-L53) +- [backend/modelscope_studio/components/antd/input/**init**.py:25-41](file://backend/modelscope_studio/components/antd/input/__init__.py#L25-L41) + +## Architecture Overview + +The following sequence diagram shows a typical component's call chain from construction to event binding: + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Py as "Antd Component Class" +participant Base as "ModelScopeComponent/ModelScopeLayoutComponent" +participant FE as "Svelte Frontend Component" +Dev->>Py : Instantiate component (pass parameters) +Py->>Base : Call parent __init__(visible, elem_*, render, ...) +Base->>Base : Initialize internal state (_internal, as_item, elem_style) +Py->>FE : Set FRONTEND_DIR and pass props +Py->>Py : Configure EVENTS/SLOTS +Dev->>Py : Bind event listeners (EventListener) +Py->>FE : Bind frontend event callbacks via internal markers +FE-->>Py : Trigger event callbacks +Py-->>Dev : Return processed value/payload +``` + +Diagram sources + +- [backend/modelscope_studio/utils/dev/component.py:54-99](file://backend/modelscope_studio/utils/dev/component.py#L54-L99) +- [backend/modelscope_studio/components/antd/button/**init**.py:51-87](file://backend/modelscope_studio/components/antd/button/__init__.py#L51-L87) +- [backend/modelscope_studio/components/antd/form/**init**.py:23-36](file://backend/modelscope_studio/components/antd/form/__init__.py#L23-L36) + +## Detailed Component Analysis + +### Button + +- Import path: `modelscope_studio.components.antd.AntdButton` or `modelscope_studio.components.antd.Button` +- Sub-components: `Group` +- Events: `click` +- Slots: `icon`, `loading.icon` +- Key parameters (selected): `value`, `block`, `danger`, `ghost`, `disabled`, `href`, `html_type`, `icon`, `icon_position`, `loading`, `shape`, `size`, `type`, `variant`, `color`, `root_class_name` +- Methods: `preprocess`/`postprocess`/`example_payload`/`example_value` +- Code snippet path (example) + - [basic usage:51-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L51-L157) +- Event binding flow + - Maps callbacks to frontend events via `EventListener("click", ...)` in `EVENTS`. +- Data binding + - When used as input/output, `value` type is string; `preprocess`/`postprocess` returns string. +- Parameter validation and exceptions + - Most parameters are nullable scalars or literal enums; no explicit validation logic seen — validation is recommended at the application layer. +- Inter-component communication + - Interacts with forms or other components via Gradio's `inputs`/`outputs` mechanism. + +Section sources + +- [backend/modelscope_studio/components/antd/button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) + +### Form and Form.Item + +- Import path: `modelscope_studio.components.antd.AntdForm` / `AntdFormItem` +- Sub-components: `Item`, `Provider` +- Events: `fields_change`, `finish`, `finish_failed`, `values_change` +- Slots: `requiredMark` +- Form key parameters (selected): `colon`, `disabled`, `component`, `feedback_icons`, `initial_values`, `label_align`, `label_col`, `label_wrap`, `layout`, `preserve`, `required_mark`, `scroll_to_first_error`, `size`, `validate_messages`, `validate_trigger`, `variant`, `wrapper_col`, `clear_on_destroy`, `root_class_name`, `class_names`, `styles` +- FormItem key parameters (selected): `label`, `form_name`, `colon`, `dependencies`, `extra`, `help`, `hidden`, `initial_value`, `label_align`, `label_col`, `message_variants`, `normalize`, `no_style`, `preserve`, `required`, `rules`, `should_update`, `tooltip`, `trigger`, `validate_debounce`, `validate_first`, `validate_status`, `validate_trigger`, `value_prop_name`, `wrapper_col`, `layout`, `root_class_name` +- Methods: `preprocess`/`postprocess`/`example_payload`/`example_value` +- Code snippet paths (example) + - [form:43-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L43-L133) + - [form item:21-126](file://backend/modelscope_studio/components/antd/form/item/__init__.py#L21-L126) + +Section sources + +- [backend/modelscope_studio/components/antd/form/**init**.py:17-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L17-L133) +- [backend/modelscope_studio/components/antd/form/item/**init**.py:9-126](file://backend/modelscope_studio/components/antd/form/item/__init__.py#L9-L126) + +### Table and Table.Column + +- Import path: `modelscope_studio.components.antd.AntdTable` / `AntdTableColumn` +- Sub-components: `Column`, `ColumnGroup`, `Expandable`, `RowSelection` +- Events: `change`, `scroll` +- Slots: `footer`, `title`, `summary`, `expandable`, `rowSelection`, `loading.tip`, `loading.indicator`, `pagination.showQuickJumper.goButton`, `pagination.itemRender`, `showSorterTooltip.title` +- Table key parameters (selected): `data_source`, `columns`, `bordered`, `components`, `expandable`, `footer`, `get_popup_container`, `loading`, `locale`, `pagination`, `row_class_name`, `row_key`, `row_selection`, `row_hoverable`, `scroll`, `show_header`, `show_sorter_tooltip`, `size`, `sort_directions`, `sticky`, `summary`, `table_layout`, `title`, `virtual`, `on_row`, `on_header_row`, `root_class_name`, `class_names`, `styles` +- Table.Column key parameters (selected): `built_in_column`, `align`, `col_span`, `data_index`, `default_filtered_value`, `filter_reset_to_default_filtered_value`, `default_sort_order`, `ellipsis`, `filter_dropdown`, `filter_dropdown_open`, `filtered`, `filtered_value`, `filter_icon`, `filter_on_close`, `filter_multiple`, `filter_mode`, `filter_search`, `filters`, `filter_dropdown_props`, `fixed`, `key`, `column_render`, `responsive`, `row_scope`, `should_cell_update`, `show_sorter_tooltip`, `sorter`, `sort_order`, `sort_icon`, `title`, `width`, `min_width`, `hidden`, `on_cell`, `on_header_cell`, `class_names`, `styles` +- Methods: `preprocess`/`postprocess`/`example_payload`/`example_value` +- Code snippet paths (example) + - [table:55-153](file://backend/modelscope_studio/components/antd/table/__init__.py#L55-L153) + - [table.column:33-150](file://backend/modelscope_studio/components/antd/table/column/__init__.py#L33-L150) + +Section sources + +- [backend/modelscope_studio/components/antd/table/**init**.py:16-153](file://backend/modelscope_studio/components/antd/table/__init__.py#L16-L153) +- [backend/modelscope_studio/components/antd/table/column/**init**.py:10-150](file://backend/modelscope_studio/components/antd/table/column/__init__.py#L10-L150) + +### Input and Select + +- Import path: `modelscope_studio.components.antd.AntdInput` / `AntdSelect` +- Sub-components: `Textarea`, `Password`, `OTP`, `Search` (Input); `Option` (Select) +- Input events: `change`, `press_enter`, `clear` +- Select events: `change`, `blur`, `focus`, `search`, `select`, `clear`, `popup_scroll`, `dropdown_visible_change`, `popup_visible_change`, `active` +- Slots (Input): `addonAfter`, `addonBefore`, `allowClear.clearIcon`, `prefix`, `suffix`, `showCount.formatter` +- Slots (Select): `allowClear.clearIcon`, `maxTagPlaceholder`, `menuItemSelectedIcon`, `dropdownRender`, `popupRender`, `optionRender`, `tagRender`, `labelRender`, `notFoundContent`, `removeIcon`, `suffixIcon`, `prefix`, `options` +- Input key parameters (selected): `addon_after`, `addon_before`, `allow_clear`, `count`, `default_value`, `read_only`, `disabled`, `max_length`, `prefix`, `show_count`, `size`, `status`, `suffix`, `type`, `placeholder`, `variant`, `root_class_name`, `class_names`, `styles` +- Select key parameters (selected): `allow_clear`, `auto_clear_search_value`, `auto_focus`, `default_active_first_option`, `default_open`, `default_value`, `disabled`, `popup_class_name`, `popup_match_select_width`, `dropdown_render`, `popup_render`, `dropdown_style`, `field_names`, `filter_option`, `filter_sort`, `get_popup_container`, `label_in_value`, `list_height`, `loading`, `max_count`, `max_tag_count`, `max_tag_placeholder`, `max_tag_text_length`, `menu_item_selected_icon`, `mode`, `not_found_content`, `open`, `option_filter_prop`, `option_label_prop`, `options`, `option_render`, `placeholder`, `placement`, `remove_icon`, `search_value`, `show_search`, `size`, `status`, `suffix_icon`, `prefix`, `tag_render`, `label_render`, `token_separators`, `variant`, `virtual`, `class_names`, `styles`, `root_class_name` +- Methods: `preprocess`/`postprocess`/`example_payload`/`example_value` +- Code snippet paths (example) + - [input:43-127](file://backend/modelscope_studio/components/antd/input/__init__.py#L43-L127) + - [select:59-231](file://backend/modelscope_studio/components/antd/select/__init__.py#L59-L231) + +Section sources + +- [backend/modelscope_studio/components/antd/input/**init**.py:16-127](file://backend/modelscope_studio/components/antd/input/__init__.py#L16-L127) +- [backend/modelscope_studio/components/antd/select/**init**.py:12-231](file://backend/modelscope_studio/components/antd/select/__init__.py#L12-L231) + +### Layout, Menu, and Modal + +- Import path: `modelscope_studio.components.antd.AntdLayout` / `AntdMenu` / `AntdModal` +- Sub-components: `Layout.Content`/`Footer`/`Header`/`Sider` (Layout); `Menu.Item` (Menu); `Modal.Static` (Modal) +- Events (Layout/Menu/Modal): `click`, `deselect`, `open_change`, `select`, `ok`, `cancel`, etc. +- Slots (Layout/Menu/Modal): See individual component definitions +- Code snippet paths (example) + - [layout:39-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L39-L91) + - [menu:36-123](file://backend/modelscope_studio/components/antd/menu/__init__.py#L36-L123) + - [modal:34-136](file://backend/modelscope_studio/components/antd/modal/__init__.py#L34-L136) + +Section sources + +- [backend/modelscope_studio/components/antd/layout/**init**.py:14-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L14-L91) +- [backend/modelscope_studio/components/antd/menu/**init**.py:12-123](file://backend/modelscope_studio/components/antd/menu/__init__.py#L12-L123) +- [backend/modelscope_studio/components/antd/modal/**init**.py:11-136](file://backend/modelscope_studio/components/antd/modal/__init__.py#L11-L136) + +### Message, Notification, Card, and Breadcrumb + +- Import path: `modelscope_studio.components.antd.AntdMessage` / `AntdNotification` / `AntdCard` / `AntdBreadcrumb` +- Events: `click`, `close` (some components) +- Slots: `icon`/`content` (Message); `actions`/`closeIcon`/`description`/`icon`/`message`/`title` (Notification); `title`/`tabList`/`tabProps.*` (Card); `separator`/`itemRender`/`items`/`dropdownIcon` (Breadcrumb) +- Code snippet paths (example) + - [message:26-91](file://backend/modelscope_studio/components/antd/message/__init__.py#L26-L91) + - [notification:26-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L26-L109) + - [card:56-149](file://backend/modelscope_studio/components/antd/card/__init__.py#L56-L149) + - [breadcrumb:20-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L20-L73) + +Section sources + +- [backend/modelscope_studio/components/antd/message/**init**.py:10-91](file://backend/modelscope_studio/components/antd/message/__init__.py#L10-L91) +- [backend/modelscope_studio/components/antd/notification/**init**.py:10-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L10-L109) +- [backend/modelscope_studio/components/antd/card/**init**.py:12-149](file://backend/modelscope_studio/components/antd/card/__init__.py#L12-L149) +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:9-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L9-L73) + +## Dependency Analysis + +- Component exports + - `modelscope_studio.components.antd.__init__` and `components.py` synchronize exports of all Antd component classes for unified imports. +- Base class dependencies + - All components depend on base component classes in `modelscope_studio.utils.dev.component`, ensuring a unified lifecycle, event, and slot mechanism. +- Frontend dependencies + - Each component points to its corresponding Svelte component directory via `FRONTEND_DIR`, maintaining consistent directory structures between frontend and backend. + +```mermaid +graph LR +A["antd/__init__.py"] --> B["Button/Form/Table/Input/Select/Layout/..."] +C["antd/components.py"] --> B +D["utils/dev/component.py"] --> B +B --> E["Svelte Frontend Components"] +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [backend/modelscope_studio/utils/dev/component.py:54-169](file://backend/modelscope_studio/utils/dev/component.py#L54-L169) + +Section sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [backend/modelscope_studio/utils/dev/component.py:54-169](file://backend/modelscope_studio/utils/dev/component.py#L54-L169) + +## Performance Considerations + +- Event binding + - Maps Python callbacks to frontend events via `EVENTS`, avoiding unnecessary re-renders; set event trigger frequency and debouncing appropriately. +- Slots and virtualization + - Components such as Table support `virtual`, `sticky`, `scroll`, and similar parameters; it is recommended to enable virtual scrolling and fixed headers in large data scenarios to improve performance. +- Render control + - Use `render` and `visible` to control component initial rendering and visibility, reducing first-screen pressure. +- Data flow + - Input components (e.g., Input, Select) are recommended to work with Form for batch validation and debouncing, reducing overhead from frequent updates. + +## Troubleshooting Guide + +- Events not triggering + - Check that `EVENTS` is correctly declared; confirm that `EventListener` names match frontend events. + - Confirm that the component has `FRONTEND_DIR` set correctly and frontend event callbacks are bound. +- Slots not working + - Verify that the corresponding slot name exists in the `SLOTS` list; ensure the slot content passed matches the expected format. +- Data type mismatch + - The return types of `preprocess`/`postprocess` for input components must match component definitions; if type errors occur, check `value` and the return type from `api_info`. +- Form validation failure + - Check FormItem's `rules`, `validate_trigger`, `validate_status`, and other configurations; adjust `validate_first` and `validate_debounce` as needed. +- Layout flickering or style anomalies + - Layout components (e.g., Layout, Menu) can optimize SSR-scenario style flickering via parameters such as `has_sider`, `inline_collapsed`, and `theme_value`. + +Section sources + +- [backend/modelscope_studio/components/antd/button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46) +- [backend/modelscope_studio/components/antd/form/item/**init**.py:13-19](file://backend/modelscope_studio/components/antd/form/item/__init__.py#L13-L19) +- [backend/modelscope_studio/components/antd/table/**init**.py:32-53](file://backend/modelscope_studio/components/antd/table/__init__.py#L32-L53) +- [backend/modelscope_studio/components/antd/menu/**init**.py:96-103](file://backend/modelscope_studio/components/antd/menu/__init__.py#L96-L103) +- [backend/modelscope_studio/components/antd/layout/**init**.py:33-37](file://backend/modelscope_studio/components/antd/layout/__init__.py#L33-L37) + +## Conclusion + +This reference document systematically covers the Python API of the Antd component library, clearly defining import paths, constructor parameters, events and slots, data binding, and state management interfaces for component classes. It is recommended to use example paths to quickly locate implementation details in actual development, and to optimize component usage experience according to the performance and troubleshooting guidelines. + +## Appendix: API Index by Category + +- General Components + - `Button`, `Message`, `Notification`, `Card`, `Breadcrumb` + - Example paths: [button:51-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L51-L157), [message:26-91](file://backend/modelscope_studio/components/antd/message/__init__.py#L26-L91), [notification:26-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L26-L109), [card:56-149](file://backend/modelscope_studio/components/antd/card/__init__.py#L56-L149), [breadcrumb:20-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L20-L73) +- Layout Components + - `Layout` (including `Content`/`Footer`/`Header`/`Sider`), `Menu` (including `Item`) + - Example paths: [layout:39-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L39-L91), [menu:36-123](file://backend/modelscope_studio/components/antd/menu/__init__.py#L36-L123) +- Navigation Components + - `Breadcrumb` (including `Item`) + - Example paths: [breadcrumb:20-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L20-L73) +- Data Entry Components + - `Input` (including `Textarea`/`Password`/`OTP`/`Search`), `Select` (including `Option`) + - Example paths: [input:43-127](file://backend/modelscope_studio/components/antd/input/__init__.py#L43-L127), [select:59-231](file://backend/modelscope_studio/components/antd/select/__init__.py#L59-L231) +- Data Display Components + - `Table` (including `Column`/`ColumnGroup`/`Expandable`/`RowSelection`) + - Example paths: [table:55-153](file://backend/modelscope_studio/components/antd/table/__init__.py#L55-L153), [table.column:33-150](file://backend/modelscope_studio/components/antd/table/column/__init__.py#L33-L150) +- Feedback Components + - `Modal` (including `Static`), `Message`, `Notification` + - Example paths: [modal:34-136](file://backend/modelscope_studio/components/antd/modal/__init__.py#L34-L136), [message:26-91](file://backend/modelscope_studio/components/antd/message/__init__.py#L26-L91), [notification:26-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L26-L109) +- Form Components + - `Form` (including `Item`/`Provider`) + - Example paths: [form:43-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L43-L133), [form.item:21-126](file://backend/modelscope_studio/components/antd/form/item/__init__.py#L21-L126) diff --git a/.wiki/en/API Reference/Python API/Antd Components API/Data Display Components API.md b/.wiki/en/API Reference/Python API/Antd Components API/Data Display Components API.md new file mode 100644 index 00000000..7a2033ee --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antd Components API/Data Display Components API.md @@ -0,0 +1,661 @@ +# Data Display Components API + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/components/antd/avatar/__init__.py](file://backend/modelscope_studio/components/antd/avatar/__init__.py) +- [backend/modelscope_studio/components/antd/badge/__init__.py](file://backend/modelscope_studio/components/antd/badge/__init__.py) +- [backend/modelscope_studio/components/antd/calendar/__init__.py](file://backend/modelscope_studio/components/antd/calendar/__init__.py) +- [backend/modelscope_studio/components/antd/card/__init__.py](file://backend/modelscope_studio/components/antd/card/__init__.py) +- [backend/modelscope_studio/components/antd/carousel/__init__.py](file://backend/modelscope_studio/components/antd/carousel/__init__.py) +- [backend/modelscope_studio/components/antd/collapse/__init__.py](file://backend/modelscope_studio/components/antd/collapse/__init__.py) +- [backend/modelscope_studio/components/antd/descriptions/__init__.py](file://backend/modelscope_studio/components/antd/descriptions/__init__.py) +- [backend/modelscope_studio/components/antd/empty/__init__.py](file://backend/modelscope_studio/components/antd/empty/__init__.py) +- [backend/modelscope_studio/components/antd/image/__init__.py](file://backend/modelscope_studio/components/antd/image/__init__.py) +- [backend/modelscope_studio/components/antd/list/__init__.py](file://backend/modelscope_studio/components/antd/list/__init__.py) +- [backend/modelscope_studio/components/antd/popover/__init__.py](file://backend/modelscope_studio/components/antd/popover/__init__.py) +- [backend/modelscope_studio/components/antd/qr_code/__init__.py](file://backend/modelscope_studio/components/antd/qr_code/__init__.py) +- [backend/modelscope_studio/components/antd/segmented/__init__.py](file://backend/modelscope_studio/components/antd/segmented/__init__.py) +- [backend/modelscope_studio/components/antd/statistic/__init__.py](file://backend/modelscope_studio/components/antd/statistic/__init__.py) +- [backend/modelscope_studio/components/antd/table/__init__.py](file://backend/modelscope_studio/components/antd/table/__init__.py) +- [backend/modelscope_studio/components/antd/tabs/__init__.py](file://backend/modelscope_studio/components/antd/tabs/__init__.py) +- [backend/modelscope_studio/components/antd/tag/__init__.py](file://backend/modelscope_studio/components/antd/tag/__init__.py) +- [backend/modelscope_studio/components/antd/tag/checkable_tag/__init__.py](file://backend/modelscope_studio/components/antd/tag/checkable_tag/__init__.py) +- [backend/modelscope_studio/components/antd/tag/checkable_tag_group/__init__.py](file://backend/modelscope_studio/components/antd/tag/checkable_tag_group/__init__.py) +- [backend/modelscope_studio/components/antd/timeline/__init__.py](file://backend/modelscope_studio/components/antd/timeline/__init__.py) +- [backend/modelscope_studio/components/antd/tooltip/__init__.py](file://backend/modelscope_studio/components/antd/tooltip/__init__.py) +- [backend/modelscope_studio/components/antd/tour/__init__.py](file://backend/modelscope_studio/components/antd/tour/__init__.py) +- [backend/modelscope_studio/components/antd/tree/__init__.py](file://backend/modelscope_studio/components/antd/tree/__init__.py) +- [frontend/antd/timeline/timeline.tsx](file://frontend/antd/timeline/timeline.tsx) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx) +- [frontend/antd/tag/checkable-tag/Index.svelte](file://frontend/antd/tag/checkable-tag/Index.svelte) +- [frontend/antd/tag/tag.tsx](file://frontend/antd/tag/tag.tsx) + + +## Update Summary + +**Changes Made** + +- Added complete API documentation for the Timeline component, including the latest feature specifications +- Added detailed documentation for the checkable tag group component, covering both CheckableTag and CheckableTagGroup +- Updated Tag component documentation, supplementing checkable tag-related functionality +- Improved documentation of inter-component relationships and usage scenarios + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is a Python API reference and practical guide for Antd data display components, covering Avatar, Badge, Calendar, Card, Carousel, Collapse, Descriptions, Empty, Image, List, Popover, QRCode, Segmented, Statistic, Table, Tabs, Tag, Timeline, Tooltip, Tour, Tree, and other components. Content includes: + +- Constructor parameters, event binding, slots and rendering behavior +- Preprocessing and postprocessing (preprocess/postprocess) workflows +- Usage example paths and common scenarios +- Rendering optimization, lazy loading, and responsive design recommendations +- Data formatting, internationalization, and theme customization approaches +- User experience and accessibility best practices + +## Project Structure + +Antd components are encapsulated as Python classes in the backend, all inheriting from a common component base class, and mapped to corresponding Svelte implementations through frontend directory mappings. Component export entries are centralized in antd/**init**.py and antd/components.py. + +```mermaid +graph TB +A["Python Component Module
backend/modelscope_studio/components/antd"] --> B["Component Export Entry
antd/__init__.py"] +A --> C["Common Component Base Class
utils.dev.ModelScope*Component"] +D["Frontend Component Directory
frontend/antd/"] <-- "resolve_frontend_dir" --> E["Component Frontend Implementation
*.tsx / Index.svelte"] +B --> F["Concrete Component Classes
AntdXxx(...)"] +F --> E +``` + +**Chart sources** + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +**Section sources** + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +## Core Components + +The following is a list of data display components and their common characteristics covered in this document: + +- Unified inheritance: most components inherit from ModelScopeLayoutComponent or ModelScopeComponent; some data-type components inherit from ModelScopeDataLayoutComponent (e.g., Avatar, Image) +- Event system: register frontend event callbacks via EVENTS list, bound to \_internal.update +- Slot system: define available slot names via SLOTS, used for passing template fragments or render functions +- Frontend directory: point to frontend component directory via resolve_frontend_dir("component-name") +- Preprocessing/postprocessing: implement preprocess and postprocess based on component type, handling strings, file paths, Gradio FileData, and other inputs/outputs + +**Section sources** + +- [backend/modelscope_studio/components/antd/avatar/**init**.py:18-114](file://backend/modelscope_studio/components/antd/avatar/__init__.py#L18-L114) +- [backend/modelscope_studio/components/antd/image/**init**.py:18-120](file://backend/modelscope_studio/components/antd/image/__init__.py#L18-L120) +- [backend/modelscope_studio/components/antd/calendar/**init**.py:11-102](file://backend/modelscope_studio/components/antd/calendar/__init__.py#L11-L102) +- [backend/modelscope_studio/components/antd/card/**init**.py:12-149](file://backend/modelscope_studio/components/antd/card/__init__.py#L12-L149) +- [backend/modelscope_studio/components/antd/carousel/**init**.py:8-95](file://backend/modelscope_studio/components/antd/carousel/__init__.py#L8-L95) +- [backend/modelscope_studio/components/antd/collapse/**init**.py:11-99](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L11-L99) +- [backend/modelscope_studio/components/antd/descriptions/**init**.py:9-86](file://backend/modelscope_studio/components/antd/descriptions/__init__.py#L9-L86) +- [backend/modelscope_studio/components/antd/empty/**init**.py:8-71](file://backend/modelscope_studio/components/antd/empty/__init__.py#L8-L71) +- [backend/modelscope_studio/components/antd/list/**init**.py:11-101](file://backend/modelscope_studio/components/antd/list/__init__.py#L11-L101) +- [backend/modelscope_studio/components/antd/popover/**init**.py:10-124](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L124) +- [backend/modelscope_studio/components/antd/qr_code/**init**.py:10-96](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L10-L96) +- [backend/modelscope_studio/components/antd/tabs/**init**.py:1-145](file://backend/modelscope_studio/components/antd/tabs/__init__.py#L1-L145) +- [backend/modelscope_studio/components/antd/timeline/**init**.py:1-81](file://backend/modelscope_studio/components/antd/timeline/__init__.py#L1-L81) +- [backend/modelscope_studio/components/antd/tooltip/**init**.py:1-145](file://backend/modelscope_studio/components/antd/tooltip/__init__.py#L1-L145) +- [backend/modelscope_studio/components/antd/tour/**init**.py:1-145](file://backend/modelscope_studio/components/antd/tour/__init__.py#L1-L145) +- [backend/modelscope_studio/components/antd/tree/**init**.py:1-145](file://backend/modelscope_studio/components/antd/tree/__init__.py#L1-L145) + +## Architecture Overview + +The following diagram shows the class relationships and event binding patterns of data display components in the Python layer: + +```mermaid +classDiagram +class ModelScopeLayoutComponent +class ModelScopeComponent +class ModelScopeDataLayoutComponent +class AntdAvatar { ++EVENTS ++SLOTS ++FRONTEND_DIR ++preprocess() ++postprocess() +} +class AntdImage { ++EVENTS ++SLOTS ++FRONTEND_DIR ++preprocess() ++postprocess() +} +class AntdCalendar { ++EVENTS ++SLOTS ++FRONTEND_DIR ++api_info() +} +class AntdCard { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdCarousel { ++EVENTS ++FRONTEND_DIR +} +class AntdCollapse { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdDescriptions { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdEmpty { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdList { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdPopover { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdQRCode { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdTag { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdTagCheckableTag { ++EVENTS ++SLOTS ++FRONTEND_DIR ++api_info() +} +class AntdTagCheckableTagGroup { ++EVENTS ++SLOTS ++FRONTEND_DIR ++api_info() +} +class AntdTimeline { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +ModelScopeDataLayoutComponent <|-- AntdAvatar +ModelScopeDataLayoutComponent <|-- AntdImage +ModelScopeLayoutComponent <|-- AntdCard +ModelScopeLayoutComponent <|-- AntdCarousel +ModelScopeLayoutComponent <|-- AntdCollapse +ModelScopeLayoutComponent <|-- AntdDescriptions +ModelScopeLayoutComponent <|-- AntdEmpty +ModelScopeLayoutComponent <|-- AntdList +ModelScopeLayoutComponent <|-- AntdPopover +ModelScopeComponent <|-- AntdCalendar +ModelScopeComponent <|-- AntdQRCode +ModelScopeLayoutComponent <|-- AntdTag +ModelScopeDataLayoutComponent <|-- AntdTagCheckableTag +ModelScopeDataLayoutComponent <|-- AntdTagCheckableTagGroup +ModelScopeLayoutComponent <|-- AntdTimeline +``` + +**Chart sources** + +- [backend/modelscope_studio/components/antd/avatar/**init**.py:18-114](file://backend/modelscope_studio/components/antd/avatar/__init__.py#L18-L114) +- [backend/modelscope_studio/components/antd/image/**init**.py:18-120](file://backend/modelscope_studio/components/antd/image/__init__.py#L18-L120) +- [backend/modelscope_studio/components/antd/calendar/**init**.py:11-102](file://backend/modelscope_studio/components/antd/calendar/__init__.py#L11-L102) +- [backend/modelscope_studio/components/antd/card/**init**.py:12-149](file://backend/modelscope_studio/components/antd/card/__init__.py#L12-L149) +- [backend/modelscope_studio/components/antd/carousel/**init**.py:8-95](file://backend/modelscope_studio/components/antd/carousel/__init__.py#L8-L95) +- [backend/modelscope_studio/components/antd/collapse/**init**.py:11-99](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L11-L99) +- [backend/modelscope_studio/components/antd/descriptions/**init**.py:9-86](file://backend/modelscope_studio/components/antd/descriptions/__init__.py#L9-L86) +- [backend/modelscope_studio/components/antd/empty/**init**.py:8-71](file://backend/modelscope_studio/components/antd/empty/__init__.py#L8-L71) +- [backend/modelscope_studio/components/antd/list/**init**.py:11-101](file://backend/modelscope_studio/components/antd/list/__init__.py#L11-L101) +- [backend/modelscope_studio/components/antd/popover/**init**.py:10-124](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L124) +- [backend/modelscope_studio/components/antd/qr_code/**init**.py:10-96](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L10-L96) +- [backend/modelscope_studio/components/antd/tag/**init**.py:12-88](file://backend/modelscope_studio/components/antd/tag/__init__.py#L12-L88) +- [backend/modelscope_studio/components/antd/tag/checkable_tag/**init**.py:11-85](file://backend/modelscope_studio/components/antd/tag/checkable_tag/__init__.py#L11-L85) +- [backend/modelscope_studio/components/antd/tag/checkable_tag_group/**init**.py:12-102](file://backend/modelscope_studio/components/antd/tag/checkable_tag_group/__init__.py#L12-L102) +- [backend/modelscope_studio/components/antd/timeline/**init**.py:9-81](file://backend/modelscope_studio/components/antd/timeline/__init__.py#L9-L81) + +## Detailed Component Analysis + +### Avatar + +- Functional purpose: Avatar display, supports icon, placeholder, and error handling events +- Key points + - Supports slots: icon, src + - Events: error + - Data model: AntdAvatarData (root supports FileData or str) + - Preprocessing/postprocessing: converts FileData to path or wraps as FileData +- Key parameters (selected) + - value, alt, gap, icon, shape, size, src_set, draggable, cross_origin, class_names, styles, root_class_name +- Usage example path + - [Example: Avatar with error handling:18-114](file://backend/modelscope_studio/components/antd/avatar/__init__.py#L18-L114) + +**Section sources** + +- [backend/modelscope_studio/components/antd/avatar/**init**.py:18-114](file://backend/modelscope_studio/components/antd/avatar/__init__.py#L18-L114) + +### Badge + +- Functional purpose: Information marking, supports dot, count, status, etc. +- Key points + - Slots: count, text + - Parameters: count, dot, overflow_count, show_zero, size, status, text, title, color, etc. +- Usage example path + - [Example: Badge with status:9-87](file://backend/modelscope_studio/components/antd/badge/__init__.py#L9-87) + +**Section sources** + +- [backend/modelscope_studio/components/antd/badge/**init**.py:9-87](file://backend/modelscope_studio/components/antd/badge/__init__.py#L9-L87) + +### Calendar + +- Functional purpose: Date selection and panel switching +- Key points + - Events: change, panel_change, select + - Slots: cellRender, fullCellRender, headerRender + - API: api_info returns a union type of number|string +- Usage example path + - [Example: Calendar events and render hooks:11-102](file://backend/modelscope_studio/components/antd/calendar/__init__.py#L11-L102) + +**Section sources** + +- [backend/modelscope_studio/components/antd/calendar/**init**.py:11-102](file://backend/modelscope_studio/components/antd/calendar/__init__.py#L11-L102) + +### Card + +- Functional purpose: Information container, supports title, extra content, cover, action area, tabs, etc. +- Key points + - Sub-components: Grid, Meta + - Events: click, tab_change + - Slots: actions, cover, extra, tabBarExtraContent, title, tabList, tabProps.\*, etc. + - Lifecycle: checks for Grid in **exit** +- Usage example path + - [Example: Card layout with tabs:12-149](file://backend/modelscope_studio/components/antd/card/__init__.py#L12-L149) + +**Section sources** + +- [backend/modelscope_studio/components/antd/card/**init**.py:12-149](file://backend/modelscope_studio/components/antd/card/__init__.py#L12-L149) + +### Carousel + +- Functional purpose: Carousel/slideshow container +- Key points + - Parameters: arrows, autoplay, autoplay_speed, adaptive_height, dot_position, dots, draggable, fade, infinite, speed, effect, after_change, before_change, wait_for_animate +- Usage example path + - [Example: Carousel configuration:8-95](file://backend/modelscope_studio/components/antd/carousel/__init__.py#L8-L95) + +**Section sources** + +- [backend/modelscope_studio/components/antd/carousel/**init**.py:8-95](file://backend/modelscope_studio/components/antd/carousel/__init__.py#L8-L95) + +### Collapse + +- Functional purpose: Content folding/expanding +- Key points + - Sub-components: Item + - Events: change + - Slots: expandIcon, items + - Parameters: accordion, active_key, bordered, collapsible, default_active_key, destroy_on_hidden, destroy_inactive_panel, expand_icon, ghost, items, size +- Usage example path + - [Example: Collapse panel with items:11-99](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L11-L99) + +**Section sources** + +- [backend/modelscope_studio/components/antd/collapse/**init**.py:11-99](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L11-L99) + +### Descriptions + +- Functional purpose: Key-value pair description display +- Key points + - Sub-components: Item + - Slots: extra, title, items + - Parameters: bordered, colon, column, content_style, layout, size, title, items, label_style +- Usage example path + - [Example: Descriptions list with items:9-86](file://backend/modelscope_studio/components/antd/descriptions/__init__.py#L9-86) + +**Section sources** + +- [backend/modelscope_studio/components/antd/descriptions/**init**.py:9-86](file://backend/modelscope_studio/components/antd/descriptions/__init__.py#L9-L86) + +### Empty + +- Functional purpose: Empty state placeholder +- Key points + - Slots: description, image + - Parameters: description, image (including constant enums), image_style +- Usage example path + - [Example: Empty state with image:8-71](file://backend/modelscope_studio/components/antd/empty/__init__.py#L8-71) + +**Section sources** + +- [backend/modelscope_studio/components/antd/empty/**init**.py:8-71](file://backend/modelscope_studio/components/antd/empty/__init__.py#L8-L71) + +### Image + +- Functional purpose: Image display and preview +- Key points + - Sub-components: PreviewGroup + - Events: error, preview_transform, preview_visible_change + - Slots: placeholder, preview.mask, preview.closeIcon, preview.toolbarRender, preview.imageRender + - Data model: AntdImageData (root supports FileData or str) + - Preprocessing/postprocessing: similar to Avatar, handles FileData and local paths +- Usage example path + - [Example: Image with preview group:18-120](file://backend/modelscope_studio/components/antd/image/__init__.py#L18-120) + +**Section sources** + +- [backend/modelscope_studio/components/antd/image/**init**.py:18-120](file://backend/modelscope_studio/components/antd/image/__init__.py#L18-L120) + +### List + +- Functional purpose: List rendering and pagination +- Key points + - Sub-components: Item, Item.Meta + - Events: pagination_change, pagination_show_size_change + - Slots: footer, header, loadMore, renderItem + - Parameters: bordered, data_source, footer, grid, header, item_layout, loading, load_more, locale, pagination, render_item, row_key, size, split +- Usage example path + - [Example: List with pagination:11-101](file://backend/modelscope_studio/components/antd/list/__init__.py#L11-L101) + +**Section sources** + +- [backend/modelscope_studio/components/antd/list/**init**.py:11-101](file://backend/modelscope_studio/components/antd/list/__init__.py#L11-L101) + +### Popover + +- Functional purpose: Bubble card with trigger +- Key points + - Events: open_change + - Slots: title, content + - Parameters: align, arrow, auto_adjust_overflow, color, default_open, destroy_tooltip_on_hide, destroy_on_hidden, fresh, get_popup_container, mouse_enter_delay, mouse_leave_delay, overlay_class_name, overlay_style, overlay_inner_style, placement, trigger, open, z_index +- Usage example path + - [Example: Popover with trigger:10-124](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L124) + +**Section sources** + +- [backend/modelscope_studio/components/antd/popover/**init**.py:10-124](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L124) + +### QRCode + +- Functional purpose: Dynamic QR code generation and status management +- Key points + - Events: refresh + - Slots: statusRender + - Parameters: type, bordered, color, bg_color, boost_level, error_level, icon, icon_size, margin_size, size, status, status_render +- Usage example path + - [Example: QR code with status rendering:10-96](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L10-96) + +**Section sources** + +- [backend/modelscope_studio/components/antd/qr_code/**init**.py:10-96](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L10-L96) + +### Segmented + +- Functional purpose: Segmented selector (data display type) +- Key points + - Sub-components: Option + - Parameters: options, block, size, disabled, onChange, etc. (per frontend definition) +- Usage example path + - [Example: Segmented with options](file://backend/modelscope_studio/components/antd/segmented/__init__.py) + +**Section sources** + +- [backend/modelscope_studio/components/antd/segmented/__init__.py] + +### Statistic + +- Functional purpose: Numeric display and countdown +- Key points + - Sub-components: Countdown, Timer + - Parameters: value, precision, prefix, suffix, formatter, groupSeparator, format, onFinish, etc. +- Usage example path + - [Example: Statistic and countdown](file://backend/modelscope_studio/components/antd/statistic/__init__.py) + +**Section sources** + +- [backend/modelscope_studio/components/antd/statistic/__init__.py] + +### Table + +- Functional purpose: Data table rendering and interaction +- Key points + - Sub-components: Column, ColumnGroup, Expandable, RowSelection, RowSelection.Selection + - Parameters: dataSource, columns, pagination, scroll, size, loading, onChange, onHeaderRow, onRow, etc. +- Usage example path + - [Example: Table with column configuration](file://backend/modelscope_studio/components/antd/table/__init__.py) + +**Section sources** + +- [backend/modelscope_studio/components/antd/table/__init__.py] + +### Tabs + +- Functional purpose: Tab container and switching +- Key points + - Sub-components: Item + - Parameters: activeKey, defaultActiveKey, type, tabPosition, size, hideAdd, addIcon, removeIcon, renderTabBar, onEdit, onChange, etc. +- Usage example path + - [Example: Tabs with items](file://backend/modelscope_studio/components/antd/tabs/__init__.py) + +**Section sources** + +- [backend/modelscope_studio/components/antd/tabs/__init__.py] + +### Tag + +- Functional purpose: Tag display and checkable tags +- Key points + - Sub-components: CheckableTag, CheckableTagGroup + - Events: close, change, click + - Slots: icon, closeIcon + - Parameters: value, disabled, href, bordered, close_icon, color, icon +- Usage example path + - [Example: Tag with checkable tags](file://backend/modelscope_studio/components/antd/tag/__init__.py) + +**Update** Added checkable tag group component support, including individual checkable tags and checkable tag groups + +**Section sources** + +- [backend/modelscope_studio/components/antd/tag/**init**.py:12-88](file://backend/modelscope_studio/components/antd/tag/__init__.py#L12-L88) + +### Timeline + +- Functional purpose: Timeline display +- Key points + - Sub-components: Item + - Events: none + - Slots: pending, pendingDot + - Parameters: mode, reverse, orientation, title_span, variant, pending, pending_dot, items +- Usage example path + - [Example: Timeline with items](file://backend/modelscope_studio/components/antd/timeline/__init__.py) + +**Update** Added complete API documentation for the Timeline component, including the latest feature specifications + +**Section sources** + +- [backend/modelscope_studio/components/antd/timeline/**init**.py:9-81](file://backend/modelscope_studio/components/antd/timeline/__init__.py#L9-L81) + +### Tooltip + +- Functional purpose: Text tooltip +- Key points + - Parameters: title, color, placement, trigger, mouseEnterDelay, mouseLeaveDelay, overlayClassName, overlayStyle, overlayInnerStyle, destroyTooltipOnHide, etc. +- Usage example path + - [Example: Text tooltip](file://backend/modelscope_studio/components/antd/tooltip/__init__.py) + +**Section sources** + +- [backend/modelscope_studio/components/antd/tooltip/__init__.py] + +### Tour + +- Functional purpose: Guided navigation +- Key points + - Sub-components: Step + - Parameters: steps, current, scrollIntoViewOptions, mask, gap, indicator, prefixCls, onClose, onChange, etc. +- Usage example path + - [Example: Tour with steps](file://backend/modelscope_studio/components/antd/tour/__init__.py) + +**Section sources** + +- [backend/modelscope_studio/components/antd/tour/__init__.py] + +### Tree + +- Functional purpose: Tree structure display and interaction +- Key points + - Sub-components: TreeNode, DirectoryTree + - Parameters: treeData, defaultExpandAll, defaultExpandedKeys, expandedKeys, selectedKeys, checkable, checkStrictly, multiple, fieldNames, onChange, onCheck, onSelect, etc. +- Usage example path + - [Example: Tree with nodes](file://backend/modelscope_studio/components/antd/tree/__init__.py) + +**Section sources** + +- [backend/modelscope_studio/components/antd/tree/__init__.py] + +### Checkable Tag Group Components + +#### AntdTagCheckableTag + +- Functional purpose: Tag component that supports checked state +- Key points + - Events: change, click + - Slots: icon + - Parameters: label, value, icon + - Data type: boolean, representing the checked state +- Usage example path + - [Example: Checkable tag](file://backend/modelscope_studio/components/antd/tag/checkable_tag/__init__.py) + +#### AntdTagCheckableTagGroup + +- Functional purpose: Container combining multiple checkable tags +- Key points + - Events: change + - Slots: options + - Parameters: options, disabled, multiple, default_value + - Data type: string, number, or string/number array, representing the selected tag values +- Usage example path + - [Example: Checkable tag group](file://backend/modelscope_studio/components/antd/tag/checkable_tag_group/__init__.py) + +**Added** Complete documentation for the checkable tag group component, covering both individual tag and tag group usage patterns + +**Section sources** + +- [backend/modelscope_studio/components/antd/tag/checkable_tag/**init**.py:11-85](file://backend/modelscope_studio/components/antd/tag/checkable_tag/__init__.py#L11-L85) +- [backend/modelscope_studio/components/antd/tag/checkable_tag_group/**init**.py:12-102](file://backend/modelscope_studio/components/antd/tag/checkable_tag_group/__init__.py#L12-L102) + +## Dependency Analysis + +- Component exports: all Antd components are centrally exported in antd/**init**.py and antd/components.py, enabling unified imports and alias usage +- Base class dependency: each component depends on the ModelScope\*Component hierarchy in utils.dev for unified event binding and frontend directory resolution +- Frontend mapping: maps Python components to frontend/antd//Index.svelte via resolve_frontend_dir("component-name") + +```mermaid +graph LR +P["Python Component Classes"] --> B["antd/__init__.py exports"] +P --> C["antd/components.py exports"] +P --> F["frontend/antd//Index.svelte"] +U["utils.dev.ModelScope*Component"] --> P +``` + +**Chart sources** + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +**Section sources** + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +## Performance Considerations + +- Rendering optimization + - Use `destroy_on_hidden`, `destroy_inactive_panel`, and similar parameters in collapse/drawer scenarios to reduce DOM overhead + - List and table components should enable virtual scrolling (scroll.y) and pagination to avoid rendering large numbers of nodes at once + - Timeline component supports the `items` parameter for direct data input, avoiding frequent re-renders +- Lazy loading + - Image component supports `placeholder` and `fallback`, improving initial screen performance when combined with lazy loading strategies + - List supports `loadMore` and `pagination` for on-demand data loading +- Responsive design + - Use `size`, `responsive`, `grid`, and other parameters to adapt to different screen sizes + - Card and Descriptions support small/default/middle sizes, adjusting to content density + - Timeline supports both horizontal and vertical orientations, adapting to different layout requirements +- Themes and styles + - Inject custom styles via `class_names`/`styles`/`root_class_name` to avoid global style pollution + - Use `color`, `status`, and other semantic parameters to express state, reducing repetitive style code + +## Troubleshooting Guide + +- Event not triggered + - Confirm that event names in the EVENTS list are consistent with frontend bindings + - Check that `_internal.update` is being called correctly +- Data not displayed or displayed incorrectly + - Avatar/Image: confirm that `value` is an http/data path or cached file path; check preprocess/postprocess workflow + - Calendar: confirm that `value` type matches the number|string type returned by api_info + - Timeline: confirm that `items` parameter format is correct; supports both direct data input and slot-provided data +- Slots not working + - Confirm that slot names in SLOTS are spelled correctly and that the frontend component has implemented the corresponding slot rendering + - Timeline supports `pending` and `pendingDot` slots; Tag component supports `icon` and `closeIcon` slots +- Performance issues + - Large lists/tables: enable pagination and virtual scrolling; avoid frequent re-renders + - Collapse panels: set `destroy_on_hidden`/`destroy_inactive_panel` appropriately + - Checkable tag group: use the `multiple` parameter to control single or multi-select mode + +**Section sources** + +- [backend/modelscope_studio/components/antd/avatar/**init**.py:89-114](file://backend/modelscope_studio/components/antd/avatar/__init__.py#L89-L114) +- [backend/modelscope_studio/components/antd/image/**init**.py:95-120](file://backend/modelscope_studio/components/antd/image/__init__.py#L95-L120) +- [backend/modelscope_studio/components/antd/calendar/**init**.py:84-102](file://backend/modelscope_studio/components/antd/calendar/__init__.py#L84-L102) +- [backend/modelscope_studio/components/antd/collapse/**init**.py:84-99](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L84-L99) +- [backend/modelscope_studio/components/antd/list/**init**.py:86-101](file://backend/modelscope_studio/components/antd/list/__init__.py#L86-L101) +- [backend/modelscope_studio/components/antd/timeline/**init**.py:65-81](file://backend/modelscope_studio/components/antd/timeline/__init__.py#L65-L81) +- [backend/modelscope_studio/components/antd/tag/**init**.py:19-27](file://backend/modelscope_studio/components/antd/tag/__init__.py#L19-L27) + +## Conclusion + +This document is based on the Python component implementations in the repository, providing an overview of the API characteristics, events and slots, data flow processing, and typical usage paths of data display components. This update specifically enhances documentation for the Timeline and checkable tag group components, providing users with a more complete component usage guide. In actual projects, it is recommended to use this reference in conjunction with frontend component documentation to ensure that event binding, slot rendering, and data formats meet business requirements. + +## Appendix + +- Internationalization support + - Pass localized text via `locale`, `title`, `description`, and other parameters; configure locale in ConfigProvider when necessary + - Timeline component supports customizing pending state text and icons through slots +- Theme customization + - Inject styles via `class_names`/`styles`/`root_class_name`; use `color`/`status` and other semantic parameters to express state + - Checkable tag group supports batch configuration of tag options via the `options` parameter +- Accessibility + - Provide explicit `aria-label` or `title` for interactive elements; ensure keyboard accessibility and visible focus + - Timeline component supports the `reverse` parameter for reverse timeline, improving user experience +- Example index + - Examples for each component can be found as `example_payload`/`example_value` return values in the corresponding component files + - Timeline component supports direct data input via the `items` parameter for simplified usage + - Checkable tag group supports multiple data formats, including simple string arrays and complex object arrays diff --git a/.wiki/en/API Reference/Python API/Antd Components API/Data Entry Components API.md b/.wiki/en/API Reference/Python API/Antd Components API/Data Entry Components API.md new file mode 100644 index 00000000..9512ca96 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antd Components API/Data Entry Components API.md @@ -0,0 +1,453 @@ +# Data Entry Components API + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/components/antd/auto_complete/__init__.py](file://backend/modelscope_studio/components/antd/auto_complete/__init__.py) +- [backend/modelscope_studio/components/antd/cascader/__init__.py](file://backend/modelscope_studio/components/antd/cascader/__init__.py) +- [backend/modelscope_studio/components/antd/checkbox/__init__.py](file://backend/modelscope_studio/components/antd/checkbox/__init__.py) +- [backend/modelscope_studio/components/antd/color_picker/__init__.py](file://backend/modelscope_studio/components/antd/color_picker/__init__.py) +- [backend/modelscope_studio/components/antd/date_picker/__init__.py](file://backend/modelscope_studio/components/antd/date_picker/__init__.py) +- [backend/modelscope_studio/components/antd/form/__init__.py](file://backend/modelscope_studio/components/antd/form/__init__.py) +- [backend/modelscope_studio/components/antd/input/__init__.py](file://backend/modelscope_studio/components/antd/input/__init__.py) +- [backend/modelscope_studio/components/antd/input_number/__init__.py](file://backend/modelscope_studio/components/antd/input_number/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for Antd data entry components, covering the following components: AutoComplete, Cascader, Checkbox, ColorPicker, DatePicker, Form, Input, InputNumber, Mentions (not found in known backend files), Radio (not found in known backend files), Rate (not found in known backend files), Select (not found in known backend files), Slider (not found in known backend files), Switch (not found in known backend files), TimePicker (not found in known backend files), Transfer (not found in known backend files), TreeSelect (not found in known backend files), Upload (not found in known backend files). +The documentation covers: constructor parameters, events and slots, property definitions, method signatures and return types, data type specifications, preprocessing/postprocessing behavior, usage examples, validation and formatting, error handling, serialization and API integration, real-time validation and UX design principles, and performance optimization recommendations. + +## Project Structure + +Antd components are exported centrally via on-demand imports in the backend, enabling unified usage. Each component has an independent Svelte implementation in the frontend directory, bridged by the backend through a unified base class and frontend directory mapping. + +```mermaid +graph TB +A["Backend Module
backend/modelscope_studio/components/antd/__init__.py"] --> B["AutoComplete
auto_complete/__init__.py"] +A --> C["Cascader
cascader/__init__.py"] +A --> D["Checkbox
checkbox/__init__.py"] +A --> E["ColorPicker
color_picker/__init__.py"] +A --> F["DatePicker
date_picker/__init__.py"] +A --> G["Form
form/__init__.py"] +A --> H["Input
input/__init__.py"] +A --> I["InputNumber
input_number/__init__.py"] +J["Frontend Directory
frontend/antd/*"]:::ext +B --> J +C --> J +D --> J +E --> J +F --> J +G --> J +H --> J +I --> J +classDef ext fill:#fff,stroke:#333,stroke-width:1px; +``` + +Chart sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/auto_complete/**init**.py:1-146](file://backend/modelscope_studio/components/antd/auto_complete/__init__.py#L1-L146) +- [backend/modelscope_studio/components/antd/cascader/**init**.py:1-191](file://backend/modelscope_studio/components/antd/cascader/__init__.py#L1-L191) +- [backend/modelscope_studio/components/antd/checkbox/**init**.py:1-83](file://backend/modelscope_studio/components/antd/checkbox/__init__.py#L1-L83) +- [backend/modelscope_studio/components/antd/color_picker/**init**.py:1-148](file://backend/modelscope_studio/components/antd/color_picker/__init__.py#L1-L148) +- [backend/modelscope_studio/components/antd/date_picker/**init**.py:1-208](file://backend/modelscope_studio/components/antd/date_picker/__init__.py#L1-L208) +- [backend/modelscope_studio/components/antd/form/**init**.py:1-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L1-L133) +- [backend/modelscope_studio/components/antd/input/**init**.py:1-127](file://backend/modelscope_studio/components/antd/input/__init__.py#L1-L127) +- [backend/modelscope_studio/components/antd/input_number/**init**.py:1-147](file://backend/modelscope_studio/components/antd/input_number/__init__.py#L1-L147) + +Section sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) + +## Core Components + +This section provides an overview of the general capabilities and differences of data entry components: + +- All components inherit from a unified data layout component base class, providing consistent lifecycle and event binding mechanisms. +- Each component provides: + - Constructor parameters: supports common properties (e.g., size, status, style, class names, etc.) and component-specific properties. + - Event list: binds frontend callbacks via event listeners. + - Slot list: used for custom rendering (e.g., dropdown panel, prefix/suffix, placeholder content, etc.). + - Data type specifications: declares input/output types through API specs. + - Preprocessing/postprocessing: type conversion or formatting of payload/value. + - Example values and example payloads: facilitates quick integration and testing. + +Section sources + +- [backend/modelscope_studio/components/antd/auto_complete/**init**.py:11-146](file://backend/modelscope_studio/components/antd/auto_complete/__init__.py#L11-L146) +- [backend/modelscope_studio/components/antd/cascader/**init**.py:13-191](file://backend/modelscope_studio/components/antd/cascader/__init__.py#L13-L191) +- [backend/modelscope_studio/components/antd/checkbox/**init**.py:12-83](file://backend/modelscope_studio/components/antd/checkbox/__init__.py#L12-L83) +- [backend/modelscope_studio/components/antd/color_picker/**init**.py:12-148](file://backend/modelscope_studio/components/antd/color_picker/__init__.py#L12-L148) +- [backend/modelscope_studio/components/antd/date_picker/**init**.py:13-208](file://backend/modelscope_studio/components/antd/date_picker/__init__.py#L13-L208) +- [backend/modelscope_studio/components/antd/form/**init**.py:17-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L17-L133) +- [backend/modelscope_studio/components/antd/input/**init**.py:16-127](file://backend/modelscope_studio/components/antd/input/__init__.py#L16-L127) +- [backend/modelscope_studio/components/antd/input_number/**init**.py:11-147](file://backend/modelscope_studio/components/antd/input_number/__init__.py#L11-L147) + +## Architecture Overview + +Backend components connect to frontend directory mappings through a unified base class. The frontend components handle UI rendering and interaction, while the backend manages data type constraints, event binding, and serialization. + +```mermaid +sequenceDiagram +participant U as "User" +participant FE as "Frontend Component (Svelte)" +participant BE as "Backend Component (Python)" +participant API as "Gradio/Server" +U->>FE : Input/Select/Click +FE-->>BE : Trigger event (e.g., change/search/select) +BE->>BE : Bind event callbacks
Update internal state +BE->>API : Serialize payload and submit +API-->>BE : Return processed value +BE-->>FE : Post-process result and update UI +``` + +Chart sources + +- [backend/modelscope_studio/components/antd/auto_complete/**init**.py:18-43](file://backend/modelscope_studio/components/antd/auto_complete/__init__.py#L18-L43) +- [backend/modelscope_studio/components/antd/cascader/**init**.py:20-36](file://backend/modelscope_studio/components/antd/cascader/__init__.py#L20-L36) +- [backend/modelscope_studio/components/antd/form/**init**.py:23-36](file://backend/modelscope_studio/components/antd/form/__init__.py#L23-L36) + +## Detailed Component Analysis + +### AutoComplete + +- Type and purpose: Auto-complete component for string input, supporting option lists and search events. +- Key properties + - Common: size, status, variant, placeholder, disabled, class_names, styles, root_class_name, as_item, etc. + - Specific: allow_clear, auto_focus, backfill, default_active_first_option, default_open, dropdown_render, popup_render, popup_class_name, popup_match_select_width, filter_option, get_popup_container, not_found_content, open, options, placement, options, etc. +- Events: change, blur, focus, search, select, clear, dropdown_visible_change, popup_visible_change. +- Slots: allowClear.clearIcon, dropdownRender, popupRender, children, notFoundContent, options. +- Data types + - Input/Output: string. + - API spec: string type. +- Preprocessing/postprocessing: pass-through. +- Usage examples + - Use as a single input in a form, combined with validation rules. + - Use `options` to provide candidate lists, combined with `search` event for remote search. +- Error handling + - Customize the prompt via `not_found_content` when no match is found. +- Real-time validation + - Trigger remote validation via `search` event, used with Form's validation trigger strategy. + +Section sources + +- [backend/modelscope_studio/components/antd/auto_complete/**init**.py:12-146](file://backend/modelscope_studio/components/antd/auto_complete/__init__.py#L12-L146) + +### Cascader + +- Type and purpose: Multi-level cascading selection, supports async loading and search. +- Key properties + - Common: size, status, variant, placeholder, disabled, class_names, styles, root_class_name, as_item, etc. + - Specific: allow_clear, auto_clear_search_value, auto_focus, change_on_select, display_render, tag_render, popup_class_name, dropdown_render, popup_render, expand_icon, prefix, expand_trigger, filed_names, get_popup_container, max_tag_count, max_tag_placeholder, max_tag_text_length, not_found_content, open, options, placement, show_search, multiple, show_checked_strategy, remove_icon, search_value, dropdown_menu_column_style, option_render, etc. +- Events: change, search, dropdown_visible_change, popup_visible_change, load_data. +- Slots: allowClear.clearIcon, suffixIcon, maxTagPlaceholder, notFoundContent, expandIcon, removeIcon, prefix, displayRender, tagRender, dropdownRender, popupRender, showSearch.render. +- Data types + - Input/Output: string array or number array (path keys). + - API spec: string array or string. +- Preprocessing/postprocessing: pass-through. +- Usage examples + - Commonly used for province/city/district selection, category filtering, and similar scenarios. + - Use `load_data` to implement lazy loading. +- Error handling + - Customize empty state via `not_found_content`. +- Real-time validation + - Combine `search` and `change` events with Form validation. + +Section sources + +- [backend/modelscope_studio/components/antd/cascader/**init**.py:13-191](file://backend/modelscope_studio/components/antd/cascader/__init__.py#L13-L191) + +### Checkbox + +- Type and purpose: Boolean value selection. +- Key properties + - Common: class_names, styles, additional_props, root_class_name, as_item, etc. + - Specific: auto_focus, default_checked, disabled, indeterminate. +- Events: change. +- Data types + - Input/Output: boolean. + - API spec: boolean type. +- Preprocessing/postprocessing: pass-through. +- Usage examples + - Use standalone or combined into a Group. +- Error handling + - No special error handling logic; follows boolean constraints. +- Real-time validation + - Can participate directly in Form validation. + +Section sources + +- [backend/modelscope_studio/components/antd/checkbox/**init**.py:12-83](file://backend/modelscope_studio/components/antd/checkbox/__init__.py#L12-L83) + +### ColorPicker + +- Type and purpose: Color value selection, supports solid color and gradient modes. +- Key properties + - Common: class_names, styles, additional_props, root_class_name, as_item, etc. + - Specific: value_format, allow_clear, arrow, presets, disabled, disabled_alpha, disabled_format, destroy_tooltip_on_hide, destroy_on_hidden, format, mode, open, default_value, default_format, show_text, placement, trigger, panel_render, size. +- Events: change, change_complete, clear, open_change, format_change. +- Slots: presets, panelRender, showText. +- Data types + - Input/Output: hex string or gradient color array object. + - API spec: string or color array object. +- Preprocessing/postprocessing: pass-through. +- Usage examples + - Used for theme color, brand color, and similar configurations. +- Error handling + - Invalid formats are intercepted by frontend validation. +- Real-time validation + - Combine `change` and `change_complete` events with validation. + +Section sources + +- [backend/modelscope_studio/components/antd/color_picker/**init**.py:12-148](file://backend/modelscope_studio/components/antd/color_picker/__init__.py#L12-L148) + +### DatePicker + +- Type and purpose: Date/time selection, supports multiple modes and range selection. +- Key properties + - Common: class_names, styles, additional_props, root_class_name, as_item, etc. + - Specific: allow_clear, auto_focus, cell_render, components, disabled, disabled_date, format, order, preserve_invalid_on_blur, input_read_only, locale, mode, need_confirm, next_icon, open, panel_render, picker, placement, placeholder, popup_class_name, popup_style, get_popup_container, min_date, max_date, prefix, prev_icon, size, presets, status, suffix_icon, super_next_icon, super_prev_icon, variant, default_picker_value, default_value, disabled_time, multiple, picker_value, render_extra_footer, show_now, show_time, show_week, preview_value. +- Events: change, ok, panel_change, open_change. +- Slots: allowClear.clearIcon, prefix, prevIcon, nextIcon, suffixIcon, superNextIcon, superPrevIcon, renderExtraFooter, cellRender, panelRender. +- Data types + - Input/Output: string, number, or array (range). + - API spec: string, number, or array. +- Preprocessing/postprocessing: pass-through. +- Usage examples + - Supports date, week, month, quarter, year, and other modes; can enable time selection and confirmation button. +- Error handling + - Restrict ranges via `disabled_date`, `min_date`, `max_date`. +- Real-time validation + - Combine `panel_change` and `change` events with validation. + +Section sources + +- [backend/modelscope_studio/components/antd/date_picker/**init**.py:13-208](file://backend/modelscope_studio/components/antd/date_picker/__init__.py#L13-L208) + +### Form + +- Type and purpose: Data collection and validation container, supports field change, submit, reset, and validation. +- Key properties + - Common: class_names, styles, additional_props, root_class_name, as_item, etc. + - Specific: form_action, colon, disabled, component, feedback_icons, initial_values, label_align, label_col, label_wrap, layout, form_name, preserve, required_mark, scroll_to_first_error, size, validate_messages, validate_trigger, variant, wrapper_col, clear_on_destroy. +- Events: fields_change, finish, finish_failed, values_change. +- Slots: requiredMark. +- Data types + - Input/Output: dict or wrapped model. + - Preprocessing: extract wrapped model into dict. +- Preprocessing/postprocessing: unpack AntdFormData to dict. +- Usage examples + - Place each data entry component as a child item in Form to manage validation and submission uniformly. +- Error handling + - Control error display and positioning via `validate_messages`, `scroll_to_first_error`. +- Real-time validation + - Control trigger timing via `validate_trigger` (e.g., onChange). + +Section sources + +- [backend/modelscope_studio/components/antd/form/**init**.py:17-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L17-L133) + +### Input + +- Type and purpose: Basic text input, supports password, search, multi-line text, OTP and other variants. +- Key properties + - Common: class_names, styles, additional_props, root_class_name, as_item, etc. + - Specific: addon_after, addon_before, allow_clear, count, default_value, read_only, disabled, max_length, prefix, show_count, size, status, suffix, type, placeholder, variant. +- Events: change, press_enter, clear. +- Slots: addonAfter, addonBefore, allowClear.clearIcon, prefix, suffix, showCount.formatter. +- Data types + - Input/Output: string. + - API spec: string. +- Preprocessing/postprocessing: pass-through. +- Usage examples + - Extend to different forms via Password, Search, Textarea, OTP subclasses. +- Error handling + - Provide feedback via `status` and validation rules. +- Real-time validation + - Combine `change` and `press_enter` events with validation. + +Section sources + +- [backend/modelscope_studio/components/antd/input/**init**.py:16-127](file://backend/modelscope_studio/components/antd/input/__init__.py#L16-L127) + +### InputNumber + +- Type and purpose: Numeric input, supports stepping, precision, up/down controls, etc. +- Key properties + - Common: class_names, styles, additional_props, root_class_name, as_item, etc. + - Specific: addon_after, addon_before, auto_focus, change_on_blur, change_on_wheel, controls, decimal_separator, placeholder, default_value, disabled, formatter, keyboard, max, min, mode, parser, precision, prefix, read_only, size, status, step, string_mode, suffix, variant. +- Events: change, press_enter, step. +- Slots: addonAfter, addonBefore, controls.upIcon, controls.downIcon, prefix, suffix. +- Data types + - Input/Output: integer or float. + - API spec: number. +- Preprocessing/postprocessing: parse string to integer or float. +- Usage examples + - Suitable for price, quantity, rating, and other numeric inputs. +- Error handling + - Constrain range and granularity via `min`/`max`, `precision`, `step`. +- Real-time validation + - Combine `change` and `step` events with validation. + +Section sources + +- [backend/modelscope_studio/components/antd/input_number/**init**.py:11-147](file://backend/modelscope_studio/components/antd/input_number/__init__.py#L11-L147) + +### Mentions (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### Radio (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### Rate (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### Select (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### Slider (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### Switch (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### TimePicker (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### Transfer (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### TreeSelect (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +### Upload (not found in backend) + +- Status: No backend implementation file found in the current repository. +- Recommendation: If needed, refer to the Antd official documentation and frontend implementation, and add the backend adapter layer. + +## Dependency Analysis + +- Inter-component coupling + - All components share the same base class and event system, with low coupling and high cohesion. + - Form acts as a container, aggregating data entry components to form a loosely-coupled form ecosystem. +- External dependencies + - The event system is based on Gradio's event listeners. + - Frontend directory mappings are resolved via utility functions, ensuring frontend-backend consistency. +- Circular dependencies + - No circular dependencies detected. + +```mermaid +graph LR +Base["Unified Base Class"] --> AC["AutoComplete"] +Base --> CS["Cascader"] +Base --> CB["Checkbox"] +Base --> CP["ColorPicker"] +Base --> DP["DatePicker"] +Base --> FM["Form"] +Base --> IN["Input"] +Base --> INN["InputNumber"] +FM --> AC +FM --> CS +FM --> CB +FM --> CP +FM --> DP +FM --> IN +FM --> INN +``` + +Chart sources + +- [backend/modelscope_studio/components/antd/auto_complete/**init**.py:12](file://backend/modelscope_studio/components/antd/auto_complete/__init__.py#L12) +- [backend/modelscope_studio/components/antd/cascader/**init**.py:13](file://backend/modelscope_studio/components/antd/cascader/__init__.py#L13) +- [backend/modelscope_studio/components/antd/checkbox/**init**.py:12](file://backend/modelscope_studio/components/antd/checkbox/__init__.py#L12) +- [backend/modelscope_studio/components/antd/color_picker/**init**.py:12](file://backend/modelscope_studio/components/antd/color_picker/__init__.py#L12) +- [backend/modelscope_studio/components/antd/date_picker/**init**.py:13](file://backend/modelscope_studio/components/antd/date_picker/__init__.py#L13) +- [backend/modelscope_studio/components/antd/form/**init**.py:17](file://backend/modelscope_studio/components/antd/form/__init__.py#L17) +- [backend/modelscope_studio/components/antd/input/**init**.py:16](file://backend/modelscope_studio/components/antd/input/__init__.py#L16) +- [backend/modelscope_studio/components/antd/input_number/**init**.py:11](file://backend/modelscope_studio/components/antd/input_number/__init__.py#L11) + +Section sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) + +## Performance Considerations + +- Event binding and callbacks + - Set event bindings judiciously (e.g., only enable search/visibility change events when necessary) to avoid excessive triggering. +- Data types and serialization + - Numeric input components perform string-to-number conversion during preprocessing, reducing overhead from frontend type inconsistencies. +- Dropdowns and popups + - For complex dropdowns (e.g., Cascader), use lazy loading and virtual scrolling (if supported by the frontend) to reduce rendering costs. +- Styles and class names + - Use `class_names` and `styles` to streamline styles, avoiding repeated computation and repaints. +- Form validation + - Set `validate_trigger` appropriately to avoid performance issues from high-frequency validation. + +## Troubleshooting Guide + +- Event not triggered + - Check that event listeners are correctly bound and confirm that the frontend callback is enabled. +- Data type mismatch + - For numeric input components, preprocessing may fail when non-numeric strings are entered; ensure input format is correct. +- Validation not working + - Confirm that Form's `validate_trigger` settings are consistent with component events; check `required_mark` and `scroll_to_first_error` configuration. +- Dropdown/popup issues + - Check `get_popup_container` and `placement` configuration, ensuring the container is visible and the position is reasonable. +- Cascading load failure + - Confirm that `load_data` callback logic is consistent with the `options` structure. + +Section sources + +- [backend/modelscope_studio/components/antd/input_number/**init**.py:128-140](file://backend/modelscope_studio/components/antd/input_number/__init__.py#L128-L140) +- [backend/modelscope_studio/components/antd/form/**init**.py:48-68](file://backend/modelscope_studio/components/antd/form/__init__.py#L48-L68) +- [backend/modelscope_studio/components/antd/cascader/**init**.py:33-36](file://backend/modelscope_studio/components/antd/cascader/__init__.py#L33-L36) + +## Conclusion + +This project provides a unified Antd data entry component backend adapter layer, covering core components such as AutoComplete, Cascader, Checkbox, ColorPicker, DatePicker, Form, Input, and InputNumber. Through a consistent event system, data type specifications, and preprocessing/postprocessing mechanisms, developers can efficiently build forms and data entry interfaces. For missing components (such as Mentions, Radio, Rate, Select, Slider, Switch, TimePicker, Transfer, TreeSelect, Upload), it is recommended to refer to the Antd official documentation and frontend implementations to add backend adapter layers and maintain ecosystem consistency. + +## Appendix + +- Usage recommendations + - Place data entry components inside a Form container to manage initial values, validation, and submission uniformly. + - For complex inputs (e.g., Cascader, DatePicker), prefer controlled mode with explicit API specs. + - Use slots and variants (`variant`) to improve accessibility and consistency. +- Best practices + - Set reasonable default values and placeholders for each input to improve user experience. + - For wide-range inputs (e.g., numbers), set `min`/`max` and `step` to avoid invalid input. + - For date inputs, specify `format` and `picker` mode explicitly to reduce ambiguity. diff --git a/.wiki/en/API Reference/Python API/Antd Components API/Feedback Components API.md b/.wiki/en/API Reference/Python API/Antd Components API/Feedback Components API.md new file mode 100644 index 00000000..c3aea9f1 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antd Components API/Feedback Components API.md @@ -0,0 +1,611 @@ +# Feedback Components API + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/alert/__init__.py](file://backend/modelscope_studio/components/antd/alert/__init__.py) +- [backend/modelscope_studio/components/antd/drawer/__init__.py](file://backend/modelscope_studio/components/antd/drawer/__init__.py) +- [backend/modelscope_studio/components/antd/message/__init__.py](file://backend/modelscope_studio/components/antd/message/__init__.py) +- [backend/modelscope_studio/components/antd/modal/__init__.py](file://backend/modelscope_studio/components/antd/modal/__init__.py) +- [backend/modelscope_studio/components/antd/notification/__init__.py](file://backend/modelscope_studio/components/antd/notification/__init__.py) +- [backend/modelscope_studio/components/antd/popconfirm/__init__.py](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py) +- [backend/modelscope_studio/components/antd/progress/__init__.py](file://backend/modelscope_studio/components/antd/progress/__init__.py) +- [backend/modelscope_studio/components/antd/result/__init__.py](file://backend/modelscope_studio/components/antd/result/__init__.py) +- [backend/modelscope_studio/components/antd/skeleton/__init__.py](file://backend/modelscope_studio/components/antd/skeleton/__init__.py) +- [backend/modelscope_studio/components/antd/spin/__init__.py](file://backend/modelscope_studio/components/antd/spin/__init__.py) +- [backend/modelscope_studio/components/antd/watermark/__init__.py](file://backend/modelscope_studio/components/antd/watermark/__init__.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/components/antd/modal/static/__init__.py](file://backend/modelscope_studio/components/antd/modal/static/__init__.py) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts](file://frontend/antd/config-provider/locales.ts) +- [frontend/antd/message/message.tsx](file://frontend/antd/message/message.tsx) +- [frontend/antd/drawer/drawer.tsx](file://frontend/antd/drawer/drawer.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for Antd feedback components, covering Alert, Drawer, Message, Modal, Notification, Popconfirm, Progress, Result, Skeleton, Spin, Watermark, and other feedback-related components. Content includes: + +- Constructor parameters and property definitions +- Method signatures and return types +- Usage examples (provided as "example paths") +- Timing control, animation, and interaction response +- Global configuration, themes, and internationalization +- UX design principles and notification strategy best practices + +## Project Structure + +Feedback components are located in the antd sub-module of the backend Python package. Each component inherits from a unified component base class, with the frontend implemented by corresponding Svelte components interfaced with the Gradio event system. + +```mermaid +graph TB +subgraph "Python Backend" +A["ModelScopeLayoutComponent
ModelScopeComponent
ModelScopeDataLayoutComponent"] +B["antd/__init__.py
exports component aliases"] +C["alert/__init__.py"] +D["drawer/__init__.py"] +E["message/__init__.py"] +F["modal/__init__.py"] +G["notification/__init__.py"] +H["popconfirm/__init__.py"] +I["progress/__init__.py"] +J["result/__init__.py"] +K["skeleton/__init__.py"] +L["spin/__init__.py"] +M["watermark/__init__.py"] +end +subgraph "Frontend Svelte" +P["config-provider/config-provider.tsx"] +Q["message/message.tsx"] +R["drawer/drawer.tsx"] +end +A --> C +A --> D +A --> E +A --> F +A --> G +A --> H +A --> I +A --> J +A --> K +A --> L +A --> M +B --> C +B --> D +B --> E +B --> F +B --> G +B --> H +B --> I +B --> J +B --> K +B --> L +B --> M +P --> E +P --> G +Q --> E +R --> D +``` + +Chart sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [frontend/antd/config-provider/config-provider.tsx:51-106](file://frontend/antd/config-provider/config-provider.tsx#L51-L106) +- [frontend/antd/message/message.tsx:55-78](file://frontend/antd/message/message.tsx#L55-L78) +- [frontend/antd/drawer/drawer.tsx:14-60](file://frontend/antd/drawer/drawer.tsx#L14-L60) + +Section sources + +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +## Core Components + +The following is an overview of common constructor parameters and properties for feedback components (grouped by component): + +- Common parameters + - visible: boolean, whether to render + - elem_id: string, element ID + - elem_classes: list or string, CSS classes + - elem_style: dict, inline styles + - render: boolean, whether to render + - as_item: string, layout item identifier + - class_names: dict or string, additional class name mapping + - styles: dict or string, additional style mapping + - root_class_name: string, root node class name + - additional_props: dict, extra properties passed through to frontend components + - \_internal: internal parameter, reserved by the framework + +- Event binding (registered via EVENTS list) + - Event callbacks are bound to frontend components via internal updates at construction time + +Section sources + +- [backend/modelscope_studio/utils/dev/component.py:28-98](file://backend/modelscope_studio/utils/dev/component.py#L28-L98) +- [backend/modelscope_studio/components/antd/alert/**init**.py:16-20](file://backend/modelscope_studio/components/antd/alert/__init__.py#L16-L20) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:14-18](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L14-L18) +- [backend/modelscope_studio/components/antd/message/**init**.py:14-21](file://backend/modelscope_studio/components/antd/message/__init__.py#L14-L21) +- [backend/modelscope_studio/components/antd/modal/**init**.py:18-25](file://backend/modelscope_studio/components/antd/modal/__init__.py#L18-L25) +- [backend/modelscope_studio/components/antd/notification/**init**.py:14-21](file://backend/modelscope_studio/components/antd/notification/__init__.py#L14-L21) +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:14-27](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L14-L27) +- [backend/modelscope_studio/components/antd/watermark/**init**.py:12-16](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L12-L16) + +## Architecture Overview + +The feedback component call chain is as follows: the Python layer constructs component instances, sets properties and events; the frontend Svelte component receives props and interfaces with Ant Design components; the global ConfigProvider provides themes and internationalization; Message/Notification display globally through frontend context. + +```mermaid +sequenceDiagram +participant Py as "Python Component Instance" +participant FE as "Svelte Frontend Component" +participant CFG as "ConfigProvider" +participant MSG as "Message Context" +participant NOTI as "Notification Context" +Py->>FE : Set properties and events +FE->>CFG : Apply theme/language configuration +CFG-->>FE : Return localization and theme +FE->>MSG : Register message display +FE->>NOTI : Register notification display +MSG-->>Py : Event callbacks e.g. click/close +NOTI-->>Py : Event callbacks e.g. click/close +``` + +Chart sources + +- [frontend/antd/config-provider/config-provider.tsx:51-106](file://frontend/antd/config-provider/config-provider.tsx#L51-L106) +- [frontend/antd/message/message.tsx:55-78](file://frontend/antd/message/message.tsx#L55-L78) +- [backend/modelscope_studio/components/antd/message/**init**.py:14-21](file://backend/modelscope_studio/components/antd/message/__init__.py#L14-L21) +- [backend/modelscope_studio/components/antd/notification/**init**.py:14-21](file://backend/modelscope_studio/components/antd/notification/__init__.py#L14-L21) + +## Detailed Component Analysis + +### Alert + +- Constructor parameters and properties + - action: string, action button content + - after_close: string, callback after closing + - banner: boolean, banner mode + - closable: boolean or dict, closable configuration + - description: string, description text + - icon: string, icon + - message: string, title + - show_icon: boolean, whether to show icon + - type: text enum (success/info/warning/error), type + - slots: supports action, closable.closeIcon, description, icon, message +- Methods + - preprocess(payload): input preprocessing + - postprocess(value): output postprocessing + - example_payload()/example_value(): example data +- Events + - close: close event binding + +Section sources + +- [backend/modelscope_studio/components/antd/alert/**init**.py:25-89](file://backend/modelscope_studio/components/antd/alert/__init__.py#L25-L89) + +### Drawer + +- Constructor parameters and properties + - after_open_change: string, callback on open state change + - auto_focus: boolean, auto focus + - body_style: dict, body style + - close_icon: string, close icon + - closable: boolean or dict, closable + - destroy_on_close/destroy_on_hidden: boolean, destroy on close/hide + - draggable: boolean, draggable + - extra: string, extra content + - footer: string, footer + - force_render: boolean, force render + - get_container: string, container selector + - height/width: number or string, size + - keyboard: boolean, keyboard support + - mask/mask_closable: boolean, mask and click-to-close mask + - placement: text enum (left/right/top/bottom), position + - push: boolean or dict, push + - resizable: boolean, resizable + - size: text enum (default/large), size + - title: string, title + - loading: boolean, loading + - open: boolean, whether open + - z_index: integer, z-index + - drawer_render: string, render function + - slots: supports closeIcon, closable.closeIcon, extra, footer, title, drawerRender +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data +- Events + - close: close event binding + - resizable_resize_start: resize start event binding + - resizable_resize: resize event binding + - resizable_resize_end: resize end event binding + +**Update** Drawer component added three resize-related event handlers: + +- resizable_resize_start: triggered when the user starts dragging to resize the drawer +- resizable_resize: continuously triggered during the resize process +- resizable_resize_end: triggered when the resize operation is complete + +These events allow developers to monitor the dynamic adjustment process of the drawer for more fine-grained interaction control. + +Section sources + +- [backend/modelscope_studio/components/antd/drawer/**init**.py:14-27](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L14-L27) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:26-126](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L26-L126) +- [frontend/antd/drawer/drawer.tsx:14-60](file://frontend/antd/drawer/drawer.tsx#L14-L60) + +### Message + +- Constructor parameters and properties + - content: string, message content + - type: text enum (success/info/warning/error/loading), type + - duration: number, duration + - icon: string, icon + - key: string/number/float, unique key + - pause_on_hover: boolean, pause on hover + - get_container: string, container selector + - rtl: boolean, right-to-left + - top: number, top offset + - slots: supports icon, content +- Methods + - preprocess(payload: str|None): str|None + - postprocess(value: str|None): str|None + - example_payload()/example_value(): example data +- Events + - click/close: click and close event binding + +Section sources + +- [backend/modelscope_studio/components/antd/message/**init**.py:26-91](file://backend/modelscope_studio/components/antd/message/__init__.py#L26-L91) +- [frontend/antd/message/message.tsx:55-78](file://frontend/antd/message/message.tsx#L55-L78) + +### Modal + +- Constructor parameters and properties + - after_close: string, callback after closing + - cancel_button_props/cancel_text: dict/string, cancel button properties and text + - centered: boolean, centered + - closable/close_icon: boolean/dict/string, closable and close icon + - confirm_loading: boolean, confirming + - destroy_on_close/destroy_on_hidden: boolean, destroy on close/hide + - focus_trigger_after_close: boolean, focus trigger after close + - focusable: boolean/dict, focusable + - footer: string or default constant, footer + - force_render: boolean, force render + - get_container: string, container selector + - keyboard: boolean, keyboard support + - mask/mask_closable: boolean, mask and click-to-close mask + - modal_render: string, render function + - ok_text/ok_type/ok_button_props: string/dict, OK button properties + - loading: boolean, loading + - title: string, title + - open: boolean, whether open + - width: number/string, width + - wrap_class_name: string, wrapper class name + - z_index: integer, z-index + - after_open_change: string, callback on open state change + - slots: supports closeIcon, cancelButtonProps.icon, cancelText, closable.closeIcon, closeIcon, footer, title, okButtonProps.icon, okText, modalRender +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data +- Events + - ok/cancel: confirm and cancel event binding +- Static sub-components + - Static: static modal component (for static scenarios) + +Section sources + +- [backend/modelscope_studio/components/antd/modal/**init**.py:34-136](file://backend/modelscope_studio/components/antd/modal/__init__.py#L34-L136) +- [backend/modelscope_studio/components/antd/modal/static/**init**.py:30-61](file://backend/modelscope_studio/components/antd/modal/static/__init__.py#L30-L61) + +### Notification + +- Constructor parameters and properties + - message/description/title: string, message, description, title + - type: text enum (success/info/warning/error), type + - btn: string, button + - close_icon: string/boolean, close icon + - duration: number, duration + - show_progress/pause_on_hover: boolean, progress bar and pause on hover + - icon: string, icon + - key: string, unique key + - placement: text enum (top/topLeft/topRight/bottom/bottomLeft/bottomRight), position + - role: text enum (alert/status), role + - bottom/top: number, margins + - rtl: boolean, right-to-left + - get_container: string, container selector + - stack: boolean/dict, stack configuration + - slots: supports actions, closeIcon, description, icon, message, title +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data +- Events + - click/close: click and close event binding + +Section sources + +- [backend/modelscope_studio/components/antd/notification/**init**.py:26-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L26-L109) + +### Popconfirm + +- Constructor parameters and properties + - title/description: string, title and description + - cancel_button_props/cancel_text: dict/string, cancel button + - disabled: boolean, disabled + - icon: string, icon + - ok_button_props/ok_text/ok_type: dict/string/enum, OK button + - show_cancel: boolean, show cancel + - align/arrow/auto_adjust_overflow: dict/boolean, positioning and auto-fit + - color: string, color + - default_open: boolean, initially open + - destroy_tooltip_on_hide/destroy_on_hidden: boolean, destroy strategy + - fresh: boolean, refresh + - get_popup_container: string, popup container + - mouse_enter_delay/mouse_leave_delay: number, delay + - overlay_class_name/overlay_style/overlay_inner_style: string/dict, overlay styles + - placement: text enum (multiple directions), position + - trigger: text enum or list (hover/focus/click/contextMenu), trigger method + - open: boolean, whether open + - z_index: integer, z-index + - slots: supports title, description, cancelButtonProps.icon, cancelText, okButtonProps.icon, okText +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data +- Events + - open_change/cancel/confirm/popup_click: open change, cancel, confirm, popup click event binding + +Section sources + +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:39-156](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L39-L156) + +### Progress + +- Constructor parameters and properties + - percent: integer, default 0, percentage + - format: string, format function + - show_info: boolean, show info + - status: text enum (success/exception/normal/active), status + - rounding: string, rounding + - stroke_color: string/list/dict, stroke color + - stroke_linecap: text enum (round/butt/square), line cap + - success: dict, success area + - trail_color: string, trail color + - type: text enum (line/circle/dashboard), type + - size: number/list/dict/enum (small/default), size + - steps: integer/dict, steps + - percent_position: dict, percent position + - stroke_width: number/float, stroke width + - gap_degree/gap_position/gap_placement: number/enum, gap degree and position +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data + +Section sources + +- [backend/modelscope_studio/components/antd/progress/**init**.py:15-100](file://backend/modelscope_studio/components/antd/progress/__init__.py#L15-L100) + +### Result + +- Constructor parameters and properties + - extra: string, extra content + - icon: string, icon + - status: text enum (success/error/info/warning/404/403/500), status + - sub_title: string, subtitle + - title: string, title + - slots: supports extra, icon, subTitle, title +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data + +Section sources + +- [backend/modelscope_studio/components/antd/result/**init**.py:17-75](file://backend/modelscope_studio/components/antd/result/__init__.py#L17-L75) + +### Skeleton + +- Constructor parameters and properties + - active: boolean, animation + - avatar: boolean/dict, avatar skeleton + - loading: boolean, loading + - paragraph: boolean/dict, paragraph skeleton + - round: boolean, rounded + - title: boolean/dict, title skeleton +- Sub-components + - Node/Avatar/Button/Image/Input: skeleton nodes and elements +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data + +Section sources + +- [backend/modelscope_studio/components/antd/skeleton/**init**.py:22-80](file://backend/modelscope_studio/components/antd/skeleton/__init__.py#L22-L80) + +### Spin + +- Constructor parameters and properties + - spinning: boolean, whether spinning + - delay: number, delay + - fullscreen: boolean, fullscreen + - indicator: string, indicator + - percent: number/float/enum ('auto'), percentage + - size: text enum (small/default/large), size + - tip: string, tip text + - wrapper_class_name: string, wrapper class name + - slots: supports tip, indicator +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data + +Section sources + +- [backend/modelscope_studio/components/antd/spin/**init**.py:17-79](file://backend/modelscope_studio/components/antd/spin/__init__.py#L17-L79) + +### Watermark + +- Constructor parameters and properties + - content: string/list, content (text or array) + - width/height: number/float, size + - inherit: boolean, inherit + - rotate: number/float, rotation angle + - z_index: integer, z-index + - image: string, image watermark + - font: dict, font configuration + - gap: list, gap + - offset: list, offset +- Methods + - preprocess()/postprocess(): preprocessing/postprocessing + - example_payload()/example_value(): example data +- Events + - remove: remove event binding + +Section sources + +- [backend/modelscope_studio/components/antd/watermark/**init**.py:18-84](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L18-L84) + +## Dependency Analysis + +- Component base classes + - ModelScopeLayoutComponent: layout-type component base class, supports events and slots + - ModelScopeComponent: data-type component base class, supports values and loading + - ModelScopeDataLayoutComponent: data+layout combined base class +- Exports and aliases + - Components are exported as public aliases via antd/**init**.py for direct import usage + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +class ModelScopeComponent { ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +class ModelScopeDataLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +class AntdAlert +class AntdDrawer +class AntdMessage +class AntdModal +class AntdNotification +class AntdPopconfirm +class AntdProgress +class AntdResult +class AntdSkeleton +class AntdSpin +class AntdWatermark +ModelScopeLayoutComponent <|-- AntdAlert +ModelScopeLayoutComponent <|-- AntdDrawer +ModelScopeLayoutComponent <|-- AntdMessage +ModelScopeLayoutComponent <|-- AntdModal +ModelScopeLayoutComponent <|-- AntdNotification +ModelScopeLayoutComponent <|-- AntdPopconfirm +ModelScopeLayoutComponent <|-- AntdResult +ModelScopeLayoutComponent <|-- AntdSkeleton +ModelScopeLayoutComponent <|-- AntdSpin +ModelScopeLayoutComponent <|-- AntdWatermark +ModelScopeComponent <|-- AntdProgress +ModelScopeDataLayoutComponent <|-- AntdSkeleton +``` + +Chart sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/components/antd/alert/**init**.py:11-15](file://backend/modelscope_studio/components/antd/alert/__init__.py#L11-L15) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:10-13](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L10-L13) +- [backend/modelscope_studio/components/antd/message/**init**.py:10-13](file://backend/modelscope_studio/components/antd/message/__init__.py#L10-L13) +- [backend/modelscope_studio/components/antd/modal/**init**.py:11-16](file://backend/modelscope_studio/components/antd/modal/__init__.py#L11-L16) +- [backend/modelscope_studio/components/antd/notification/**init**.py:10-13](file://backend/modelscope_studio/components/antd/notification/__init__.py#L10-L13) +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:10-13](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L10-L13) +- [backend/modelscope_studio/components/antd/progress/**init**.py:8-11](file://backend/modelscope_studio/components/antd/progress/__init__.py#L8-L11) +- [backend/modelscope_studio/components/antd/result/**init**.py:8-11](file://backend/modelscope_studio/components/antd/result/__init__.py#L8-L11) +- [backend/modelscope_studio/components/antd/skeleton/**init**.py:11-14](file://backend/modelscope_studio/components/antd/skeleton/__init__.py#L11-L14) +- [backend/modelscope_studio/components/antd/spin/**init**.py:8-11](file://backend/modelscope_studio/components/antd/spin/__init__.py#L8-L11) +- [backend/modelscope_studio/components/antd/watermark/**init**.py:8-11](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L8-L11) + +Section sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/components/antd/**init**.py:1-151](file://backend/modelscope_studio/components/antd/__init__.py#L1-L151) + +## Performance Considerations + +- Event binding and callbacks + - Bind callbacks at construction time via the EVENTS list to avoid the overhead of repeated binding at runtime +- Rendering strategy + - destroy_on_close/destroy_on_hidden: destroy on close or hide to reduce memory usage + - force_render: force render on demand to avoid unnecessary re-renders +- Animation and transitions + - Control visual feedback and performance balance through frontend component animation configurations (e.g., Spin's delay, Progress's active) +- Global components + - Message/Notification use context management to avoid frequent creation and destruction of instances + +## Troubleshooting Guide + +- Events not triggered + - Check that the EVENTS list and callback bindings are correct + - Confirm that the frontend component has correctly received and forwarded events +- Display issues + - Check state parameters such as visible, render, open + - For global components (Message/Notification), confirm container selectors and mount targets +- Theme and internationalization not taking effect + - Confirm ConfigProvider's locale and themeMode settings + - Check that the language pack in locales.ts is available + +Section sources + +- [backend/modelscope_studio/components/antd/alert/**init**.py:16-20](file://backend/modelscope_studio/components/antd/alert/__init__.py#L16-L20) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:14-18](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L14-L18) +- [backend/modelscope_studio/components/antd/message/**init**.py:14-21](file://backend/modelscope_studio/components/antd/message/__init__.py#L14-L21) +- [backend/modelscope_studio/components/antd/modal/**init**.py:18-25](file://backend/modelscope_studio/components/antd/modal/__init__.py#L18-L25) +- [backend/modelscope_studio/components/antd/notification/**init**.py:14-21](file://backend/modelscope_studio/components/antd/notification/__init__.py#L14-L21) +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:14-27](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L14-L27) +- [backend/modelscope_studio/components/antd/watermark/**init**.py:12-16](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L12-L16) +- [frontend/antd/config-provider/config-provider.tsx:51-106](file://frontend/antd/config-provider/config-provider.tsx#L51-L106) +- [frontend/antd/config-provider/locales.ts:159-806](file://frontend/antd/config-provider/locales.ts#L159-L806) + +## Conclusion + +This reference document covers the Python API, frontend integration, and global configuration essentials for feedback components. In practice, it is recommended to: + +- Clarify component responsibilities and applicable scenarios (alerts, dialogs, progress, skeleton, loading, watermark) +- Set event and lifecycle parameters appropriately to ensure smooth interactions +- Use ConfigProvider for unified theme and internationalization management +- Follow notification strategies and UX design principles to avoid excessive interruptions + +## Appendix + +- Usage examples (provided as "example paths") + - Message: see [docs/components/antd/message/README-zh_CN.md:1-8](file://docs/components/antd/message/README-zh_CN.md#L1-L8) + - Notification: see [docs/components/antd/notification/README-zh_CN.md:1-8](file://docs/components/antd/notification/README-zh_CN.md#L1-L8) +- Global configuration and internationalization + - ConfigProvider: see [frontend/antd/config-provider/config-provider.tsx:51-106](file://frontend/antd/config-provider/config-provider.tsx#L51-L106) + - Language packs: see [frontend/antd/config-provider/locales.ts:159-806](file://frontend/antd/config-provider/locales.ts#L159-L806) diff --git a/.wiki/en/API Reference/Python API/Antd Components API/General Components API.md b/.wiki/en/API Reference/Python API/Antd Components API/General Components API.md new file mode 100644 index 00000000..6afa4888 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antd Components API/General Components API.md @@ -0,0 +1,370 @@ +# General Components API + + +**Files Referenced in This Document** +- [button/__init__.py](file://backend/modelscope_studio/components/antd/button/__init__.py) +- [float_button/__init__.py](file://backend/modelscope_studio/components/antd/float_button/__init__.py) +- [icon/__init__.py](file://backend/modelscope_studio/components/antd/icon/__init__.py) +- [typography/__init__.py](file://backend/modelscope_studio/components/antd/typography/__init__.py) +- [affix/__init__.py](file://backend/modelscope_studio/components/antd/affix/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for Antd general components, covering Button, FloatButton, Icon, Typography, and Affix. Contents include: + +- Constructor parameters, property definitions, method signatures, and return types for each component class +- Standard instantiation examples (basic usage and advanced configuration) +- Event handling mechanisms, style customization approaches, and responsive behavior +- Parameter validation rules, exception handling strategies, and best practices +- API index organized by function for quick reference + +## Project Structure + +These components all reside in the backend Python package, wrapped through a unified layout component base class, pointing to corresponding frontend directories for UI rendering. + +```mermaid +graph TB +subgraph "Python Backend" +A["AntdButton
Constructor Parameters/Properties/Methods"] +B["AntdFloatButton
Constructor Parameters/Properties/Methods"] +C["AntdIcon
Constructor Parameters/Properties/Methods"] +D["AntdTypography
Aggregator: Text/Title/Paragraph/Link"] +E["AntdAffix
Constructor Parameters/Properties/Methods"] +end +subgraph "Frontend Directories" +F["button frontend directory"] +G["float-button frontend directory"] +H["icon frontend directory"] +I["typography frontend directory"] +J["affix frontend directory"] +end +A --> F +B --> G +C --> H +D --> I +E --> J +``` + +Diagram sources + +- [button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) +- [float_button/**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) +- [icon/**init**.py:9-88](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L88) +- [typography/**init**.py:1-12](file://backend/modelscope_studio/components/antd/typography/__init__.py#L1-L12) +- [affix/**init**.py:10-86](file://backend/modelscope_studio/components/antd/affix/__init__.py#L10-L86) + +Section sources + +- [button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) +- [float_button/**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) +- [icon/**init**.py:9-88](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L88) +- [typography/**init**.py:1-12](file://backend/modelscope_studio/components/antd/typography/__init__.py#L1-L12) +- [affix/**init**.py:10-86](file://backend/modelscope_studio/components/antd/affix/__init__.py#L10-L86) + +## Core Components + +This section provides an overview of the five general components' responsibilities and typical use cases: + +- **Button**: Triggers actions; supports multiple types, variants, sizes, shapes, and states (disabled, danger, ghost, loading). +- **FloatButton**: Floating global function button; can include description, tooltip, badge, and link. +- **Icon**: Semantic vector icon; supports rotation, spin animation, and dual-tone icon color settings. +- **Typography**: Text typography collection; contains Text, Title, Paragraph, and Link sub-components. +- **Affix**: Fixed position container; used to stick child elements to the top or bottom of the viewport. + +Section sources + +- [button/**init**.py:15-38](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L38) +- [float_button/**init**.py:12-21](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L21) +- [icon/**init**.py:9-14](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L14) +- [typography/**init**.py:7-12](file://backend/modelscope_studio/components/antd/typography/__init__.py#L7-L12) +- [affix/**init**.py:10-20](file://backend/modelscope_studio/components/antd/affix/__init__.py#L10-L20) + +## Architecture Overview + +Components follow the "Python wrapper + frontend rendering" pattern, injecting common properties (visibility, DOM ID, class names, inline styles, render toggle, etc.) through the unified layout component base class, and pointing to the corresponding frontend directory via `resolve_frontend_dir`. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Py as "AntdButton/AntdFloatButton/AntdIcon/AntdAffix" +participant Base as "ModelScopeLayoutComponent/ModelScopeDataLayoutComponent" +participant FE as "Frontend Component Directory" +Dev->>Py : Instantiate component with parameters +Py->>Base : Call parent constructor, inject common properties +Py->>FE : Set FRONTEND_DIR pointing to corresponding frontend directory +Base-->>Dev : Return renderable component object +``` + +Diagram sources + +- [button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) +- [float_button/**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) +- [icon/**init**.py:9-88](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L88) +- [affix/**init**.py:10-86](file://backend/modelscope_studio/components/antd/affix/__init__.py#L10-L86) + +## Detailed Component Analysis + +### Button Component API + +- Type and inheritance + - Class name: `AntdButton` + - Base class: `ModelScopeLayoutComponent` + - Nested sub-component: `Group` (button group) +- Events + - `click`: Click event; binds internal callback to enable event listening +- Slots + - `icon`, `loading.icon` +- Key properties and meanings + - `auto_insert_space`: Whether to automatically insert a space between Chinese characters + - `block`: Whether to span the full width of the parent container + - `class_names`: Semantic DOM class names + - `danger`/`disabled`/`ghost`/`loading`: Danger/disabled/ghost/loading states + - `href`/`html_type`: Link navigation and native HTML type + - `icon`/`icon_position`: Icon and icon position + - `shape`/`size`/`type`/`variant`/`color`: Shape, size, type, variant, color + - `styles`/`root_class_name`: Semantic styles and root class name + - Other Gradio common properties: `visible`, `elem_id`, `elem_classes`, `elem_style`, `render` +- Methods + - `preprocess(payload)`: Accepts string or None, returns string or None + - `postprocess(value)`: Accepts string or None, returns string or None + - `example_payload`/`example_value`: Example payload and example value +- Instantiation notes + - Use `type`/`variant`/`color`/`shape`/`size` to control appearance and semantics + - `loading` can be boolean or dict (if custom loading icon is needed) + - `href` works with `html_type='button'` or `'submit'`/`'reset'` +- Best practices + - Use `primary` type for main actions; use `danger` for destructive actions + - Set `loading` to prevent duplicate submissions + - For icon buttons, use `icon_position='start'`/`'end'` + +Section sources + +- [button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) + +### FloatButton Component API + +- Type and inheritance + - Class name: `AntdFloatButton` + - Base class: `ModelScopeLayoutComponent` + - Nested sub-components: `BackTop` (back to top), `Group` (button group) +- Events + - `click`: Click event; binds internal callback to enable event listening +- Slots + - `icon`, `description`, `tooltip`, `tooltip.title`, `badge.count` +- Key properties and meanings + - `icon`/`description`: Icon and description text + - `tooltip`: Tooltip text or configuration object + - `type`/`shape`: Type (default/primary), shape (circle/square) + - `href`/`href_target`/`html_type`: Hyperlink target and native HTML type + - `badge`: Badge configuration (some state-related properties not supported) + - `class_names`/`styles`/`root_class_name`: Styles and class names + - Other Gradio common properties: `visible`, `elem_id`, `elem_classes`, `elem_style`, `render` +- Methods + - `preprocess(payload)`: Accepts None, returns None + - `postprocess(value)`: Accepts None, returns None + - `example_payload`/`example_value`: Example payload and example value +- Instantiation notes + - Commonly used for global function entry points (e.g., back to top, quick actions) + - `tooltip` supports strings or objects to extend title, etc. +- Best practices + - Use `circle` shape to improve discoverability + - Combine with `BackTop` for "back to top" experience + +Section sources + +- [float_button/**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) + +### Icon Component API + +- Type and inheritance + - Class name: `AntdIcon` + - Base class: `ModelScopeDataLayoutComponent` + - Nested sub-component: `IconfontProvider` (IconFont provider) +- Events + - `click`: Click event; binds internal callback to enable event listening +- Slots + - `component`: Custom root node component +- Key properties and meanings + - `value`: Default icon name (e.g., `"GithubOutlined"`) + - `spin`: Whether to apply spin animation + - `rotate`: Rotation angle (degrees) + - `two_tone_color`: Primary color for dual-tone icons + - `component`: Root node component replacement + - `class_names`/`styles`: Styles and class names + - Other Gradio common properties: `visible`, `elem_id`, `elem_classes`, `elem_style`, `render` +- Methods + - `preprocess(payload)`: Accepts string or None, returns string or None + - `postprocess(value)`: Accepts string or None, returns string or None + - `example_payload`/`example_value`: Example payload and example value +- Instantiation notes + - When used as decorative elements, prefer semantic icon names + - `spin` and `rotate` can be used in combination +- Best practices + - Use in buttons or navigation with `icon_position` + - Explicitly specify the primary color for dual-tone icon scenarios + +Section sources + +- [icon/**init**.py:9-88](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L88) + +### Typography Component API + +- Type and inheritance + - Class name: `AntdTypography` + - Aggregator: Contains four sub-components: `Text`, `Title`, `Paragraph`, `Link` +- Notes + - This aggregator class only exports sub-components; specific sub-component definitions are in their respective modules +- Instantiation notes + - Access sub-components via `AntdTypography.Text`/`Title`/`Paragraph`/`Link` +- Best practices + - Use `Title` for documents and page headings + - Use `Paragraph` for body text + - Use `Link` for clickable links + +Section sources + +- [typography/**init**.py:1-12](file://backend/modelscope_studio/components/antd/typography/__init__.py#L1-L12) + +### Affix Component API + +- Type and inheritance + - Class name: `AntdAffix` + - Base class: `ModelScopeLayoutComponent` +- Events + - `change`: State change event (attached/detached); binds internal callback to enable event listening +- Key properties and meanings + - `offset_bottom`: Offset from the bottom of the viewport (pixels) + - `offset_top`: Offset from the top of the viewport (pixels) + - `get_target`: Specifies the scroll area DOM node selector + - `class_names`/`styles`/`root_class_name`: Styles and class names + - Other Gradio common properties: `visible`, `elem_id`, `elem_classes`, `elem_style`, `render` +- Methods + - `preprocess(payload)`: Accepts None, returns None + - `postprocess(value)`: Accepts None, returns None + - `example_payload`/`example_value`: Example payload and example value +- Instantiation notes + - Be careful not to block other page content, especially on small-screen devices + - `get_target` can restrict the scroll container to avoid global scroll interference +- Best practices + - Use for menus, toolbars, and other elements that need to remain in the visible area + - Combine with interaction feedback (e.g., `change` event) to update state + +Section sources + +- [affix/**init**.py:10-86](file://backend/modelscope_studio/components/antd/affix/__init__.py#L10-L86) + +## Dependency Analysis + +- Common dependencies + - Base class: `ModelScopeLayoutComponent` or `ModelScopeDataLayoutComponent` + - Event system: `gradio.events.EventListener` + - Frontend directory resolution: `resolve_frontend_dir` +- Inter-component relationships + - Button: Contains `ButtonGroup` + - FloatButton: Contains `BackTop` and `FloatButtonGroup` + - Icon: Contains `IconfontProvider` + - Typography: Aggregates `Text`/`Title`/`Paragraph`/`Link` +- Dependency visualization + +```mermaid +graph LR +subgraph "Events and Base Classes" +EL["EventListener"] +LCB["ModelScopeLayoutComponent"] +DLCB["ModelScopeDataLayoutComponent"] +end +BTN["AntdButton"] --> LCB +BTN --> EL +BTN --> |"resolve_frontend_dir('button')"| FE_BTN["button frontend directory"] +FLT["AntdFloatButton"] --> LCB +FLT --> EL +FLT --> |"resolve_frontend_dir('float-button')"| FE_FLT["float-button frontend directory"] +ICO["AntdIcon"] --> DLCB +ICO --> EL +ICO --> |"resolve_frontend_dir('icon')"| FE_ICO["icon frontend directory"] +TYP["AntdTypography"] --> |"exports Text/Title/Paragraph/Link"| SUB["Sub-components"] +AFF["AntdAffix"] --> LCB +AFF --> EL +AFF --> |"resolve_frontend_dir('affix')"| FE_AFF["affix frontend directory"] +``` + +Diagram sources + +- [button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) +- [float_button/**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) +- [icon/**init**.py:9-88](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L88) +- [typography/**init**.py:1-12](file://backend/modelscope_studio/components/antd/typography/__init__.py#L1-L12) +- [affix/**init**.py:10-86](file://backend/modelscope_studio/components/antd/affix/__init__.py#L10-L86) + +## Performance Considerations + +- Rendering and events + - Control rendering timing and visibility via Gradio common properties to reduce unnecessary redraws + - Enable event binding only when needed (e.g., `click`/`change`) to avoid excessive monitoring +- Icons and loading + - Use `spin`/`rotate` judiciously to avoid extra overhead on low-end devices + - Button's `loading` state prevents duplicate submissions, indirectly reducing server load +- Containers and scrolling + - Affix's `get_target` should be as precise as possible to avoid frequent calculations on large scroll containers +- Recommendations + - Use heavy components (e.g., Tooltip/Popover) sparingly in large lists; use lazy loading if necessary + - Maintain consistency when using appearance properties like `shape`/`size`/`type` to reduce style switching costs + +## Troubleshooting Guide + +- Events not triggering + - Confirm `EVENTS` is correctly configured and components are in an interactive state (not `disabled`/`loading`) + - For FloatButton/Affix, check that `click`/`change` events are bound +- Styles not taking effect + - Check whether `class_names`/`styles` conflicts with theme variables + - Confirm `root_class_name` is not overridden by external styles +- Icon display anomalies + - Confirm `value` is a supported icon name + - If using a custom `component`, ensure the component is renderable and has no circular dependencies +- Floating button blocking content + - Adjust `offset_top`/`offset_bottom` or use `get_target` to precisely control the scroll area +- Loading state not working + - When Button's `loading` is boolean or dict, confirm the parameter format is correct + +Section sources + +- [button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46) +- [float_button/**init**.py:24-29](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L24-L29) +- [affix/**init**.py:21-26](file://backend/modelscope_studio/components/antd/affix/__init__.py#L21-L26) + +## Conclusion + +The above covers the Python API reference and best practice summary for Antd general components. Through a unified base class and event system, these components provide rich appearance and interaction capabilities while remaining simple and easy to use. It is recommended to choose component types and configuration options appropriate for the business scenario in real projects, paying attention to performance and maintainability. + +## Appendix + +- API index by category + - Button components: `AntdButton` (with `Group`), `AntdFloatButton` (with `BackTop`/`Group`) + - Icon components: `AntdIcon` (with `IconfontProvider`) + - Text typography: `AntdTypography` (`Text`/`Title`/`Paragraph`/`Link`) + - Positioning containers: `AntdAffix` +- Quick parameter reference + - Appearance: `type`, `variant`, `color`, `shape`, `size` + - State: `disabled`, `danger`, `ghost`, `loading` + - Behavior: `href`, `html_type`, `icon`, `icon_position`, `tooltip`, `badge` + - Style: `class_names`, `styles`, `root_class_name` + - Events: `click`, `change` +- Example path guide (no code content) + - Button basic usage and loading state: [button/**init**.py:88-108](file://backend/modelscope_studio/components/antd/button/__init__.py#L88-L108) + - FloatButton floating entry with back-to-top combination: [float_button/**init**.py:59-70](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L59-L70) + - Icon animation and dual-tone: [icon/**init**.py:47-53](file://backend/modelscope_studio/components/antd/icon/__init__.py#L47-L53) + - Affix positioning and scroll area: [affix/**init**.py:47-52](file://backend/modelscope_studio/components/antd/affix/__init__.py#L47-L52) diff --git a/.wiki/en/API Reference/Python API/Antd Components API/Layout Components API.md b/.wiki/en/API Reference/Python API/Antd Components API/Layout Components API.md new file mode 100644 index 00000000..4f76af5a --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antd Components API/Layout Components API.md @@ -0,0 +1,439 @@ +# Layout Components API + + +**Files Referenced in This Document** +- [divider/__init__.py](file://backend/modelscope_studio/components/antd/divider/__init__.py) +- [flex/__init__.py](file://backend/modelscope_studio/components/antd/flex/__init__.py) +- [grid/row/__init__.py](file://backend/modelscope_studio/components/antd/grid/row/__init__.py) +- [grid/col/__init__.py](file://backend/modelscope_studio/components/antd/grid/col/__init__.py) +- [layout/__init__.py](file://backend/modelscope_studio/components/antd/layout/__init__.py) +- [layout/content/__init__.py](file://backend/modelscope_studio/components/antd/layout/content/__init__.py) +- [layout/footer/__init__.py](file://backend/modelscope_studio/components/antd/layout/footer/__init__.py) +- [layout/header/__init__.py](file://backend/modelscope_studio/components/antd/layout/header/__init__.py) +- [layout/sider/__init__.py](file://backend/modelscope_studio/components/antd/layout/sider/__init__.py) +- [space/__init__.py](file://backend/modelscope_studio/components/antd/space/__init__.py) +- [space/compact/__init__.py](file://backend/modelscope_studio/components/antd/space/compact/__init__.py) +- [splitter/__init__.py](file://backend/modelscope_studio/components/antd/splitter/__init__.py) +- [splitter/panel/__init__.py](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for Antd layout components, covering Divider, Flex, Grid (Row/Col), Layout (Layout/Header/Sider/Content/Footer), Space, and Splitter (Splitter/Panel). Contents include: + +- Constructor parameters, property definitions, method signatures, and return types for each component class +- Standard layout combination usage examples (responsive layout, grid system, flex layout) +- Nesting rules, spacing control, and alignment +- Layout breakpoint configuration, media query integration, and mobile adaptation +- Component collaboration patterns and performance optimization recommendations + +## Project Structure + +These layout components all reside in the backend Python package, using a unified base class and frontend directory resolution mechanism, allowing them to map to the corresponding frontend implementations at runtime. + +```mermaid +graph TB +subgraph "Antd Layout Components" +D["Divider"] +F["Flex"] +G["Grid
Row/Col"] +L["Layout
Layout/Header/Sider/Content/Footer"] +S["Space
Space/Compact"] +SP["Splitter
Splitter/Panel"] +end +D --> |"uses"| D +F --> |"uses"| F +G --> |"uses"| G +L --> |"contains"| L +S --> |"uses"| S +SP --> |"contains"| SP +``` + +**Diagram sources** + +- [divider/**init**.py:1-95](file://backend/modelscope_studio/components/antd/divider/__init__.py#L1-L95) +- [flex/**init**.py:1-98](file://backend/modelscope_studio/components/antd/flex/__init__.py#L1-L98) +- [grid/row/**init**.py:1-94](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L1-L94) +- [grid/col/**init**.py:1-114](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L1-L114) +- [layout/**init**.py:1-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L1-L91) +- [layout/content/**init**.py:1-75](file://backend/modelscope_studio/components/antd/layout/content/__init__.py#L1-L75) +- [layout/footer/**init**.py:1-75](file://backend/modelscope_studio/components/antd/layout/footer/__init__.py#L1-L75) +- [layout/header/**init**.py:1-75](file://backend/modelscope_studio/components/antd/layout/header/__init__.py#L1-L75) +- [layout/sider/**init**.py:1-128](file://backend/modelscope_studio/components/antd/layout/sider/__init__.py#L1-L128) +- [space/**init**.py:1-104](file://backend/modelscope_studio/components/antd/space/__init__.py#L1-L104) +- [space/compact/**init**.py:1-81](file://backend/modelscope_studio/components/antd/space/compact/__init__.py#L1-L81) +- [splitter/**init**.py:1-97](file://backend/modelscope_studio/components/antd/splitter/__init__.py#L1-L97) +- [splitter/panel/**init**.py:1-86](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L1-L86) + +**Section sources** + +- [divider/**init**.py:1-95](file://backend/modelscope_studio/components/antd/divider/__init__.py#L1-L95) +- [flex/**init**.py:1-98](file://backend/modelscope_studio/components/antd/flex/__init__.py#L1-L98) +- [grid/row/**init**.py:1-94](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L1-L94) +- [grid/col/**init**.py:1-114](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L1-L114) +- [layout/**init**.py:1-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L1-L91) +- [space/**init**.py:1-104](file://backend/modelscope_studio/components/antd/space/__init__.py#L1-L104) +- [splitter/**init**.py:1-97](file://backend/modelscope_studio/components/antd/splitter/__init__.py#L1-L97) + +## Core Components + +- **Divider**: A dividing line for separating content areas; supports horizontal/vertical, title position, dashed/solid style, plain text style, etc. +- **Flex**: A flex layout container; supports main-axis/cross-axis alignment, wrapping, spacing, direction, etc. +- **Grid**: Grid system; Row provides row-level alignment, spacing, and wrapping; Col provides column span, offset, order, responsive breakpoints, etc. +- **Layout**: Overall page layout; contains Header, Sider, Content, Footer sub-components; supports responsive collapse and breakpoint events. +- **Space**: Sets spacing between child elements; supports direction, alignment, auto-wrap, separator; `Space.Compact` is used for compact form arrangements. +- **Splitter**: Draggable split panel; supports horizontal/vertical layout, panel size range, collapse, and drag events. + +**Section sources** + +- [divider/**init**.py:8-95](file://backend/modelscope_studio/components/antd/divider/__init__.py#L8-L95) +- [flex/**init**.py:8-98](file://backend/modelscope_studio/components/antd/flex/__init__.py#L8-L98) +- [grid/row/**init**.py:8-94](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L8-L94) +- [grid/col/**init**.py:8-114](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L8-L114) +- [layout/**init**.py:14-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L14-L91) +- [space/**init**.py:9-104](file://backend/modelscope_studio/components/antd/space/__init__.py#L9-L104) +- [splitter/**init**.py:11-97](file://backend/modelscope_studio/components/antd/splitter/__init__.py#L11-L97) + +## Architecture Overview + +The following class diagram shows the inheritance and composition relationships of layout components, as well as key properties and methods. + +```mermaid +classDiagram +class AntdDivider { ++__init__(value, dashed, variant, orientation, orientation_margin, plain, type, size, ...) ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdFlex { ++__init__(orientation, vertical, wrap, justify, align, flex, gap, component, ...) ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdRow { ++__init__(align, gutter, justify, wrap, ...) +} +class AntdCol { ++__init__(flex, offset, order, pull, push, span, xs, sm, md, lg, xl, xxl, ...) +} +class AntdLayout { ++__init__(has_sider, ...) ++Content ++Footer ++Header ++Sider +} +class AntdLayoutContent +class AntdLayoutFooter +class AntdLayoutHeader +class AntdLayoutSider { ++__init__(breakpoint, collapsed, collapsed_width, collapsible, default_collapsed, reverse_arrow, theme_value, trigger, width, ...) +} +class AntdSpace { ++__init__(align, direction/orientation, size, split/separator, wrap, ...) ++Compact +} +class AntdSpaceCompact { ++__init__(block, direction, size, ...) +} +class AntdSplitter { ++__init__(layout/orientation, lazy, ...) ++Panel +} +class AntdSplitterPanel { ++__init__(default_size, min, max, size, collapsible, resizable, ...) +} +AntdLayout --> AntdLayoutContent : "contains" +AntdLayout --> AntdLayoutFooter : "contains" +AntdLayout --> AntdLayoutHeader : "contains" +AntdLayout --> AntdLayoutSider : "contains" +AntdSpace --> AntdSpaceCompact : "contains" +AntdSplitter --> AntdSplitterPanel : "contains" +``` + +**Diagram sources** + +- [divider/**init**.py:8-95](file://backend/modelscope_studio/components/antd/divider/__init__.py#L8-L95) +- [flex/**init**.py:8-98](file://backend/modelscope_studio/components/antd/flex/__init__.py#L8-L98) +- [grid/row/**init**.py:8-94](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L8-L94) +- [grid/col/**init**.py:8-114](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L8-L114) +- [layout/**init**.py:14-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L14-L91) +- [layout/sider/**init**.py:11-128](file://backend/modelscope_studio/components/antd/layout/sider/__init__.py#L11-L128) +- [space/**init**.py:9-104](file://backend/modelscope_studio/components/antd/space/__init__.py#L9-L104) +- [splitter/**init**.py:11-97](file://backend/modelscope_studio/components/antd/splitter/__init__.py#L11-L97) +- [splitter/panel/**init**.py:8-86](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L8-L86) + +## Detailed Component Analysis + +### Divider + +- Constructor parameters + - `value`: Optional string as the title text inside the divider + - `dashed`: Optional boolean, whether to use dashed line + - `variant`: Enum value, `'dashed'` | `'dotted'` | `'solid'` + - `orientation`: Enum value, `'left'` | `'right'` | `'center'` | `'start'` | `'end'` + - `orientation_margin`: Optional string or number, margin between title and boundary + - `plain`: Optional boolean, plain text style + - `type`: Enum value, `'horizontal'` | `'vertical'` + - `size`: Optional enum value, `'small'` | `'middle'` | `'large'` (only valid for horizontal) + - Other common properties: `root_class_name`, `class_names`, `styles`, `as_item`, `elem_id`, `elem_classes`, `elem_style`, `visible`, `render`, etc. +- Methods + - `preprocess(payload)`: Accepts string or None, returns string or None + - `postprocess(value)`: Accepts string or None, returns string or None + - `example_payload`/`example_value`: Returns None +- Use cases + - Separating article paragraphs, table action columns, etc. + +**Section sources** + +- [divider/**init**.py:21-95](file://backend/modelscope_studio/components/antd/divider/__init__.py#L21-L95) + +### Flex (Flex Layout) + +- Constructor parameters + - `orientation`: Enum value, `'horizontal'` | `'vertical'` + - `vertical`: Boolean, vertical direction (equivalent to `flex-direction: column`) + - `wrap`: Enum value or boolean, `'nowrap'` | `'wrap'` | `'wrap-reverse'` or boolean + - `justify`: Main-axis alignment (various values) + - `align`: Cross-axis alignment (various values) + - `flex`: Flex shorthand property + - `gap`: Spacing size, supports enum or number + - `component`: Custom element type + - Other common properties as above +- Methods + - `preprocess`/`postprocess`: Accepts/returns None + - `example_payload`/`example_value`: Returns None +- Use cases + - Setting element spacing and alignment as a replacement for traditional CSS flex layout + +**Section sources** + +- [flex/**init**.py:21-98](file://backend/modelscope_studio/components/antd/flex/__init__.py#L21-L98) + +### Grid (Grid System) + +- Row + - Constructor parameters + - `align`: Vertical alignment, `'top'` | `'middle'` | `'bottom'` | `'stretch'` or object + - `gutter`: Grid spacing, supports number, string, object, or array + - `justify`: Horizontal arrangement, various values + - `wrap`: Boolean, auto wrap + - Other common properties as above + - Methods + - `preprocess`/`postprocess`: Accepts/returns None + - `example_payload`/`example_value`: Returns None +- Col + - Constructor parameters + - `flex`: Flex layout style + - `offset`: Number of grid columns to offset to the right + - `order`: Sort order + - `pull`/`push`: Move left/right + - `span`: Number of grid columns to occupy (0 corresponds to `display: none`) + - `xs`/`sm`/`md`/`lg`/`xl`/`xxl`: Span at different breakpoints or objects containing the above properties + - Other common properties as above + - Methods + - `preprocess`/`postprocess`: Accepts/returns None + - `example_payload`/`example_value`: Returns None +- Use cases + - Responsive layout based on 24-column grid; supports horizontal/vertical alignment, spacing, and breakpoints + +**Section sources** + +- [grid/row/**init**.py:30-94](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L30-L94) +- [grid/col/**init**.py:30-114](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L30-L114) + +### Layout (Page Layout) + +- Layout + - Nested sub-components: `Content`, `Footer`, `Header`, `Sider` + - Constructor parameters + - `has_sider`: Whether to include a sidebar (avoids SSR flickering) + - Other common properties as above + - Methods + - `preprocess`/`postprocess`: Accepts/returns None + - `example_payload`/`example_value`: Returns None +- Header/Footer/Content + - Constructor parameters: `class_names`, `styles`, `additional_props`, `root_class_name`, `elem_id`, `elem_classes`, `elem_style`, `visible`, `render`, etc. + - Methods: Same as above +- Sider + - Constructor parameters + - `breakpoint`: Responsive breakpoint + - `collapsed`/`collapsible`/`default_collapsed`: Collapse state related + - `collapsed_width`: Width when collapsed + - `reverse_arrow`: Reverse arrow direction (expands to the right) + - `theme_value`: Theme (light/dark); use when conflicting with Gradio preset attribute + - `trigger`: Custom trigger + - `width`: Width + - `zero_width_trigger_style`: Special trigger style when `collapsed_width` is 0 + - Other common properties as above + - Methods: Same as above +- Events + - Layout/Sider/Header/Footer/Content: Support `click` event binding + - Sider: Supports `collapse`, `breakpoint` events +- Use cases + - Overall page layout; combined with Sider for sidebar navigation and responsive collapse + +**Section sources** + +- [layout/**init**.py:14-91](file://backend/modelscope_studio/components/antd/layout/__init__.py#L14-L91) +- [layout/content/**init**.py:10-75](file://backend/modelscope_studio/components/antd/layout/content/__init__.py#L10-L75) +- [layout/footer/**init**.py:10-75](file://backend/modelscope_studio/components/antd/layout/footer/__init__.py#L10-L75) +- [layout/header/**init**.py:10-75](file://backend/modelscope_studio/components/antd/layout/header/__init__.py#L10-L75) +- [layout/sider/**init**.py:11-128](file://backend/modelscope_studio/components/antd/layout/sider/__init__.py#L11-L128) + +### Space + +- Space + - Nested sub-component: `Compact` + - Constructor parameters + - `align`: Child item alignment + - `direction`/`orientation`: Direction (`orientation` is v6 alias) + - `size`: Spacing size, supports enum, number, or array + - `split`/`separator`: Separator (`separator` is v6 alias) + - `wrap`: Auto wrap when horizontal + - Other common properties as above + - Methods + - `preprocess`/`postprocess`: Accepts/returns None + - `example_payload`/`example_value`: Returns None +- Space.Compact + - Constructor parameters + - `block`: Whether to fill parent width + - `direction`: Direction + - `size`: Child component size + - Other common properties as above + - Methods: Same as above +- Use cases + - Equal spacing arrangement of multiple inline elements; use `Compact` for compact form connections + +**Section sources** + +- [space/**init**.py:9-104](file://backend/modelscope_studio/components/antd/space/__init__.py#L9-L104) +- [space/compact/**init**.py:8-81](file://backend/modelscope_studio/components/antd/space/compact/__init__.py#L8-L81) + +### Splitter (Split Panel) + +- Splitter + - Nested sub-component: `Panel` + - Constructor parameters + - `layout`/`orientation`: Layout direction (`orientation` is v6 alias) + - `lazy`: Whether to use lazy rendering + - Other common properties as above + - Events + - `resize_start`, `resize`, `resize_end`, `collapse` + - Methods + - `preprocess`/`postprocess`: Accepts/returns None + - `example_payload`/`example_value`: Returns None +- Splitter.Panel + - Constructor parameters + - `default_size`/`min`/`max`/`size`: Initial/minimum/maximum/controlled size (supports px or percentage) + - `collapsible`: Quick collapse + - `resizable`: Whether to enable drag-and-drop + - Other common properties as above + - Methods: Same as above +- Use cases + - Divides the page into multiple draggable and resizable areas; supports collapse and range restrictions + +**Section sources** + +- [splitter/**init**.py:11-97](file://backend/modelscope_studio/components/antd/splitter/__init__.py#L11-L97) +- [splitter/panel/**init**.py:8-86](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L8-L86) + +## Dependency Analysis + +- Common component characteristics + - All inherit from the unified layout component base class, with the same preprocessing/postprocessing interface and common properties (e.g., `visible`, `elem_id`, `elem_classes`, `elem_style`, `render`, etc.) + - Locate corresponding frontend component implementations via the frontend directory resolution function +- Inter-component coupling + - Layout acts as the root container, internally composing Header/Sider/Content/Footer + - Space and Flex are semantically complementary: Space focuses on "spacing", Flex focuses on "layout" + - Grid's Row/Col can be combined with Flex/Splitter to achieve complex layouts + - Splitter can work with Space/Divider to implement panel separation and spacing control + +```mermaid +graph LR +L["Layout"] --> H["Header"] +L --> SD["Sider"] +L --> C["Content"] +L --> F["Footer"] +G["Grid.Row"] --> GC["Grid.Col"] +Fx["Flex"] -.-> G +Sp["Space"] -.-> G +Spp["Splitter"] -.-> G +Dv["Divider"] -.-> G +``` + +**Diagram sources** + +- [layout/**init**.py:28-31](file://backend/modelscope_studio/components/antd/layout/__init__.py#L28-L31) +- [grid/row/**init**.py:1-94](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L1-L94) +- [grid/col/**init**.py:1-114](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L1-L114) +- [flex/**init**.py:1-98](file://backend/modelscope_studio/components/antd/flex/__init__.py#L1-L98) +- [space/**init**.py:1-104](file://backend/modelscope_studio/components/antd/space/__init__.py#L1-L104) +- [splitter/**init**.py:1-97](file://backend/modelscope_studio/components/antd/splitter/__init__.py#L1-L97) +- [divider/**init**.py:1-95](file://backend/modelscope_studio/components/antd/divider/__init__.py#L1-L95) + +## Performance Considerations + +- Use lazy loading and deferred rendering appropriately: Splitter supports `lazy` to avoid unnecessary panel initialization +- Control the number of event bindings: Layout/Sider event callbacks should be enabled on demand to reduce unnecessary DOM updates +- Choose between grid and flex layout: Use Space for spacing between many inline elements, Flex for block-level layouts; avoid redundant wrapping +- Responsive breakpoints: Configure Grid's `xs`/`sm`/`md`/`lg`/`xl`/`xxl` based on actual device distribution; avoid excessive granularity causing computation overhead +- SSR optimization: Layout's `has_sider` can avoid flickering during server-side rendering + +## Troubleshooting Guide + +- Theme conflict hint: Sider's `theme` conflicts with Gradio preset attributes; use `theme_value` instead +- Events not working: Confirm event listeners are correctly bound (e.g., `click`, `collapse`, `breakpoint`) and the corresponding callbacks are enabled on the frontend side +- Grid overflow: When the sum of Col `span` values in a Row exceeds 24, they will wrap; check breakpoint configuration and layout logic +- Split panel anomalies: Ensure panel size units are consistent (px or percentage) and set reasonable `min`/`max` values + +**Section sources** + +- [layout/sider/**init**.py:101-104](file://backend/modelscope_studio/components/antd/layout/sider/__init__.py#L101-L104) + +## Conclusion + +This reference document covers the Python API for Antd layout components, clearly defining constructor parameters, methods, and typical usage for each component, while providing combination usage recommendations and performance optimization strategies. Through the collaboration of Layout, Grid, Flex, Space, Splitter, and Divider, a diverse range of layouts can be built from basic grids to complex interactive designs. + +## Appendix + +### Common Layout Combination Examples (Conceptual) + +- Responsive layout + - Use Layout + Sider with collapse/expand at different breakpoints; Sider supports `breakpoint` and `collapse` events + - Grid's `xs`/`sm`/`md`/`lg`/`xl`/`xxl` breakpoint configuration for multi-device adaptation +- Grid system + - Row provides `gutter`, `justify`, `align`, `wrap`; Col provides `span`, `offset`, `order`, `pull`/`push`, responsive breakpoints +- Flex layout + - Flex provides `orientation`/`vertical`, `wrap`, `justify`, `align`, `gap`, `flex`, etc.; suitable for flexible alignment and spacing control +- Spacing and separation + - Space for inline element spacing; `Space.Compact` for compact form arrangements; Divider for content separation + +### Breakpoints and Media Queries + +- Breakpoint constants: `xs` (<576px), `sm` (≥576px), `md` (≥768px), `lg` (≥992px), `xl` (≥1200px), `xxl` (≥1600px) +- Media query integration: Map to layout behavior at different screen sizes via Grid's `xs`/`sm`/`md`/`lg`/`xl`/`xxl` parameters + +### Nesting Rules and Best Practices + +- Layout must contain some sub-components from Header/Sider/Content/Footer, and sub-components must be placed inside Layout +- Grid's Col must be placed directly inside Row, and content elements placed inside Col +- Flex adds no extra wrapper, suitable for block-level layouts; Space adds a wrapper around each child element for inline alignment +- Splitter Panels are resized by dragging; it is recommended to set `min`/`max` and `collapsible` to improve usability diff --git a/.wiki/en/API Reference/Python API/Antd Components API/Navigation Components API.md b/.wiki/en/API Reference/Python API/Antd Components API/Navigation Components API.md new file mode 100644 index 00000000..ed52390f --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antd Components API/Navigation Components API.md @@ -0,0 +1,569 @@ +# Navigation Components API + + +**Files Referenced in This Document** +- [anchor/__init__.py](file://backend/modelscope_studio/components/antd/anchor/__init__.py) +- [anchor/item/__init__.py](file://backend/modelscope_studio/components/antd/anchor/item/__init__.py) +- [breadcrumb/__init__.py](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py) +- [breadcrumb/item/__init__.py](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py) +- [dropdown/__init__.py](file://backend/modelscope_studio/components/antd/dropdown/__init__.py) +- [dropdown/button/__init__.py](file://backend/modelscope_studio/components/antd/dropdown/button/__init__.py) +- [menu/__init__.py](file://backend/modelscope_studio/components/antd/menu/__init__.py) +- [menu/item/__init__.py](file://backend/modelscope_studio/components/antd/menu/item/__init__.py) +- [pagination/__init__.py](file://backend/modelscope_studio/components/antd/pagination/__init__.py) +- [steps/__init__.py](file://backend/modelscope_studio/components/antd/steps/__init__.py) +- [steps/item/__init__.py](file://backend/modelscope_studio/components/antd/steps/item/__init__.py) + + +## Update Summary + +**Changes** + +- Updated Menu component API documentation with new `popupRender` slot feature description +- Added detailed description of the `popup_render` parameter for the Menu component +- Compared the difference in `popupRender` functionality between Menu and Dropdown components + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference and usage guide for Ant Design navigation-related components, covering the following components: + +- Anchor +- Breadcrumb +- Dropdown +- Menu +- Pagination +- Steps + +Contents include: constructor parameters for component and sub-item classes, event listening, slots, state management key points, routing/frontend interaction patterns, accessibility and keyboard navigation recommendations, as well as performance optimization and best practices. + +## Project Structure + +Navigation components reside in the backend Python package, organized in a "component-level directory + sub-item directory" pattern for easy extension and maintenance. Each component class is responsible for rendering and event binding; sub-item classes carry specific item data structures. + +```mermaid +graph TB +subgraph "Antd Components" +A["anchor/__init__.py"] +B["breadcrumb/__init__.py"] +C["dropdown/__init__.py"] +D["menu/__init__.py"] +E["pagination/__init__.py"] +F["steps/__init__.py"] +end +subgraph "Sub-items" +A1["anchor/item/__init__.py"] +B1["breadcrumb/item/__init__.py"] +C1["dropdown/button/__init__.py"] +D1["menu/item/__init__.py"] +F1["steps/item/__init__.py"] +end +A --> A1 +B --> B1 +C --> C1 +D --> D1 +F --> F1 +``` + +**Section sources** + +- [anchor/**init**.py:1-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L1-L117) +- [breadcrumb/**init**.py:1-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L1-L73) +- [dropdown/**init**.py:1-119](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L1-L119) +- [menu/**init**.py:1-125](file://backend/modelscope_studio/components/antd/menu/__init__.py#L1-L125) +- [pagination/**init**.py:1-107](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L1-L107) +- [steps/**init**.py:1-95](file://backend/modelscope_studio/components/antd/steps/__init__.py#L1-L95) + +## Core Components + +This section provides an overview of the responsibilities, typical usage, and key parameters of each navigation component. + +- **Anchor** + - Responsibility: Provides anchor jumps within a single page; supports fixed mode and direction settings. + - Key parameters: `affix`, `bounds`, `get_container`, `offset_top`, `direction`, `replace`, `items`, etc. + - Events: `change`, `click`, `affix_change`. + - Slots: `items`. + - Use cases: Long document table of contents, section positioning. + +- **Breadcrumb** + - Responsibility: Displays the current page's position in the hierarchy. + - Key parameters: `item_render`, `params`, `items`, `separator`. + - Slots: `separator`, `itemRender`, `items`, `dropdownIcon`. + - Use cases: Page path navigation, hierarchical browsing. + +- **Dropdown** + - Responsibility: Pop-up menu triggered by click/hover. + - Key parameters: `arrow`, `auto_adjust_overflow`, `disabled`, `placement`, `trigger`, `menu`, `open`, etc. + - Events: `open_change`, `menu_click`, `menu_select`, `menu_deselect`, `menu_open_change`. + - Slots: `menu.expandIcon`, `menu.overflowedIndicator`, `menu.items`, `dropdownRender`, `popupRender`. + - Use cases: Action entry points, feature set expansion. + +- **Menu** + - Responsibility: Vertical/horizontal/inline navigation menu. + - Key parameters: `open_keys`, `selected_keys`, `mode`, `theme`/`theme_value`, `inline_indent`, `items`, `multiple`, `trigger_sub_menu_action`, `popup_render`, etc. + - Events: `click`, `deselect`, `open_change`, `select`. + - Slots: `expandIcon`, `overflowedIndicator`, `items`, `popupRender`. + - Use cases: Site main navigation, sidebar navigation. + +- **Pagination** + - Responsibility: Page display and navigation for large datasets. + - Key parameters: `current`, `default_current`, `page_size`, `default_page_size`, `total`, `pageSizeOptions`, `showQuickJumper`, `showSizeChanger`, `simple`, `size`, etc. + - Events: `change`, `show_size_change`. + - Slots: `showQuickJumper.goButton`, `itemRender`. + - Use cases: List/table pagination. + +- **Steps** + - Responsibility: Guides users through multi-step processes. + - Key parameters: `current`, `direction`, `label_placement`, `title_placement`, `percent`, `progress_dot`, `size`, `status`, `type`, `items`. + - Events: `change`. + - Slots: `progressDot`, `items`. + - Use cases: Wizards, multi-step form submissions. + +**Section sources** + +- [anchor/**init**.py:11-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L11-L117) +- [breadcrumb/**init**.py:9-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L9-L73) +- [dropdown/**init**.py:11-119](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L11-L119) +- [menu/**init**.py:12-125](file://backend/modelscope_studio/components/antd/menu/__init__.py#L12-L125) +- [pagination/**init**.py:10-107](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L10-L107) +- [steps/**init**.py:11-95](file://backend/modelscope_studio/components/antd/steps/__init__.py#L11-L95) + +## Architecture Overview + +Navigation components uniformly inherit from the layout component base class, and interact with the frontend through frontend directory mapping and event binding. Components support additional property passing, style/class name injection, visibility and render control, and other common capabilities. + +```mermaid +classDiagram +class ModelScopeLayoutComponent +class AntdAnchor { ++__init__(...) ++EVENTS ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess(...) ++postprocess(...) ++example_payload() ++example_value() +} +class AntdBreadcrumb { ++__init__(...) ++EVENTS ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess(...) ++postprocess(...) ++example_payload() ++example_value() +} +class AntdDropdown { ++__init__(...) ++EVENTS ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess(...) ++postprocess(...) ++example_payload() ++example_value() +} +class AntdMenu { ++__init__(...) ++EVENTS ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess(...) ++postprocess(...) ++example_payload() ++example_value() +} +class AntdPagination { ++__init__(...) ++EVENTS ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess(...) ++postprocess(...) ++example_payload() ++example_value() +} +class AntdSteps { ++__init__(...) ++EVENTS ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess(...) ++postprocess(...) ++example_payload() ++example_value() +} +AntdAnchor --> ModelScopeLayoutComponent +AntdBreadcrumb --> ModelScopeLayoutComponent +AntdDropdown --> ModelScopeLayoutComponent +AntdMenu --> ModelScopeLayoutComponent +AntdPagination --> ModelScopeLayoutComponent +AntdSteps --> ModelScopeLayoutComponent +``` + +**Diagram sources** + +- [anchor/**init**.py:11-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L11-L117) +- [breadcrumb/**init**.py:9-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L9-L73) +- [dropdown/**init**.py:11-119](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L11-L119) +- [menu/**init**.py:12-125](file://backend/modelscope_studio/components/antd/menu/__init__.py#L12-L125) +- [pagination/**init**.py:10-107](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L10-L107) +- [steps/**init**.py:11-95](file://backend/modelscope_studio/components/antd/steps/__init__.py#L11-L95) + +## Detailed Component Analysis + +### Anchor API + +- Class: `AntdAnchor` +- Sub-item class: `AntdAnchorItem` +- Events + - `change`: Monitors anchor link changes + - `click`: Handles click events + - `affix_change`: Fixed state change callback +- Slots + - `items`: Anchor item collection +- Key parameters + - `affix`: Whether to enable fixed mode + - `bounds`: Boundary distance of anchor area + - `get_container`: Scroll container selector + - `get_current_anchor`: Custom highlighted anchor + - `offset_top`: Top offset when calculating scroll position + - `show_ink_in_fixed`: Whether to show ink bar in fixed mode + - `target_offset`: Anchor scroll offset, defaults to `offsetTop` + - `items`: Item data, supports nested `children` + - `direction`: Vertical or horizontal direction + - `replace`: Replace browser history instead of adding +- Methods + - `preprocess(payload)`: Returns None + - `postprocess(value)`: Returns None + - `example_payload()`: Returns None + - `example_value()`: Returns None +- Usage examples (path reference) + - Page anchor navigation: [anchor/**init**.py:38-98](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L38-L98) + +**Section sources** + +- [anchor/**init**.py:11-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L11-L117) +- [anchor/item/**init**.py](file://backend/modelscope_studio/components/antd/anchor/item/__init__.py) + +### Breadcrumb API + +- Class: `AntdBreadcrumb` +- Sub-item class: `AntdBreadcrumbItem` +- Slots + - `separator`: Separator + - `itemRender`: Custom item rendering + - `items`: Item collection + - `dropdownIcon`: Dropdown icon +- Key parameters + - `item_render`: Custom item rendering function + - `params`: Rendering parameters + - `items`: Item array + - `separator`: Separator string +- Methods + - `preprocess(payload)`: Returns None + - `postprocess(value)`: Returns None + - `example_payload()`: Returns None + - `example_value()`: Returns None +- Usage examples (path reference) + - Breadcrumb navigation: [breadcrumb/**init**.py:20-54](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L20-L54) + +**Section sources** + +- [breadcrumb/**init**.py:9-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L9-L73) +- [breadcrumb/item/**init**.py](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py) + +### Dropdown API + +- Class: `AntdDropdown` +- Sub-item class: `AntdDropdownButton` +- Events + - `open_change`: Dropdown open/close state change + - `menu_click`: Menu item click + - `menu_select`: Menu item selected + - `menu_deselect`: Menu item deselected + - `menu_open_change`: Sub-menu open/close state change +- Slots + - `menu.expandIcon`: Menu expand icon + - `menu.overflowedIndicator`: Overflow indicator + - `menu.items`: Menu item collection + - `dropdownRender`: Custom dropdown rendering + - `popupRender`: Custom popup rendering +- Key parameters + - `arrow`: Whether to show arrow + - `auto_adjust_overflow`: Whether to auto-adjust overflow + - `auto_focus`: Whether to auto-focus + - `disabled`: Whether to disable + - `destroy_popup_on_hide`: Destroy popup when hidden + - `destroy_on_hidden`: Destroy after hidden + - `dropdown_render`: Dropdown rendering function + - `popup_render`: Popup rendering function + - `get_popup_container`: Popup mount container + - `menu`: Menu configuration object + - `overlay_class_name`: Overlay class name + - `overlay_style`: Overlay style + - `placement`: Popup placement + - `trigger`: Trigger mode (`click`/`hover`/`contextMenu`) + - `open`: Controlled open state + - `inner_elem_style`: Inner element style +- Methods + - `preprocess(payload)`: Returns None + - `postprocess(value)`: Returns None + - `example_payload()`: Returns None + - `example_value()`: Returns None +- Usage examples (path reference) + - Dropdown menu: [dropdown/**init**.py:40-100](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L40-L100) + +**Section sources** + +- [dropdown/**init**.py:11-119](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L11-L119) +- [dropdown/button/**init**.py](file://backend/modelscope_studio/components/antd/dropdown/button/__init__.py) + +### Menu API + +- Class: `AntdMenu` +- Sub-item class: `AntdMenuItem` +- Events + - `click`: Menu item click + - `deselect`: Menu item deselected + - `open_change`: Sub-menu open/close state change + - `select`: Menu item selected +- Slots + - `expandIcon`: Expand icon + - `overflowedIndicator`: Overflow indicator + - `items`: Menu item collection + - `popupRender`: Popup rendering +- Key parameters + - `open_keys`: Controlled open sub-menu keys + - `selected_keys`: Controlled selected menu keys + - `selectable`: Whether selectable + - `default_open_keys`: Default open sub-menu keys + - `default_selected_keys`: Default selected menu keys + - `expand_icon`: Expand icon + - `force_sub_menu_render`: Whether to force render sub-menus + - `inline_collapsed`: Inline collapse + - `inline_indent`: Inline indent pixels + - `items`: Menu item array + - `mode`: Mode (`vertical`/`horizontal`/`inline`) + - `multiple`: Whether multi-select + - `overflowed_indicator`: Overflow indicator + - `sub_menu_close_delay`: Sub-menu close delay + - `sub_menu_open_delay`: Sub-menu open delay + - `theme`/`theme_value`: Theme (light/dark); prefer `theme_value` + - `trigger_sub_menu_action`: Trigger sub-menu action (`click`/`hover`) + - `popup_render`: Popup rendering function +- Methods + - `preprocess(payload)`: Returns None + - `postprocess(value)`: Returns None + - `example_payload()`: Returns None + - `example_value()`: Returns None +- Usage examples (path reference) + - Navigation menu: [menu/**init**.py:36-103](file://backend/modelscope_studio/components/antd/menu/__init__.py#L36-L103) + +**Update** Added `popupRender` parameter for custom menu popup rendering + +**Section sources** + +- [menu/**init**.py:12-125](file://backend/modelscope_studio/components/antd/menu/__init__.py#L12-L125) +- [menu/item/**init**.py](file://backend/modelscope_studio/components/antd/menu/item/__init__.py) + +### Pagination API + +- Class: `AntdPagination` +- Events + - `change`: Page number or page size change + - `show_size_change`: Page size changed +- Slots + - `showQuickJumper.goButton`: Quick jump button + - `itemRender`: Custom page number rendering +- Key parameters + - `align`: Alignment (`start`/`center`/`end`) + - `current`: Current page + - `default_current`: Default current page + - `default_page_size`: Default page size + - `page_size`: Current page size + - `disabled`: Whether to disable + - `hide_on_single_page`: Hide when single page + - `item_render`: Page item rendering function + - `page_size_options`: Page size options + - `responsive`: Responsive layout + - `show_less_items`: Show fewer page numbers + - `show_quick_jumper`: Quick jump toggle or config + - `show_size_changer`: Page size changer toggle or config + - `show_title`: Whether to show title + - `show_total`: Total count rendering template + - `simple`: Simple mode toggle or config + - `size`: Size (`small`/`default`) + - `total`: Total item count +- Methods + - `preprocess(payload)`: Returns None + - `postprocess(value)`: Returns None + - `example_payload()`: Returns None + - `example_value()`: Returns None +- Usage examples (path reference) + - Pagination control: [pagination/**init**.py:26-88](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L26-L88) + +**Section sources** + +- [pagination/**init**.py:10-107](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L10-L107) + +### Steps API + +- Class: `AntdSteps` +- Sub-item class: `AntdStepsItem` +- Events + - `change`: Step change +- Slots + - `progressDot`: Progress dot rendering + - `items`: Step item collection +- Key parameters + - `current`: Current step index + - `direction`: Direction (`horizontal`/`vertical`) + - `initial`: Initial step + - `label_placement`: Label placement (`horizontal`/`vertical`) + - `title_placement`: Title placement + - `percent`: Completion percentage + - `progress_dot`: Whether to use dot-style progress + - `responsive`: Responsive + - `size`: Size (`small`/`default`) + - `status`: Status (`wait`/`process`/`finish`/`error`) + - `type`: Type (`default`/`navigation`/`inline`) + - `items`: Step item array +- Methods + - `preprocess(payload)`: Returns None + - `postprocess(value)`: Returns None + - `example_payload()`: Returns None + - `example_value()`: Returns None +- Usage examples (path reference) + - Steps bar: [steps/**init**.py:25-75](file://backend/modelscope_studio/components/antd/steps/__init__.py#L25-L75) + +**Section sources** + +- [steps/**init**.py:11-95](file://backend/modelscope_studio/components/antd/steps/__init__.py#L11-L95) +- [steps/item/**init**.py](file://backend/modelscope_studio/components/antd/steps/item/__init__.py) + +## Dependency Analysis + +- Common dependencies + - Base class: `ModelScopeLayoutComponent` (unified lifecycle and rendering) + - Event system: `gradio.events.EventListener` (event binding) + - Frontend directory resolution: `resolve_frontend_dir` (maps frontend directories by component name) +- Inter-component coupling + - Components are relatively independent; each carries item data via its own sub-item class, reducing coupling + - Unified event and slot mechanism for easy extension and reuse +- External dependencies + - Works with frontend Svelte components through event binding and props passing for interaction + +```mermaid +graph LR +Base["ModelScopeLayoutComponent"] --> Anchor["AntdAnchor"] +Base --> Breadcrumb["AntdBreadcrumb"] +Base --> Dropdown["AntdDropdown"] +Base --> Menu["AntdMenu"] +Base --> Pagination["AntdPagination"] +Base --> Steps["AntdSteps"] +Events["EventListener"] --> Anchor +Events --> Breadcrumb +Events --> Dropdown +Events --> Menu +Events --> Pagination +Events --> Steps +Resolve["resolve_frontend_dir"] --> Anchor +Resolve --> Breadcrumb +Resolve --> Dropdown +Resolve --> Menu +Resolve --> Pagination +Resolve --> Steps +``` + +**Diagram sources** + +- [anchor/**init**.py:7-99](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L7-L99) +- [breadcrumb/**init**.py:5-56](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L5-L56) +- [dropdown/**init**.py:5-102](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L5-L102) +- [menu/**init**.py:6-105](file://backend/modelscope_studio/components/antd/menu/__init__.py#L6-L105) +- [pagination/**init**.py:5-90](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L5-L90) +- [steps/**init**.py:5-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L5-L77) + +## Performance Considerations + +- Enable event binding on demand: Enable frontend binding only when the corresponding event listener is registered, avoiding unnecessary overhead. +- Controlled state: Use controlled properties like `open_keys`, `selected_keys`, `current` to reduce repeated renders. +- Slots and custom rendering: Use `itemRender`/`dropdownRender` and other slots appropriately; avoid overly complex logic causing re-renders. +- List rendering: Pagination and Menu `items` should be as flat as possible to reduce rendering costs from deep nesting. +- Fixed and scrolling: Anchor's `affix` and `bounds` parameters should be optimized in conjunction with page scroll performance to avoid frequent reflows. +- `popupRender` usage: Menu component's `popupRender` functionality should be used carefully; avoid heavy computations in rendering functions to avoid affecting menu performance. + +## Troubleshooting Guide + +- Events not triggering + - Check if event listeners are correctly registered (e.g., `change`, `click`, `open_change`, etc.) + - Confirm the frontend has the corresponding event binding enabled (triggered by component's internal `_internal` property update) +- Styles/class names not taking effect + - Confirm that `class_names`/`styles`/`root_class_name` are correctly passed + - Check for conflicts with overlay style `overlay_style`/`overlay_class_name` +- Dropdown not showing + - Check `disabled`, `destroy_on_hidden`, `get_popup_container`, and other configurations + - Confirm trigger mode `trigger` and `placement` are appropriate + - Verify `popupRender` slot is correctly configured +- Pagination not working + - Check `total`, `page_size`, `current`, and other parameters for consistency + - Confirm event callbacks update controlled state +- Steps state anomaly + - Check the `current`, `status`, `type`, `direction` parameter combination + - Confirm `items` structure matches the index +- Menu component `popupRender` issues + - Confirm the `popupRender` function or slot is correctly passed to the frontend component + - Check if the return value format of `popupRender` meets Ant Design requirements + - Verify `popupRender` does not cause menu rendering performance issues + +**Section sources** + +- [anchor/**init**.py:20-33](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L20-L33) +- [dropdown/**init**.py:16-32](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L16-L32) +- [menu/**init**.py:18-31](file://backend/modelscope_studio/components/antd/menu/__init__.py#L18-L31) +- [pagination/**init**.py:14-21](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L14-L21) +- [steps/**init**.py:16-20](file://backend/modelscope_studio/components/antd/steps/__init__.py#L16-L20) + +## Conclusion + +This guide systematically covers navigation component APIs, events, slots, and usage points, providing practical recommendations for frontend interaction, state management, accessibility, and performance optimization. It is recommended to choose the appropriate component and parameter combination for the business scenario in real projects to ensure a good user experience and development efficiency. + +**Update** The new `popupRender` slot feature added to the Menu component provides developers with more flexible menu popup customization capabilities; however, performance impact and compatibility requirements must be considered when using it. + +## Appendix + +- Accessibility and keyboard navigation recommendations + - Provide a clear focus order and keyboard operations for interactive elements (e.g., Enter/Space to trigger, Esc to close) + - Provide ARIA attributes for menus and dropdowns (role, aria-expanded, aria-haspopup, etc.) + - Provide clear semantic labels and status hints for pagination and steps +- Routing integration + - Anchor and Steps can be linked with frontend routing, updating current state via event callbacks + - Breadcrumb can dynamically generate items based on the routing path + - Menu component's `popupRender` can be used to implement custom routing navigation popups +- Best practices + - Structure `items` data and avoid heavy computations in rendering functions + - Use controlled properties appropriately to avoid state desynchronization + - Adapt responsive layouts and touch interactions for mobile + - When using `popupRender`, ensure the returned React component structure conforms to Ant Design specifications + - Avoid async operations in `popupRender` to prevent affecting menu response performance diff --git a/.wiki/en/API Reference/Python API/Antd Components API/Other Components API.md b/.wiki/en/API Reference/Python API/Antd Components API/Other Components API.md new file mode 100644 index 00000000..44723699 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antd Components API/Other Components API.md @@ -0,0 +1,422 @@ +# Other Components API + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/config_provider/__init__.py](file://backend/modelscope_studio/components/antd/config_provider/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts](file://frontend/antd/config-provider/locales.ts) +- [frontend/antd/config-provider/Index.svelte](file://frontend/antd/config-provider/Index.svelte) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [docs/demos/example.py](file://docs/demos/example.py) +- [docs/components/antd/config_provider/README.md](file://docs/components/antd/config_provider/README.md) +- [frontend/antd/config-provider/package.json](file://frontend/antd/config-provider/package.json) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for "Other Components" in Ant Design Studio, focusing on the complete API specification and usage instructions for ConfigProvider (global configuration provider). Content covers: + +- Constructor parameters, property definitions, method signatures and return types +- Standard global configuration usage: theme customization, language settings, component defaults +- Scope management, configuration inheritance, and dynamic update mechanisms +- Internationalization configuration, theme switching, and component behavior customization +- Best practices and performance optimization recommendations + +## Project Structure + +ConfigProvider is implemented as a Python class in the backend and wrapped in Svelte on the frontend, interfacing with Ant Design's ConfigProvider while supporting multiple languages through the localization module. + +```mermaid +graph TB +subgraph "Python Backend" +PY_INIT["backend/modelscope_studio/components/antd/__init__.py"] +PY_CP["backend/modelscope_studio/components/antd/config_provider/__init__.py"] +PY_DEV["backend/modelscope_studio/utils/dev/component.py"] +PY_RESOLVE["backend/modelscope_studio/utils/dev/resolve_frontend_dir.py"] +end +subgraph "Frontend" +FE_INDEX["frontend/antd/config-provider/Index.svelte"] +FE_TSX["frontend/antd/config-provider/config-provider.tsx"] +FE_LOCALES["frontend/antd/config-provider/locales.ts"] +FE_PKG["frontend/antd/config-provider/package.json"] +end +PY_INIT --> PY_CP +PY_CP --> PY_RESOLVE +PY_CP --> PY_DEV +PY_CP --> FE_INDEX +FE_INDEX --> FE_TSX +FE_TSX --> FE_LOCALES +FE_INDEX --> FE_PKG +``` + +**Chart sources** + +- [backend/modelscope_studio/components/antd/**init**.py:32](file://backend/modelscope_studio/components/antd/__init__.py#L32) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:22](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L22) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4) +- [frontend/antd/config-provider/Index.svelte:11](file://frontend/antd/config-provider/Index.svelte#L11) +- [frontend/antd/config-provider/config-provider.tsx:51](file://frontend/antd/config-provider/config-provider.tsx#L51) +- [frontend/antd/config-provider/locales.ts:7](file://frontend/antd/config-provider/locales.ts#L7) +- [frontend/antd/config-provider/package.json:1](file://frontend/antd/config-provider/package.json#L1) + +**Section sources** + +- [backend/modelscope_studio/components/antd/**init**.py:32](file://backend/modelscope_studio/components/antd/__init__.py#L32) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:22](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L22) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4) +- [frontend/antd/config-provider/Index.svelte:11](file://frontend/antd/config-provider/Index.svelte#L11) +- [frontend/antd/config-provider/config-provider.tsx:51](file://frontend/antd/config-provider/config-provider.tsx#L51) +- [frontend/antd/config-provider/locales.ts:7](file://frontend/antd/config-provider/locales.ts#L7) +- [frontend/antd/config-provider/package.json:1](file://frontend/antd/config-provider/package.json#L1) + +## Core Components + +- Component name: AntdConfigProvider +- Module: backend.modelscope_studio.components.antd.config_provider +- Base class: ModelScopeLayoutComponent +- Frontend mapping: frontend/antd/config-provider/Index.svelte → frontend/antd/config-provider/config-provider.tsx +- Purpose: Provides unified global configuration (theme, language, size, prefix, popup container, etc.) to all Ant Design components within the application, supporting slot injection and dynamic updates. + +Key points: + +- Supported slots: renderEmpty +- Events: none +- Frontend directory resolution: points to frontend component directory via resolve_frontend_dir("config-provider") +- Skip API export: skip_api returns True to avoid exposing this component in certain automated exports + +**Section sources** + +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:22](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L22) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:28](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L28) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:95](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L95) +- [backend/modelscope_studio/utils/dev/component.py:20](file://backend/modelscope_studio/utils/dev/component.py#L20) + +## Architecture Overview + +The ConfigProvider call chain is as follows: + +```mermaid +sequenceDiagram +participant App as "Application Blocks" +participant CP_Py as "AntdConfigProvider (Python)" +participant CP_Index as "Index.svelte" +participant CP_TSX as "config-provider.tsx" +participant AD as "Ant Design ConfigProvider" +App->>CP_Py : Create and pass configuration parameters +CP_Py->>CP_Index : Resolve frontend directory and render +CP_Index->>CP_TSX : Pass props and slots +CP_TSX->>AD : Inject theme, language, container callback, etc. +AD-->>CP_TSX : Provide context +CP_TSX-->>CP_Index : Render sub-tree +CP_Index-->>App : Child components inherit global configuration +``` + +**Chart sources** + +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:95](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L95) +- [frontend/antd/config-provider/Index.svelte:11](file://frontend/antd/config-provider/Index.svelte#L11) +- [frontend/antd/config-provider/config-provider.tsx:108](file://frontend/antd/config-provider/config-provider.tsx#L108) + +## Detailed Component Analysis + +### Constructor and Property Definitions + +- Class name: AntdConfigProvider +- Inherits: ModelScopeLayoutComponent +- Key properties (partial): + - component_disabled: optional boolean, controls component disabled state + - component_size: optional string, values small/middle/large or None + - csp: optional dict, for CSP configuration + - direction: optional string, values ltr/rtl or None + - get_popup_container: optional string, specifies the popup mount container + - get_target_container: optional string, specifies the target container + - icon_prefix_cls: optional string, icon prefix class name + - locale: optional string, value is a predefined LocaleType + - popup_match_select_width: optional boolean or number, affects popup width strategy + - popup_overflow: optional string, values viewport/scroll + - prefix_cls: optional string, component prefix class name + - render_empty: optional string, for empty state rendering + - theme: optional dict (deprecated), warning prompts to use theme_config + - theme_config: optional dict, theme configuration (recommended) + - variant: optional string, values outlined/filled/borderless + - virtual: optional boolean + - warning: optional dict, warning configuration + - Element-level styles and class names: class_names, styles + - Layout and visibility: visible, elem_id, elem_classes, elem_style, render, as_item + - Extra properties: additional_props + - Other common properties: \_internal (internally reserved) + +Note: + +- Relationship between theme and theme_config: passing theme will trigger a warning; use theme_config instead +- Slots: only renderEmpty is supported + +Method signatures and return types: + +- preprocess(payload: None) -> None +- postprocess(value: None) -> None +- example_payload() -> Any +- example_value() -> Any + +**Section sources** + +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:31](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L31) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:42](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L42) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:86](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L86) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:101](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L101) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:104](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L104) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:108](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L108) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:111](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L111) + +### Frontend Implementation Key Points + +- Types and imports: based on Ant Design's ConfigProvider types, extended with themeMode and theme.algorithm fields +- Theme algorithm: automatically selects dark/compact algorithm based on themeMode, can be merged with external theme.algorithm +- Language settings: locale is inferred from browser environment by default, with en_US as fallback; loads corresponding language packs and dayjs language asynchronously on demand +- Container callbacks: getPopupContainer, getTargetContainer, renderEmpty are wrapped via useFunction to ensure reactive updates +- Slot handling: injects dot-separated paths from slots into corresponding prop positions; renderEmpty supports ReactSlot + +```mermaid +flowchart TD +Start(["Enter Component"]) --> LocaleCheck["Check if localeProp exists"] +LocaleCheck --> HasLocale{"Exists?"} +HasLocale --> |Yes| LoadLocale["Load Antd locale and dayjs locale by locale"] +HasLocale --> |No| UseDefault["Use en_US and default dayjs locale"] +LoadLocale --> ApplyLocale["Set antd locale and dayjs locale"] +UseDefault --> ApplyLocale +ApplyLocale --> ThemeAlg["Merge themeMode and theme.algorithm"] +ThemeAlg --> Render["Render with injected props/slots"] +Render --> End(["Done"]) +``` + +**Chart sources** + +- [frontend/antd/config-provider/config-provider.tsx:96](file://frontend/antd/config-provider/config-provider.tsx#L96) +- [frontend/antd/config-provider/config-provider.tsx:127](file://frontend/antd/config-provider/config-provider.tsx#L127) +- [frontend/antd/config-provider/config-provider.tsx:110](file://frontend/antd/config-provider/config-provider.tsx#L110) + +**Section sources** + +- [frontend/antd/config-provider/config-provider.tsx:51](file://frontend/antd/config-provider/config-provider.tsx#L51) +- [frontend/antd/config-provider/config-provider.tsx:77](file://frontend/antd/config-provider/config-provider.tsx#L77) +- [frontend/antd/config-provider/config-provider.tsx:96](file://frontend/antd/config-provider/config-provider.tsx#L96) +- [frontend/antd/config-provider/config-provider.tsx:127](file://frontend/antd/config-provider/config-provider.tsx#L127) +- [frontend/antd/config-provider/config-provider.tsx:110](file://frontend/antd/config-provider/config-provider.tsx#L110) + +### Internationalization Configuration + +- Language enumeration: LocaleType is a string literal union type covering multiple languages and regions +- Language mapping: lang2RegionMap maps short language codes to specific region codes +- Language loading: locales maps each region code to an async loader function returning antd locale and dayjs locale +- Default language: getDefaultLocale sets dayjs language to English + +Usage recommendations: + +- Use enum values from LocaleType for the locale parameter +- If locale is not provided, it will be auto-inferred from the browser environment with fallback to en_US + +**Section sources** + +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:8](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L8) +- [frontend/antd/config-provider/locales.ts:12](file://frontend/antd/config-provider/locales.ts#L12) +- [frontend/antd/config-provider/locales.ts:89](file://frontend/antd/config-provider/locales.ts#L89) +- [frontend/antd/config-provider/locales.ts:7](file://frontend/antd/config-provider/locales.ts#L7) + +### Theme and Variant Configuration + +- Theme entry: theme_config (recommended) or deprecated theme +- Theme algorithm: themeMode controls dark/compact, can be merged with external algorithm +- Component variant: variant supports outlined/filled/borderless + +Best practices: + +- Use theme_config for theme customization to avoid conflicts with Gradio presets +- Control themeMode via toggle variables to achieve dynamic switching between light/dark/compact themes + +**Section sources** + +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:86](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L86) +- [frontend/antd/config-provider/config-provider.tsx:88](file://frontend/antd/config-provider/config-provider.tsx#L88) +- [frontend/antd/config-provider/config-provider.tsx:127](file://frontend/antd/config-provider/config-provider.tsx#L127) + +### Scope Management, Inheritance, and Dynamic Updates + +- Scope: ConfigProvider as a layout component means all components in its subtree inherit the global configuration +- Inheritance: child components don't need to repeatedly pass the same configuration, reading directly from context +- Dynamic updates: output to ConfigProvider via Gradio's update to change theme_config, locale, direction, etc. in real time + +Reference examples: + +- Documentation examples demonstrate how to dynamically update ConfigProvider's locale, direction, and theme_config during interactions + +**Section sources** + +- [docs/demos/example.py:6](file://docs/demos/example.py#L6) +- [docs/components/antd/config_provider/README.md:7](file://docs/components/antd/config_provider/README.md#L7) + +### API Definitions and Type Summary + +- Constructor parameters (selected) + - component_disabled: bool | None + - component_size: "small"|"middle"|"large" | None + - csp: dict | None + - direction: "ltr"|"rtl" | None + - get_popup_container: str | None + - get_target_container: str | None + - icon_prefix_cls: str | None + - locale: LocaleType | None + - popup_match_select_width: bool | int | float | None + - popup_overflow: "viewport"|"scroll" | None + - prefix_cls: str | None + - render_empty: str | None + - theme: dict | None + - theme_config: dict | None + - variant: "outlined"|"filled"|"borderless" | None + - virtual: bool | None + - warning: dict | None + - class_names: dict | str | None + - styles: dict | str | None + - as_item: str | None + - \_internal: None + - visible: bool + - elem_id: str | None + - elem_classes: list[str] | str | None + - elem_style: dict | None + - render: bool + - additional_props: dict | None + - Other common keyword arguments + +- Methods + - preprocess(payload: None) -> None + - postprocess(value: None) -> None + - example_payload() -> Any + - example_value() -> Any + +- Properties + - skip_api: True + - FRONTEND_DIR: resolved by resolve_frontend_dir("config-provider") + +**Section sources** + +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:31](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L31) +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:95](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L95) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4) + +## Dependency Analysis + +- Python layer + - Inherits from ModelScopeLayoutComponent, enabling layout context capabilities + - Resolves frontend component directory via resolve_frontend_dir + - Exported as ConfigProvider in antd/**init**.py + +- Frontend layer + - Index.svelte converts Python-passed props and slots into React Props + - config-provider.tsx interfaces with Ant Design ConfigProvider, injecting themes, language, container callbacks, and slots + - locales.ts provides language mapping and async loading + +```mermaid +graph LR +PY["AntdConfigProvider"] --> RES["resolve_frontend_dir"] +PY --> DEV["ModelScopeLayoutComponent"] +PY --> EXP["antd/__init__.py export"] +EXP --> IDX["Index.svelte"] +IDX --> TSX["config-provider.tsx"] +TSX --> LOCALES["locales.ts"] +``` + +**Chart sources** + +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4) +- [backend/modelscope_studio/utils/dev/component.py:11](file://backend/modelscope_studio/utils/dev/component.py#L11) +- [backend/modelscope_studio/components/antd/**init**.py:32](file://backend/modelscope_studio/components/antd/__init__.py#L32) +- [frontend/antd/config-provider/Index.svelte:11](file://frontend/antd/config-provider/Index.svelte#L11) +- [frontend/antd/config-provider/config-provider.tsx:51](file://frontend/antd/config-provider/config-provider.tsx#L51) +- [frontend/antd/config-provider/locales.ts:7](file://frontend/antd/config-provider/locales.ts#L7) + +**Section sources** + +- [backend/modelscope_studio/components/antd/**init**.py:32](file://backend/modelscope_studio/components/antd/__init__.py#L32) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4) +- [frontend/antd/config-provider/Index.svelte:11](file://frontend/antd/config-provider/Index.svelte#L11) +- [frontend/antd/config-provider/config-provider.tsx:51](file://frontend/antd/config-provider/config-provider.tsx#L51) +- [frontend/antd/config-provider/locales.ts:7](file://frontend/antd/config-provider/locales.ts#L7) + +## Performance Considerations + +- Theme switching + - Use the themeMode and theme.algorithm merge strategy to avoid frequent rebuilding of theme objects + - Only trigger language pack loading when locale changes, reducing unnecessary async overhead +- Popup container and target container + - Wrap callbacks via useFunction to reduce re-renders caused by function reference changes +- Slot rendering + - renderEmpty is rendered via ReactSlot to avoid additional DOM operations +- Prefix and styles + - Use prefix_cls and class_names/styles to control style scope, avoiding global pollution + +[This section provides general guidance and does not directly analyze specific files] + +## Troubleshooting Guide + +- Theme conflicts + - Passing theme will trigger a warning; use theme_config instead +- Language not taking effect + - Confirm that locale is a valid value from LocaleType; if empty, it falls back to en_US + - Check that the locales mapping contains the corresponding region code +- Popup position issues + - Check that the container returned by get_popup_container/get_target_container exists and is correct +- Slots not displaying + - Confirm that the slot name and path are consistent (e.g., renderEmpty), and that it is correctly injected on the frontend + +**Section sources** + +- [backend/modelscope_studio/components/antd/config_provider/**init**.py:86](file://backend/modelscope_studio/components/antd/config_provider/__init__.py#L86) +- [frontend/antd/config-provider/config-provider.tsx:96](file://frontend/antd/config-provider/config-provider.tsx#L96) +- [frontend/antd/config-provider/config-provider.tsx:117](file://frontend/antd/config-provider/config-provider.tsx#L117) + +## Conclusion + +AntdConfigProvider provides global configuration capabilities for Ant Design components, covering key dimensions such as theme, language, size, container, and empty state rendering. Through unified encapsulation on the Python side and efficient frontend integration, developers can conveniently implement configuration inheritance and dynamic updates within scope. It is recommended to use theme_config for theme customization and combine locale with direction for internationalization and layout adaptation. + +[This section is a summary and does not directly analyze specific files] + +## Appendix + +### Usage Examples and References + +- Basic usage example (documentation demo) + - Example demonstrates nesting ConfigProvider within Application and AutoLoading scopes, with DatePicker used inside + - Reference path: docs/demos/example.py + +- Documentation page + - README contains a basic example placeholder; actual demo is in demos/basic.py + +**Section sources** + +- [docs/demos/example.py:6](file://docs/demos/example.py#L6) +- [docs/components/antd/config_provider/README.md:7](file://docs/components/antd/config_provider/README.md#L7) + +### Component Registration and Exports + +- Exported as ConfigProvider alias in antd/**init**.py +- Imported and exported as AntdConfigProvider in components.py + +**Section sources** + +- [backend/modelscope_studio/components/antd/**init**.py:32](file://backend/modelscope_studio/components/antd/__init__.py#L32) +- [backend/modelscope_studio/components/antd/components.py:31](file://backend/modelscope_studio/components/antd/components.py#L31) diff --git a/.wiki/en/API Reference/Python API/Antdx Components API/Antdx Components API.md b/.wiki/en/API Reference/Python API/Antdx Components API/Antdx Components API.md new file mode 100644 index 00000000..1901618e --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antdx Components API/Antdx Components API.md @@ -0,0 +1,443 @@ +# Antdx Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/antdx/bubble/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/__init__.py) +- [backend/modelscope_studio/components/antdx/conversations/__init__.py](file://backend/modelscope_studio/components/antdx/conversations/__init__.py) +- [backend/modelscope_studio/components/antdx/prompts/__init__.py](file://backend/modelscope_studio/components/antdx/prompts/__init__.py) +- [backend/modelscope_studio/components/antdx/attachments/__init__.py](file://backend/modelscope_studio/components/antdx/attachments/__init__.py) +- [backend/modelscope_studio/components/antdx/sender/__init__.py](file://backend/modelscope_studio/components/antdx/sender/__init__.py) +- [backend/modelscope_studio/components/antdx/actions/__init__.py](file://backend/modelscope_studio/components/antdx/actions/__init__.py) +- [backend/modelscope_studio/components/antdx/file_card/__init__.py](file://backend/modelscope_studio/components/antdx/file_card/__init__.py) +- [backend/modelscope_studio/components/antdx/folder/__init__.py](file://backend/modelscope_studio/components/antdx/folder/__init__.py) +- [backend/modelscope_studio/components/antdx/code_highlighter/__init__.py](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py) +- [backend/modelscope_studio/components/antdx/notification/__init__.py](file://backend/modelscope_studio/components/antdx/notification/__init__.py) +- [backend/modelscope_studio/components/antdx/sources/__init__.py](file://backend/modelscope_studio/components/antdx/sources/__init__.py) +- [backend/modelscope_studio/components/antdx/suggestion/__init__.py](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py) +- [backend/modelscope_studio/components/antdx/think/__init__.py](file://backend/modelscope_studio/components/antdx/think/__init__.py) +- [backend/modelscope_studio/components/antdx/thought_chain/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for the Antdx component library, focusing on ML and AI application-related components under `modelscope_studio.components.antdx.*`. It covers the complete import paths, constructor parameters, property definitions, method signatures, and return type descriptions for 20+ component classes, and provides standard instantiation examples and best practices for typical scenarios such as conversational systems, file handling, and user input. It also documents the event handling mechanisms, lifecycle management, state synchronization strategies, and performance optimization recommendations. + +## Project Structure + +Antdx components reside in the backend Python package `modelscope_studio/components/antdx/`, organized by functional domain: each subdirectory corresponds to a component or component family (e.g., bubble, conversations, sender), and exports are unified through `__init__.py`. `components.py` and `__init__.py` provide consistent aggregated export entry points for direct import from `modelscope_studio.components.antdx.*`. + +```mermaid +graph TB +A["Python Package
modelscope_studio.components.antdx"] --> B["actions/*"] +A --> C["attachments/*"] +A --> D["bubble/*"] +A --> E["conversations/*"] +A --> F["file_card/*"] +A --> G["folder/*"] +A --> H["prompts/*"] +A --> I["sender/*"] +A --> J["sources/*"] +A --> K["suggestion/*"] +A --> L["think/*"] +A --> M["thought_chain/*"] +A --> N["notification/*"] +A --> O["code_highlighter/*"] +A --> P["x_provider/*"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +Section Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Core Components + +The following lists all ML and AI scenario-related component classes in `modelscope_studio.components.antdx.*` with their import paths and usage overview: + +- Layout & Display + - Bubble: For message/text display and interaction, supports editing, typing animation, variants, shapes, etc. + - Conversations: For multi-conversation management and menu interactions. + - Prompts: For displaying a set of clickable prompt items. + - Suggestions: For input suggestions and selection. + - Think: For displaying a "thinking" state and expand control. + - ThoughtChain: For displaying reasoning processes in tree/chain form. + - CodeHighlighter: For code block rendering and theme control. + - Notification: For Web Notification integration and event binding. + - Sources: For displaying source entries and expand control. + - Welcome: For landing page or welcome message display (present in exports). + - XProvider: For global context injection (present in exports). + +- Data & Input + - Attachments: For file upload, drag-and-drop, preview, download, and removal. + - Sender: For user input, keyboard shortcuts, voice, paste, and submit events. + - FileCard: For card-style display and operations on individual files. + - Folder: For tree-style directory browsing and file/folder selection. + - Actions: For a group of clickable action items and dropdown menus. + +- Pro Extensions (Pro module) + - Chatbot: For conversational flows and message stream management (present in exports). + - MultimodalInput: For multimodal input including text, images, audio, and video (present in exports). + - MonacoEditor: For code editing and highlighting (present in exports). + - WebSandbox: For secure sandbox execution (present in exports). + +Section Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Architecture Overview + +Antdx components are wrapped through a unified base class, inheriting from Gradio's component system, supporting event listeners, slots, style and class name injection, and frontend resource directory resolution. Most components are layout-type components (`skip_api=True`) that do not directly expose API schemas; a few data-type components (such as Attachments and Sender) implement `preprocess/postprocess` and expose API specifications. + +```mermaid +classDiagram +class ModelScopeLayoutComponent +class ModelScopeDataLayoutComponent +class AntdXBubble +class AntdXConversations +class AntdXPrompts +class AntdXAttachments +class AntdXSender +class AntdXActions +class AntdXFileCard +class AntdXFolder +class AntdXCodeHighlighter +class AntdXNotification +class AntdXSources +class AntdXSuggestion +class AntdXThink +class AntdXThoughtChain +AntdXBubble --|> ModelScopeLayoutComponent +AntdXConversations --|> ModelScopeLayoutComponent +AntdXPrompts --|> ModelScopeLayoutComponent +AntdXFileCard --|> ModelScopeLayoutComponent +AntdXFolder --|> ModelScopeLayoutComponent +AntdXCodeHighlighter --|> ModelScopeLayoutComponent +AntdXNotification --|> ModelScopeLayoutComponent +AntdXSources --|> ModelScopeLayoutComponent +AntdXSuggestion --|> ModelScopeLayoutComponent +AntdXThink --|> ModelScopeLayoutComponent +AntdXThoughtChain --|> ModelScopeLayoutComponent +AntdXAttachments --|> ModelScopeDataLayoutComponent +AntdXSender --|> ModelScopeDataLayoutComponent +AntdXActions --|> ModelScopeLayoutComponent +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/bubble/**init**.py:13-135](file://backend/modelscope_studio/components/antdx/bubble/__init__.py#L13-L135) +- [backend/modelscope_studio/components/antdx/conversations/**init**.py:11-109](file://backend/modelscope_studio/components/antdx/conversations/__init__.py#L11-L109) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) +- [backend/modelscope_studio/components/antdx/attachments/**init**.py:22-227](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L22-L227) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:14-149](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L14-L149) +- [backend/modelscope_studio/components/antdx/actions/**init**.py:15-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L112) +- [backend/modelscope_studio/components/antdx/file_card/**init**.py:11-112](file://backend/modelscope_studio/components/antdx/file_card/__init__.py#L11-L112) +- [backend/modelscope_studio/components/antdx/folder/**init**.py:12-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L12-L114) +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:6-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L6-L71) +- [backend/modelscope_studio/components/antdx/notification/**init**.py:10-97](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L10-L97) +- [backend/modelscope_studio/components/antdx/sources/**init**.py:11-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L11-L92) +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) + +## Detailed Component Analysis + +### Bubble + +- Import Path: `modelscope_studio.components.antdx.Bubble` +- Purpose: Message/text display, supports editing, typing animation, variants, shapes, etc. +- Key Parameters (selected): content, avatar, footer, header, loading, placement, editable, shape, typing, streaming, variant, footer_placement, loading_render, content_render, root_class_name, class_names, styles, additional_props, visibility and style attributes. +- Events: typing, typing_complete, edit_confirm, edit_cancel. +- Slots: avatar, editable.okText, editable.cancelText, content, footer, header, extra, loadingRender, contentRender. +- Lifecycle & API: skip*api=True, does not expose API; preprocess/postprocess/example*\* are empty implementations. + +Section Sources + +- [backend/modelscope_studio/components/antdx/bubble/**init**.py:13-135](file://backend/modelscope_studio/components/antdx/bubble/__init__.py#L13-L135) + +### Conversations + +- Import Path: `modelscope_studio.components.antdx.Conversations` +- Sub-components: Item +- Key Parameters: active_key, default_active_key, items, menu, groupable, shortcut_keys, creation, styles, class_names, root_class_name, additional_props. +- Events: active_change, menu_click, menu_deselect, menu_open_change, menu_select, groupable_expand, creation_click. +- Slots: menu.expandIcon, menu.overflowedIndicator, menu.trigger, groupable.label, items, creation.icon, creation.label. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/conversations/**init**.py:11-109](file://backend/modelscope_studio/components/antdx/conversations/__init__.py#L11-L109) + +### Prompts + +- Import Path: `modelscope_studio.components.antdx.Prompts` +- Sub-components: Item +- Key Parameters: items, prefix_cls, title, vertical, fade_in, fade_in_left, wrap, styles, class_names, root_class_name, additional_props. +- Events: item_click. +- Slots: title, items. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) + +### Attachments + +- Import Path: `modelscope_studio.components.antdx.Attachments` +- Data Model: ListFiles +- Key Parameters: image_props, accept, action, before_upload, custom_request, data, default_file_list, directory, disabled, items, get_drop_container, overflow, placeholder, headers, icon_render, is_image_url, item_render, list_type, max_count, method, multiple, form_name, open_file_dialog_on_click, preview_file, progress, show_upload_list, with_credentials, class_names, root_style, styles, root_class_name, visibility and polling attributes. +- Events: change, drop, download, preview, remove. +- Lifecycle & API: skip_api=False; preprocess converts payload to file path list; postprocess converts file path list to ListFiles; api_info returns ListFiles JSON Schema. +- Typical Usage: As an input component receiving file lists, as an output component returning file metadata. + +Section Sources + +- [backend/modelscope_studio/components/antdx/attachments/**init**.py:22-227](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L22-L227) + +### Sender + +- Import Path: `modelscope_studio.components.antdx.Sender` +- Sub-components: Header, Switch +- Key Parameters: value, allow_speech, class_names, components, default_value, disabled, auto_size, loading, suffix, footer, header, prefix, read_only, styles, submit_type, placeholder, slot_config, skill, root_class_name, additional_props. +- Events: change, submit, cancel, allow_speech_recording_change, key_down, key_press, focus, blur, paste, paste_file, skill_closable_close. +- Slots: suffix, header, prefix, footer, skill.title, skill.toolTip.title, skill.closable.closeIcon. +- Lifecycle & API: skip*api=False; preprocess/postprocess return string; api_info returns string type description; example*\* returns None. + +Section Sources + +- [backend/modelscope_studio/components/antdx/sender/**init**.py:14-149](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L14-L149) + +### Actions + +- Import Path: `modelscope_studio.components.antdx.Actions` +- Sub-components: ActionItem, Item, Feedback, Copy, Audio +- Key Parameters: additional_props, items, variant, dropdown_props, fade_in, fade_in_left, class_names, styles. +- Events: click, dropdown_open_change, dropdown_menu_click, dropdown_menu_deselect, dropdown_menu_open_change, dropdown_menu_select. +- Slots: items, dropdownProps.dropdownRender, dropdownProps.popupRender, dropdownProps.menu.expandIcon, dropdownProps.menu.overflowedIndicator, dropdownProps.menu.items. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/**init**.py:15-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L112) + +### FileCard + +- Import Path: `modelscope_studio.components.antdx.FileCard` +- Sub-components: List +- Key Parameters: image_props, filename, byte, size, description, loading, type, src, mask, icon, video_props, audio_props, spin_props, class_names, styles, additional_props. +- Events: click. +- Slots: imageProps.placeholder, imageProps.preview.mask, imageProps.preview.closeIcon, imageProps.preview.toolbarRender, imageProps.preview.imageRender, description, icon, mask, spinProps.icon, spinProps.description, spinProps.indicator. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/file_card/**init**.py:11-112](file://backend/modelscope_studio/components/antdx/file_card/__init__.py#L11-L112) + +### Folder + +- Import Path: `modelscope_studio.components.antdx.Folder` +- Sub-components: TreeNode, DirectoryIcon +- Key Parameters: additional_props, tree_data, selectable, selected_file, default_selected_file, directory_tree_width, empty_render, preview_render, expanded_paths, default_expanded_paths, default_expand_all, directory_title, preview_title, directory_icons, class_names, styles, root_class_name. +- Events: file_click, folder_click, selected_file_change, expanded_paths_change, file_content_service_load_file_content. +- Slots: emptyRender, previewRender, directoryTitle, previewTitle, treeData, directoryIcons. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:12-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L12-L114) + +### CodeHighlighter + +- Import Path: `modelscope_studio.components.antdx.CodeHighlighter` +- Key Parameters: value, lang, header, highlight_props, prism_light_mode, styles, class_names, additional_props, root_class_name. +- Slots: header. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:6-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L6-L71) + +### Notification + +- Import Path: `modelscope_studio.components.antdx.Notification` +- Key Parameters: title, duration, badge, body, data, dir, icon, lang, require_interaction, silent, tag, additional_props. +- Events: permission, click, close, error, show. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/notification/**init**.py:10-97](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L10-L97) + +### Sources + +- Import Path: `modelscope_studio.components.antdx.Sources` +- Sub-components: Item +- Key Parameters: title, items, expand_icon_position, default_expanded, expanded, inline, active_key, popover_overlay_width, styles, class_names, root_class_name, additional_props. +- Events: expand, click. +- Slots: items. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/sources/**init**.py:11-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L11-L92) + +### Suggestion + +- Import Path: `modelscope_studio.components.antdx.Suggestion` +- Sub-components: Item +- Key Parameters: additional_props, items, block, open, should_trigger, class_names, styles, root_class_name. +- Events: select, open_change. +- Slots: items, children. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) + +### Think + +- Import Path: `modelscope_studio.components.antdx.Think` +- Key Parameters: additional_props, icon, styles, class_names, loading, title, root_class_name, default_expanded, expanded, blink. +- Events: expand. +- Slots: loading, icon, title. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) + +### ThoughtChain + +- Import Path: `modelscope_studio.components.antdx.ThoughtChain` +- Sub-components: Item, ThoughtChainItem +- Key Parameters: expanded_keys, default_expanded_keys, items, line, prefix_cls, styles, class_names, root_class_name, additional_props. +- Events: expand. +- Slots: items. +- Lifecycle & API: skip_api=True. + +Section Sources + +- [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) + +## Dependency Analysis + +- Components uniformly inherit from `ModelScopeLayoutComponent` or `ModelScopeDataLayoutComponent`; the latter supports `preprocess/postprocess` and API specification export for data types. +- Most components are layout-type components with `skip_api=True` that do not expose an API; a few data-type components (Attachments, Sender) implement data serialization specifications. +- Components resolve frontend resource directories via `resolve_frontend_dir("xxx", type="antdx")`, ensuring one-to-one correspondence with frontend components. + +```mermaid +graph LR +A["AntdXBubble"] --> B["ModelScopeLayoutComponent"] +C["AntdXAttachments"] --> D["ModelScopeDataLayoutComponent"] +E["AntdXSender"] --> D +F["AntdXConversations"] --> B +G["AntdXPrompts"] --> B +H["AntdXActions"] --> B +I["AntdXFileCard"] --> B +J["AntdXFolder"] --> B +K["AntdXCodeHighlighter"] --> B +L["AntdXNotification"] --> B +M["AntdXSources"] --> B +N["AntdXSuggestion"] --> B +O["AntdXThink"] --> B +P["AntdXThoughtChain"] --> B +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/bubble/**init**.py:13-135](file://backend/modelscope_studio/components/antdx/bubble/__init__.py#L13-L135) +- [backend/modelscope_studio/components/antdx/attachments/**init**.py:22-227](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L22-L227) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:14-149](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L14-L149) +- [backend/modelscope_studio/components/antdx/conversations/**init**.py:11-109](file://backend/modelscope_studio/components/antdx/conversations/__init__.py#L11-L109) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) +- [backend/modelscope_studio/components/antdx/actions/**init**.py:15-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L112) +- [backend/modelscope_studio/components/antdx/file_card/**init**.py:11-112](file://backend/modelscope_studio/components/antdx/file_card/__init__.py#L11-L112) +- [backend/modelscope_studio/components/antdx/folder/**init**.py:12-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L12-L114) +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:6-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L6-L71) +- [backend/modelscope_studio/components/antdx/notification/**init**.py:10-97](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L10-L97) +- [backend/modelscope_studio/components/antdx/sources/**init**.py:11-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L11-L92) +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) + +## Performance Considerations + +- Event Binding: Callbacks are bound via `EventListener` at construction time, avoiding performance overhead from duplicate bindings. +- Data Component Serialization: Attachments and Sender explicitly implement `preprocess/postprocess`, reducing unnecessary data conversion overhead. +- Frontend Resources: `resolve_frontend_dir` ensures only necessary resources are loaded, avoiding redundant bundling. +- Rendering Optimization: Layout-type components with `skip_api=True` reduce additional processing at the API layer. + +## Troubleshooting Guide + +- Events Not Triggering: Check that callbacks in the EVENTS list are correctly bound, and confirm that the frontend component has the corresponding events enabled. +- File Upload Issues: Verify the Attachments parameters such as action, headers, with_credentials, and max_count; ensure the server is accessible and the cache directory has proper permissions. +- Input Value Not Updating: The value and default_value of Sender must maintain consistent data types; pay attention to the timing of change/submit/cancel events. +- Style and Slots: If slot content is not displayed, check whether the SLOTS definition matches the slot names passed in. + +## Conclusion + +The Antdx component library provides a rich set of layout, input, and data components centered around AI/ML application scenarios. It meets typical requirements for conversational systems, file handling, and user input while ensuring good extensibility and consistency through unified event and slot mechanisms. In practice, it is recommended to prioritize data-type components (such as Attachments and Sender) for clearer API behavior and data flow, while using layout-type components to build friendly interactive interfaces. + +## Appendix + +### API Index (by Scenario) + +- General Components + - Bubble, Conversations, Prompts, Suggestions, Think, ThoughtChain, CodeHighlighter, Notification, Sources, FileCard, Folder, Actions +- Wake/Input Components + - Sender (with Header, Switch) +- Utility Components + - Attachments (file upload/download/preview/removal) +- Feedback Components + - Actions (action group and feedback) +- Expression Components + - CodeHighlighter (code highlighting) +- State & Process Components + - Think, ThoughtChain, Notification, Sources, Folder, FileCard + +### Standard Instantiation Examples (Path References) + +- Conversational System + - Use Bubble, Conversations, Prompts, Sender, and Actions together to build a conversational interface. + - Example path references: [Bubble constructor:56-116](file://backend/modelscope_studio/components/antdx/bubble/__init__.py#L56-L116), [Conversations constructor:49-91](file://backend/modelscope_studio/components/antdx/conversations/__init__.py#L49-L91), [Prompts constructor:28-71](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L28-L71), [Sender constructor:68-128](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L68-L128), [Actions constructor:58-94](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L58-L94) +- File Handling + - Use Attachments to receive file lists, combined with Sender's paste/paste_file events for drag-and-drop and clipboard upload. + - Example path references: [Attachments constructor:66-160](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L66-L160), [Sender events and parameters:21-59](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L21-L59) +- User Input + - Use Sender's submit/cancel events and value/default_value to control input state. + - Example path references: [Sender events and parameters:21-99](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L21-L99) + +### ML Integration Interfaces and Data Formats + +- Data-type Components (Attachments, Sender) + - preprocess: Converts payload to the internal representation expected by the component (e.g., file path list). + - postprocess: Converts internal value to the data structure for external output (e.g., ListFiles). + - api_info: Exports JSON Schema, specifying API input/output types. +- Layout-type Components (all other components) + - Typically skip_api=True, not exposing an API; state changes are driven by properties and events. + +### Lifecycle and Event Handling Mechanism + +- Event Binding: Callbacks are registered via `EventListener` in the constructor; the component internally binds to frontend events via `_internal.update`. +- Slots: Supported slot names are defined via SLOTS; the component internally parses and renders the corresponding content. +- Styles and Class Names: Uniform style injection is supported via styles, class_names, and root_class_name. diff --git a/.wiki/en/API Reference/Python API/Antdx Components API/Confirmation Components API.md b/.wiki/en/API Reference/Python API/Antdx Components API/Confirmation Components API.md new file mode 100644 index 00000000..bc2b26d8 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antdx Components API/Confirmation Components API.md @@ -0,0 +1,366 @@ +# Confirmation Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/thought_chain/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py) +- [backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py) +- [backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py) +- [frontend/antdx/thought-chain/thought-chain.tsx](file://frontend/antdx/thought-chain/thought-chain.tsx) +- [frontend/antdx/thought-chain/item/thought-chain.item.tsx](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx) +- [frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [docs/components/antdx/thought_chain/demos/basic.py](file://docs/components/antdx/thought_chain/demos/basic.py) +- [docs/components/antdx/thought_chain/demos/item_status.py](file://docs/components/antdx/thought_chain/demos/item_status.py) +- [docs/components/antdx/thought_chain/demos/nested_use.py](file://docs/components/antdx/thought_chain/demos/nested_use.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for Antdx confirmation components (AntdX), focusing on the ThoughtChain component's thought chain management, decision process tracking, and state visualization capabilities. Key areas covered: + +- Hierarchical structure management and node state control for ThoughtChain and ThoughtChainItem +- Chain operation processing and node connection relationships +- Data structure definitions, state change listeners, and result output mechanisms +- Standard usage examples for scenarios such as AI decision process display, thought chain analysis, and action confirmation +- Component state management strategies, event propagation mechanisms, and performance monitoring configurations +- Integration approaches with chatbots (Chatbot) and reasoning process visualization + +## Project Structure + +The ThoughtChain-related implementation in Antdx consists of backend Python components and a frontend Svelte/React wrapper layer: + +- Backend Python Components: Wrap Gradio layout components, responsible for property forwarding and frontend resource location +- Frontend Wrapper Layer: Bridges Ant Design X's ThoughtChain and ThoughtChain.Item components to the Gradio ecosystem, supporting slot rendering and context injection + +```mermaid +graph TB +subgraph "Backend Python Components" +A["AntdXThoughtChain
__init__.py"] +B["AntdXThoughtChainItem
item/__init__.py"] +C["AntdXThoughtChainThoughtChainItem
thought_chain_item/__init__.py"] +end +subgraph "Frontend Wrapper Layer" +D["thought-chain/thought-chain.tsx"] +E["thought-chain/item/thought-chain.item.tsx"] +F["thought-chain-item/thought-chain.thought-chain-item.tsx"] +end +A --> D +B --> E +C --> F +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [backend/modelscope_studio/components/antdx/thought_chain/item/**init**.py:8-78](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L8-L78) +- [backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/**init**.py:8-81](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L8-L81) +- [frontend/antdx/thought-chain/thought-chain.tsx:11-42](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L42) +- [frontend/antdx/thought-chain/item/thought-chain.item.tsx:9-32](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L9-L32) +- [frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx:7-13](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L7-L13) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [frontend/antdx/thought-chain/thought-chain.tsx:11-42](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L42) + +## Core Components + +- AntdXThoughtChain: Thought chain container, supports expanded keys, line styles, prefix class names, and other properties; listens for "expand" events to implement expanded key change callbacks; supports the "items" slot +- AntdXThoughtChainItem: Top-level node, supports title, description, icon, status, variant, blink, and other properties; supports "description", "icon", "title" slots +- AntdXThoughtChainThoughtChainItem: Nested node, supports content, extra, footer, icon, title, status, collapsible, blink, and other properties; supports "content", "description", "footer", "icon", "title" slots + +All of the above components inherit from ModelScopeLayoutComponent, with general Gradio layout component features, and specify the frontend directory via `resolve_frontend_dir`. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [backend/modelscope_studio/components/antdx/thought_chain/item/**init**.py:8-78](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L8-L78) +- [backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/**init**.py:8-81](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L8-L81) + +## Architecture Overview + +The diagram below shows the complete chain from Python calls to frontend rendering, as well as the role positions of slots and context: + +```mermaid +sequenceDiagram +participant Py as "Python Components
AntdXThoughtChain/AntdXThoughtChainItem" +participant Wrap as "Frontend Wrapper Layer
thought-chain.tsx / item/thought-chain.item.tsx" +participant ADX as "Ant Design X
@ant-design/x" +participant Slot as "Slot System
ReactSlot / renderItems" +Py->>Wrap : Pass properties and visibility +Wrap->>ADX : Render ThoughtChain/Item +Wrap->>Slot : Parse and render slot content +ADX-->>Wrap : Render result +Wrap-->>Py : Return value/placeholder render +``` + +**Diagram Sources** + +- [frontend/antdx/thought-chain/thought-chain.tsx:11-42](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L42) +- [frontend/antdx/thought-chain/item/thought-chain.item.tsx:9-32](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L9-L32) +- [frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx:7-13](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L7-L13) + +## Detailed Component Analysis + +### AntdXThoughtChain (Thought Chain Container) + +- Role and Responsibility + - Container for displaying multiple thought chain nodes + - Supports expanded key control, default expanded keys, line styles, prefix class names, and other appearance and interaction parameters + - Events: expand (triggered when expanded keys change) + - Slots: items (for batch injecting nodes) +- Key Properties + - expanded_keys: Currently expanded node key list + - default_expanded_keys: Initial default expanded key list + - items: Node data array (optional) + - line: Line style (boolean or specific string) + - prefix_cls: Prefix class name + - styles/class_names/root_class_name: Style and class name extensions +- Processing Flow + - Frontend parses slot items via context or directly uses the passed items + - Uses renderItems to clone slot nodes into React structures + - Renders the @ant-design/x ThoughtChain component + +```mermaid +flowchart TD +Start(["Enter AntdXThoughtChain"]) --> CheckItems["Check if items are passed"] +CheckItems --> |Yes| UsePassed["Use passed items"] +CheckItems --> |No| ResolveSlot["Resolve slot items/default"] +ResolveSlot --> RenderItems["Call renderItems to clone nodes"] +UsePassed --> RenderItems +RenderItems --> RenderADX["Render @ant-design/x ThoughtChain"] +RenderADX --> End(["Complete"]) +``` + +**Diagram Sources** + +- [frontend/antdx/thought-chain/thought-chain.tsx:14-39](file://frontend/antdx/thought-chain/thought-chain.tsx#L14-L39) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [frontend/antdx/thought-chain/thought-chain.tsx:11-42](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L42) + +### AntdXThoughtChainItem (Top-level Node) + +- Role and Responsibility + - Represents a top-level node in the thought chain + - Supports title, description, icon, status, variant, blink, and other properties + - Supports "description", "icon", "title" slots for custom rendering +- Key Properties + - title/description/icon: Node title, description, icon + - status: Node status (pending/success/error/abort) + - variant: Node appearance variant (solid/outlined/text) + - blink: Whether to blink as a prompt + - prefix_cls/class_names/styles: Style and class name extensions +- Slots + - description/title/icon: Replace the content of the corresponding area + +```mermaid +classDiagram +class AntdXThoughtChainItem { ++title : str|None ++description : str|None ++icon : str|None ++status : enum ++variant : enum ++blink : bool|None ++prefix_cls : str|None ++class_names : dict|str|None ++styles : dict|str|None +} +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/item/**init**.py:18-58](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L18-L58) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/item/**init**.py:8-78](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L8-L78) +- [frontend/antdx/thought-chain/item/thought-chain.item.tsx:9-32](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L9-L32) + +### AntdXThoughtChainThoughtChainItem (Nested Node) + +- Role and Responsibility + - Represents a nested node used inside a ThoughtChain + - Supports content, extra, footer, icon, title, status, collapsible, blink, and other properties + - Supports "content", "description", "footer", "icon", "title" slots +- Key Properties + - key: Node unique identifier + - title/description/content/extra/footer/icon: Content for each area of the node + - status: Node status + - collapsible: Whether collapsible + - blink: Whether to blink as a prompt +- Slots + - content/description/footer/icon/title: Replace the content of the corresponding area + +```mermaid +classDiagram +class AntdXThoughtChainThoughtChainItem { ++key : str|None ++title : str|None ++description : str|None ++content : str|None ++extra : str|None ++footer : str|None ++icon : str|None ++status : enum ++collapsible : bool|None ++blink : bool|None +} +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/**init**.py:18-60](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L18-L60) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/**init**.py:8-81](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L8-L81) +- [frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx:7-13](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L7-L13) + +### Data Structures and Node Connection Relationships + +- Node Data Structure + - items array: Each element corresponds to a ThoughtChainItem or ThoughtChainThoughtChainItem + - Fields include but are not limited to: title, description, content, icon, status, key, collapsible, etc. +- Connection Relationships + - AntdXThoughtChain acts as the root container; multiple ThoughtChainItems can be nested inside + - The content slot of each ThoughtChainItem can nest another ThoughtChain again, forming multi-level nesting +- State Changes and Listeners + - expand event: Triggered when expanded keys change; can be used for dynamically updating UI or logging + - status property: Used to intuitively reflect the execution status of nodes (success/failure/in-progress/abort) + +**Section Sources** + +- [frontend/antdx/thought-chain/thought-chain.tsx:14-39](file://frontend/antdx/thought-chain/thought-chain.tsx#L14-L39) +- [docs/components/antdx/thought_chain/demos/nested_use.py:10-64](file://docs/components/antdx/thought_chain/demos/nested_use.py#L10-L64) +- [docs/components/antdx/thought_chain/demos/item_status.py:9-33](file://docs/components/antdx/thought_chain/demos/item_status.py#L9-L33) + +### State Management Strategy and Event Propagation + +- State Management + - Drive UI state changes via the status property (e.g., color, icon, blink) + - Control node expansion/collapse via expanded_keys/default_expanded_keys +- Event Propagation + - The expand event is listened to at the container level; `bind_expand_event` can be set in the callback to enable event binding + - Event callbacks are typically used for linked updates to other components or logging +- Result Output Mechanism + - The component does not directly produce output values; external logic (e.g., button click) can be used to update the items or state of ThoughtChain via Gradio + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:20-25](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L20-L25) + +### Performance Monitoring Configuration + +- Recommended Practices + - For scenarios with large numbers of nodes, prefer passing data via the items parameter at once to reduce slot parsing overhead + - Use expanded_keys/default_expanded_keys wisely to avoid rendering too many nodes at once + - When frequent state updates are needed, batch update items to reduce multiple re-renders +- Monitoring Metrics + - Page rendering time, node count, expand/collapse frequency, state switch count + +[This section contains general recommendations and does not require specific file references] + +## Dependency Analysis + +- Component Export and Aggregation + - The antdx component module uniformly exports ThoughtChain and its sub-items for on-demand import in business code +- Frontend Dependencies + - @ant-design/x provides core rendering capabilities + - sveltify bridges Svelte components to React/Gradio + - renderItems is used for cloning and rendering slot nodes + +```mermaid +graph LR +Export["antdx/components.py Export"] --> A["AntdXThoughtChain"] +Export --> B["AntdXThoughtChainItem"] +Export --> C["AntdXThoughtChainThoughtChainItem"] +A --> D["thought-chain/thought-chain.tsx"] +B --> E["thought-chain/item/thought-chain.item.tsx"] +C --> F["thought-chain-item/thought-chain.thought-chain-item.tsx"] +D --> ADX["@ant-design/x"] +E --> ADX +F --> ADX +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/components.py:35-40](file://backend/modelscope_studio/components/antdx/components.py#L35-L40) +- [frontend/antdx/thought-chain/thought-chain.tsx:3-6](file://frontend/antdx/thought-chain/thought-chain.tsx#L3-L6) +- [frontend/antdx/thought-chain/item/thought-chain.item.tsx:4-7](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L4-L7) +- [frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx:3-5](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L3-L5) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/components.py:35-40](file://backend/modelscope_studio/components/antdx/components.py#L35-L40) + +## Performance Considerations + +- Rendering Optimization + - Use the items parameter rather than numerous slots to reduce frontend parsing costs + - For long lists, consider pagination or lazy loading +- State Updates + - Batch update items to avoid frequent incremental changes + - Use the expand event wisely to avoid excessive responses causing redraws +- Styles and Class Names + - Use styles/class_names/root_class_name to precisely control styles and avoid global pollution + +[This section contains general recommendations and does not require specific file references] + +## Troubleshooting Guide + +- Common Issues + - Slot not taking effect: Confirm the slot name is correct and matches the slots supported by the component + - State not updating: Check whether status is correctly set and ensure external logic has triggered a Gradio update + - Expanded keys not working: Confirm that the expand event is bound and expanded_keys/default_expanded_keys are set appropriately +- Troubleshooting Steps + - Validate component behavior using a minimal example + - Gradually add slots and state to narrow down the problem scope + - Check the browser console and network panel to confirm that frontend resources are loading normally + +**Section Sources** + +- [docs/components/antdx/thought_chain/demos/basic.py:31-74](file://docs/components/antdx/thought_chain/demos/basic.py#L31-L74) +- [docs/components/antdx/thought_chain/demos/item_status.py:9-33](file://docs/components/antdx/thought_chain/demos/item_status.py#L9-L33) + +## Conclusion + +Antdx's ThoughtChain component provides a reliable visualization foundation for AI decision process display, thought chain analysis, and action confirmation through a clear hierarchical structure and rich state control. Combined with the slot system and event mechanism, it can be flexibly extended and customized in complex scenarios. For large-scale data scenarios, it is recommended to use item parameter passing and batch update strategies for better performance. + +[This section contains summary content and does not require specific file references] + +## Appendix + +### Standard Usage Examples (Paths) + +- Basic Usage: Display multiple ThoughtChainItems with configured states and slots + - [docs/components/antdx/thought_chain/demos/basic.py:31-74](file://docs/components/antdx/thought_chain/demos/basic.py#L31-L74) +- State Toggle Demo: Drive node state changes via buttons + - [docs/components/antdx/thought_chain/demos/item_status.py:46-67](file://docs/components/antdx/thought_chain/demos/item_status.py#L46-L67) +- Nested Usage: Nest another ThoughtChain within node content + - [docs/components/antdx/thought_chain/demos/nested_use.py:19-64](file://docs/components/antdx/thought_chain/demos/nested_use.py#L19-L64) + +### Quick API Reference (Paths) + +- Container Component: AntdXThoughtChain + - [backend/modelscope_studio/components/antdx/thought_chain/**init**.py:30-68](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L30-L68) +- Top-level Node: AntdXThoughtChainItem + - [backend/modelscope_studio/components/antdx/thought_chain/item/**init**.py:18-60](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L18-L60) +- Nested Node: AntdXThoughtChainThoughtChainItem + - [backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/**init**.py:18-63](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L18-L63) diff --git a/.wiki/en/API Reference/Python API/Antdx Components API/Expression Components API.md b/.wiki/en/API Reference/Python API/Antdx Components API/Expression Components API.md new file mode 100644 index 00000000..ead87d5c --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antdx Components API/Expression Components API.md @@ -0,0 +1,359 @@ +# Expression Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/antdx/attachments/__init__.py](file://backend/modelscope_studio/components/antdx/attachments/__init__.py) +- [backend/modelscope_studio/components/antdx/sender/__init__.py](file://backend/modelscope_studio/components/antdx/sender/__init__.py) +- [backend/modelscope_studio/components/antdx/sender/header/__init__.py](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py) +- [backend/modelscope_studio/components/antdx/sender/switch/__init__.py](file://backend/modelscope_studio/components/antdx/sender/switch/__init__.py) +- [backend/modelscope_studio/components/antdx/suggestion/__init__.py](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py) +- [backend/modelscope_studio/components/antdx/suggestion/item/__init__.py](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document is the Python API reference for Antdx expression components, focusing on the following capabilities: + +- File attachment handling: Upload, drag-and-drop, download, preview, removal, type restrictions, and list display strategies +- Input and send control: Text input box management, submit types (Enter/Shift+Enter), paste and keyboard events, voice input toggle +- Multimodal input support: Extended header area, switch, and skill panel via Sender sub-components +- Quick commands: Suggestion component and its items' triggering, selection, and panel state management +- Chatbot integration: Data flow and interaction protocol based on Gradio data classes and event callbacks + +## Project Structure + +Antdx components reside in the backend Python package, exported through a unified entry point, and mapped to Svelte implementations in the frontend via corresponding directory mappings. The expression component-related modules are organized as follows: + +- Top-level exports: `antdx/__init__.py` and `antdx/components.py` provide aggregated component exports +- Attachments: `antdx/attachments` +- Sender: `antdx/sender` (with header, switch sub-components) +- Suggestion: `antdx/suggestion` (with item sub-component) + +```mermaid +graph TB +subgraph "Python Backend" +A["antdx/__init__.py"] +B["antdx/components.py"] +C["attachments/__init__.py"] +D["sender/__init__.py"] +E["sender/header/__init__.py"] +F["sender/switch/__init__.py"] +G["suggestion/__init__.py"] +H["suggestion/item/__init__.py"] +end +A --> C +A --> D +A --> E +A --> F +A --> G +A --> H +B --> C +B --> D +B --> E +B --> F +B --> G +B --> H +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +Section Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Core Components + +- AntdXAttachments: File attachment upload and management, supports drag-and-drop, preview, download, removal, type filtering, list styles, placeholders, etc. +- AntdXSender: Input and send control, supports auto height, read-only, loading state, placeholder, submit type, voice input, file paste, keyboard events, etc. +- AntdXSenderHeader: Sender header area, supports expand/collapse, title, closable, etc. +- AntdXSenderSwitch: Built-in switch for Sender, supports checked/unchecked labels and icons +- AntdXSuggestion: Quick command suggestion panel, supports items list, open state, select event +- AntdXSuggestionItem: Suggestion item, supports label, icon, extra content, and other slots + +Section Sources + +- [backend/modelscope_studio/components/antdx/attachments/**init**.py:22-227](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L22-L227) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:14-149](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L14-L149) +- [backend/modelscope_studio/components/antdx/sender/header/**init**.py:8-74](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py#L8-L74) +- [backend/modelscope_studio/components/antdx/sender/switch/**init**.py:8-81](file://backend/modelscope_studio/components/antdx/sender/switch/__init__.py#L8-L81) +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/suggestion/item/**init**.py:8-68](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py#L8-L68) + +## Architecture Overview + +The frontend-backend interaction of expression components follows the Gradio data class and event model: + +- Backend components define data models (e.g., ListFiles) and event listeners +- Frontend maps to the corresponding Svelte components based on FRONTEND_DIR +- Data format conversion between Python and frontend is done via preprocess/postprocess +- Event callbacks are bound to frontend events via `_internal.update` + +```mermaid +sequenceDiagram +participant U as "User" +participant FE as "Frontend Component (Svelte)" +participant PY as "Backend Component (Python)" +participant GR as "Gradio Data Class" +U->>FE : Trigger event (input/paste/drag-and-drop/click) +FE->>PY : Event callback binding (_internal.update) +PY->>GR : preprocess(payload) convert to internal value +GR-->>PY : Return processed value +PY-->>FE : postprocess(value) return frontend display value +FE-->>U : Update UI (list/preview/state) +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/attachments/**init**.py:168-207](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L168-L207) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:134-142](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L134-L142) + +## Component Details + +### Attachments Component (AntdXAttachments) + +- Key Features + - Supports file upload, drag-and-drop upload, batch selection, maximum count limit + - Supports file type filtering (accept), HTTP request parameters (headers, data, method) + - Supports custom upload requests (custom_request), pre-upload hooks (before_upload) + - List styles and overflow strategies (list_type, overflow), shows upload list by default + - Placeholder and image preview enhancements (placeholder, imageProps.\*) + - Events: change, drop, download, preview, remove + - Slots: showUploadList._, iconRender, itemRender, placeholder._, imageProps.\*, etc. +- Data Flow + - preprocess: Converts the ListFiles passed from the frontend to a local path string list + - postprocess: Downloads local paths/URLs to the cache and packages them as ListFiles to return to the frontend +- File Handling Strategy + - Remote URLs: Downloaded to cache directory + - Local paths: Used directly + - Preview: Uses Gradio FileData metadata (orig_name, size) + +```mermaid +flowchart TD +Start(["Enter preprocess"]) --> CheckNull{"Is payload empty?"} +CheckNull --> |Yes| ReturnNone["Return None"] +CheckNull --> |No| Loop["Iterate each FileData"] +Loop --> Process["_process_single_file
Generate temp filename"] +Process --> Append["Collect string paths"] +Append --> DonePre["Return string list"] +subgraph "postprocess" +PStart["Receive string list"] --> PNull{"Is empty?"} +PNull --> |Yes| PEmpty["Return empty list"] +PNull --> |No| PLoop["Iterate paths"] +PLoop --> PType{"Is URL?"} +PType --> |Yes| PDownload["Download to cache"] +PType --> |No| PUse["Use directly"] +PDownload --> PBuild["Build FileData(orig_name,size)"] +PUse --> PBuild +PBuild --> PEnd["Return ListFiles"] +end +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/attachments/**init**.py:162-207](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L162-L207) + +Section Sources + +- [backend/modelscope_studio/components/antdx/attachments/**init**.py:22-227](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L22-L227) + +### Sender Component (AntdXSender) + +- Key Features + - Input box management: auto_size, placeholder, disabled, read_only, loading + - Submit control: submit_type (enter or shiftEnter) + - Events: change, submit, cancel, allow_speech_recording_change, key_down/key_press, focus/blur, paste/paste_file, skill_closable_close + - Slots: suffix, header, prefix, footer, skill.\*, etc. + - Sub-components: Header, Switch (for extending the header area and switch) +- Data Flow + - preprocess/postprocess: Pass through string values +- Multimodal Input Support + - allow_speech: Enable voice input (boolean or dict) + - paste_file: File paste event + - skill.\*: Skill panel title, tooltip, and closable icon + +```mermaid +sequenceDiagram +participant U as "User" +participant FE as "Sender Frontend" +participant PY as "AntdXSender" +U->>FE : Input/keypress/paste/click send +FE->>PY : Event callback (e.g. change/submit/paste_file) +PY-->>FE : Control submit behavior based on submit_type +FE-->>U : Update state (loading/disabled) +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/sender/**init**.py:21-59](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L21-L59) + +Section Sources + +- [backend/modelscope_studio/components/antdx/sender/**init**.py:14-149](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L14-L149) + +### Sender Header (AntdXSenderHeader) + +- Key Features + - Expand/collapse: open, closable + - Title: title + - Slots: title +- Usage + - Used as a Sender sub-component for holding the header title and close button + +Section Sources + +- [backend/modelscope_studio/components/antdx/sender/header/**init**.py:8-74](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py#L8-L74) + +### Sender Switch (AntdXSenderSwitch) + +- Key Features + - Value: value (bool) + - Labels and Icons: checked_children, un_checked_children, icon + - States: disabled, loading + - Slots: checkedChildren, unCheckedChildren, icon +- Usage + - Used as a Sender sub-component for toggling certain send behaviors or modes + +Section Sources + +- [backend/modelscope_studio/components/antdx/sender/switch/**init**.py:8-81](file://backend/modelscope_studio/components/antdx/sender/switch/__init__.py#L8-L81) + +### Suggestion Component (AntdXSuggestion) and Item (AntdXSuggestionItem) + +- Suggestion Panel + - items: Suggestion item list (string or dict) + - Open state: open, block, should_trigger + - Events: select, open_change + - Slots: items, children +- Suggestion Item + - label, icon, extra, key + - Slots: label, icon, extra + +```mermaid +classDiagram +class AntdXSuggestion { ++items ++open ++block ++should_trigger ++EVENTS ++SLOTS +} +class AntdXSuggestionItem { ++value ++label ++icon ++extra ++key ++EVENTS ++SLOTS +} +AntdXSuggestion --> AntdXSuggestionItem : "contains multiple items" +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/suggestion/item/**init**.py:8-68](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py#L8-L68) + +Section Sources + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/suggestion/item/**init**.py:8-68](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py#L8-L68) + +## Dependency Analysis + +- Component Aggregation + - `antdx/__init__.py` and `antdx/components.py` uniformly export all sub-components for on-demand import by upper-level applications +- Component Cohesion + - Each component independently defines EVENTS, SLOTS, FRONTEND_DIR with clear responsibilities +- Event Coupling + - Frontend events are mapped to backend callbacks via EventListener and `_internal.update` +- Data Class Dependencies + - The Attachments component uses Gradio ListFiles and FileData to ensure cross-platform data consistency + +```mermaid +graph LR +A["antdx/__init__.py"] --> C["attachments/__init__.py"] +A --> D["sender/__init__.py"] +D --> E["sender/header/__init__.py"] +D --> F["sender/switch/__init__.py"] +A --> G["suggestion/__init__.py"] +G --> H["suggestion/item/__init__.py"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +Section Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Performance Considerations + +- File Handling + - Remote URL downloads should be combined with cache directories and async strategies to avoid blocking the main thread + - Large file uploads should use chunked or server-side direct upload strategies +- Event Callbacks + - Avoid heavy computations in callbacks for high-frequency events (e.g., change, key_down) +- UI Rendering + - Enable virtualization (if applicable) during list rendering to reduce DOM nodes + - Image preview and thumbnail generation should be done in background threads whenever possible + +## Troubleshooting Guide + +- Attachments Cannot Upload/Preview + - Check that accept and headers/data/method configurations are correct + - Confirm that custom_request and before_upload callbacks do not throw errors +- Remote Files Cannot Download + - Check URL accessibility and with_credentials settings + - Check cache directory permissions and disk space +- Sender Events Not Working + - Confirm that submit_type and keyboard event bindings match + - Check whether disabled/read_only/loading states are preventing interaction +- Suggestion Panel Not Showing + - Check whether items is empty or the should_trigger condition is met + - Confirm that open/open_change events are correctly bound + +## Conclusion + +Antdx expression components provide complete file attachment, input sending, and quick command capabilities through a clear event and slot system. Relying on Gradio data classes and the event model, flexible data conversion and interaction control can be performed on the Python side while maintaining a consistent frontend UI experience. + +## Appendix: Usage Examples and Best Practices + +- File Upload and Preview + - Use AntdXAttachments' accept to restrict types; set headers and data for authentication and additional parameter passing + - Control list styles and visibility via list_type and show_upload_list + - Enhance image preview experience with preview_file and imageProps.\* +- Input and Send Control + - Use submit_type to precisely control submit timing (enter/shiftEnter) + - Extend the header area and toggle via Sender.Header and Sender.Switch + - Handle file paste scenarios via paste/paste_file events +- Quick Commands + - Control the suggestion panel using AntdXSuggestion's items and open + - Enrich command display with AntdXSuggestionItem's label/icon/extra +- Integration with Chatbot + - Use Sender's value as the message body, and the attachment list as multimodal input + - Assemble the message body via event callbacks on the backend and call the bot API + - Use preprocess/postprocess for message and file serialization/deserialization diff --git a/.wiki/en/API Reference/Python API/Antdx Components API/Feedback Components API.md b/.wiki/en/API Reference/Python API/Antdx Components API/Feedback Components API.md new file mode 100644 index 00000000..f6018c66 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antdx Components API/Feedback Components API.md @@ -0,0 +1,446 @@ +# Feedback Components API + + +**Files Referenced in This Document** +- [actions/__init__.py](file://backend/modelscope_studio/components/antdx/actions/__init__.py) +- [action_item/__init__.py](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py) +- [item/__init__.py](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py) +- [copy/__init__.py](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py) +- [audio/__init__.py](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py) +- [feedback/__init__.py](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py) +- [notification/__init__.py](file://backend/modelscope_studio/components/antdx/notification/__init__.py) +- [components.py](file://backend/modelscope_studio/components/antdx/components.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document is the Python API reference for Antdx feedback components, covering: the Actions component for action list management, action item configuration, and user interaction; ActionsItem for defining action items; ActionItem for specific action implementations; the Copy component for copy functionality; the Audio component for audio processing; the Feedback component for user feedback collection; and the Notification component for notification management, message push, and user feedback responses. The document also provides event handling strategies, state synchronization mechanisms, and user experience optimization configurations, along with reference solutions for chatbot integration and real-time user behavior feedback. + +## Project Structure + +Antdx feedback-related components reside in the backend Python package, organized by functional modules. Frontend resources are provided by Svelte components in the frontend directory. The Python layer exposes a unified interface to the application layer through Gradio component encapsulation and event binding. + +```mermaid +graph TB +subgraph "Antdx Components (Python)" +A["actions/__init__.py
AntdXActions"] +B["actions/action_item/__init__.py
AntdXActionsActionItem"] +C["actions/item/__init__.py
AntdXActionsItem"] +D["actions/copy/__init__.py
AntdXActionsCopy"] +E["actions/audio/__init__.py
AntdXActionsAudio"] +F["actions/feedback/__init__.py
AntdXActionsFeedback"] +G["notification/__init__.py
AntdXNotification"] +end +subgraph "Export Entry" +H["components.py
Unified Export"] +end +A --> B +A --> C +A --> D +A --> E +A --> F +H --> A +H --> G +``` + +**Diagram Sources** + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [actions/**init**.py:15-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L112) +- [action_item/**init**.py:10-80](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L10-L80) +- [item/**init**.py:10-77](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L10-L77) +- [copy/**init**.py:10-72](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L10-L72) +- [audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) +- [feedback/**init**.py:10-74](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L10-L74) +- [notification/**init**.py:10-97](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L10-L97) + +**Section Sources** + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Core Components + +- AntdXActions: Action set container, supports event binding and slot extension, used to hold multiple action items and submenus. +- AntdXActionsActionItem: Custom action item, supports label, icon, danger style, trigger method, and sub-items. +- AntdXActionsItem: Standard action item, supports states (loading/running/error/default), icon switching, and style customization. +- AntdXActionsCopy: Copy action, bound to click event, supports custom icon and text. +- AntdXActionsAudio: Audio status indicator, supports state enumeration and style customization. +- AntdXActionsFeedback: Feedback component for like/dislike/default states, supports click and state change events. +- AntdXNotification: Notification component, supports permission, click, close, error, show events, and multilingual/direction attributes. + +All of the above components inherit from a unified layout component base class, with Gradio-compatible event binding and rendering control capabilities. + +**Section Sources** + +- [actions/**init**.py:15-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L112) +- [action_item/**init**.py:10-80](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L10-L80) +- [item/**init**.py:10-77](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L10-L77) +- [copy/**init**.py:10-72](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L10-L72) +- [audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) +- [feedback/**init**.py:10-74](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L10-L74) +- [notification/**init**.py:10-97](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L10-L97) + +## Architecture Overview + +Antdx feedback components are exposed at the Python layer as Gradio components; the frontend implements UI behavior and interaction through corresponding Svelte components. Components bind callbacks via event listeners to relay user operations to the backend for event delivery and state updates. + +```mermaid +sequenceDiagram +participant U as "User" +participant A as "AntdXActions" +participant AI as "AntdXActionsActionItem" +participant AF as "AntdXActionsFeedback" +participant AN as "AntdXNotification" +U->>A : Trigger click/dropdown event +A-->>U : Trigger bound event callback +U->>AI : Click custom action item +AI-->>U : Trigger item_click callback +U->>AF : Click feedback button +AF-->>U : Trigger click/change callback +U->>AN : Trigger notification show/click/close +AN-->>U : Trigger permission/click/close/error/show callback +``` + +**Diagram Sources** + +- [actions/**init**.py:26-46](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L26-L46) +- [action_item/**init**.py:15-21](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L15-L21) +- [feedback/**init**.py:15-23](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L15-L23) +- [notification/**init**.py:14-30](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L14-L30) + +## Detailed Component Analysis + +### Actions Component (AntdXActions) + +- Responsibility: Serves as the action set container, managing action item lists, dropdown menu properties, and animation effects; supports event binding and slot extension. +- Key Properties + - items: Action item array for initializing the action list. + - variant: Appearance variant (e.g., borderless/outlined/filled). + - dropdown_props: Dropdown menu related property object. + - fade_in/fade_in_left: Entry animation toggles. + - class_names/styles: Style class names and inline style mappings. + - Slots: items, dropdownRender, popupRender, menu.expandIcon, overflowedIndicator, menu.items. +- Events + - click: Triggered when any action item is clicked. + - dropdown_open_change/dropdown_menu_open_change: Dropdown open/menu open state changes. + - dropdown_menu_click/dropdown_menu_deselect/dropdown_menu_select: Menu item click/deselect/select events. +- Processing Flow + - Internal binding flags are set at initialization so frontend events can be sent back to the backend. + - During rendering, action items and menu structures are dynamically generated based on items and dropdown_props. + - Custom rendering logic is extended through slots. + +```mermaid +classDiagram +class AntdXActions { ++Properties : items, variant, dropdown_props, fade_in, fade_in_left ++Methods : preprocess(), postprocess() ++Events : click, dropdown_open_change, dropdown_menu_*... ++Slots : items, dropdownRender, popupRender, menu.expandIcon, overflowedIndicator, menu.items +} +``` + +**Diagram Sources** + +- [actions/**init**.py:58-94](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L58-L94) + +**Section Sources** + +- [actions/**init**.py:15-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L112) + +### ActionsItem (AntdXActionsItem) + +- Responsibility: Standard action item, supports state switching and icon replacement. +- Key Properties + - status: State enumeration (loading/error/running/default). + - label: Display label. + - default_icon/running_icon: Default icon and running icon. + - class_names/styles: Style class names and inline style mappings. + - Slots: defaultIcon, runningIcon. +- Events + - click: Triggered when the item is clicked. +- Usage Recommendations + - Use with the items field of the Actions component for batch configuration. + - Customize icons and labels in different states through slots. + +```mermaid +classDiagram +class AntdXActionsItem { ++Properties : status, label, default_icon, running_icon ++Methods : preprocess(), postprocess() ++Events : click ++Slots : defaultIcon, runningIcon +} +``` + +**Diagram Sources** + +- [item/**init**.py:24-59](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L24-L59) + +**Section Sources** + +- [item/**init**.py:10-77](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L10-L77) + +### ActionItem (AntdXActionsActionItem) + +- Responsibility: Custom action item, supports label, icon, danger style, sub-items, and trigger method. +- Key Properties + - label/icon: Label and icon. + - danger: Whether to use danger style. + - trigger_sub_menu_action: Sub-menu trigger method (hover/click). + - sub_items: Sub-item array. + - action_render: Custom rendering function identifier. + - Slots: label, icon, actionRender, subItems. +- Events + - item_click: Triggered when the custom action button is clicked. +- Usage Recommendations + - Suitable for complex menus or scenarios requiring custom rendering. + - Sub-items are injected via the subItems slot, forming a nested menu tree. + +```mermaid +classDiagram +class AntdXActionsActionItem { ++Properties : label, icon, danger, trigger_sub_menu_action, sub_items, action_render ++Methods : preprocess(), postprocess() ++Events : item_click ++Slots : label, icon, actionRender, subItems +} +``` + +**Diagram Sources** + +- [action_item/**init**.py:26-62](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L26-L62) + +**Section Sources** + +- [action_item/**init**.py:10-80](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L10-L80) + +### Copy Component (AntdXActionsCopy) + +- Responsibility: Provides one-click copy functionality, commonly used for copying code blocks, links, and other text. +- Key Properties + - text: Text to be copied. + - icon: Custom icon. + - class_names/styles: Style class names and inline style mappings. + - Slots: icon. +- Events + - click: Triggered when the copy button is clicked. +- Usage Recommendations + - Use in combination with ActionItem or ActionsItem to improve user operation efficiency. + - Be mindful of browser permission and Clipboard API compatibility. + +```mermaid +classDiagram +class AntdXActionsCopy { ++Properties : text, icon ++Methods : preprocess(), postprocess() ++Events : click ++Slots : icon +} +``` + +**Diagram Sources** + +- [copy/**init**.py:24-54](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L24-L54) + +**Section Sources** + +- [copy/**init**.py:10-72](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L10-L72) + +### Audio Component (AntdXActionsAudio) + +- Responsibility: Audio status indicator for displaying recording/playback/loading/error states. +- Key Properties + - status: State enumeration (loading/error/running/default). + - class_names/styles: Style class names and inline style mappings. + - Slots: None. +- Events + - click: Triggered when the audio control is clicked. +- Usage Recommendations + - Pair with recording/playback functionality to provide immediate status feedback. + - Customize through styles to match the theme palette. + +```mermaid +classDiagram +class AntdXActionsAudio { ++Properties : status ++Methods : preprocess(), postprocess() ++Events : click +} +``` + +**Diagram Sources** + +- [audio/**init**.py:24-53](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L24-L53) + +**Section Sources** + +- [audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) + +### Feedback Component (AntdXActionsFeedback) + +- Responsibility: Collects user feedback on content/conversations, supports like/dislike/default states. +- Key Properties + - value: Current feedback value (like/dislike/default). + - class_names/styles: Style class names and inline style mappings. + - Slots: None. +- Events + - click: Triggered when the feedback button is clicked. + - change: Triggered when the feedback state changes. +- Usage Recommendations + - Pair with chatbot outputs or content cards to form a complete feedback loop. + - Report data via the change event, combined with backend storage and statistics. + +```mermaid +classDiagram +class AntdXActionsFeedback { ++Properties : value ++Methods : preprocess(), postprocess() ++Events : click, change +} +``` + +**Diagram Sources** + +- [feedback/**init**.py:28-56](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L28-L56) + +**Section Sources** + +- [feedback/**init**.py:10-74](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L10-L74) + +### Notification Component (AntdXNotification) + +- Responsibility: System notification management, supports permission, click, close, error, show events, and internationalization/direction attributes. +- Key Properties + - title/body: Title and body text. + - duration: Display duration. + - badge/lang/dir/icon/tag/data/silent/require_interaction: Badge, language, direction, icon, tag, data, silent mode, require interaction. + - Slots: None. +- Events + - permission/click/close/error/show: Permission request, click, close, error, show. +- Usage Recommendations + - Used for system notifications, permission prompts, error alerts, and user feedback responses. + - Combine with the Feedback component to form a "notification-feedback" closed loop. + +```mermaid +classDiagram +class AntdXNotification { ++Properties : title, body, duration, badge, lang, dir, icon, tag, data, silent, require_interaction ++Methods : preprocess(), postprocess() ++Events : permission, click, close, error, show +} +``` + +**Diagram Sources** + +- [notification/**init**.py:35-79](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L35-L79) + +**Section Sources** + +- [notification/**init**.py:10-97](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L10-L97) + +## Dependency Analysis + +- Unified Export: `components.py` centralizes all Antdx component exports for on-demand import by upper-level applications. +- Component Relationships: The Actions container combines ActionItem, Item, Copy, Audio, Feedback, and other sub-components; Notification exists independently and can work in conjunction with Feedback. + +```mermaid +graph LR +subgraph "Export Layer" +C["components.py"] +end +subgraph "Actions Family" +A1["AntdXActions"] +A2["AntdXActionsActionItem"] +A3["AntdXActionsItem"] +A4["AntdXActionsCopy"] +A5["AntdXActionsAudio"] +A6["AntdXActionsFeedback"] +end +subgraph "Notification" +N1["AntdXNotification"] +end +C --> A1 +C --> N1 +A1 --> A2 +A1 --> A3 +A1 --> A4 +A1 --> A5 +A1 --> A6 +``` + +**Diagram Sources** + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [actions/**init**.py:15-25](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L25) +- [notification/**init**.py:10-13](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L10-L13) + +**Section Sources** + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Performance Considerations + +- Minimize Event Binding: Only enable event binding when needed to avoid unnecessary callback overhead. +- Slot Rendering: Use slots wisely to reduce repeated rendering and keep the DOM structure concise. +- State Synchronization: Use component state and event linkage to avoid frequent full refreshes. +- Styles and Animation: Use entry animations and complex styles cautiously to ensure smooth performance on low-end devices. + +## Troubleshooting Guide + +- Events Not Triggering + - Check that event bindings are correctly enabled (e.g., click, dropdown\_\*, item_click, change). + - Confirm that frontend slot and property configurations match. +- State Inconsistency + - Verify the value range and default value of value/status. + - Check the state change logic in the change event. +- Style Issues + - Check whether class_names/styles has overridden the default styles. + - Confirm theme and global style conflicts. +- Notification Not Working + - Check the handling flow for the permission event. + - Confirm display duration and interaction requirement configurations. + +**Section Sources** + +- [actions/**init**.py:26-46](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L26-L46) +- [action_item/**init**.py:15-21](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L15-L21) +- [feedback/**init**.py:15-23](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L15-L23) +- [notification/**init**.py:14-30](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L14-L30) + +## Conclusion + +Antdx feedback components provide complete capabilities from action item management, copy and audio status indication to user feedback and notification management through a clear component layering and event binding mechanism. Combined with unified exports and slot extensions, developers can quickly build high-quality user feedback and interaction experiences across various scenarios. + +## Appendix: Usage Examples and Best Practices + +- User Operation Feedback + - Add the Feedback component after content cards or conversation outputs, bind click and change events to report user preferences. + - Example path: [feedback/**init**.py:15-23](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L15-L23) +- Quick Actions + - Use Actions to combine ActionItem and Item, configure subItems to form secondary menus; customize icons and labels through slots. + - Example paths: [actions/**init**.py:48-56](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L48-L56), [action_item/**init**.py:23-24](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L23-L24) +- Audio Interaction + - Use the Audio component to display recording/playback states, combined with the click event to control play/pause. + - Example path: [audio/**init**.py:15-19](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L15-L19) +- Copy Functionality + - Place the Copy component next to code blocks or links, bind the click event to improve copy efficiency. + - Example path: [copy/**init**.py:15-19](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L15-L19) +- Notification Management + - Use the Notification component for system prompts and permission alerts, bind permission/click/close/error/show events. + - Example path: [notification/**init**.py:14-30](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L14-L30) +- Integration with Chatbot + - Insert the Feedback component after chat outputs, report user feedback through the change event; use Notification when needed for confirmation or error alerts. + - Example paths: [feedback/**init**.py:15-23](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L15-L23), [notification/**init**.py:14-30](file://backend/modelscope_studio/components/antdx/notification/__init__.py#L14-L30) diff --git a/.wiki/en/API Reference/Python API/Antdx Components API/General Components API.md b/.wiki/en/API Reference/Python API/Antdx Components API/General Components API.md new file mode 100644 index 00000000..ecfb2e3d --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antdx Components API/General Components API.md @@ -0,0 +1,390 @@ +# General Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/antdx/bubble/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/__init__.py) +- [backend/modelscope_studio/components/antdx/bubble/list/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/list/__init__.py) +- [backend/modelscope_studio/components/antdx/bubble/list/item/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/list/item/__init__.py) +- [backend/modelscope_studio/components/antdx/bubble/list/role/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/list/role/__init__.py) +- [backend/modelscope_studio/components/antdx/conversations/__init__.py](file://backend/modelscope_studio/components/antdx/conversations/__init__.py) +- [backend/modelscope_studio/components/antdx/conversations/item/__init__.py](file://backend/modelscope_studio/components/antdx/conversations/item/__init__.py) +- [backend/modelscope_studio/components/antdx/prompts/__init__.py](file://backend/modelscope_studio/components/antdx/prompts/__init__.py) +- [backend/modelscope_studio/components/antdx/prompts/item/__init__.py](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py) +- [docs/components/antdx/bubble/README-zh_CN.md](file://docs/components/antdx/bubble/README-zh_CN.md) +- [docs/components/antdx/conversations/README-zh_CN.md](file://docs/components/antdx/conversations/README-zh_CN.md) +- [docs/components/antdx/prompts/README-zh_CN.md](file://docs/components/antdx/prompts/README-zh_CN.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for Antdx general components, focusing on the following core components: + +- Bubble: Conversation bubble rendering and interaction +- BubbleList: Message list management +- BubbleListItem: Message item processing +- BubbleListRole: Role identification +- Conversations: Conversation management, message storage, and state synchronization +- Prompts: Prompt template management, dynamic content rendering, and user interaction + +The documentation provides constructor parameters, property definitions, event and slot (slots) specifications for each component, and gives standard component instantiation and composition patterns for typical AI scenarios, helping developers quickly build conversational systems, message display, and prompt management features. + +## Project Structure + +Antdx components reside in the backend Python package, wrapped through a unified layout component base class, and mapped to the corresponding frontend component directories. Component export entry points are centralized in `antdx/components.py` for on-demand import. + +```mermaid +graph TB +subgraph "Python Backend" +A["components.py
Export Entry"] +B["bubble/*
Conversation Bubble Component Family"] +C["conversations/*
Conversation List Component Family"] +D["prompts/*
Prompts Component Family"] +end +A --> B +A --> C +A --> D +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +Section Sources + +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Core Components + +This section provides an overview of the three core component families and their responsibility boundaries: + +- Bubble Family: Responsible for rendering and interaction of individual messages or role-level bubbles, supporting typing animation, editability, variants, shapes, etc. +- BubbleList Family: Responsible for scrolling, role grouping, and item rendering in message lists, supporting auto-scroll and role configuration. +- Conversations Family: Responsible for conversation list management, selection state toggling, menu operations, and creation buttons. +- Prompts Family: Responsible for displaying preset prompts and click interactions, supporting vertical arrangement, fade-in effects, line wrapping, etc. + +Section Sources + +- [backend/modelscope_studio/components/antdx/bubble/**init**.py:13-135](file://backend/modelscope_studio/components/antdx/bubble/__init__.py#L13-L135) +- [backend/modelscope_studio/components/antdx/bubble/list/**init**.py:12-84](file://backend/modelscope_studio/components/antdx/bubble/list/__init__.py#L12-L84) +- [backend/modelscope_studio/components/antdx/conversations/**init**.py:11-109](file://backend/modelscope_studio/components/antdx/conversations/__init__.py#L11-L109) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) + +## Architecture Overview + +The diagram below shows the organization and dependency relationships of Antdx components at the Python layer: + +```mermaid +graph TB +subgraph "Antdx Components" +B1["AntdXBubble"] +B2["AntdXBubbleList"] +B3["AntdXBubbleListItem"] +B4["AntdXBubbleListRole"] +C1["AntdXConversations"] +C2["AntdXConversationsItem"] +P1["AntdXPrompts"] +P2["AntdXPromptsItem"] +end +E1["Event Binding
EventListener"] +S1["Slot Definition
SLOTS"] +B1 --> B2 +B2 --> B3 +B2 --> B4 +C1 --> C2 +P1 --> P2 +B1 --- E1 +B2 --- E1 +B3 --- E1 +B4 --- E1 +C1 --- E1 +P1 --- E1 +B1 --- S1 +B2 --- S1 +B3 --- S1 +B4 --- S1 +C1 --- S1 +P1 --- S1 +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/bubble/**init**.py:21-54](file://backend/modelscope_studio/components/antdx/bubble/__init__.py#L21-L54) +- [backend/modelscope_studio/components/antdx/bubble/list/**init**.py:19-30](file://backend/modelscope_studio/components/antdx/bubble/list/__init__.py#L19-L30) +- [backend/modelscope_studio/components/antdx/bubble/list/item/**init**.py:14-47](file://backend/modelscope_studio/components/antdx/bubble/list/item/__init__.py#L14-L47) +- [backend/modelscope_studio/components/antdx/bubble/list/role/**init**.py:14-46](file://backend/modelscope_studio/components/antdx/bubble/list/role/__init__.py#L14-L46) +- [backend/modelscope_studio/components/antdx/conversations/**init**.py:18-47](file://backend/modelscope_studio/components/antdx/conversations/__init__.py#L18-L47) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-26](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L26) + +## Detailed Component Analysis + +### Bubble Component + +- Component Purpose: Used to render a single conversation bubble, supports multiple appearance variants, shapes, typing animation, editability, avatar, header/footer, extra area, loading, and custom content rendering. +- Key Properties (constructor parameters) + - content: Bubble content text + - avatar: Avatar URL or placeholder + - extra: Additional elements + - footer/header: Footer/header content + - loading: Whether to show loading state + - placement: Alignment position (start/end) + - editable: Whether editable (boolean or dict) + - shape: Bubble shape (round/corner/default) + - typing: Typing animation (bool/dict/string) + - streaming: Streaming render toggle + - variant: Appearance variant (filled/borderless/outlined/shadow) + - footer_placement: Footer position (outside/inside-start/end) + - loading_render/content_render: Custom loading and content rendering + - class_names/styles/root_class_name: Style and class name control + - Other general properties: visible, elem_id, elem_classes, elem_style, render, etc. +- Events + - typing: Typing animation callback + - typing_complete: Typing complete callback; triggers immediately on render if typing is not set + - edit_confirm: Edit confirmation callback + - edit_cancel: Edit cancellation callback +- Slots + - avatar, editable.okText, editable.cancelText, content, footer, header, extra, loadingRender, contentRender +- Nested Sub-components + - List: Message list container + - System: System message bubble + - Divider: Divider line + +Section Sources + +- [backend/modelscope_studio/components/antdx/bubble/**init**.py:56-116](file://backend/modelscope_studio/components/antdx/bubble/__init__.py#L56-L116) +- [backend/modelscope_studio/components/antdx/bubble/**init**.py:21-54](file://backend/modelscope_studio/components/antdx/bubble/__init__.py#L21-L54) + +### BubbleList Component + +- Component Purpose: Message list container, responsible for scrolling, role grouping, and item rendering, supports auto-scroll and role configuration. +- Key Properties + - items: Message item array (dict) + - role: Role configuration (dict) + - auto_scroll: Whether to auto-scroll to the bottom + - class_names/styles/root_class_name: Style and class name control + - Other general properties: visible, elem_id, elem_classes, elem_style, render, etc. +- Events + - scroll: List scroll callback +- Slots + - items, role +- Nested Sub-components + - Item: Message item + - Role: Role identifier + +Section Sources + +- [backend/modelscope_studio/components/antdx/bubble/list/**init**.py:32-64](file://backend/modelscope_studio/components/antdx/bubble/list/__init__.py#L32-L64) +- [backend/modelscope_studio/components/antdx/bubble/list/**init**.py:19-30](file://backend/modelscope_studio/components/antdx/bubble/list/__init__.py#L19-L30) + +### BubbleListItem Component + +- Component Purpose: A single item in the message list, behaves essentially the same as Bubble but used as a list item. +- Key Properties + - content, avatar, extra, footer, header, loading, placement, editable, shape, typing, streaming, variant, footer_placement, loading_render, content_render, class_names/styles/root_class_name, etc. +- Events + - typing, typing_complete, edit_confirm, edit_cancel +- Slots + - avatar, editable.okText, editable.cancelText, content, footer, header, extra, loadingRender, contentRender + +Section Sources + +- [backend/modelscope_studio/components/antdx/bubble/list/item/**init**.py:49-108](file://backend/modelscope_studio/components/antdx/bubble/list/item/__init__.py#L49-L108) +- [backend/modelscope_studio/components/antdx/bubble/list/item/**init**.py:14-47](file://backend/modelscope_studio/components/antdx/bubble/list/item/__init__.py#L14-L47) + +### BubbleListRole Component + +- Component Purpose: Used to identify roles in lists, supports role avatar, header/footer, extra area, loading, and custom content rendering. +- Key Properties + - role: Role identifier text + - avatar, extra, footer, header, loading, placement, editable, shape, typing, streaming, variant, footer_placement, loading_render, content_render, class_names/styles/root_class_name, etc. +- Events + - typing, typing_complete, edit_confirm, edit_cancel +- Slots + - avatar, editable.okText, editable.cancelText, footer, header, extra, loadingRender, contentRender + +Section Sources + +- [backend/modelscope_studio/components/antdx/bubble/list/role/**init**.py:48-107](file://backend/modelscope_studio/components/antdx/bubble/list/role/__init__.py#L48-L107) +- [backend/modelscope_studio/components/antdx/bubble/list/role/**init**.py:14-46](file://backend/modelscope_studio/components/antdx/bubble/list/role/__init__.py#L14-L46) + +### Conversations Component + +- Component Purpose: For managing and viewing conversation lists, supports selection state toggling, menu operations, grouping, keyboard shortcuts, and creation buttons. +- Key Properties + - active_key/default_active_key: Current active item key + - items: Conversation item array (dict) + - menu: Menu configuration (string or dict) + - groupable: Whether groupable (boolean or dict) + - shortcut_keys: Keyboard shortcut mappings + - creation: Create button configuration (dict) + - styles/class_names/root_class_name: Style and class name control + - Other general properties: visible, elem_id, elem_classes, elem_style, render, etc. +- Events + - active_change: Selection change callback + - menu_click/menu_deselect/menu_open_change/menu_select: Menu-related callbacks + - groupable_expand: Group expand callback + - creation_click: Create button click callback +- Slots + - menu.expandIcon, menu.overflowedIndicator, menu.trigger, groupable.label, items, creation.icon, creation.label +- Nested Sub-components + - Item: Conversation item + +Section Sources + +- [backend/modelscope_studio/components/antdx/conversations/**init**.py:49-89](file://backend/modelscope_studio/components/antdx/conversations/__init__.py#L49-L89) +- [backend/modelscope_studio/components/antdx/conversations/**init**.py:18-47](file://backend/modelscope_studio/components/antdx/conversations/__init__.py#L18-L47) + +### ConversationsItem Component + +- Component Purpose: A single item in the conversation list, supports label, icon, type, group, disabled, dashed, etc. +- Key Properties + - label: Label text + - key: Unique key + - type: Type (e.g., divider) + - group: Belonging group + - icon: Icon + - disabled: Whether disabled + - dashed: Whether dashed + - additional_props/as_item/\_internal: Internal and extension properties + - Other general properties: visible, elem_id, elem_classes, elem_style, render, etc. + +Section Sources + +- [backend/modelscope_studio/components/antdx/conversations/item/**init**.py:21-55](file://backend/modelscope_studio/components/antdx/conversations/item/__init__.py#L21-L55) + +### Prompts Component + +- Component Purpose: For displaying preset prompts, supports title, vertical arrangement, fade-in effect, line wrapping, etc. +- Key Properties + - items: Prompt item array (dict) + - prefix_cls: Prefix class name + - title: Title + - vertical: Whether vertically arranged + - fade_in/fade_in_left: Fade-in effect (left/right) + - wrap: Whether to wrap + - styles/class_names/root_class_name: Style and class name control + - Other general properties: visible, elem_id, elem_classes, elem_style, render, etc. +- Events + - item_click: Prompt item click callback +- Slots + - title, items +- Nested Sub-components + - Item: Prompt item + +Section Sources + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:28-68](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L28-L68) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-26](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L26) + +### PromptsItem Component + +- Component Purpose: A single item in the prompt list, supports label, description, icon, disabled, and key. +- Key Properties + - label: Label text + - key: Unique key + - description: Description text + - icon: Icon + - disabled: Whether disabled + - additional_props/as_item/\_internal: Internal and extension properties + - Other general properties: visible, elem_id, elem_classes, elem_style, render, etc. + +Section Sources + +- [backend/modelscope_studio/components/antdx/prompts/item/**init**.py:18-48](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py#L18-L48) + +## Dependency Analysis + +- Component Export: All antdx components are centrally exported through `components.py` for unified import and use. +- Component Hierarchy: The Bubble family (Bubble, BubbleList, BubbleListItem, BubbleListRole) forms a complete message rendering chain; the Conversations family and Prompts family handle conversation management and prompt management respectively. +- Events and Slots: Each component defines EVENTS and SLOTS lists to declare supported event callbacks and slot names, ensuring consistency between frontend and backend conventions. + +```mermaid +graph LR +A["components.py Export"] --> B["Bubble Family"] +A --> C["Conversations Family"] +A --> D["Prompts Family"] +B --> B1["Bubble"] +B --> B2["BubbleList"] +B2 --> B3["BubbleListItem"] +B2 --> B4["BubbleListRole"] +C --> C1["Conversations"] +C1 --> C2["ConversationsItem"] +D --> D1["Prompts"] +D1 --> D2["PromptsItem"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +Section Sources + +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Performance Considerations + +- Streaming Rendering and Typing Animation: Use streaming and typing parameters wisely to avoid stuttering when rendering large numbers of messages simultaneously. +- Auto-scroll: It is recommended to enable auto_scroll in BubbleList when messages are frequently updated to maintain the best user experience. +- Slots and Custom Rendering: Although loadingRender and contentRender are flexible, avoid heavy computations in rendering functions; cache results when necessary. +- Event Binding: Only enable relevant event bindings when needed (e.g., typing_complete) to reduce unnecessary callback overhead. +- Appearance and Shape: variant and shape affect rendering complexity; choose based on actual needs. + +## Troubleshooting Guide + +- Events Not Triggering + - Check that the binding names in EVENTS are correct, and confirm that the frontend has the corresponding `bind_*` events enabled. + - Confirm whether the visible and render states of the component affect event propagation. +- Slot Content Not Displaying + - Confirm that the slot name spelling matches the SLOTS list. + - Check whether the slot scope matches the slot content passed from the parent component. +- Style Issues + - Use class_names/styles/root_class_name for local overrides to avoid global style conflicts. +- Scroll Problems + - BubbleList's auto_scroll is related to the external container height setting; check container height and overflow settings. +- Typing Animation Not Working + - Confirm the type and value range of the typing parameter; avoid passing unsupported types. + +## Conclusion + +Antdx general components provide complete capabilities from message rendering and list management to conversation and prompt management. Through unified event and slot conventions, developers can quickly build conversational systems and prompt panels, and achieve high-performance, maintainable frontend experiences by combining style and interaction configurations. + +## Appendix + +### Typical Scenarios and Instantiation Paths + +- Conversation Bubble Basic Rendering and Typing Animation + - Reference path: [docs/components/antdx/bubble/README-zh_CN.md:7-12](file://docs/components/antdx/bubble/README-zh_CN.md#L7-L12) +- Message List and Auto-scroll + - Reference path: [docs/components/antdx/bubble/README-zh_CN.md:10-12](file://docs/components/antdx/bubble/README-zh_CN.md#L10-L12) +- Conversation List and Menu Operations + - Reference path: [docs/components/antdx/conversations/README-zh_CN.md:7-9](file://docs/components/antdx/conversations/README-zh_CN.md#L7-L9) +- Prompt Panel and Nested Usage + - Reference path: [docs/components/antdx/prompts/README-zh_CN.md:7-8](file://docs/components/antdx/prompts/README-zh_CN.md#L7-L8) + +### Data Formats and Field Descriptions (Summary) + +- Bubble/BubbleListItem/BubbleListRole + - content, avatar, extra, footer, header, loading, placement, editable, shape, typing, streaming, variant, footer_placement, loading_render, content_render, class_names, styles, root_class_name +- BubbleList + - items, role, auto_scroll, class_names, styles, root_class_name +- Conversations + - active_key, default_active_key, items, menu, groupable, shortcut_keys, creation, styles, class_names, root_class_name +- ConversationsItem + - label, key, type, group, icon, disabled, dashed, additional_props, as_item, \_internal +- Prompts + - items, prefix_cls, title, vertical, fade_in, fade_in_left, wrap, styles, class_names, root_class_name +- PromptsItem + - label, key, description, icon, disabled, additional_props, as_item, \_internal diff --git a/.wiki/en/API Reference/Python API/Antdx Components API/Utility Components API.md b/.wiki/en/API Reference/Python API/Antdx Components API/Utility Components API.md new file mode 100644 index 00000000..83a58798 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antdx Components API/Utility Components API.md @@ -0,0 +1,399 @@ +# Utility Components API + + +**Files Referenced in This Document** +- [components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [code_highlighter/__init__.py](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py) +- [file_card/__init__.py](file://backend/modelscope_studio/components/antdx/file_card/__init__.py) +- [folder/__init__.py](file://backend/modelscope_studio/components/antdx/folder/__init__.py) +- [mermaid/__init__.py](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py) +- [sources/__init__.py](file://backend/modelscope_studio/components/antdx/sources/__init__.py) +- [think/__init__.py](file://backend/modelscope_studio/components/antdx/think/__init__.py) +- [x_provider/__init__.py](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document is the Python API reference for Antdx utility components, covering the complete API specifications and usage instructions for the following components: + +- CodeHighlighter: Code syntax highlighting +- FileCard: File card display (with List sub-component) +- Folder: Folder tree structure (with directory icon and tree node sub-components) +- Mermaid: Diagram rendering +- Sources: Source reference management (with item sub-component) +- Think: Thought annotation +- XProvider: Global configuration container + +The document systematically covers constructor parameters, property definitions, events and slots, data processing and formatting options, style and class name customization, as well as performance and rendering strategies, and provides standard usage examples and extension recommendations. + +## Project Structure + +Antdx components reside in the backend Python package, wrapped through a unified layout component base class for frontend components, with exported aliases for direct use. The core entry is in antdx's `__init__.py`, and `components.py` handles aggregated exports. + +```mermaid +graph TB +A["backend/modelscope_studio/components/antdx/components.py"] --> B["backend/modelscope_studio/components/antdx/__init__.py"] +B --> C1["CodeHighlighter"] +B --> C2["FileCard"] +B --> C3["Folder"] +B --> C4["Mermaid"] +B --> C5["Sources"] +B --> C6["Think"] +B --> C7["XProvider"] +``` + +Diagram Sources + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [**init**.py:14-41](file://backend/modelscope_studio/components/antdx/__init__.py#L14-L41) + +Section Sources + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [**init**.py:14-41](file://backend/modelscope_studio/components/antdx/__init__.py#L14-L41) + +## Core Components + +This section provides an overview of the responsibilities and general features of each component: + +- All inherit from the unified layout component base class, with general properties for visibility, element ID, class names, inline styles, and render toggle. +- Most components declare supported slots (SLOTS) and events (EVENTS) for frontend rendering and interaction binding. +- Most components set skip_api to True, indicating they do not participate in standard API serialization and are rendered directly by the frontend. + +Section Sources + +- [code_highlighter/**init**.py:6-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L6-L71) +- [file_card/**init**.py:11-112](file://backend/modelscope_studio/components/antdx/file_card/__init__.py#L11-L112) +- [folder/**init**.py:12-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L12-L114) +- [mermaid/**init**.py:8-77](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L8-L77) +- [sources/**init**.py:11-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L11-L92) +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [x_provider/**init**.py:10-101](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L10-L101) + +## Architecture Overview + +The diagram below shows the encapsulation relationship and export paths of Python layer to frontend components: + +```mermaid +classDiagram +class AntdXCodeHighlighter { ++Constructor Parameters : value, lang, header, highlight_props, prism_light_mode, styles, class_names, additional_props, root_class_name, as_item, visible, elem_id, elem_classes, elem_style, render ++Properties : SLOTS, EVENTS, skip_api ++Methods : preprocess(), postprocess(), example_payload(), example_value() +} +class AntdXFileCard { ++Constructor Parameters : image_props, filename, byte, size, description, loading, type, src, mask, icon, video_props, audio_props, spin_props, styles, class_names, additional_props, as_item, visible, elem_id, elem_classes, elem_style, render ++Properties : SLOTS, EVENTS(List), skip_api ++Methods : preprocess(), postprocess(), example_payload(), example_value() +} +class AntdXFolder { ++Constructor Parameters : tree_data, selectable, selected_file, default_selected_file, directory_tree_width, empty_render, preview_render, expanded_paths, default_expanded_paths, default_expand_all, directory_title, preview_title, directory_icons, styles, class_names, additional_props, as_item, visible, elem_id, elem_classes, elem_style, render ++Properties : SLOTS, EVENTS, TreeNode, DirectoryIcon, skip_api ++Methods : preprocess(), postprocess(), example_payload(), example_value() +} +class AntdXMermaid { ++Constructor Parameters : value, highlight_props, config, actions, prefix_cls, styles, class_names, additional_props, root_class_name, as_item, visible, elem_id, elem_classes, elem_style, render ++Properties : SLOTS, EVENTS, skip_api ++Methods : preprocess(), postprocess(), example_payload(), example_value() +} +class AntdXSources { ++Constructor Parameters : title, items, expand_icon_position, default_expanded, expanded, inline, active_key, popover_overlay_width, styles, class_names, additional_props, as_item, visible, elem_id, elem_classes, elem_style, render ++Properties : SLOTS, EVENTS(Item), skip_api ++Methods : preprocess(), postprocess(), example_payload(), example_value() +} +class AntdXThink { ++Constructor Parameters : icon, styles, class_names, loading, title, root_class_name, default_expanded, expanded, blink, as_item, visible, elem_id, elem_classes, elem_style, render ++Properties : SLOTS, EVENTS, skip_api ++Methods : preprocess(), postprocess(), example_payload(), example_value() +} +class AntdXXProvider { ++Constructor Parameters : component_disabled, component_size, csp, direction, get_popup_container, get_target_container, icon_prefix_cls, locale, popup_match_select_width, popup_overflow, prefix_cls, render_empty, theme, theme_config, variant, virtual, warning, styles, class_names, additional_props, as_item, visible, elem_id, elem_classes, elem_style, render ++Properties : SLOTS, EVENTS, skip_api ++Methods : preprocess(), postprocess(), example_payload(), example_value() +} +``` + +Diagram Sources + +- [code_highlighter/**init**.py:6-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L6-L71) +- [file_card/**init**.py:11-112](file://backend/modelscope_studio/components/antdx/file_card/__init__.py#L11-L112) +- [folder/**init**.py:12-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L12-L114) +- [mermaid/**init**.py:8-77](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L8-L77) +- [sources/**init**.py:11-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L11-L92) +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [x_provider/**init**.py:10-101](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L10-L101) + +## Detailed Component Analysis + +### CodeHighlighter (Code Syntax Highlighting) + +- Component Purpose: For highlighting code snippets, supports language and theme mode configurations. +- Key Parameters + - value: Code string to highlight + - lang: Language identifier + - header: Title or boolean control + - highlight_props: Highlight-related configuration + - prism_light_mode: Light mode toggle + - styles/class_names/additional_props/root_class_name/as_item: Style and class names, additional properties, root class name, as item + - visible/elem_id/elem_classes/elem_style/render: General layout properties +- Slots: header +- Events: None +- Data Processing: skip_api is True, not participating in standard API; preprocess/postprocess return original value +- Performance: Direct frontend rendering, avoids extra serialization overhead + +Section Sources + +- [code_highlighter/**init**.py:6-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L6-L71) + +### FileCard (File Card) + +- Component Purpose: Displays file information, supports multiple types including image, audio, video, and ordinary files, configurable size, loading state, mask, and media properties. +- Key Parameters + - image_props: Image preview related properties + - filename: File name + - byte: Byte count + - size: Size small/default + - description: Description text + - loading: Whether to show loading state + - type: Type image/file/audio/video or custom string + - src: Resource URL (supports string or dict containing path/url) + - mask: Mask text + - icon: Built-in icon category or custom string + - video_props/audio_props/spin_props: Video/audio/loading indicator configurations + - styles/class_names/additional_props/as_item/visible/elem_id/elem_classes/elem_style/render: General layout properties +- Slots: imageProps.placeholder, imageProps.preview.mask, imageProps.preview.closeIcon, imageProps.preview.toolbarRender, imageProps.preview.imageRender, description, icon, mask, spinProps.icon, spinProps.description, spinProps.indicator +- Events: click (bound to internal event) +- Data Processing: skip_api is True; preprocess/postprocess return original value; src supports static file service wrapping +- Performance: Direct frontend rendering; src field automatically handles static resource paths + +Section Sources + +- [file_card/**init**.py:11-112](file://backend/modelscope_studio/components/antdx/file_card/__init__.py#L11-L112) + +### Folder (Folder Tree Structure) + +- Component Purpose: Displays folder tree and selection/expansion behavior, supports preview rendering, empty state rendering, directory icons, etc. +- Key Parameters + - tree_data: Tree data + - selectable: Whether selectable + - selected_file/default_selected_file: Selected file list + - directory_tree_width: Directory tree width + - empty_render/preview_render: Empty state and preview rendering + - expanded_paths/default_expanded_paths/default_expand_all: Expansion path control + - directory_title/preview_title: Titles + - directory_icons: Directory icon mappings + - styles/class_names/additional_props/root_class_name/as_item/visible/elem_id/elem_classes/elem_style/render: General layout properties +- Sub-components: TreeNode, DirectoryIcon +- Slots: emptyRender, previewRender, directoryTitle, previewTitle, treeData, directoryIcons +- Events: file_click, folder_click, selected_file_change, expanded_paths_change, file_content_service_load_file_content (bound to internal events) +- Data Processing: skip_api is True; preprocess/postprocess return original value +- Performance: Direct frontend rendering; supports default expand all + +Section Sources + +- [folder/**init**.py:12-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L12-L114) + +### Mermaid (Diagram Rendering) + +- Component Purpose: Renders diagrams based on Mermaid syntax, supports highlight configuration, theme configuration, and custom actions. +- Key Parameters + - value: Mermaid text + - highlight_props: Highlight configuration + - config: Global configuration + - actions: Custom actions + - prefix_cls: Prefix class name + - styles/class_names/additional_props/root_class_name/as_item/visible/elem_id/elem_classes/elem_style/render: General layout properties +- Slots: header, actions.customActions +- Events: render_type_change (bound to internal event) +- Data Processing: skip_api is True; preprocess/postprocess return original value +- Performance: Direct frontend rendering + +Section Sources + +- [mermaid/**init**.py:8-77](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L8-L77) + +### Sources (Source Reference Management) + +- Component Purpose: Manages source reference entries in a collapsible panel form, supports expansion position, active key, popover width, etc. +- Key Parameters + - title: Title + - items: Entry list + - expand_icon_position: Expansion icon position start/end + - default_expanded/expanded: Default/current expanded state + - inline: Whether inline + - active_key: Active key + - popover_overlay_width: Popover width + - styles/class_names/additional_props/root_class_name/as_item/visible/elem_id/elem_classes/elem_style/render: General layout properties +- Sub-components: Item +- Slots: items +- Events: expand, click (bound to internal events) +- Data Processing: skip_api is True; preprocess/postprocess return original value +- Performance: Direct frontend rendering + +Section Sources + +- [sources/**init**.py:11-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L11-L92) + +### Think (Thought Annotation) + +- Component Purpose: Used to display thought processes or prompt information, supports loading state, title, blink, etc. +- Key Parameters + - icon: Icon + - styles/class_names/additional_props/root_class_name/as_item/visible/elem_id/elem_classes/elem_style/render: General layout properties + - loading: Loading state (string or boolean) + - title: Title + - default_expanded/expanded: Default/current expanded state + - blink: Blink toggle +- Slots: loading, icon, title +- Events: expand (bound to internal event) +- Data Processing: skip_api is True; preprocess/postprocess return original value +- Performance: Direct frontend rendering + +Section Sources + +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) + +### XProvider (Global Configuration) + +- Component Purpose: Global configuration container, passes theme, language, direction, variant, and other configurations to the sub-component tree. +- Key Parameters + - component_disabled: Disable component + - component_size: Component size small/middle/large + - csp: Content Security Policy + - direction: Direction ltr/rtl + - get_popup_container/get_target_container: Popup container selector + - icon_prefix_cls: Icon prefix class name + - locale: Locale environment + - popup_match_select_width: Popup matches select width + - popup_overflow: Popup overflow strategy viewport/scroll + - prefix_cls: Component prefix class name + - render_empty: Empty state rendering + - theme/theme_config: Theme and theme configuration (conflict warning exists) + - variant: Appearance outlined/filled/borderless + - virtual: Virtualization + - warning: Warning configuration + - styles/class_names/additional_props/as_item/visible/elem_id/elem_classes/elem_style/render: General layout properties +- Slots: renderEmpty +- Events: None +- Data Processing: skip_api is True; preprocess/postprocess return original value +- Performance: Direct frontend rendering; note the conflict warning between theme and theme_config + +Section Sources + +- [x_provider/**init**.py:10-101](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L10-L101) + +## Dependency Analysis + +- Export Relationships: `components.py` aggregates imports from all component modules under antdx; `__init__.py` exports component classes as user-friendly aliases. +- Component Relationships: Some components provide sub-components (e.g., FileCard.List, Folder.TreeNode/Folder.DirectoryIcon, Sources.Item, Think, etc.) for composing complex UIs. +- Event Binding: Most components update internal state flags through event listener callbacks, thereby triggering frontend event binding. + +```mermaid +graph LR +subgraph "Export Layer" +E1["components.py"] --> E2["__init__.py"] +end +subgraph "Component Layer" +F1["code_highlighter/__init__.py"] +F2["file_card/__init__.py"] +F3["folder/__init__.py"] +F4["mermaid/__init__.py"] +F5["sources/__init__.py"] +F6["think/__init__.py"] +F7["x_provider/__init__.py"] +end +E2 --> F1 +E2 --> F2 +E2 --> F3 +E2 --> F4 +E2 --> F5 +E2 --> F6 +E2 --> F7 +``` + +Diagram Sources + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [**init**.py:14-41](file://backend/modelscope_studio/components/antdx/__init__.py#L14-L41) + +Section Sources + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [**init**.py:14-41](file://backend/modelscope_studio/components/antdx/__init__.py#L14-L41) + +## Performance Considerations + +- Skip API Serialization: All components set skip_api to True, avoiding unnecessary Python-to-frontend data round trips and improving rendering efficiency. +- Direct Frontend Connection: Components point to frontend component directories via `resolve_frontend_dir`, reducing intermediate layer conversion costs. +- Static Resources: FileCard wraps src with static file service, reducing resource access latency. +- Default Expand All: Folder supports `default_expand_all`, which can expand everything at initialization to reduce user interaction steps. +- Theme and Variants: XProvider provides unified theme and appearance configuration, avoiding repeated computations and style switching overhead. + +## Troubleshooting Guide + +- Component Not Working + - Check whether visible and render are True + - Confirm that elem_id/elem_classes/elem_style are correctly passed in +- File Resources Cannot Load + - When FileCard's src is a dict, ensure it contains path or url; use static file service wrapping if necessary +- Events Not Triggering + - Confirm that event listener names match the EVENTS definitions of the component + - Check whether the frontend correctly binds the internal event flag +- Theme Conflicts + - The theme property in XProvider conflicts with Gradio presets; use theme_config instead +- Rendering Issues + - Slot content for Mermaid/CodeHighlighter/Sources/Think must be provided according to specifications to avoid frontend parsing errors + +Section Sources + +- [file_card/**init**.py:87-93](file://backend/modelscope_studio/components/antdx/file_card/__init__.py#L87-L93) +- [x_provider/**init**.py:74-78](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L74-L78) + +## Conclusion + +Antdx utility components provide a concise and powerful Python API through the unified layout component base class and direct frontend rendering strategy. Each component is organized around the pattern of "parameter-driven + slots + event binding", meeting common scenarios (code highlighting, file display, tree navigation, diagrams, source references, thought annotation, global configuration) while leaving ample room for extension and customization. In practice, it is recommended to prioritize using the sub-components and slots provided by each component, use XProvider for global style and theme management, and follow the best practices for static resources and event binding. + +## Appendix: Usage Examples and Best Practices + +- Code Highlighting + - Scenario: Display code snippets in conversations or documents + - Recommendations: Specify lang and highlight_props; enable prism_light_mode if necessary + - Reference path: [code_highlighter/**init**.py:15-52](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L15-L52) +- File Card + - Scenario: Upload or browse file lists + - Recommendations: Set icon based on type; wrap src with static file service; set size and loading appropriately + - Reference path: [file_card/**init**.py:32-94](file://backend/modelscope_studio/components/antdx/file_card/__init__.py#L32-L94) +- Folder Tree + - Scenario: File browsing and selection + - Recommendations: Keep tree_data structure clear; enable default_expand_all only with manageable data volume; use directory_icons for custom icons + - Reference path: [folder/**init**.py:43-96](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L43-L96) +- Diagram + - Scenario: Visualize algorithms or business processes + - Recommendations: Use standard Mermaid syntax for value; configure config and actions as needed + - Reference path: [mermaid/**init**.py:21-58](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L21-L58) +- Source References + - Scenario: Display reference sources and entries + - Recommendations: Standardize items structure; choose inline and expand_icon_position based on interface style + - Reference path: [sources/**init**.py:30-73](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L30-L73) +- Thought Annotation + - Scenario: Prompt users to focus on key points or loading state + - Recommendations: Express intent clearly with title and icon; use blink only for emphasis + - Reference path: [think/**init**.py:21-60](file://backend/modelscope_studio/components/antdx/think/__init__.py#L21-L60) +- Global Configuration + - Scenario: Unify theme, language, direction, and appearance + - Recommendations: Prefer theme_config; configure locale and direction by region; maintain consistency between prefix_cls and icon_prefix_cls + - Reference path: [x_provider/**init**.py:19-82](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L19-L82) diff --git a/.wiki/en/API Reference/Python API/Antdx Components API/Wake Components API.md b/.wiki/en/API Reference/Python API/Antdx Components API/Wake Components API.md new file mode 100644 index 00000000..fb4cbc6e --- /dev/null +++ b/.wiki/en/API Reference/Python API/Antdx Components API/Wake Components API.md @@ -0,0 +1,334 @@ +# Wake Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/welcome/__init__.py](file://backend/modelscope_studio/components/antdx/welcome/__init__.py) +- [backend/modelscope_studio/components/antdx/prompts/__init__.py](file://backend/modelscope_studio/components/antdx/prompts/__init__.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) +- [docs/components/antdx/welcome/app.py](file://docs/components/antdx/welcome/app.py) +- [docs/components/antdx/prompts/app.py](file://docs/components/antdx/prompts/app.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for Antdx wake components, focusing on the following goals: + +- Document the welcome interface display, welcome message configuration, and user guidance flow of the Welcome component +- Explain the prompt set management, prompt template definition, and dynamic prompt generation mechanisms of the Prompts component +- Provide the message format, personalization configuration options, and multilingual support descriptions for the Welcome component +- Give standard usage examples for AI assistant startup, user guidance, and prompt activation scenarios +- Explain initialization parameters, callback function configurations, and user experience optimization strategies +- Describe integration approaches with conversational systems and state synchronization mechanisms + +## Project Structure + +Antdx components reside in the backend Python package, bridged through a unified layout component base class and frontend directory resolution mechanism. Both Welcome and Prompts components inherit from the general layout component base class and point to the corresponding frontend component directory via `resolve_frontend_dir`. + +```mermaid +graph TB +subgraph "Python Backend" +A["ModelScopeLayoutComponent
Component Base Class"] +B["AntdXWelcome
Welcome Component"] +C["AntdXPrompts
Prompts Component"] +D["AntdXPromptsItem
Prompt Item Component"] +E["resolve_frontend_dir
Frontend Directory Resolver"] +end +subgraph "Frontend Components" +F["welcome component directory"] +G["prompts component directory"] +H["prompts/item sub-component directory"] +end +A --> B +A --> C +C --> D +E --> F +E --> G +E --> H +B -.-> F +C -.-> G +D -.-> H +``` + +Diagram Sources + +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:55-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L55-L55) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:70-70](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L70-L70) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-16](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L16) + +Section Sources + +- [backend/modelscope_studio/components/antdx/components.py:24-39](file://backend/modelscope_studio/components/antdx/components.py#L24-L39) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) + +## Core Components + +- AntdXWelcome: For rendering a welcome interface, supports slot-based configuration for title, description, icon, extra content, and style and variant control. +- AntdXPrompts: For displaying a set of prompt word cards, supports title, vertical arrangement, fade-in animation, line wrapping, and other configurations; includes an item_click callback event to respond to click behavior. + +Section Sources + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) + +## Architecture Overview + +Antdx components connect to the corresponding frontend component directory through a unified layout component base class and frontend directory resolver. Components set the frontend directory path during initialization and participate in layout updates and internal state passing through Gradio's BlockContext mechanism. + +```mermaid +sequenceDiagram +participant Py as "Python Component" +participant Base as "ModelScopeLayoutComponent" +participant Resolver as "resolve_frontend_dir" +participant FE as "Frontend Component Directory" +Py->>Base : Initialize component, set visibility/element properties +Py->>Resolver : Resolve frontend directory component name/sub-component/type +Resolver-->>Py : Return relative path +Py->>FE : Load corresponding frontend component resources +Py->>Base : Enter context to trigger layout update +``` + +Diagram Sources + +- [backend/modelscope_studio/utils/dev/component.py:24-26](file://backend/modelscope_studio/utils/dev/component.py#L24-L26) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-16](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L16) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:55-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L55-L55) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:70-70](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L70-L70) + +## Detailed Component Analysis + +### Welcome Component API + +- Component: AntdXWelcome +- Inheritance: ModelScopeLayoutComponent +- Slot Support: extra, icon, description, title +- Key Parameters + - extra: Extra content (string or None) + - icon: Icon resource path (processed through static file service) + - description: Description text + - title: Title text + - variant: Appearance variant (filled or borderless) + - styles/class_names/root_class_name: Style and class name configuration + - Element properties: elem_id, elem_classes, elem_style, visible, render, etc. +- Lifecycle and Preprocessing + - preprocess/postprocess/example_payload/example_value all return empty values, indicating this component does not perform data conversion or example value generation +- Events + - No public event bindings (EVENTS is empty) + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__enter__() ++__exit__() ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdXWelcome { ++additional_props ++extra ++icon ++styles ++class_names ++description ++variant ++title ++root_class_name ++FRONTEND_DIR ++skip_api ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +ModelScopeLayoutComponent <|-- AntdXWelcome +``` + +Diagram Sources + +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) + +Section Sources + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:17-54](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L17-L54) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:57-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L57-L73) + +### Prompts Component API + +- Component: AntdXPrompts +- Inheritance: ModelScopeLayoutComponent +- Internal Items: AntdXPromptsItem (exposed via the Item property) +- Slot Support: title, items +- Key Parameters + - items: Prompt item list (list of dicts; specific fields are defined by the frontend convention) + - prefix_cls: Prefix class name (for style isolation) + - title: Prompt set title + - vertical: Whether to arrange vertically + - fade_in/fade_in_left: Fade-in animation toggles + - wrap: Whether to wrap + - styles/class_names/root_class_name/additional_props: Style and extension properties + - Element properties: elem_id, elem_classes, elem_style, visible, render, etc. +- Events + - item_click: Triggered when a prompt item is clicked; internally configured via `_internal.update(bind_itemClick_event=True)` for frontend event binding +- Lifecycle and Preprocessing + - preprocess/postprocess/example_payload/example_value all return empty values, indicating this component does not perform data conversion or example value generation + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__enter__() ++__exit__() ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdXPrompts { ++Item ++EVENTS ++SLOTS ++items ++prefix_cls ++title ++vertical ++fade_in ++fade_in_left ++wrap ++styles ++class_names ++root_class_name ++additional_props ++FRONTEND_DIR ++skip_api ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdXPromptsItem { ++... +} +ModelScopeLayoutComponent <|-- AntdXPrompts +AntdXPrompts o--> AntdXPromptsItem : "internal items" +``` + +Diagram Sources + +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) + +Section Sources + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-23](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L23) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:28-68](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L28-L68) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:72-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L72-L88) + +### Usage Examples and Best Practices + +- AI Assistant Startup and Welcome Page Display + - Render the Welcome component at application startup, set the title, description, and icon; add guidance buttons or action areas via the extra slot as needed + - Control appearance style via variant; achieve theme adaptation via styles/class_names/root_class_name +- User Guidance and Prompt Activation + - Use the Prompts component to display a set of prompt word cards, set title and items, and enable fade_in/fade_in_left for enhanced visual experience + - Monitor user selections via the item_click event; combined with the conversational system, inject the selected prompt into the input box or directly initiate a conversation +- Multilingual Support + - Title, description, and prompt text should come from localization resources; the text parameters of both Welcome and Prompts support string types, making it easy to replace with different language versions +- State Synchronization and Integration + - Components participate in layout updates via Gradio BlockContext; to integrate with a conversational system, trigger business logic in the item_click callback (e.g., write prompt content to the input field or send a request) and complete state rendering on the frontend + +Section Sources + +- [docs/components/antdx/welcome/app.py:1-7](file://docs/components/antdx/welcome/app.py#L1-L7) +- [docs/components/antdx/prompts/app.py:1-7](file://docs/components/antdx/prompts/app.py#L1-L7) + +## Dependency Analysis + +- Component Exports + - `antdx/__init__.py` exports Welcome and Prompts as aliases for easy named imports from outside + - `antdx/components.py` aggregates all sub-modules to ensure the complete import chain +- Base Class and Utilities + - ModelScopeLayoutComponent provides unified layout component capabilities and lifecycle hooks + - `resolve_frontend_dir` maps component names to frontend directories, supporting sub-components and multi-level directory concatenation + +```mermaid +graph LR +A["antdx/__init__.py"] --> B["Welcome Export"] +A --> C["Prompts Export"] +D["antdx/components.py"] --> E["Aggregated Import"] +E --> B +E --> C +F["utils/dev/component.py"] --> G["ModelScopeLayoutComponent"] +H["utils/dev/resolve_frontend_dir.py"] --> I["Frontend Directory Resolution"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:24-39](file://backend/modelscope_studio/components/antdx/components.py#L24-L39) +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-16](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L16) + +Section Sources + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:24-39](file://backend/modelscope_studio/components/antdx/components.py#L24-L39) + +## Performance Considerations + +- Component Skips API: Both components have skip_api returning True, meaning no additional API interface layer will be generated, reducing server-side overhead +- Preprocessing and Postprocessing: preprocess/postprocess return empty values, avoiding unnecessary data conversions and contributing to low-latency rendering +- Animation and Layout: Prompts' fade-in and line-wrap options only affect frontend rendering; exercise caution when enabling animations with large numbers of prompt items to balance smoothness and performance + +## Troubleshooting Guide + +- Component Not Displaying + - Check whether visible and render parameters are correctly set + - Confirm that elem_id/elem_classes/elem_style are not causing style overrides +- Icon or Resource Cannot Load + - Confirm that the icon path has been processed via the static file service (serve_static_file) +- Events Not Triggering + - Confirm that the item_click event was bound during initialization (internally triggered via `_internal.update(bind_itemClick_event=True)`) +- Frontend Directory Resolution Failed + - Check whether the component name and type in `resolve_frontend_dir` match the actual frontend directory structure + +Section Sources + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:47-47](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L47-L47) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:20-22](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L20-L22) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-16](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L16) + +## Conclusion + +AntdXWelcome and AntdXPrompts achieve seamless connection with frontend components through the unified layout component base class and frontend directory resolution mechanism. Welcome focuses on the copywriting and style configuration of the welcome page, while Prompts specializes in the display and interaction of prompt sets. Both can integrate with conversational systems through Gradio's layout and event mechanisms to realize a complete user experience loop from "welcome guidance" to "prompt activation". + +## Appendix + +- Initialization Parameter Quick Reference + - Welcome: extra, icon, description, title, variant, styles, class_names, root_class_name, elem_id, elem_classes, elem_style, visible, render + - Prompts: items, prefix_cls, title, vertical, fade_in, fade_in_left, wrap, styles, class_names, root_class_name, additional_props, elem_id, elem_classes, elem_style, visible, render +- Event Quick Reference + - Prompts: item_click (triggered when a prompt item is clicked) diff --git a/.wiki/en/API Reference/Python API/Basic Components API.md b/.wiki/en/API Reference/Python API/Basic Components API.md new file mode 100644 index 00000000..6ef5d075 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Basic Components API.md @@ -0,0 +1,495 @@ +# Basic Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/components/base/application/__init__.py](file://backend/modelscope_studio/components/base/application/__init__.py) +- [backend/modelscope_studio/components/base/auto_loading/__init__.py](file://backend/modelscope_studio/components/base/auto_loading/__init__.py) +- [backend/modelscope_studio/components/base/slot/__init__.py](file://backend/modelscope_studio/components/base/slot/__init__.py) +- [backend/modelscope_studio/components/base/each/__init__.py](file://backend/modelscope_studio/components/base/each/__init__.py) +- [backend/modelscope_studio/components/base/filter/__init__.py](file://backend/modelscope_studio/components/base/filter/__init__.py) +- [backend/modelscope_studio/components/base/fragment/__init__.py](file://backend/modelscope_studio/components/base/fragment/__init__.py) +- [backend/modelscope_studio/components/base/div/__init__.py](file://backend/modelscope_studio/components/base/div/__init__.py) +- [backend/modelscope_studio/components/base/text/__init__.py](file://backend/modelscope_studio/components/base/text/__init__.py) +- [backend/modelscope_studio/components/base/span/__init__.py](file://backend/modelscope_studio/components/base/span/__init__.py) +- [backend/modelscope_studio/components/base/markdown/__init__.py](file://backend/modelscope_studio/components/base/markdown/__init__.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/app_context.py](file://backend/modelscope_studio/utils/dev/app_context.py) +- [docs/components/base/application/README.md](file://docs/components/base/application/README.md) +- [docs/components/base/each/README.md](file://docs/components/base/each/README.md) +- [docs/components/base/slot/README.md](file://docs/components/base/slot/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document is the Python API reference for the base component library, covering core components under `modelscope_studio.components.base.*`, including Application, AutoLoading, Slot, Each, Filter, Fragment, Layout components (represented by common layout components such as Div/Span/Markdown), Text, and others. The documentation is organized based on the repository source code and accompanying docs, focusing on: + +- Complete import paths and usage patterns +- Constructor parameters, property definitions, method signatures, and return types +- Component composition patterns (application containers, conditional rendering, list iteration) +- Lifecycle management, context passing, and slot system interfaces +- Performance optimization strategies, memory management, and error handling mechanisms +- Component inheritance patterns, extension development, and best practices + +## Project Structure + +Base components reside in the backend Python package `modelscope_studio/components/base`, aggregated through a unified export entry point; frontend resources are resolved by utility modules and bound to corresponding frontend directories. + +```mermaid +graph TB +subgraph "Python Backend" +BASE["backend/modelscope_studio/components/base/__init__.py"] +APP["application/__init__.py"] +AUTO["auto_loading/__init__.py"] +SLOT["slot/__init__.py"] +EACH["each/__init__.py"] +FILTER["filter/__init__.py"] +FRAG["fragment/__init__.py"] +DIV["div/__init__.py"] +TEXT["text/__init__.py"] +SPAN["span/__init__.py"] +MARK["markdown/__init__.py"] +DEV["utils/dev/component.py"] +CTX["utils/dev/app_context.py"] +end +BASE --> APP +BASE --> AUTO +BASE --> SLOT +BASE --> EACH +BASE --> FILTER +BASE --> FRAG +BASE --> DIV +BASE --> TEXT +BASE --> SPAN +BASE --> MARK +APP --> DEV +AUTO --> DEV +SLOT --> DEV +EACH --> DEV +FILTER --> DEV +FRAG --> DEV +DIV --> DEV +TEXT --> DEV +SPAN --> DEV +MARK --> DEV +APP --> CTX +DEV --> CTX +``` + +Diagram sources + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:8-65](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L8-L65) +- [backend/modelscope_studio/components/base/slot/**init**.py:8-50](file://backend/modelscope_studio/components/base/slot/__init__.py#L8-L50) +- [backend/modelscope_studio/components/base/each/**init**.py:17-73](file://backend/modelscope_studio/components/base/each/__init__.py#L17-L73) +- [backend/modelscope_studio/components/base/filter/**init**.py:8-45](file://backend/modelscope_studio/components/base/filter/__init__.py#L8-L45) +- [backend/modelscope_studio/components/base/fragment/**init**.py:8-49](file://backend/modelscope_studio/components/base/fragment/__init__.py#L8-L49) +- [backend/modelscope_studio/components/base/div/**init**.py:10-86](file://backend/modelscope_studio/components/base/div/__init__.py#L10-L86) +- [backend/modelscope_studio/components/base/text/**init**.py:8-57](file://backend/modelscope_studio/components/base/text/__init__.py#L8-L57) +- [backend/modelscope_studio/components/base/span/**init**.py:10-87](file://backend/modelscope_studio/components/base/span/__init__.py#L10-L87) +- [backend/modelscope_studio/components/base/markdown/**init**.py:11-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L11-L174) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) + +Section sources + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +## Core Components + +The following is an overview of import paths and key capabilities for each core base component (sorted alphabetically): + +- Application + - Import path: `from modelscope_studio.components.base import Application` + - Capabilities: Application root container; listens to page lifecycle events (mount, resize, unmount, custom); provides page environment data (screen size, language, theme, userAgent). + - Key notes: Must be used as the root container for all components; supports custom event bridging (`window.ms_globals.dispatch` → Python-side events). + +- AutoLoading + - Import path: `from modelscope_studio.components.base import AutoLoading` + - Capabilities: Auto-loading state wrapper; supports slots (render, errorRender, loadingText); controllable mask, timer, and error display. + +- Slot + - Import path: `from modelscope_studio.components.base import Slot` + - Capabilities: Slot placeholder component; used together with the target component's `SLOTS`; supports `params_mapping` for parameter mapping. + +- Each + - Import path: `from modelscope_studio.components.base import Each` + - Capabilities: List iteration rendering; injects context; supports `as_item` filtering and deep merge via `context_value`. + +- Filter + - Import path: `from modelscope_studio.components.base import Filter` + - Capabilities: Conditional filter component; determines whether to render a subtree based on parameter mapping. + +- Fragment + - Import path: `from modelscope_studio.components.base import Fragment` + - Capabilities: Grouping container; produces no additional DOM; suitable for logical grouping and slot mounting. + +- Div/Text/Span/Markdown + - Import path: `from modelscope_studio.components.base import Div, Text, Span, Markdown` + - Capabilities: Basic layout and text components; support additional properties, event binding, copy button, and other features. + +Section sources + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [docs/components/base/application/README.md:1-56](file://docs/components/base/application/README.md#L1-L56) +- [docs/components/base/each/README.md:1-32](file://docs/components/base/each/README.md#L1-L32) +- [docs/components/base/slot/README.md:1-17](file://docs/components/base/slot/README.md#L1-L17) + +## Architecture Overview + +The runtime architecture of base components revolves around "application context + component base classes + frontend resource resolution". Components assert the existence of an Application context during construction, and pass layout and index information to the frontend via the internal `_internal` dictionary; some components support slots and event binding, which are ultimately consumed by the frontend rendering engine. + +```mermaid +graph TB +APP["Application
Application Root Container"] --> CTX["AppContext
Global Context"] +CTX --> BASE["ModelScopeLayoutComponent / ModelScopeComponent
Component Base Class"] +BASE --> EACH["Each"] +BASE --> SLOT["Slot"] +BASE --> FILTER["Filter"] +BASE --> FRAG["Fragment"] +BASE --> LAYOUT["Div / Span / Markdown and other layout components"] +BASE --> AUTO["AutoLoading"] +BASE --> DATA["ModelScopeDataLayoutComponent
Layout Component with Data Model"] +DATA --> APPCOMP["Application"] +DATA --> MARK["Markdown"] +subgraph "Frontend Resource Resolution" +RESOLVE["resolve_frontend_dir(type='base')"] +end +BASE --> RESOLVE +DATA --> RESOLVE +AUTO --> RESOLVE +LAYOUT --> RESOLVE +``` + +Diagram sources + +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/components/base/markdown/**init**.py:11-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L11-L174) +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:8-65](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L8-L65) +- [backend/modelscope_studio/components/base/div/**init**.py:10-86](file://backend/modelscope_studio/components/base/div/__init__.py#L10-L86) +- [backend/modelscope_studio/components/base/slot/**init**.py:8-50](file://backend/modelscope_studio/components/base/slot/__init__.py#L8-L50) +- [backend/modelscope_studio/components/base/each/**init**.py:17-73](file://backend/modelscope_studio/components/base/each/__init__.py#L17-L73) +- [backend/modelscope_studio/components/base/filter/**init**.py:8-45](file://backend/modelscope_studio/components/base/filter/__init__.py#L8-L45) +- [backend/modelscope_studio/components/base/fragment/**init**.py:8-49](file://backend/modelscope_studio/components/base/fragment/__init__.py#L8-L49) + +## Detailed Component Analysis + +### Application + +- Import path: `from modelscope_studio.components.base import Application` +- Inheritance: `ModelScopeDataLayoutComponent` +- Events: + - `mount`: Page mounted + - `resize`: Window size changed + - `unmount`: Page unmounted + - `custom`: Custom event triggered via `window.ms_globals.dispatch` +- Data models: + - `ApplicationPageScreenData`: width, height, scrollX, scrollY + - `ApplicationPageData`: screen, language, theme, userAgent +- Key behavior: + - Sets `AppContext` during construction + - Supports `preprocess`/`postprocess` pass-through + - Provides `example_payload`/`example_value` + +Section sources + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [docs/components/base/application/README.md:1-56](file://docs/components/base/application/README.md#L1-L56) + +### AutoLoading + +- Import path: `from modelscope_studio.components.base import AutoLoading` +- Inheritance: `ModelScopeLayoutComponent` +- Slots: `render`, `errorRender`, `loadingText` +- Key properties: + - `generating`, `show_error`, `show_mask`, `show_timer`, `loading_text` +- Key behavior: + - `skip_api=True`, does not participate in the standard API flow + - `preprocess`/`postprocess` handles strings as pass-through + +Section sources + +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:8-65](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L8-L65) + +### Slot + +- Import path: `from modelscope_studio.components.base import Slot` +- Inheritance: `ModelScopeLayoutComponent` +- Key properties: + - `value`: Slot name + - `params_mapping`: JavaScript function string for parameter mapping +- Key behavior: + - When the parent is also a Slot, `value` is concatenated to form a hierarchical path + - `skip_api=True` + +Section sources + +- [backend/modelscope_studio/components/base/slot/**init**.py:8-50](file://backend/modelscope_studio/components/base/slot/__init__.py#L8-L50) +- [docs/components/base/slot/README.md:1-17](file://docs/components/base/slot/README.md#L1-L17) + +### Each + +- Import path: `from modelscope_studio.components.base import Each` +- Inheritance: `ModelScopeDataLayoutComponent` +- Data model: `ModelScopeEachData` (root: list) +- Key properties: + - `value`: `list[dict]` or `Callable` + - `context_value`: `dict`, used for deep merge into context + - `as_item`: string, for filtering context fields +- Key behavior: + - `preprocess` unpacks `ModelScopeEachData` into a list + - `postprocess` returns a list + - `skip_api=False`, participates in the API flow + +Section sources + +- [backend/modelscope_studio/components/base/each/**init**.py:17-73](file://backend/modelscope_studio/components/base/each/__init__.py#L17-L73) +- [docs/components/base/each/README.md:1-32](file://docs/components/base/each/README.md#L1-L32) + +### Filter + +- Import path: `from modelscope_studio.components.base import Filter` +- Inheritance: `ModelScopeLayoutComponent` +- Key properties: + - `params_mapping`: Parameter mapping string +- Key behavior: + - `skip_api=True`, does not participate in the API flow + +Section sources + +- [backend/modelscope_studio/components/base/filter/**init**.py:8-45](file://backend/modelscope_studio/components/base/filter/__init__.py#L8-L45) + +### Fragment + +- Import path: `from modelscope_studio.components.base import Fragment` +- Inheritance: `ModelScopeLayoutComponent` +- Key behavior: + - `skip_api=True`, does not participate in the API flow + - Suitable for logical grouping and slot mounting + +Section sources + +- [backend/modelscope_studio/components/base/fragment/**init**.py:8-49](file://backend/modelscope_studio/components/base/fragment/__init__.py#L8-L49) + +### Div + +- Import path: `from modelscope_studio.components.base import Div` +- Inheritance: `ModelScopeLayoutComponent` +- Events: `click`, `dblclick`, `mousedown`, `mouseup`, `mouseover`, `mouseout`, `mousemove`, `scroll` +- Key properties: + - `value`: string + - `additional_props`: dict, additional properties +- Key behavior: + - `skip_api=True` + +Section sources + +- [backend/modelscope_studio/components/base/div/**init**.py:10-86](file://backend/modelscope_studio/components/base/div/__init__.py#L10-L86) + +### Text + +- Import path: `from modelscope_studio.components.base import Text` +- Inheritance: `ModelScopeComponent` +- Key behavior: + - `skip_api=True` + +Section sources + +- [backend/modelscope_studio/components/base/text/**init**.py:8-57](file://backend/modelscope_studio/components/base/text/__init__.py#L8-L57) + +### Span + +- Import path: `from modelscope_studio.components.base import Span` +- Inheritance: `ModelScopeLayoutComponent` +- Events: `click`, `dblclick`, `mousedown`, `mouseup`, `mouseover`, `mouseout`, `mousemove`, `scroll` +- Key properties: + - `value`: string + - `additional_props`: dict, additional properties +- Key behavior: + - `skip_api=True` + +Section sources + +- [backend/modelscope_studio/components/base/span/**init**.py:10-87](file://backend/modelscope_studio/components/base/span/__init__.py#L10-L87) + +### Markdown + +- Import path: `from modelscope_studio.components.base import Markdown` +- Inheritance: `ModelScopeDataLayoutComponent` +- Events: `change`, `copy`, `click`, `dblclick`, `mousedown`, `mouseup`, `mouseover`, `mouseout`, `mousemove`, `scroll` +- Slots: `copyButtons` +- Key properties: + - `value`: string + - `rtl`, `latex_delimiters`, `sanitize_html`, `line_breaks`, `header_links`, `allow_tags`, `show_copy_button`, `copy_buttons`, `additional_props` +- Key behavior: + - `preprocess` returns as-is + - `postprocess` strips indentation and returns a string + - `api_info` returns `{"type": "string"}` + +Section sources + +- [backend/modelscope_studio/components/base/markdown/**init**.py:11-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L11-L174) + +## Dependency Analysis + +- Component base classes and context + - All base components depend on the base classes (`ModelScopeLayoutComponent`, `ModelScopeComponent`, `ModelScopeDataLayoutComponent`) defined in `utils/dev/component.py`, and assert the existence of `AppContext` during construction. + - `utils/dev/app_context.py` provides `set_app`/`assert_app`/`get_app` to ensure components are used within an Application root container. + +- Frontend resource resolution + - Each component resolves its frontend directory via `resolve_frontend_dir("xxx", type="base")`, ensuring consistency between frontend and backend resources. + +```mermaid +graph LR +CTX["AppContext"] --> |assert_app| BASE["Component Base Class"] +BASE --> |inherits| LCOMP["ModelScopeLayoutComponent"] +BASE --> |inherits| DCOMP["ModelScopeDataLayoutComponent"] +BASE --> |inherits| SCOMP["ModelScopeComponent"] +LCOMP --> |frontend| RES["resolve_frontend_dir('...')"] +DCOMP --> |frontend| RES +SCOMP --> |frontend| RES +``` + +Diagram sources + +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +Section sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) + +## Performance Considerations + +- Avoiding unnecessary API interactions + - Most base components have `skip_api=True` (e.g., AutoLoading, Slot, Filter, Fragment, Div/Span/Text/Markdown), meaning they do not participate in the standard API flow, reducing frontend-backend round-trip overhead. +- List rendering optimization + - `Each`'s `value` supports `Callable` for lazy evaluation in complex scenarios; combining `as_item`/`context_value` reduces redundant attribute passing and conflicts. +- Event binding + - Bind events only when necessary (e.g., mouse and scroll events for Div/Markdown) to avoid excessive bindings that could increase frontend pressure. +- Memory management + - Components uniformly mark `layout=True` in `__exit__`, ensuring the frontend correctly releases and rebuilds; avoid holding long-lived references within the component tree. +- HTML sanitization + - `Markdown`'s `postprocess` sanitizes content, reducing rendering jitter and abnormal character issues. + +## Troubleshooting Guide + +- Missing Application root container + - Symptom: Warning indicating no Application component found. + - Resolution: Ensure all components are wrapped inside an Application. + - Reference: Warning message from `AppContext.assert_app`. + +- Slot not taking effect + - Symptom: Slot fails to be inserted into the target component. + - Resolution: Confirm the target component's `SLOTS` supports the slot name; verify that `params_mapping` is correctly configured. + +- Each context conflict + - Symptom: Attribute conflicts or overrides when iterating multiple components. + - Resolution: Use `as_item` for field filtering; use `context_value` for deep merge to inject uniformly if necessary. + +- AutoLoading not displaying + - Symptom: loading/error/render slots not showing. + - Resolution: Confirm that `generating`/`show_error`/`show_mask` state matches the slot naming. + +Section sources + +- [backend/modelscope_studio/utils/dev/app_context.py:16-20](file://backend/modelscope_studio/utils/dev/app_context.py#L16-L20) +- [docs/components/base/slot/README.md:1-17](file://docs/components/base/slot/README.md#L1-L17) +- [docs/components/base/each/README.md:16-22](file://docs/components/base/each/README.md#L16-L22) +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:15-46](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L15-L46) + +## Conclusion + +The base component library provides a unified application root container, layout and text components, conditional and loop rendering helper components, and a slot system. Through strict context constraints and frontend resource resolution mechanisms, it ensures stable operation of components within the Gradio ecosystem. It is recommended to use `Each`'s `as_item` and `context_value` for context management, choose `skip_api` components appropriately to reduce API overhead, and leverage Application's lifecycle events and custom events for page behavior control when needed. + +## Appendix: Usage Examples and Best Practices + +### Application Container and Page Environment + +- Wrap the outermost layer of the application with Application, and listen to page lifecycle events. +- Obtain user language, theme, screen information, and UA from Application's `value`. + +Section sources + +- [docs/components/base/application/README.md:12-20](file://docs/components/base/application/README.md#L12-L20) +- [backend/modelscope_studio/components/base/application/**init**.py:30-54](file://backend/modelscope_studio/components/base/application/__init__.py#L30-L54) + +### Conditional Rendering (Filter) + +- Use Filter with `params_mapping` to determine whether to render a subtree. +- Suitable for dynamically hiding/showing parts of the content based on context parameters. + +Section sources + +- [backend/modelscope_studio/components/base/filter/**init**.py:13-25](file://backend/modelscope_studio/components/base/filter/__init__.py#L13-L25) + +### List Iteration (Each) + +- Each accepts a list or callable, injects context; supports `as_item` and `context_value`. +- Suitable for rendering lists of unknown length and injecting uniform attributes. + +Section sources + +- [docs/components/base/each/README.md:7-22](file://docs/components/base/each/README.md#L7-L22) +- [backend/modelscope_studio/components/base/each/**init**.py:23-52](file://backend/modelscope_studio/components/base/each/__init__.py#L23-L52) + +### Slot System (Slot) + +- Slot works with the target component's `SLOTS`; `params_mapping` supports parameter mapping. +- Suitable for complex layouts and pluggable content areas. + +Section sources + +- [docs/components/base/slot/README.md:1-17](file://docs/components/base/slot/README.md#L1-L17) +- [backend/modelscope_studio/components/base/slot/**init**.py:13-30](file://backend/modelscope_studio/components/base/slot/__init__.py#L13-L30) + +### Auto Loading (AutoLoading) + +- Wrap areas that may take time to load; use render/errorRender/loadingText slots. +- Control mask, timer, and error display to improve user experience. + +Section sources + +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:17-46](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L17-L46) + +### Layout and Text Components + +- Div/Span: For basic block-level/inline layout; support various mouse and scroll events. +- Text/Markdown: Text rendering; Markdown supports copy buttons and LaTeX expression configuration. + +Section sources + +- [backend/modelscope_studio/components/base/div/**init**.py:44-67](file://backend/modelscope_studio/components/base/div/__init__.py#L44-L67) +- [backend/modelscope_studio/components/base/span/**init**.py:44-67](file://backend/modelscope_studio/components/base/span/__init__.py#L44-L67) +- [backend/modelscope_studio/components/base/text/**init**.py:17-37](file://backend/modelscope_studio/components/base/text/__init__.py#L17-L37) +- [backend/modelscope_studio/components/base/markdown/**init**.py:54-141](file://backend/modelscope_studio/components/base/markdown/__init__.py#L54-L141) + +### Component Inheritance and Extension Development + +- New components are recommended to inherit the appropriate base class: + - Requires data model and layout: `ModelScopeDataLayoutComponent` + - Layout only: `ModelScopeLayoutComponent` + - Pure component: `ModelScopeComponent` +- Set `FRONTEND_DIR` in the constructor to ensure frontend resources are correctly resolved. +- If slots are needed, define `SLOTS` and document the supported slot names and their purposes. + +Section sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) diff --git a/.wiki/en/API Reference/Python API/Pro Components API.md b/.wiki/en/API Reference/Python API/Pro Components API.md new file mode 100644 index 00000000..ea03c438 --- /dev/null +++ b/.wiki/en/API Reference/Python API/Pro Components API.md @@ -0,0 +1,487 @@ +# Pro Components API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/pro/__init__.py](file://backend/modelscope_studio/components/pro/__init__.py) +- [backend/modelscope_studio/components/pro/components.py](file://backend/modelscope_studio/components/pro/components.py) +- [backend/modelscope_studio/components/pro/chatbot/__init__.py](file://backend/modelscope_studio/components/pro/chatbot/__init__.py) +- [backend/modelscope_studio/components/pro/multimodal_input/__init__.py](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py) +- [backend/modelscope_studio/components/pro/web_sandbox/__init__.py](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py) +- [backend/modelscope_studio/components/pro/monaco_editor/__init__.py](file://backend/modelscope_studio/components/pro/monaco_editor/__init__.py) +- [backend/modelscope_studio/components/pro/monaco_editor/diff_editor/__init__.py](file://backend/modelscope_studio/components/pro/monaco_editor/diff_editor/__init__.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) +- [backend/modelscope_studio/utils/dev/process_links.py](file://backend/modelscope_studio/utils/dev/process_links.py) +- [docs/demos/example.py](file://docs/demos/example.py) +- [docs/layout_templates/chatbot/app.py](file://docs/layout_templates/chatbot/app.py) +- [docs/layout_templates/chatbot/demos/basic.py](file://docs/layout_templates/chatbot/demos/basic.py) +- [docs/components/pro/chatbot/demos/chatbot_config.py](file://docs/components/pro/chatbot/demos/chatbot_config.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is the Python API reference for the pro component library (`modelscope_studio.components.pro`), covering the following AI application-specific components: + +- **Chatbot**: Conversational message container and rendering component; supports user/assistant messages, welcome prompts, suggested prompts, tool calls, file content, and other rich capabilities. +- **MultimodalInput**: Multimodal input component; supports text and attachment uploads, paste, drag-and-drop, voice, and other input modalities. +- **WebSandbox**: Web sandbox component; renders React/HTML templates in an isolated environment; supports compile and render error events. +- **MonacoEditor**: Code editor component; supports language highlighting, read-only mode, option configuration, mount/change/validate events; provides a DiffEditor subclass. + +This document records import paths, constructor parameters, property definitions, method signatures, and return types for each component. It provides standard instantiation and usage examples for complex AI applications, covering advanced use cases such as chatbot integration, multimodal input handling, and web sandbox isolation. It also explains event binding, data flow processing strategies, frontend/backend data conversion logic, and performance and concurrency considerations. + +## Project Structure + +Pro components reside in the backend Python package `modelscope_studio/components/pro`, divided into four submodules by function: chatbot, multimodal_input, web_sandbox, and monaco_editor, with a unified export entry and alias exports. + +```mermaid +graph TB +subgraph "Python Backend" +PRO["pro/__init__.py
Unified Exports"] +COMP["pro/components.py
Alias Exports"] +CHAT["pro/chatbot/__init__.py"] +MMI["pro/multimodal_input/__init__.py"] +WS["pro/web_sandbox/__init__.py"] +ME["pro/monaco_editor/__init__.py"] +MED["pro/monaco_editor/diff_editor/__init__.py"] +end +subgraph "Common Base Classes" +DEV["utils/dev/component.py
ModelScope*Component Family"] +RES["utils/dev/resolve_frontend_dir.py"] +LNK["utils/dev/process_links.py"] +end +PRO --> CHAT +PRO --> MMI +PRO --> WS +PRO --> ME +ME --> MED +COMP --> CHAT +COMP --> MMI +COMP --> WS +COMP --> ME +COMP --> MED +CHAT --> DEV +MMI --> DEV +WS --> DEV +ME --> DEV +MED --> DEV +CHAT --> RES +MMI --> RES +WS --> RES +ME --> RES +MED --> RES +CHAT --> LNK +``` + +Diagram sources + +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:286-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L286-L495) +- [backend/modelscope_studio/components/pro/multimodal_input/**init**.py:82-259](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py#L82-L259) +- [backend/modelscope_studio/components/pro/web_sandbox/**init**.py:15-86](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py#L15-L86) +- [backend/modelscope_studio/components/pro/monaco_editor/**init**.py:16-107](file://backend/modelscope_studio/components/pro/monaco_editor/__init__.py#L16-L107) +- [backend/modelscope_studio/components/pro/monaco_editor/diff_editor/**init**.py:10-106](file://backend/modelscope_studio/components/pro/monaco_editor/diff_editor/__init__.py#L10-L106) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-17](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L17) +- [backend/modelscope_studio/utils/dev/process_links.py:9-61](file://backend/modelscope_studio/utils/dev/process_links.py#L9-L61) + +Section sources + +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) + +## Core Components + +This section provides an overview of the responsibilities and typical use cases for the four pro components: + +- **Chatbot**: Used to build conversational interfaces; manages message lists, welcome prompts, suggested prompts, action buttons, Markdown rendering, file/tool content, and more. +- **MultimodalInput**: Used to receive multimodal input with text and attachments; supports upload, paste, drag-and-drop, preview, download, and other workflows. +- **WebSandbox**: Used to render templates (React/HTML) in an isolated environment; captures compile and render error events. +- **MonacoEditor**: Used to embed a code editor in the browser; supports language, read-only, options, mount/change/validate events; provides DiffEditor for diff view. + +Section sources + +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:286-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L286-L495) +- [backend/modelscope_studio/components/pro/multimodal_input/**init**.py:82-259](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py#L82-L259) +- [backend/modelscope_studio/components/pro/web_sandbox/**init**.py:15-86](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py#L15-L86) +- [backend/modelscope_studio/components/pro/monaco_editor/**init**.py:16-107](file://backend/modelscope_studio/components/pro/monaco_editor/__init__.py#L16-L107) + +## Architecture Overview + +Pro components extend the Gradio component system through unified base classes and frontend directory resolution to bridge frontend and backend. Components set `FRONTEND_DIR` during initialization, pointing to the corresponding frontend Svelte component directory; `preprocess`/`postprocess` handles frontend/backend data conversion; `EVENTS`/`SLOTS` provide event and slot extension points. + +```mermaid +sequenceDiagram +participant Py as "Python Component" +participant Base as "ModelScope*Component Base Class" +participant FE as "Frontend Component (Svelte)" +participant App as "Gradio App" +App->>Py : Instantiate component (pass value/config) +Py->>Base : Call parent constructor (inherit Gradio Component) +Py->>Py : Set FRONTEND_DIR / data model / events / SLOTS +Py->>FE : Pass config and data during rendering +FE-->>Py : Trigger event callbacks (e.g. change/copy/edit/delete/like/retry/suggestion_select/welcome_prompt_select) +Py-->>App : Return processed value (possibly via postprocess) +``` + +Diagram sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-17](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L17) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:286-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L286-L495) +- [backend/modelscope_studio/components/pro/multimodal_input/**init**.py:82-259](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py#L82-L259) +- [backend/modelscope_studio/components/pro/web_sandbox/**init**.py:15-86](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py#L15-L86) +- [backend/modelscope_studio/components/pro/monaco_editor/**init**.py:16-107](file://backend/modelscope_studio/components/pro/monaco_editor/__init__.py#L16-L107) + +## Detailed Component Analysis + +### Chatbot Component + +- Import paths + - Main class: `modelscope_studio.components.pro.Chatbot` + - Alias: `modelscope_studio.components.pro.ProChatbot` +- Purpose + - Manages conversational message lists; supports user/assistant messages, welcome prompts, suggested prompts, action buttons, Markdown rendering, file/tool content, and more. +- Key data models + - `ChatbotWelcomeConfig`, `ChatbotPromptsConfig`, `ChatbotPromptConfig`, `ChatbotMarkdownConfig`, `ChatbotUserConfig`, `ChatbotBotConfig`, `ChatbotDataMessageContent`, `ChatbotDataMessage`, `ChatbotDataMessages`, `ChatbotDataMeta` +- Constructor parameter highlights + - `value`: Can be a callback or message list/dict; supports message status `pending`/`done`, separators, metadata feedback, etc. + - Height and scrolling: `height`, `min_height`, `max_height`, `auto_scroll`, `show_scroll_to_bottom_button`, `scroll_to_bottom_button_offset` + - Welcome and Markdown: `welcome_config`, `markdown_config` + - User/assistant styles and actions: `user_config`, `bot_config` (includes `actions`/`disabled_actions`, `avatar`, `typing`, etc.) + - Others: `elem_id`, `elem_classes`, `elem_style`, `visible`, `render`, etc. +- Methods and behavior + - `preprocess`: Normalizes file paths in message content for frontend display + - `postprocess`: Converts file paths to `FileData` structures; supports local and remote URLs + - Events: `change`, `copy`, `edit`, `delete`, `like`, `retry`, `suggestion_select`, `welcome_prompt_select` + - Slots: `role` +- Usage examples (reference) + - Basic chat template app entry: [docs/layout_templates/chatbot/app.py:1-7](file://docs/layout_templates/chatbot/app.py#L1-L7) + - Chat config and event demo: [docs/components/pro/chatbot/demos/chatbot_config.py:1-40](file://docs/components/pro/chatbot/demos/chatbot_config.py#L1-L40) + +```mermaid +classDiagram +class ModelScopeProChatbot { ++EVENTS ++SLOTS ++FRONTEND_DIR ++data_model ++__init__(...) ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class ChatbotWelcomeConfig +class ChatbotPromptsConfig +class ChatbotPromptConfig +class ChatbotMarkdownConfig +class ChatbotUserConfig +class ChatbotBotConfig +class ChatbotDataMessageContent +class ChatbotDataMessage +class ChatbotDataMessages +class ChatbotDataMeta +ModelScopeProChatbot --> ChatbotWelcomeConfig : "uses" +ModelScopeProChatbot --> ChatbotPromptsConfig : "uses" +ModelScopeProChatbot --> ChatbotMarkdownConfig : "uses" +ModelScopeProChatbot --> ChatbotUserConfig : "uses" +ModelScopeProChatbot --> ChatbotBotConfig : "uses" +ModelScopeProChatbot --> ChatbotDataMessageContent : "uses" +ModelScopeProChatbot --> ChatbotDataMessage : "uses" +ModelScopeProChatbot --> ChatbotDataMessages : "uses" +ModelScopeProChatbot --> ChatbotDataMeta : "uses" +``` + +Diagram sources + +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:14-285](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L14-L285) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:286-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L286-L495) + +Section sources + +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:14-285](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L14-L285) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:286-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L286-L495) +- [docs/layout_templates/chatbot/app.py:1-7](file://docs/layout_templates/chatbot/app.py#L1-L7) +- [docs/components/pro/chatbot/demos/chatbot_config.py:1-40](file://docs/components/pro/chatbot/demos/chatbot_config.py#L1-L40) + +### MultimodalInput Component + +- Import paths + - Main class: `modelscope_studio.components.pro.MultimodalInput` + - Alias: `modelscope_studio.components.pro.ProMultimodalInput` +- Purpose + - Accepts multimodal input with text and attachments; supports upload, paste, drag-and-drop, preview, download, and other workflows. +- Key data models + - `MultimodalInputUploadConfig`: Upload behavior and UI configuration + - `MultimodalInputValue`: Input value containing `files` and `text` +- Constructor parameter highlights + - `value`: `MultimodalInputValue` or its dict form + - Mode and size: `mode`, `auto_size`, `footer`/`header`/`prefix`/`suffix`, `placeholder`, `submit_type` + - Upload config: `upload_config` (includes `fullscreen_drop`, `allow_upload`, `allow_paste_file`, `allow_speech`, `max_count`, `directory`, `multiple`, `overflow`, `title`, `image_props`, `placeholder`, etc.) + - Style and state: `disabled`, `read_only`, `loading`, `class_names`, `styles`, `root_class_name` + - Others: `elem_id`, `elem_classes`, `elem_style`, `visible`, `render`, etc. +- Methods and behavior + - `preprocess`: Converts uploaded files to cacheable named strings for subsequent processing + - `postprocess`: Downloads remote URLs to local cache and wraps them as `FileData` lists + - Events: `change`, `submit`, `cancel`, `key_down`/`key_press`, `focus`, `blur`, `upload`, `paste`, `paste_file`, `skill_closable_close`, `drop`, `download`, `preview`, `remove` + - Slots: `suffix`, `header`, `prefix`, `footer`, `skill.title`, `skill.toolTip.title`, `skill.closable.closeIcon` +- Usage examples (reference) + - Example app entry: [docs/demos/example.py:1-11](file://docs/demos/example.py#L1-L11) + +```mermaid +classDiagram +class ModelScopeProMultimodalInput { ++EVENTS ++SLOTS ++FRONTEND_DIR ++data_model ++__init__(...) ++preprocess(payload) ++postprocess(value) ++_process_single_file(f) ++_download_files(value) ++skip_api ++example_payload() ++example_value() +} +class MultimodalInputUploadConfig +class MultimodalInputValue +ModelScopeProMultimodalInput --> MultimodalInputUploadConfig : "uses" +ModelScopeProMultimodalInput --> MultimodalInputValue : "uses" +``` + +Diagram sources + +- [backend/modelscope_studio/components/pro/multimodal_input/**init**.py:18-259](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py#L18-L259) +- [backend/modelscope_studio/components/pro/multimodal_input/**init**.py:82-259](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py#L82-L259) + +Section sources + +- [backend/modelscope_studio/components/pro/multimodal_input/**init**.py:18-259](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py#L18-L259) +- [backend/modelscope_studio/components/pro/multimodal_input/**init**.py:82-259](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py#L82-L259) +- [docs/demos/example.py:1-11](file://docs/demos/example.py#L1-L11) + +### WebSandbox Component + +- Import paths + - Main class: `modelscope_studio.components.pro.WebSandbox` + - Alias: `modelscope_studio.components.pro.ProWebSandbox` +- Purpose + - Renders React/HTML templates in an isolated environment; supports compile and render error event monitoring. +- Key data models + - `SandboxFileData`: Template file structure (code, is_entry) +- Constructor parameter highlights + - `value`: dict where keys are file names and values are strings or `SandboxFileData` + - Template type: `template` (`'react'` | `'html'`) + - Error display: `show_render_error`, `show_compile_error`, `compile_error_render` + - External dependencies: `imports` (module mapping) + - Size: `height` + - Others: `elem_id`, `elem_classes`, `elem_style`, `visible`, `render`, etc. +- Methods and behavior + - `preprocess`/`postprocess`: Direct pass-through (`skip_api=True`) + - Events: `compile_success`, `compile_error`, `render_error`, `custom` + - Slots: `compileErrorRender` +- Usage examples (reference) + - Example app entry: [docs/demos/example.py:1-11](file://docs/demos/example.py#L1-L11) + +```mermaid +classDiagram +class ModelScopeProWebSandbox { ++EVENTS ++SLOTS ++FRONTEND_DIR ++__init__(...) ++preprocess(payload) ++postprocess(value) ++skip_api ++example_payload() ++example_value() +} +class SandboxFileData +ModelScopeProWebSandbox --> SandboxFileData : "uses" +``` + +Diagram sources + +- [backend/modelscope_studio/components/pro/web_sandbox/**init**.py:10-86](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py#L10-L86) +- [backend/modelscope_studio/components/pro/web_sandbox/**init**.py:15-86](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py#L15-L86) + +Section sources + +- [backend/modelscope_studio/components/pro/web_sandbox/**init**.py:10-86](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py#L10-L86) +- [backend/modelscope_studio/components/pro/web_sandbox/**init**.py:15-86](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py#L15-L86) +- [docs/demos/example.py:1-11](file://docs/demos/example.py#L1-L11) + +### MonacoEditor Component + +- Import paths + - Main class: `modelscope_studio.components.pro.MonacoEditor` + - Alias: `modelscope_studio.components.pro.ProMonacoEditor` + - DiffEditor: `modelscope_studio.components.pro.MonacoEditorDiffEditor` (as a subclass) +- Purpose + - Provides a code editor with language, read-only, options, mount/change/validate events; DiffEditor provides a diff view. +- Constructor parameter highlights + - `value`: Initial editing content + - Language and read-only: `language`, `read_only` + - Lifecycle hooks: `before_mount`, `after_mount` + - Service overrides: `override_services` + - Loading text: `loading` + - Editor options: `options` + - Line positioning: `line` + - Size: `height` + - Others: `elem_id`, `elem_classes`, `elem_style`, `visible`, `render`, etc. +- Methods and behavior + - `preprocess`/`postprocess`: Direct pass-through (`skip_api=False`) + - Events: `mount`, `change`, `validate` + - Slots: `loading` + - DiffEditor: Shares loader configuration with the main editor; supports `original`/`original_language`/`modified_language` +- Usage examples (reference) + - Example app entry: [docs/demos/example.py:1-11](file://docs/demos/example.py#L1-L11) + +```mermaid +classDiagram +class ModelScopeProMonacoEditor { ++EVENTS ++SLOTS ++LOADER ++FRONTEND_DIR ++__init__(...) ++preprocess(payload) ++postprocess(value) ++api_info() ++skip_api ++example_payload() ++example_value() +} +class ModelScopeProMonacoEditorDiffEditor { ++EVENTS ++SLOTS ++FRONTEND_DIR ++__init__(...) ++preprocess(payload) ++postprocess(value) ++api_info() ++skip_api ++example_payload() ++example_value() +} +ModelScopeProMonacoEditor <|-- ModelScopeProMonacoEditorDiffEditor : "subclass" +``` + +Diagram sources + +- [backend/modelscope_studio/components/pro/monaco_editor/**init**.py:16-107](file://backend/modelscope_studio/components/pro/monaco_editor/__init__.py#L16-L107) +- [backend/modelscope_studio/components/pro/monaco_editor/diff_editor/**init**.py:10-106](file://backend/modelscope_studio/components/pro/monaco_editor/diff_editor/__init__.py#L10-L106) + +Section sources + +- [backend/modelscope_studio/components/pro/monaco_editor/**init**.py:16-107](file://backend/modelscope_studio/components/pro/monaco_editor/__init__.py#L16-L107) +- [backend/modelscope_studio/components/pro/monaco_editor/diff_editor/**init**.py:10-106](file://backend/modelscope_studio/components/pro/monaco_editor/diff_editor/__init__.py#L10-L106) +- [docs/demos/example.py:1-11](file://docs/demos/example.py#L1-L11) + +## Dependency Analysis + +- Component base classes + - `ModelScopeLayoutComponent`: Layout component base class; suitable for container components that do not need data transfer (e.g., WebSandbox) + - `ModelScopeComponent`: Basic component base class; suitable for data-driven components (e.g., Chatbot/MultimodalInput/MonacoEditor) + - `ModelScopeDataLayoutComponent`: Combines data and layout capabilities; suitable for components that require frontend/backend data exchange (e.g., Chatbot/MultimodalInput/MonacoEditor) +- Frontend directory resolution + - `resolve_frontend_dir`: Generates relative paths based on component name and type (pro/antd/antdx/base) to ensure frontend resources load correctly +- Data link processing + - `process_links`: Converts links in HTML/Markdown, transforming local files into accessible cache URLs + +```mermaid +graph LR +A["ModelScopeLayoutComponent"] --> C["WebSandbox"] +B["ModelScopeComponent"] --> D["Chatbot"] +B --> E["MultimodalInput"] +B --> F["MonacoEditor"] +G["ModelScopeDataLayoutComponent"] --> D +G --> E +G --> F +H["resolve_frontend_dir"] --> C +H --> D +H --> E +H --> F +I["process_links"] --> D +``` + +Diagram sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-17](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L17) +- [backend/modelscope_studio/utils/dev/process_links.py:9-61](file://backend/modelscope_studio/utils/dev/process_links.py#L9-L61) + +Section sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-17](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L17) +- [backend/modelscope_studio/utils/dev/process_links.py:9-61](file://backend/modelscope_studio/utils/dev/process_links.py#L9-L61) + +## Performance Considerations + +- Data serialization and transmission + - Chatbot/MultimodalInput/MonacoEditor are data-driven components; `preprocess`/`postprocess` handles file path and `FileData` conversions, avoiding memory pressure from processing large files directly in the frontend. +- Frontend resource loading + - MonacoEditor supports local or CDN loader configuration; choosing appropriately can reduce initial load time; DiffEditor reuses the main editor's loader configuration. +- Event binding and updates + - Components dynamically bind events via `_internal.update`, avoiding unnecessary re-renders; WebSandbox's `skip_api=True` reduces API layer overhead. +- File processing + - MultimodalInput downloads remote URLs to the cache directory in `postprocess`, avoiding repeated network requests; `process_links` converts local resources to cache URLs, improving stability and performance. + +## Troubleshooting Guide + +- Editor loading failure + - Check MonacoEditor's `LOADER` configuration (mode/local/cdn); verify CDN reachability or switch to local loading. + - Check whether mount/change/validate events are triggered to locate the problem stage. +- Files cannot be displayed or download anomalies + - Chatbot's file content is converted to `FileData` in `postprocess`; check whether the path is a local file or a valid URL. + - MultimodalInput's `postprocess` downloads remote URLs to cache; verify cache directory permissions and network reachability. +- Sandbox compile/render errors + - WebSandbox provides `compile_error`/`render_error` events; combine with the `compileErrorRender` slot to locate errors. +- Broken links + - Use `process_links` to convert links in HTML/Markdown, ensuring local resources are correctly cached and accessible. + +Section sources + +- [backend/modelscope_studio/components/pro/monaco_editor/**init**.py:44-107](file://backend/modelscope_studio/components/pro/monaco_editor/__init__.py#L44-L107) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:475-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L475-L495) +- [backend/modelscope_studio/components/pro/multimodal_input/**init**.py:233-259](file://backend/modelscope_studio/components/pro/multimodal_input/__init__.py#L233-L259) +- [backend/modelscope_studio/components/pro/web_sandbox/**init**.py:19-86](file://backend/modelscope_studio/components/pro/web_sandbox/__init__.py#L19-L86) +- [backend/modelscope_studio/utils/dev/process_links.py:9-61](file://backend/modelscope_studio/utils/dev/process_links.py#L9-L61) + +## Conclusion + +The pro component library, centered around conversation, multimodal input, web sandbox, and code editing, provides a complete Python API and frontend integration solution. Through a unified base class system, flexible event and slot mechanisms, and comprehensive frontend/backend data conversion, it meets the development requirements of complex AI applications. It is recommended to combine examples and best practices in real projects, and to configure loaders, events, and data flows appropriately for a stable and high-performance user experience. + +## Appendix + +- Unified exports and aliases + - Main module exports: `Chatbot`, `MonacoEditor`, `MonacoEditorDiffEditor`, `MultimodalInput`, `WebSandbox` + - Alias exports: `ProChatbot`, `ProMonacoEditor`, `ProMonacoEditorDiffEditor`, `ProMultimodalInput`, `ProWebSandbox` +- Example entries + - Basic example: [docs/demos/example.py:1-11](file://docs/demos/example.py#L1-L11) + - Chat template app: [docs/layout_templates/chatbot/app.py:1-7](file://docs/layout_templates/chatbot/app.py#L1-L7) + - Chat config and event demo: [docs/components/pro/chatbot/demos/chatbot_config.py:1-40](file://docs/components/pro/chatbot/demos/chatbot_config.py#L1-L40) + +Section sources + +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) +- [docs/demos/example.py:1-11](file://docs/demos/example.py#L1-L11) +- [docs/layout_templates/chatbot/app.py:1-7](file://docs/layout_templates/chatbot/app.py#L1-L7) +- [docs/components/pro/chatbot/demos/chatbot_config.py:1-40](file://docs/components/pro/chatbot/demos/chatbot_config.py#L1-L40) diff --git a/.wiki/en/API Reference/Python API/Python API.md b/.wiki/en/API Reference/Python API/Python API.md new file mode 100644 index 00000000..50f1d05d --- /dev/null +++ b/.wiki/en/API Reference/Python API/Python API.md @@ -0,0 +1,433 @@ +# Python API + + +**Files Referenced in This Document** +- [backend/modelscope_studio/__init__.py](file://backend/modelscope_studio/__init__.py) +- [backend/modelscope_studio/components/__init__.py](file://backend/modelscope_studio/components/__init__.py) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/components/pro/__init__.py](file://backend/modelscope_studio/components/pro/__init__.py) +- [backend/modelscope_studio/components/pro/components.py](file://backend/modelscope_studio/components/pro/components.py) +- [backend/modelscope_studio/components/antd/button/__init__.py](file://backend/modelscope_studio/components/antd/button/__init__.py) +- [backend/modelscope_studio/components/antd/form/__init__.py](file://backend/modelscope_studio/components/antd/form/__init__.py) +- [backend/modelscope_studio/components/base/application/__init__.py](file://backend/modelscope_studio/components/base/application/__init__.py) +- [backend/modelscope_studio/components/pro/chatbot/__init__.py](file://backend/modelscope_studio/components/pro/chatbot/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: API Index and Usage Examples](#appendix-api-index-and-usage-examples) + +## Introduction + +This document is the Python API reference for ModelScope Studio, focusing on the component system and calling conventions of the backend Python package `modelscope_studio`. The document covers: + +- Component import paths and named export conventions (`modelscope_studio.components.antd.*`, `modelscope_studio.components.antdx.*`, `modelscope_studio.components.base.*`, `modelscope_studio.components.pro.*`) +- Constructor parameters, supported events, slots, data models, and preprocess/postprocess flows for key component classes +- Standard instantiation examples (basic usage and advanced configuration), and lifecycle and state management essentials +- Parameter validation and exception handling mechanism notes +- Version compatibility information and common issue troubleshooting + +## Project Structure + +The Python package is located at `backend/modelscope_studio`; the top level aggregates sub-modules via `__all__` exports; components are organized hierarchically in four sub-packages: `antd`, `antdx`, `base`, and `pro`. Each sub-package provides both `__init__.py` and `components.py` entries for different aggregation strategies. + +```mermaid +graph TB +A["backend/modelscope_studio/__init__.py"] --> B["backend/modelscope_studio/components/__init__.py"] +B --> C["antd Sub-Package"] +B --> D["antdx Sub-Package"] +B --> E["base Sub-Package"] +B --> F["pro Sub-Package"] +C --> C1["antd/__init__.py
Named exports of component classes"] +D --> D1["antdx/__init__.py
Named exports of component classes"] +E --> E1["base/__init__.py
Named exports of base component classes"] +F --> F1["pro/__init__.py
Named exports of pro component classes"] +``` + +**Diagram Sources** + +- [backend/modelscope_studio/**init**.py:1-3](file://backend/modelscope_studio/__init__.py#L1-L3) +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) + +**Section Sources** + +- [backend/modelscope_studio/**init**.py:1-3](file://backend/modelscope_studio/__init__.py#L1-L3) +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) + +## Core Components + +This section provides an overview of import paths and named exports for the four component families, and explains the responsibility boundaries and typical use cases of each family. + +- `modelscope_studio.components.antd.*` + - Responsibility: Python wrappers for the Ant Design component ecosystem, covering common UI components for layout, forms, feedback, navigation, and data entry. + - Typical components: Button, Form, Input, Select, Table, Modal, Message, Notification, etc. + - Import: `from modelscope_studio.components.antd import Button, Form, ...` + - Named exports: See [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) and [backend/modelscope_studio/components/antd/components.py:1-144](file://backend/modelscope_studio/components/antd/components.py#L1-L144) + +- `modelscope_studio.components.antdx.*` + - Responsibility: Ant Design X extended component set, designed for conversational interaction and knowledge work scenarios (e.g., message bubbles, conversation lists, prompt panels, etc.). + - Typical components: Bubble, Conversations, Prompts, Sender, ThoughtChain, Welcome, etc. + - Import: `from modelscope_studio.components.antdx import Bubble, Conversations, ...` + - Named exports: See [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) and [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +- `modelscope_studio.components.base.*` + - Responsibility: Base layout and container components providing general capabilities such as application-level containers, loop rendering, conditional filtering, placeholder text, etc. + - Typical components: Application, Each, Filter, Fragment, Markdown, Slot, Text, Div, etc. + - Import: `from modelscope_studio.components.base import Application, Each, ...` + - Named exports: See [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +- `modelscope_studio.components.pro.*` + - Responsibility: Professional domain components designed for specific business scenarios (e.g., chatbot, code editor, multimodal input, web sandbox, etc.). + - Typical components: Chatbot, MonacoEditor, MultimodalInput, WebSandbox. + - Import: `from modelscope_studio.components.pro import Chatbot, MonacoEditor, ...` + - Named exports: See [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) and [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) + +**Section Sources** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-144](file://backend/modelscope_studio/components/antd/components.py#L1-L144) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) + +## Architecture Overview + +The diagram below shows the relationship between Python layer component classes and frontend directory resolution, and the key nodes of event binding and data flow. + +```mermaid +graph TB +subgraph "Python Layer" +P1["AntdButton.__init__()
Constructor params & event binding"] +P2["AntdForm.__init__()
Form config & event binding"] +P3["ModelScopeApplication.__init__()
App context & event binding"] +P4["ModelScopeProChatbot.__init__()
Message config & static resource handling"] +end +subgraph "Frontend Directory Resolution" +F1["resolve_frontend_dir('button')"] +F2["resolve_frontend_dir('form')"] +F3["resolve_frontend_dir('application', type='base')"] +F4["resolve_frontend_dir('chatbot', type='pro')"] +end +P1 --> F1 +P2 --> F2 +P3 --> F3 +P4 --> F4 +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antd/button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) +- [backend/modelscope_studio/components/antd/form/**init**.py:17-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L17-L133) +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:286-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L286-L495) + +## Detailed Component Analysis + +### Component: AntdButton + +- Import Path: `from modelscope_studio.components.antd import Button` +- Purpose: Wraps the Ant Design button, supporting multiple types, sizes, shapes, loading state, danger state, ghost state, etc. +- Key Points: + - Supported events: `click` + - Slots: `icon`, `loading.icon` + - Preprocess/postprocess: Simple string-to-string conversion + - Frontend directory: `resolve_frontend_dir("button")` + +```mermaid +classDiagram +class AntdButton { ++Constructor params(...) ++EVENTS ++SLOTS ++FRONTEND_DIR ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antd/button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) + +**Section Sources** + +- [backend/modelscope_studio/components/antd/button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) + +### Component: AntdForm and AntdFormItem + +- Import Path: `from modelscope_studio.components.antd import Form, Form.Item` +- Purpose: Wraps the Ant Design form, supporting events for field changes, submit, failure, value changes, etc., as well as form item rules and providers. +- Key Points: + - Supported events: `fields_change`, `finish`, `finish_failed`, `values_change` + - Data model: `AntdFormData` + - Preprocess/postprocess: Extracts the `root` field from the data model or passes through as-is + - Frontend directory: `resolve_frontend_dir("form")` + +```mermaid +classDiagram +class AntdForm { ++Item ++Provider ++data_model ++EVENTS ++FRONTEND_DIR ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdFormItem { ++Constructor params(...) ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdFormProvider { ++Constructor params(...) ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdFormData { ++root +} +AntdForm --> AntdFormItem : "Contains" +AntdForm --> AntdFormProvider : "Contains" +AntdForm --> AntdFormData : "Uses" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antd/form/**init**.py:17-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L17-L133) + +**Section Sources** + +- [backend/modelscope_studio/components/antd/form/**init**.py:17-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L17-L133) + +### Component: ModelScopeApplication + +- Import Path: `from modelscope_studio.components.base import Application` +- Purpose: Application-level container providing page environment data (screen size, theme, language, etc.) and lifecycle events (mount, resize, unmount, custom). +- Key Points: + - Supported events: `custom`, `mount`, `resize`, `unmount` + - Data model: `ApplicationPageData` + - Preprocess/postprocess: Pass-through + - Frontend directory: `resolve_frontend_dir("application", type="base")` + +```mermaid +classDiagram +class ModelScopeApplication { ++EVENTS ++data_model ++FRONTEND_DIR ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class ApplicationPageData { ++screen ++language ++theme ++userAgent +} +ModelScopeApplication --> ApplicationPageData : "Uses" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) + +**Section Sources** + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) + +### Component: ModelScopeProChatbot + +- Import Path: `from modelscope_studio.components.pro import Chatbot` +- Purpose: Professional chatbot component supporting rich configurations including welcome messages, prompts, user/assistant messages, action buttons, file/tool/suggestion content, etc. +- Key Points: + - Supported events: `change`, `copy`, `edit`, `delete`, `like`, `retry`, `suggestion_select`, `welcome_prompt_select` + - Data model: `ChatbotDataMessages` (root is a message list) + - Preprocess/postprocess: Typed processing of message content (file to FileData, static resource path handling) + - Frontend directory: `resolve_frontend_dir("chatbot", type="pro")` + +```mermaid +classDiagram +class ModelScopeProChatbot { ++EVENTS ++data_model ++FRONTEND_DIR ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class ChatbotDataMessages { ++root +} +class ChatbotDataMessage { ++role ++status ++content ++meta +} +ModelScopeProChatbot --> ChatbotDataMessages : "Uses" +ChatbotDataMessages --> ChatbotDataMessage : "Contains" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:286-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L286-L495) + +**Section Sources** + +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:286-495](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L286-L495) + +## Dependency Analysis + +- Component classes generally inherit from `ModelScopeDataLayoutComponent` or `ModelScopeLayoutComponent`, unifying the frontend directory resolution and event binding mechanism. +- The event system is based on `gradio.events.EventListener`, injecting event binding flags into the internal update logic via callbacks. +- Data models mostly adopt `GradioRootModel`/`GradioModel` for consistent data structures and serialization between frontend and backend. + +```mermaid +graph LR +A["AntdButton"] --> B["ModelScopeLayoutComponent"] +C["AntdForm"] --> D["ModelScopeDataLayoutComponent"] +E["ModelScopeApplication"] --> D +F["ModelScopeProChatbot"] --> D +B --> G["resolve_frontend_dir(...)"] +D --> G +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antd/button/**init**.py:7-8](file://backend/modelscope_studio/components/antd/button/__init__.py#L7-L8) +- [backend/modelscope_studio/components/antd/form/**init**.py:8-9](file://backend/modelscope_studio/components/antd/form/__init__.py#L8-L9) +- [backend/modelscope_studio/components/base/application/**init**.py:8-9](file://backend/modelscope_studio/components/base/application/__init__.py#L8-L9) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:11](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L11) + +**Section Sources** + +- [backend/modelscope_studio/components/antd/button/**init**.py:7-8](file://backend/modelscope_studio/components/antd/button/__init__.py#L7-L8) +- [backend/modelscope_studio/components/antd/form/**init**.py:8-9](file://backend/modelscope_studio/components/antd/form/__init__.py#L8-L9) +- [backend/modelscope_studio/components/base/application/**init**.py:8-9](file://backend/modelscope_studio/components/base/application/__init__.py#L8-L9) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:11](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L11) + +## Performance Considerations + +- Keep component preprocess/postprocess lightweight; avoid heavy computations in the Python layer. +- For large file content (e.g., file messages in the chatbot), it is recommended to perform minimal wrapping during postprocessing (e.g., retaining only necessary metadata) to reduce transmission overhead. +- Set component height and scrolling behavior appropriately to avoid unnecessary reflow and repaints. + +## Troubleshooting Guide + +- Event Not Triggered + - Check that event listeners are correctly registered (e.g., Button's `click`, Form's `finish`), and confirm that the callback has injected the binding flag. + - Reference: [backend/modelscope_studio/components/antd/button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46), [backend/modelscope_studio/components/antd/form/**init**.py:23-36](file://backend/modelscope_studio/components/antd/form/__init__.py#L23-L36) +- Frontend Directory Resolution Failure + - Confirm that the path returned by `resolve_frontend_dir` exists and is accessible. + - Reference: [backend/modelscope_studio/components/antd/button/**init**.py:139](file://backend/modelscope_studio/components/antd/button/__init__.py#L139), [backend/modelscope_studio/components/antd/form/**init**.py:114](file://backend/modelscope_studio/components/antd/form/__init__.py#L114) +- Data Model Mismatch + - Use `data_model` for preprocess/postprocess to ensure the payload/value structure is consistent with the model. + - Reference: [backend/modelscope_studio/components/antd/form/**init**.py:13-14](file://backend/modelscope_studio/components/antd/form/__init__.py#L13-L14), [backend/modelscope_studio/components/pro/chatbot/**init**.py:388](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L388) + +**Section Sources** + +- [backend/modelscope_studio/components/antd/button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46) +- [backend/modelscope_studio/components/antd/form/**init**.py:13-14](file://backend/modelscope_studio/components/antd/form/__init__.py#L13-L14) +- [backend/modelscope_studio/components/antd/form/**init**.py:23-36](file://backend/modelscope_studio/components/antd/form/__init__.py#L23-L36) +- [backend/modelscope_studio/components/antd/button/**init**.py:139](file://backend/modelscope_studio/components/antd/button/__init__.py#L139) +- [backend/modelscope_studio/components/antd/form/**init**.py:114](file://backend/modelscope_studio/components/antd/form/__init__.py#L114) +- [backend/modelscope_studio/components/pro/chatbot/**init**.py:388](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L388) + +## Conclusion + +ModelScope Studio's Python API, with its clear component family divisions and unified event/data model design, provides a complete component system from basic layout to professional domains. Through clearly defined import paths and named exports, developers can quickly locate and use the components they need; meanwhile, the event binding and data preprocess/postprocess mechanisms ensure consistency and extensibility of frontend-backend collaboration. + +## Appendix: API Index and Usage Examples + +### API Index (by Component Family) + +- `modelscope_studio.components.antd.*` + - Button: `from modelscope_studio.components.antd import Button` + - Form: `from modelscope_studio.components.antd import Form` + - Form.Item: `from modelscope_studio.components.antd import Form.Item` + - More components: See [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) + +- `modelscope_studio.components.antdx.*` + - Actions, Bubble, Conversations, Prompts, Sender, ThoughtChain, Welcome, etc. + - Import example: `from modelscope_studio.components.antdx import Bubble, Conversations` + - See [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) + +- `modelscope_studio.components.base.*` + - Application, Each, Filter, Fragment, Markdown, Slot, Text, Div, etc. + - Import example: `from modelscope_studio.components.base import Application` + - See [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +- `modelscope_studio.components.pro.*` + - Chatbot, MonacoEditor, MultimodalInput, WebSandbox, etc. + - Import example: `from modelscope_studio.components.pro import Chatbot` + - See [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) + +### Usage Examples (Path References) + +- Basic Button (AntdButton) + - Example path: [backend/modelscope_studio/components/antd/button/**init**.py:51-87](file://backend/modelscope_studio/components/antd/button/__init__.py#L51-L87) +- Form (AntdForm) and Form Item (AntdFormItem) + - Example path: [backend/modelscope_studio/components/antd/form/**init**.py:43-80](file://backend/modelscope_studio/components/antd/form/__init__.py#L43-L80) +- Application Container (ModelScopeApplication) + - Example path: [backend/modelscope_studio/components/base/application/**init**.py:59-71](file://backend/modelscope_studio/components/base/application/__init__.py#L59-L71) +- Chatbot (ModelScopeProChatbot) + - Example path: [backend/modelscope_studio/components/pro/chatbot/**init**.py:319-343](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L319-L343) + +### Lifecycle and Event Callbacks + +- AntdButton + - Events: `click` + - Slots: `icon`, `loading.icon` + - Reference: [backend/modelscope_studio/components/antd/button/**init**.py:41-49](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L49) +- AntdForm + - Events: `fields_change`, `finish`, `finish_failed`, `values_change` + - Data model: `AntdFormData` + - Reference: [backend/modelscope_studio/components/antd/form/**init**.py:23-36](file://backend/modelscope_studio/components/antd/form/__init__.py#L23-L36) +- ModelScopeApplication + - Events: `custom`, `mount`, `resize`, `unmount` + - Data model: `ApplicationPageData` + - Reference: [backend/modelscope_studio/components/base/application/**init**.py:30-54](file://backend/modelscope_studio/components/base/application/__init__.py#L30-L54) +- ModelScopeProChatbot + - Events: `change`, `copy`, `edit`, `delete`, `like`, `retry`, `suggestion_select`, `welcome_prompt_select` + - Data model: `ChatbotDataMessages` + - Reference: [backend/modelscope_studio/components/pro/chatbot/**init**.py:289-314](file://backend/modelscope_studio/components/pro/chatbot/__init__.py#L289-L314) + +### Parameter Validation and Exception Handling + +- Parameter Validation + - Constructor parameters are mostly optional or have default values; type annotations cover common enums and dictionary structures. + - Reference: [backend/modelscope_studio/components/antd/button/**init**.py:51-87](file://backend/modelscope_studio/components/antd/button/__init__.py#L51-L87), [backend/modelscope_studio/components/antd/form/**init**.py:43-80](file://backend/modelscope_studio/components/antd/form/__init__.py#L43-L80) +- Exception Handling + - It is recommended to catch exceptions in event callbacks at the business layer and log the error context. + - When frontend directory resolution fails, check whether the path returned by `resolve_frontend_dir` exists. + +### Version Compatibility + +- Current version: 2.0.0 + - Reference: [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) diff --git a/.wiki/en/Ant Design Components/Ant Design Components.md b/.wiki/en/Ant Design Components/Ant Design Components.md new file mode 100644 index 00000000..4b73b6df --- /dev/null +++ b/.wiki/en/Ant Design Components/Ant Design Components.md @@ -0,0 +1,531 @@ +# Ant Design Components + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [frontend/antd/package.json](file://frontend/antd/package.json) +- [frontend/antdx/package.json](file://frontend/antdx/package.json) +- [docs/app.py](file://docs/app.py) +- [docs/helper/Docs.py](file://docs/helper/Docs.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [README-zh_CN.md](file://README-zh_CN.md) +- [.changeset/pink-sails-itch.md](file://.changeset/pink-sails-itch.md) +- [.changeset/eleven-aliens-sell.md](file://.changeset/eleven-aliens-sell.md) +- [backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py) +- [backend/modelscope_studio/components/antdx/folder/directory_icon/__init__.py](file://backend/modelscope_studio/components/antdx/folder/directory_icon/__init__.py) +- [backend/modelscope_studio/components/antdx/sender/header/__init__.py](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py) + + +## Update Summary + +**Changes made** + +- Updated version information reflecting major upgrades from Gradio 5.x to 6.0, Ant Design 5.x to 6.0, and Ant Design X 1.x to 2.0 +- Added complete feature introduction for Ant Design X component library, including new components like ThoughtChain, Folder, Sender, etc. +- Expanded component classification with new component groups and feature descriptions +- Updated architecture documentation to reflect the new component organization structure + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Ant Design X Component Library](#ant-design-x-component-library) +7. [Dependency Analysis](#dependency-analysis) +8. [Performance Considerations](#performance-considerations) +9. [Troubleshooting Guide](#troubleshooting-guide) +10. [Conclusion](#conclusion) +11. [Appendix](#appendix) + +## Introduction + +This document covers the Ant Design component library in ModelScope Studio, systematically organizing component classifications, features, and usage methods across six major categories: General Components, Layout Components, Navigation Components, Data Entry Components, Data Display Components, and Feedback Components. With the major upgrades to Gradio 6.0, Ant Design 6.0, and Ant Design X 2.0, the component library now supports richer interaction capabilities and a more modern design system. The documentation also provides property descriptions, event handling, style customization, responsive and internationalization support, performance optimization, and best practices, along with rich examples and scenario-based explanations to help developers get started quickly and achieve high-quality implementations. + +## Project Structure + +ModelScope Studio exports Ant Design components as a Python package and bridges them to Ant Design React components through frontend Svelte packages, forming a dual-layer architecture of "Python layer component definition + frontend rendering bridge". It now also integrates the Ant Design X component library, providing richer interactive components. The documentation site aggregates documentation and examples for each component through a unified entry point for easy browsing and comparison. + +```mermaid +graph TB +subgraph "Backend Python" +A["backend/modelscope_studio/components/antd/__init__.py
Export all Ant Design component classes"] +B["backend/modelscope_studio/components/antd/components.py
Centralized import and export"] +C["backend/modelscope_studio/components/antdx/__init__.py
Export all Ant Design X component classes"] +D["backend/modelscope_studio/components/antdx/components.py
Centralized import and export"] +E["backend/modelscope_studio/utils/dev/component.py
Component base class and context"] +end +subgraph "Frontend Svelte" +F["frontend/antd/package.json
Ant Design package metadata"] +G["frontend/antdx/package.json
Ant Design X package metadata"] +H["frontend/antd/button/Index.svelte
Button component bridge example"] +end +subgraph "Documentation and Site" +I["docs/app.py
Component classification and menu generation"] +J["docs/helper/Docs.py
Documentation parsing and example rendering"] +end +A --> H +C --> H +B --> H +D --> H +E --> A +F --> H +G --> H +I --> J +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-147](file://backend/modelscope_studio/components/antd/components.py#L1-L147) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/utils/dev/component.py:1-169](file://backend/modelscope_studio/utils/dev/component.py#L1-L169) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [docs/app.py:19-438](file://docs/app.py#L19-L438) +- [docs/helper/Docs.py:12-178](file://docs/helper/Docs.py#L12-L178) + +**Section Source** + +- [docs/app.py:19-438](file://docs/app.py#L19-L438) +- [docs/helper/Docs.py:12-178](file://docs/helper/Docs.py#L12-L178) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-147](file://backend/modelscope_studio/components/antd/components.py#L1-L147) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/utils/dev/component.py:1-169](file://backend/modelscope_studio/utils/dev/component.py#L1-L169) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + +## Core Components + +- Component Export and Naming: The backend uniformly exports Ant Design component classes through **init**.py and components.py, now including Ant Design X components, facilitating on-demand import and batch usage. +- Component Base Classes: ModelScopeComponent/ModelScopeLayoutComponent/ModelScopeDataLayoutComponent provide unified visibility, element ID, class name, inline style, slot, and lifecycle behaviors. +- Frontend Bridge: Svelte components dynamically load Ant Design React components through importComponent, uniformly handling props, slots, and style injection. +- Version Upgrade: Upgraded from Gradio 5.x to 6.0, supporting a more powerful event system and component lifecycle management. + +**Section Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-147](file://backend/modelscope_studio/components/antd/components.py#L1-L147) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/utils/dev/component.py:54-169](file://backend/modelscope_studio/utils/dev/component.py#L54-L169) +- [frontend/antd/button/Index.svelte:10-74](file://frontend/antd/button/Index.svelte#L10-L74) + +## Architecture Overview + +The diagram below shows the key flow from Python component invocation to frontend rendering, and how the documentation site organizes and presents component examples. It now includes support for Ant Design X components. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Py as "Python Component Layer
antd/__init__.py + antdx/__init__.py" +participant Bridge as "Svelte Bridge Layer
Index.svelte" +participant Antd as "Ant Design React Component" +participant Antdx as "Ant Design X Component" +participant Docs as "Documentation Site
docs/app.py + Docs" +Dev->>Py : Import and instantiate component +Py->>Bridge : Pass component properties and slots +Bridge->>Bridge : processProps/className/id/style processing +Bridge->>Antd : Dynamically load and render Ant Design component +Bridge->>Antdx : Dynamically load and render Ant Design X component +Antd-->>Dev : Render result +Antdx-->>Dev : Render result +Docs->>Py : Aggregate component documentation and examples +Docs->>Bridge : Render examples and code blocks +``` + +**Diagram Source** + +- [docs/app.py:19-438](file://docs/app.py#L19-L438) +- [docs/helper/Docs.py:82-178](file://docs/helper/Docs.py#L82-L178) +- [frontend/antd/button/Index.svelte:24-74](file://frontend/antd/button/Index.svelte#L24-L74) + +## Component Details + +### General Components + +- Button: Supports link navigation, icons, sizes, and theme variants; controls target behavior through href_target; supports slots and style customization. +- FloatButton: Supports back-to-top, grouping, and icons; can combine multiple floating actions. +- Icon: Supports icon font providers; can be used with other components. +- Typography: Supports semantic typography elements like headings, text, paragraphs, and links. + +Usage Tips + +- Property Mapping: The frontend uniformly passes through visible, elem_id, elem_classes, elem_style, value, etc. through processProps. +- Slots: The Svelte side gets the default slot through getSlots for rendering child nodes. +- Example: The button component bridge example demonstrates dynamic loading and style concatenation. + +**Section Source** + +- [frontend/antd/button/Index.svelte:24-74](file://frontend/antd/button/Index.svelte#L24-L74) +- [docs/app.py:198-209](file://docs/app.py#L198-L209) + +### Layout Components + +- Divider: Supports horizontal/vertical and dashed styles. +- Flex: Provides flexible flex container capabilities. +- Grid: Row and Col support responsive breakpoints and gutters. +- Layout: Contains Header, Sider, Content, Footer subcomponents, suitable for building page skeletons. +- Space: Supports compact mode and wrapping child items. +- Splitter: Supports panels and drag splitting. +- Masonry: Supports responsive column count and automatic item height adjustment. + +Usage Tips + +- Responsive: Grid and Flex provide multi-breakpoint configurations for mobile and desktop adaptation. +- Styling: elem_style can be applied directly to containers for positioning, dimensions, and margin control. + +**Section Source** + +- [docs/app.py:216-233](file://docs/app.py#L216-L233) + +### Navigation Components + +- Anchor: Supports scroll positioning and anchor items. +- Breadcrumb: Supports custom separators and route items. +- Dropdown: Supports button dropdowns and menu items. +- Menu: Supports multi-level menus and selected state. +- Pagination: Supports page switching and sizes. +- Steps: Supports step status and descriptions. + +Usage Tips + +- Events: Navigation components typically trigger page transitions or content updates through callbacks or state changes. +- Internationalization: Language environment can be set uniformly through ConfigProvider (see "Internationalization Support"). + +**Section Source** + +- [docs/app.py:240-257](file://docs/app.py#L240-L257) + +### Data Entry Components + +- AutoComplete: Supports options and backfill. +- Cascader: Supports multi-level linkage and lazy loading. +- Checkbox: Supports groups and options. +- ColorPicker: Supports presets and formatting. +- DatePicker: Supports range selection and preset shortcuts. +- Form: Supports field validation rules, dynamic add/remove, and Provider. +- Input: Supports password, search, textarea, and OTP. +- InputNumber: Supports step and precision. +- Mentions: Supports keyword mentions and options. +- Radio: Supports buttons and groups. +- Rate: Supports readonly and half-star. +- Select: Supports multi-select and search. +- Slider: Supports marks and range. +- Switch: Supports disabled and loading. +- TimePicker: Supports range selection. +- Transfer: Supports source and target lists. +- TreeSelect: Supports directory tree and nodes. +- Upload: Supports drag and drop and custom requests. + +Usage Tips + +- Validation: FormItemRule provides validation rule definitions; dynamic forms support conditional rendering and field add/remove. +- Events: Common events like onChange/onFocus/onBlur can be used for linkage and state management. +- Styling: elem_style/elem_classes are used for fine-tuning appearance and layout. + +**Section Source** + +- [docs/app.py:264-317](file://docs/app.py#L264-L317) + +### Data Display Components + +- Avatar: Supports avatar groups and badges. +- Badge: Supports ribbons and badges. +- Calendar: Supports month view and event markers. +- Card: Supports grid and meta information. +- Carousel: Supports auto-play and indicators. +- Collapse: Supports accordion and panel items. +- Descriptions: Supports key-value pair display. +- Empty: Supports custom images and actions. +- Image: Supports preview groups and lazy loading. +- List: Supports items and meta information. +- Popover: Supports triggers and content. +- QRCode: Supports colors and sizes. +- Segmented: Supports options and disabled. +- Statistic: Supports countdown and timer. +- Table: Supports columns, expansion, selection, and sorting. +- Tabs: Supports tab items and types. +- Tag: Supports checkable tags. +- Timeline: Supports nodes and directions. +- Tooltip: Supports triggers and positions. +- Tour: Supports steps and highlights. +- Tree: Supports directory tree and nodes. + +Usage Tips + +- Table: Supports fixed columns, sorting, filtering, and pagination; can combine with Segmented for dimension switching. +- Image: ImagePreviewGroup provides multi-image preview capability. +- Interaction: Popover/Tooltip/Tour improve information density and guidance efficiency. + +**Section Source** + +- [docs/app.py:324-386](file://docs/app.py#L324-L386) + +### Feedback Components + +- Alert: Supports multiple types and closable. +- Drawer: Supports positions and nested content. +- Message: Supports global messages and duration. +- Modal: Supports static dialogs and mask layers. +- Notification: Supports multiple notifications and closable. +- Popconfirm: Supports confirm and cancel callbacks. +- Progress: Supports circle and percentage. +- Result: Supports success/error/waiting status pages. +- Skeleton: Supports avatar, button, input, and image. +- Spin: Supports fullscreen and inline. +- Watermark: Supports text and image watermarks. + +Usage Tips + +- Global Components: Message/Notification/Modal/Drawer are typically invoked through APIs rather than direct rendering. +- Animation and Transitions: Progress/Spin/Skeleton improve loading experience and placeholder effects. +- Accessibility: It is recommended to provide keyboard-accessible and screen-reader-friendly cues for interactive components. + +**Section Source** + +- [docs/app.py:393-425](file://docs/app.py#L393-L425) + +### Other Components + +- Affix: Supports pinning and offset. +- ConfigProvider: Provides theme, language, and global style overrides. + +Usage Tips + +- Internationalization: ConfigProvider supports locales injection for Chinese/English switching. +- Theme: Override global theme variables through ConfigProvider for consistent style. + +**Section Source** + +- [docs/app.py:432-437](file://docs/app.py#L432-L437) + +## Ant Design X Component Library + +### New Component Overview + +Ant Design X is an extension component library of Ant Design, providing richer interactive components and solutions for professional application scenarios. This upgrade includes the following main components: + +#### Thought Chain Component + +- ThoughtChain: Thought chain container component, supports multi-step thought process display +- ThoughtChainItem: Thought chain item component, supports state management, collapsible, and blinking effects +- Supports pending, success, error, abort states +- Configurable content, description, footer, icon, and title + +#### File Management Components + +- Folder: Folder component, supports directory tree and file management +- FolderDirectoryIcon: Directory icon component, supports different file type icon display +- FileCard: File card component, supports file list display +- FileCardList: File list component, supports file item management + +#### Conversation Interaction Components + +- Bubble: Message bubble component, supports user and system message display +- BubbleList: Message list component, supports message items and role management +- Conversations: Conversation component, supports history conversation management +- Sender: Sender component, supports message sending and header management +- SenderHeader: Sender header component, supports expand state control + +#### Content Display Components + +- CodeHighlighter: Code highlighting component, supports multiple programming language syntax highlighting +- Mermaid: Chart component, supports Mermaid syntax chart rendering +- Prompts: Prompt component, supports prompt management and display +- Sources: Source component, supports content source display +- Suggestion: Suggestion component, supports smart suggestion display + +#### Interaction Tool Components + +- Actions: Action component, supports multiple action buttons +- Attachments: Attachment component, supports file attachment management +- Notification: Notification component, supports system notification display +- Welcome: Welcome component, supports welcome page display +- XProvider: Provider component, supports context provision + +Usage Tips + +- Slot System: Most components support named slots like content, description, footer, icon, title, etc. +- Event System: Supports event listening like open_change +- State Management: Supports state properties like open, closable, collapsible, etc. +- Style Customization: Supports styles and class_names properties for style customization + +**Section Source** + +- [backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/**init**.py:1-81](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L1-L81) +- [backend/modelscope_studio/components/antdx/folder/directory_icon/**init**.py:1-61](file://backend/modelscope_studio/components/antdx/folder/directory_icon/__init__.py#L1-L61) +- [backend/modelscope_studio/components/antdx/sender/header/**init**.py:1-74](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py#L1-L74) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Dependency Analysis + +- Python Layer Export: **init**.py and components.py centrally export Ant Design and Ant Design X component classes for unified import. +- Frontend Bridge: Svelte components dynamically load Ant Design React and Ant Design X components through importComponent, with processProps uniformly handling properties and styles. +- Documentation Site: docs/app.py aggregates component documentation and examples, Docs.py parses Markdown and renders examples and code blocks. + +```mermaid +graph LR +PyInit["backend/.../antd/__init__.py"] --> PyComp["backend/.../antd/components.py"] +PyInitX["backend/.../antdx/__init__.py"] --> PyCompX["backend/.../antdx/components.py"] +PyComp --> SvelteBtn["frontend/antd/button/Index.svelte"] +PyCompX --> SvelteBtn +DocsApp["docs/app.py"] --> DocsHelper["docs/helper/Docs.py"] +DocsHelper --> SvelteBtn +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-147](file://backend/modelscope_studio/components/antd/components.py#L1-L147) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [frontend/antd/button/Index.svelte:10-74](file://frontend/antd/button/Index.svelte#L10-L74) +- [docs/app.py:19-438](file://docs/app.py#L19-L438) +- [docs/helper/Docs.py:12-178](file://docs/helper/Docs.py#L12-L178) + +**Section Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-147](file://backend/modelscope_studio/components/antd/components.py#L1-L147) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [frontend/antd/button/Index.svelte:10-74](file://frontend/antd/button/Index.svelte#L10-L74) +- [docs/app.py:19-438](file://docs/app.py#L19-L438) +- [docs/helper/Docs.py:12-178](file://docs/helper/Docs.py#L12-L178) + +## Performance Considerations + +- Dynamic Loading: The frontend implements on-demand loading through importComponent, reducing initial bundle size and first-screen blocking. +- Property Pass-through: processProps uniformly handles properties and styles, avoiding repeated calculations and redundant rendering. +- Tables and Lists: Use virtualization and pagination reasonably to avoid rendering large numbers of nodes at once. +- Images and Skeleton: Use Skeleton and Image.lazy to reduce resource pressure and blank screen time. +- Global Components: Message/Notification/Modal etc. should limit concurrent quantity to avoid lag caused by frequent popups. +- Styling: elem_style/elem_classes should be reused as much as possible to avoid excessive inline styles causing repaints. +- Component Lazy Loading: Ant Design X components support lazy loading to improve application startup performance. + +## Troubleshooting Guide + +- Blank page or component not displaying + - Confirm that Application and ConfigProvider are wrapped in the outer layer. + - Enable ssr_mode=False when starting in Hugging Face Space. + - Check dependency version compatibility of Ant Design X components. +- Abnormal component styles + - Use elem_style/elem_classes to adjust container styles; avoid conflicts with global styles. + - Check whether theme and font resources are correctly imported. + - Confirm that Ant Design X component style files are correctly loaded. +- Internationalization not taking effect + - Inject locales through ConfigProvider; ensure language keys match Ant Design language packs. +- Examples not running + - Confirm that component documentation paths and example files exist in docs/app.py; check Docs.py example module loading logic. + - Check whether import paths for new components are correct. +- Version compatibility issues + - Ensure Gradio, Ant Design, and Ant Design X versions match. + - Check whether component properties are compatible with new versions. + +**Section Source** + +- [README-zh_CN.md:32-32](file://README-zh_CN.md#L32-L32) +- [docs/app.py:577-595](file://docs/app.py#L577-L595) +- [docs/helper/Docs.py:58-75](file://docs/helper/Docs.py#L58-L75) + +## Conclusion + +ModelScope Studio's Ant Design component library achieves seamless integration of Ant Design components in the Gradio ecosystem through a clear Python export layer and frontend bridge layer. With the major upgrades to Gradio 6.0, Ant Design 6.0, and Ant Design X 2.0, the component library now provides richer interaction capabilities and a more modern design system. With a unified base class system, slot mechanism, event system, and documentation site, developers can efficiently build beautiful and maintainable interfaces. It is recommended to combine responsive and internationalization strategies in actual projects, follow performance optimization and best practices to achieve a better user experience. + +## Appendix + +### Component Properties and Events Common Notes + +- Common Properties + - visible: Controls component visibility + - elem_id: Element ID + - elem_classes: Class name array or string + - elem_style: Inline style object + - value: Component value (if applicable) +- Events + - onChange/onFocus/onBlur: Common for input components + - onClick/onContextMenu: Common for button and interactive components + - onConfirm/onCancel: Common for confirmation components + - open_change: For state changes in expandable components +- Slots + - Default slot is used to render child nodes; some components support named slots like content, description, footer, icon, title, etc. + +**Section Source** + +- [backend/modelscope_studio/utils/dev/component.py:54-169](file://backend/modelscope_studio/utils/dev/component.py#L54-L169) +- [frontend/antd/button/Index.svelte:24-74](file://frontend/antd/button/Index.svelte#L24-L74) + +### Responsive Design and Internationalization Support + +- Responsive + - Grid and Flex provide multi-breakpoint configurations; it is recommended to set breakpoints and spacing separately for mobile and desktop. +- Internationalization + - Inject locales through ConfigProvider to achieve Chinese/English switching; note the correspondence between language packs and component text. + +**Section Source** + +- [docs/app.py:435-437](file://docs/app.py#L435-L437) + +### Code Examples and Scenario-based Applications + +- Example Organization + - The documentation site automatically scans the demos directory through Docs.py, rendering examples and code blocks; supports collapsible display and title annotation. +- Scenario Suggestions + - Forms: Use Form + FormItem + validation rules, combined with dynamic forms for conditional rendering. + - Data Tables: Combine Pagination and virtual scrolling to improve interaction smoothness with large data volumes. + - Navigation: Use Menu + Breadcrumb + Steps to build clear hierarchy and process guidance. + - Feedback: Use Message/Notification/Modal/Drawer to provide timely user feedback and operation confirmation. + - Thought Chain: Use ThoughtChain + ThoughtChainItem to build AI application thought process display. + - File Management: Use Folder + FileCard + Attachments to implement file management system. + +**Section Source** + +- [docs/helper/Docs.py:82-178](file://docs/helper/Docs.py#L82-L178) +- [docs/app.py:19-438](file://docs/app.py#L19-L438) + +### Parameter Mapping Supplementary Notes + +- Collapse Component Properties + - active_key: Currently expanded panel key + - default_active_key: Default expanded panel key + - accordion: Accordion mode + - bordered: Whether to have border + - collapsible: Collapsible trigger area + - destroy_inactive_panel: Destroy collapsed hidden panels + - expand_icon: Custom expand icon + - expand_icon_placement: Expand icon position, options are `start` or `end` + - ghost: Transparent borderless + - size: Size + +### Version Upgrade Notes + +- Gradio 6.0 Upgrade + - Supports new event system and component lifecycle management + - Improved component state management and data flow +- Ant Design 6.0 Upgrade + - More modern design system and visual specifications + - Enhanced accessibility support + - Improved theme customization capabilities +- Ant Design X 2.0 Upgrade + - Added rich interactive components + - Improved component API and slot system + - Enhanced TypeScript type support + +**Section Source** + +- [.changeset/pink-sails-itch.md:12-12](file://.changeset/pink-sails-itch.md#L12-L12) +- [.changeset/eleven-aliens-sell.md:12-12](file://.changeset/eleven-aliens-sell.md#L12-L12) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) diff --git a/.wiki/en/Ant Design Components/Components Overview.md b/.wiki/en/Ant Design Components/Components Overview.md new file mode 100644 index 00000000..1886a7a4 --- /dev/null +++ b/.wiki/en/Ant Design Components/Components Overview.md @@ -0,0 +1,384 @@ +# Components Overview + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [frontend/antd/package.json](file://frontend/antd/package.json) +- [docs/components/antd/overview/README.md](file://docs/components/antd/overview/README.md) +- [docs/README.md](file://docs/README.md) +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/components/pro/__init__.py](file://backend/modelscope_studio/components/pro/__init__.py) +- [docs/app.py](file://docs/app.py) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts](file://frontend/antd/config-provider/locales.ts) +- [docs/components/antd/button/demos/basic.py](file://docs/components/antd/button/demos/basic.py) +- [docs/components/antd/form/demos/basic.py](file://docs/components/antd/form/demos/basic.py) +- [docs/components/antd/layout/demos/basic.py](file://docs/components/antd/layout/demos/basic.py) +- [frontend/svelte-preprocess-react/svelte-contexts/slot.svelte.ts](file://frontend/svelte-preprocess-react/svelte-contexts/slot.svelte.ts) +- [frontend/svelte-preprocess-react/component/import.ts](file://frontend/svelte-preprocess-react/component/import.ts) +- [frontend/svelte-preprocess-react/component/props.svelte.ts](file://frontend/svelte-preprocess-react/component/props.svelte.ts) +- [docs/components/base/fragment/README-zh_CN.md](file://docs/components/base/fragment/README-zh_CN.md) +- [CHANGELOG.md](file://CHANGELOG.md) +- [pnpm-lock.yaml](file://pnpm-lock.yaml) +- [package.json](file://package.json) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) + + +## Update Summary + +**Changes made** + +- Updated version information to reflect the upgrade from Ant Design 5.x to 6.3.5 +- Updated migration information from Gradio 5.x to 6.0 +- Updated component version compatibility notes +- Updated version-related information for theme customization and internationalization mechanisms + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Classification and Organization](#component-classification-and-organization) +6. [Usage Principles and Best Practices](#usage-principles-and-best-practices) +7. [Responsive Design and Internationalization](#responsive-design-and-internationalization) +8. [Theme Customization and Style System](#theme-customization-and-style-system) +9. [Typical Scenarios and Combined Usage](#typical-scenarios-and-combined-usage) +10. [Component Dependencies and Integration Patterns](#component-dependencies-and-integration-patterns) +11. [Performance Considerations](#performance-considerations) +12. [Troubleshooting Guide](#troubleshooting-guide) +13. [Conclusion](#conclusion) + +## Introduction + +This overview covers the overall presentation of the Ant Design component library in modelscope_studio, including features, design philosophy, overall architecture, component classification system, usage principles, responsive design and internationalization, theme customization, typical scenarios and combination methods, and inter-component dependencies and integration patterns. The component library is built on Gradio 6.0, providing richer page layouts and interaction capabilities, and adapts to Ant Design 6.3.5 styles and behaviors through a unified configuration container. + +**Update** The project has been upgraded from Gradio 5.x to 6.0, and Ant Design from 5.x to 6.3.5, bringing better performance and compatibility. + +**Version**: This document applies to ModelScope Studio 2.0+, supporting Gradio 6.0, Ant Design 6.3.5, and Ant Design X 2.0 + +## Project Structure + +- Backend Module Export: The Python layer exports all Ant Design components through module aggregation, facilitating direct on-demand import and usage. +- Frontend Implementation: Each Ant Design component is implemented in Svelte/React form, with typed properties and slot mechanism, achieving bridge with Gradio 6.0. +- Documentation and Examples: Accompanying documentation and demo scripts covering quick start, property constraints, event binding, slot rendering, function parameter passing, internationalization, and theme customization topics. + +```mermaid +graph TB +subgraph "Backend" +PY_INIT["backend/modelscope_studio/components/antd/__init__.py"] +PY_COMP["backend/modelscope_studio/components/antd/components.py"] +BASE_INIT["backend/modelscope_studio/components/base/__init__.py"] +PRO_INIT["backend/modelscope_studio/components/pro/__init__.py"] +VERSION["backend/modelscope_studio/version.py"] +end +subgraph "Frontend" +PKG["frontend/antd/package.json"] +CFG_TSX["frontend/antd/config-provider/config-provider.tsx"] +LOCALES["frontend/antd/config-provider/locales.ts"] +BUTTON_PKG["frontend/antd/button/package.json"] +FORM_PKG["frontend/antd/form/package.json"] +end +subgraph "Documentation and Examples" +OVERVIEW["docs/components/antd/overview/README.md"] +APP_PY["docs/app.py"] +DEMO_BTN["docs/components/antd/button/demos/basic.py"] +DEMO_FORM["docs/components/antd/form/demos/basic.py"] +DEMO_LAYOUT["docs/components/antd/layout/demos/basic.py"] +end +PY_INIT --> PY_COMP +PY_COMP --> PKG +PKG --> CFG_TSX +CFG_TSX --> LOCALES +PY_INIT --> OVERVIEW +APP_PY --> OVERVIEW +DEMO_BTN --> OVERVIEW +DEMO_FORM --> OVERVIEW +DEMO_LAYOUT --> OVERVIEW +BASE_INIT --> OVERVIEW +PRO_INIT --> OVERVIEW +VERSION --> OVERVIEW +BUTTON_PKG --> CFG_TSX +FORM_PKG --> CFG_TSX +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-144](file://backend/modelscope_studio/components/antd/components.py#L1-L144) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:313-465](file://frontend/antd/config-provider/locales.ts#L313-L465) +- [docs/components/antd/overview/README.md:1-75](file://docs/components/antd/overview/README.md#L1-L75) +- [docs/app.py:200-399](file://docs/app.py#L200-L399) +- [docs/components/antd/button/demos/basic.py:1-26](file://docs/components/antd/button/demos/basic.py#L1-L26) +- [docs/components/antd/form/demos/basic.py:1-94](file://docs/components/antd/form/demos/basic.py#L1-L94) +- [docs/components/antd/layout/demos/basic.py:1-88](file://docs/components/antd/layout/demos/basic.py#L1-L88) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [frontend/antd/button/package.json:1-15](file://frontend/antd/button/package.json#L1-L15) +- [frontend/antd/form/package.json:1-15](file://frontend/antd/form/package.json#L1-L15) + +**Section Source** + +- [docs/README.md:19-75](file://docs/README.md#L19-L75) +- [docs/components/antd/overview/README.md:1-75](file://docs/components/antd/overview/README.md#L1-L75) +- [docs/app.py:200-399](file://docs/app.py#L200-L399) +- [CHANGELOG.md:13](file://CHANGELOG.md#L13) + +## Core Components + +- Component Export: The backend exports all Ant Design components through module aggregation, forming a unified namespace for direct import and usage. +- Configuration Container: ConfigProvider provides global configuration for theme, language, popup container, etc., compatible with Ant Design 6.3.5 and injecting Gradio 6.0 style adaptation. +- Base Components: Application, AutoLoading, Fragment, and other base capabilities ensure correct component tree rendering and loading state feedback. +- Pro Components: Extended components for advanced scenarios (such as chatbot, editor, Web Sandbox, etc.). + +**Update** All components are now compatible with Ant Design 6.3.5 and Gradio 6.0 new features. + +**Section Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-144](file://backend/modelscope_studio/components/antd/components.py#L1-L144) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [pnpm-lock.yaml:2830](file://pnpm-lock.yaml#L2830-L2835) + +## Architecture Overview + +The overall architecture revolves around the closed loop of "backend component export + frontend bridge rendering + documentation and examples". The backend is responsible for component classes and property mapping, the frontend is responsible for converting properties and slots to React/JSX rendering, and injecting themes and internationalization through ConfigProvider; documentation and examples provide usage patterns and constraint explanations. + +**Update** The architecture is now fully adapted to Gradio 6.0's new event system and component lifecycle. + +```mermaid +graph TB +A["Backend Component Export
backend/modelscope_studio/components/antd/__init__.py"] --> B["Frontend Bridge Component
frontend/antd/*/*.tsx"] +B --> C["Configuration Container
frontend/antd/config-provider/config-provider.tsx"] +C --> D["Internationalization and Locale
frontend/antd/config-provider/locales.ts"] +E["Base Components
backend/modelscope_studio/components/base/__init__.py"] --> A +F["Pro Extension Components
backend/modelscope_studio/components/pro/__init__.py"] --> A +G["Documentation and Examples
docs/components/antd/*/demos/*.py"] --> A +G --> B +G --> C +H["Version Management
backend/modelscope_studio/version.py"] --> A +I["Dependency Lock
pnpm-lock.yaml"] --> B +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:313-465](file://frontend/antd/config-provider/locales.ts#L313-L465) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [docs/components/antd/button/demos/basic.py:1-26](file://docs/components/antd/button/demos/basic.py#L1-L26) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [pnpm-lock.yaml:2830](file://pnpm-lock.yaml#L2830-L2835) + +## Component Classification and Organization + +According to the navigation structure in the documentation, Ant Design components are divided into six major categories for easy retrieval and usage by functional domain: + +- General Components + - Includes: Button, Icon, Typography, etc. + - Examples: Button, Icon, Typography +- Layout Components + - Includes: Divider, Flex, Grid, Layout, Space, Splitter, etc. + - Examples: Grid, Flex, Splitter, Page Layout +- Navigation Components + - Includes: Anchor, Breadcrumb, Dropdown, Menu, Pagination, Steps, etc. + - Examples: Anchor, Breadcrumb, Dropdown, Navigation Menu, Pagination, Steps +- Data Entry Components + - Includes: AutoComplete, Cascader, Checkbox, ColorPicker, DatePicker, Form, Input, InputNumber, Mentions, Radio, Rate, Select, Slider, Switch, TimePicker, Transfer, TreeSelect, Upload, etc. + - Examples: Form, Input, Select, Time/Date, Switch, Slider, Upload +- Data Display Components + - Includes: Avatar, Badge, Calendar, Card, Carousel, Collapse, Descriptions, Empty, Image, List, Popover, QRCode, Segmented, Statistic, Table, Tabs, Tag, Timeline, Tooltip, Tour, Tree, etc. + - Examples: Card, Table, Tag, Timeline, Tree, Statistic +- Feedback Components + - Includes: Alert, Drawer, Message, Modal, Notification, etc. + - Examples: Alert, Drawer, Message, Modal, Notification + +**Update** All components have been adapted to Ant Design 6.3.5's new API and style specifications. + +The above classification and examples are from the documentation's navigation and example scripts, making it easy for developers to quickly locate components and reference usage. + +**Section Source** + +- [docs/app.py:200-399](file://docs/app.py#L200-L399) +- [docs/components/antd/button/demos/basic.py:1-26](file://docs/components/antd/button/demos/basic.py#L1-L26) +- [docs/components/antd/form/demos/basic.py:1-94](file://docs/components/antd/form/demos/basic.py#L1-L94) +- [docs/components/antd/layout/demos/basic.py:1-88](file://docs/components/antd/layout/demos/basic.py#L1-L88) + +## Usage Principles and Best Practices + +- Unified Entry: Import all components through the antd module to avoid scattered imports. +- Wrapper Container: All antd components must be placed between Application and ConfigProvider to ensure dependencies and styles work properly. +- Loading State Feedback: It is recommended to use AutoLoading to automatically display loading animations during requests to improve user experience. +- Event Binding: Events use Gradio 6.0's event binding form, with parameters stored in specific fields as arrays, note the destructure and handling. +- Slot Mechanism: Python cannot directly pass components as parameters; use Slot to wrap modules; if only strings or numbers, they can be passed directly as properties. +- Function Parameter Passing: Pass JS functions as strings, the frontend will automatically compile them into functions; functions returning ReactNode can be handled in two ways: rendered as regular nodes or generated through the global React object. +- Slot Compatibility: Some component slots only support modelscope_studio components; if you need to insert other Gradio components, wrap them with Fragment. + +**Update** The event system is fully adapted to Gradio 6.0's new event model, and the slot mechanism has been optimized accordingly. + +**Section Source** + +- [docs/components/antd/overview/README.md:13-75](file://docs/components/antd/overview/README.md#L13-L75) +- [docs/components/base/fragment/README-zh_CN.md:1-10](file://docs/components/base/fragment/README-zh_CN.md#L1-L10) + +## Responsive Design and Internationalization + +- Responsive Design: Components follow Ant Design 6.3.5's responsive specifications, combining Flex, Grid, and other layout components to achieve adaptive layouts. +- Internationalization: ConfigProvider supports multi-language switching, with built-in extensive language and region mapping, automatically loading corresponding language packs and date library languages to meet multi-language site requirements. + +```mermaid +sequenceDiagram +participant U as "User" +participant CFG as "ConfigProvider" +participant L as "locales.ts" +participant D as "dayjs" +U->>CFG : Set language identifier +CFG->>L : Parse language identifier and load corresponding language pack +L-->>CFG : Return Antd 6.3.5 language pack and dayjs language +CFG->>D : Set dayjs language +CFG-->>U : Apply language configuration +``` + +**Diagram Source** + +- [frontend/antd/config-provider/config-provider.tsx:85-105](file://frontend/antd/config-provider/config-provider.tsx#L85-L105) +- [frontend/antd/config-provider/locales.ts:313-465](file://frontend/antd/config-provider/locales.ts#L313-L465) + +**Section Source** + +- [frontend/antd/config-provider/config-provider.tsx:15-27](file://frontend/antd/config-provider/config-provider.tsx#L15-L27) +- [frontend/antd/config-provider/locales.ts:313-465](file://frontend/antd/config-provider/locales.ts#L313-L465) + +## Theme Customization and Style System + +- Theme Mode: Control dark/compact algorithms through ConfigProvider's themeMode, supporting dynamic switching. +- Theme Tokens: Support setting primary color and other tokens, combining with algorithms to achieve unified theme style. +- Style Injection: Use style provider to ensure component prefix and style isolation, avoiding conflicts. + +```mermaid +flowchart TD +Start(["Enter ConfigProvider"]) --> Parse["Parse themeMode and algorithm"] +Parse --> Merge["Merge algorithm and theme tokens"] +Merge --> Apply["Apply to Ant Design 6.3.5 theme"] +Apply --> Inject["Inject style provider"] +Inject --> End(["Complete theme rendering"]) +``` + +**Diagram Source** + +- [frontend/antd/config-provider/config-provider.tsx:88-143](file://frontend/antd/config-provider/config-provider.tsx#L88-L143) + +**Section Source** + +- [frontend/antd/config-provider/config-provider.tsx:53-151](file://frontend/antd/config-provider/config-provider.tsx#L53-L151) + +## Typical Scenarios and Combined Usage + +- Quick Start: Under Application and ConfigProvider wrapper, use Button, Icon, Typography, and other general components to build basic interfaces. +- Form Scenarios: Use Form and Form.Item combined with Input, Select, DatePicker, Upload, and other data entry components, combined with validation rules and submit callbacks. +- Page Layout: Use Layout, Grid, Flex, Space, and other layout components to build page skeletons, combined with Sider, Header, Content, Footer to achieve complex page structures. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant App as "Application" +participant Cfg as "ConfigProvider" +participant Btn as "Button" +participant Form as "Form" +participant Lay as "Layout" +Dev->>App : Create application context +App->>Cfg : Inject global configuration (theme/language) +Cfg->>Btn : Render button component +Cfg->>Form : Render form component +Cfg->>Lay : Render layout component +Btn-->>Dev : Trigger events and interactions +Form-->>Dev : Collect data and validate +Lay-->>Dev : Layout structure output +``` + +**Diagram Source** + +- [docs/components/antd/button/demos/basic.py:5-26](file://docs/components/antd/button/demos/basic.py#L5-L26) +- [docs/components/antd/form/demos/basic.py:16-94](file://docs/components/antd/form/demos/basic.py#L16-L94) +- [docs/components/antd/layout/demos/basic.py:42-88](file://docs/components/antd/layout/demos/basic.py#L42-L88) + +**Section Source** + +- [docs/components/antd/button/demos/basic.py:1-26](file://docs/components/antd/button/demos/basic.py#L1-L26) +- [docs/components/antd/form/demos/basic.py:1-94](file://docs/components/antd/form/demos/basic.py#L1-L94) +- [docs/components/antd/layout/demos/basic.py:1-88](file://docs/components/antd/layout/demos/basic.py#L1-L88) + +## Component Dependencies and Integration Patterns + +- Component Dependencies: Each component is exposed through backend export modules, with frontend managing versions and types as independent packages. +- Slots and Context: The frontend supports complex nesting and dynamic rendering through slot context and parameter mapping mechanisms. +- Initialization Flow: Before component loading, wait for initialization to complete to ensure global objects are available. +- Event and Property Mapping: The frontend uniformly maps properties and events to ensure consistency with Gradio 6.0's event model. + +**Update** Dependency relationships have been updated to reflect new version requirements for Gradio 6.0 and Ant Design 6.3.5. + +```mermaid +graph LR +PY["Backend Export Module"] --> FE["Frontend Component Implementation"] +FE --> CTX["Slot Context and Parameter Mapping"] +FE --> INIT["Initialization Flow"] +FE --> EVT["Event and Property Mapping"] +CTX --> REN["Render Pipeline"] +INIT --> REN +EVT --> REN +SUB["Sub-package Management"] --> FE +LOCK["Dependency Lock"] --> FE +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [frontend/svelte-preprocess-react/svelte-contexts/slot.svelte.ts:55-102](file://frontend/svelte-preprocess-react/svelte-contexts/slot.svelte.ts#L55-L102) +- [frontend/svelte-preprocess-react/component/import.ts:1-20](file://frontend/svelte-preprocess-react/component/import.ts#L1-L20) +- [frontend/svelte-preprocess-react/component/props.svelte.ts:258-312](file://frontend/svelte-preprocess-react/component/props.svelte.ts#L258-L312) +- [frontend/antd/button/package.json:1-15](file://frontend/antd/button/package.json#L1-L15) +- [pnpm-lock.yaml:2830](file://pnpm-lock.yaml#L2830-L2835) + +**Section Source** + +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/svelte-preprocess-react/svelte-contexts/slot.svelte.ts:55-102](file://frontend/svelte-preprocess-react/svelte-contexts/slot.svelte.ts#L55-L102) +- [frontend/svelte-preprocess-react/component/import.ts:1-20](file://frontend/svelte-preprocess-react/component/import.ts#L1-L20) +- [frontend/svelte-preprocess-react/component/props.svelte.ts:258-312](file://frontend/svelte-preprocess-react/component/props.svelte.ts#L258-L312) + +## Performance Considerations + +- On-demand Rendering: Reduce unnecessary component instantiation through slots and conditional rendering. +- Theme and Internationalization Lazy Loading: Language packs and theme algorithms are loaded on-demand, reducing initial overhead. +- Event and Property Mapping: Unified mapping reduces repeated calculations and DOM operations. +- Layout Component Optimization: Prefer modern layouts like Flex and Grid to reduce reflow and repaint. + +**Update** Performance optimization has been adjusted for Gradio 6.0's new architecture, providing better rendering performance. + +[This section is general guidance, no specific file references needed] + +## Troubleshooting Guide + +- Page preview unsuccessful: Confirm all components are wrapped in Application. +- Abnormal styles: Confirm ConfigProvider is correctly wrapped, and themeMode, locale settings are as expected. +- Events not responding: Check whether event binding uses Gradio 6.0 form, and whether parameters are correctly destructured. +- Slots not working: Confirm using Slot to wrap modules, or directly passing strings/numbers; if you need to insert other Gradio components, wrap with Fragment. +- Function parameter issues: Pass functions as strings, the frontend will automatically compile; functions returning ReactNode can choose slots or generate through global React object. + +**Update** Troubleshooting guide has been updated to reflect Gradio 6.0's new event system and component lifecycle changes. + +**Section Source** + +- [docs/components/antd/overview/README.md:13-75](file://docs/components/antd/overview/README.md#L13-L75) +- [docs/components/base/fragment/README-zh_CN.md:1-10](file://docs/components/base/fragment/README-zh_CN.md#L1-L10) + +## Conclusion + +modelscope_studio deeply integrates Ant Design 6.3.5 components with the Gradio 6.0 ecosystem, providing unified component export, configuration container, and documentation examples to help developers quickly build beautiful and maintainable interfaces. Through clear classification system, strict usage principles, and complete internationalization, theme, and slot mechanisms, the component library achieves a good balance between usability and extensibility. It is recommended to follow the "Application + ConfigProvider" wrapper principle in actual projects, make good use of slots and event mapping, and combine with layout components to achieve responsive and accessibility-friendly interfaces. + +**Update** The version upgrade brings better performance, more stable event system, and more modern theme support, providing developers with a better development experience. diff --git a/.wiki/en/Ant Design Components/Data Display Components/Avatar and Badge.md b/.wiki/en/Ant Design Components/Data Display Components/Avatar and Badge.md new file mode 100644 index 00000000..183344fe --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Avatar and Badge.md @@ -0,0 +1,328 @@ +# Avatar and Badge + + +**Files referenced in this document** +- [avatar.tsx](file://frontend/antd/avatar/avatar.tsx) +- [avatar group entry Index.svelte](file://frontend/antd/avatar/group/Index.svelte) +- [avatar.group.tsx](file://frontend/antd/avatar/group/avatar.group.tsx) +- [avatar.group.less](file://frontend/antd/avatar/group/avatar.group.less) +- [badge.tsx](file://frontend/antd/badge/badge.tsx) +- [badge ribbon entry Index.svelte](file://frontend/antd/badge/ribbon/Index.svelte) +- [ribbon.badge.tsx](file://frontend/antd/badge/ribbon/badge.ribbon.tsx) +- [avatar docs README.md](file://docs/components/antd/avatar/README.md) +- [badge docs README.md](file://docs/components/antd/badge/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the Avatar and Badge component families, systematically covering size control, shape settings, Avatar.Group stacking and masking, Badge count display and dot marking, Badge.Ribbon ribbon effects, and other capabilities. It also provides placeholder handling, threshold settings, custom style solutions, as well as responsive and multi-layout adaptation recommendations. The document is based on actual implementations in the repository, with visual diagrams to help readers quickly understand and correctly use the components. + +## Project Structure + +- Avatar components are located in frontend/antd/avatar, containing two sub-modules: single avatar and avatar group. The avatar group dynamically imports its internal implementation via a composite Svelte entry file. +- Badge components are located in frontend/antd/badge, containing two sub-modules: basic badge and ribbon badge. The ribbon badge is also dynamically imported via a composite Svelte entry file. +- Documentation examples are in docs/components/antd/avatar and docs/components/antd/badge, providing demo entries for basic and combined usage. + +```mermaid +graph TB +subgraph "Avatar Components" +AV["avatar.tsx"] +AGI["avatar/group/Index.svelte"] +AGC["avatar/group/avatar.group.tsx"] +AGL["avatar/group/avatar.group.less"] +end +subgraph "Badge Components" +BD["badge.tsx"] +RBDI["badge/ribbon/Index.svelte"] +RBD["badge/ribbon/badge.ribbon.tsx"] +end +AV --> |"Wrap Ant Design"| AV +AGI --> |"Dynamic import"| AGC +AGC --> |"Render"| AV +AGC --> |"Styles"| AGL +BD --> |"Wrap Ant Design"| BD +RBDI --> |"Dynamic import"| RBD +RBD --> |"Wrap content"| RBD +``` + +**Diagram Source** + +- [avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) +- [avatar group entry Index.svelte:1-62](file://frontend/antd/avatar/group/Index.svelte#L1-L62) +- [avatar.group.tsx:1-52](file://frontend/antd/avatar/group/avatar.group.tsx#L1-L52) +- [avatar.group.less:1-12](file://frontend/antd/avatar/group/avatar.group.less#L1-L12) +- [badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) +- [badge ribbon entry Index.svelte:1-62](file://frontend/antd/badge/ribbon/Index.svelte#L1-L62) +- [ribbon.badge.tsx:1-22](file://frontend/antd/badge/ribbon/badge.ribbon.tsx#L1-L22) + +**Section Source** + +- [avatar docs README.md:1-9](file://docs/components/antd/avatar/README.md#L1-L9) +- [badge docs README.md:1-9](file://docs/components/antd/badge/README.md#L1-L9) + +## Core Components + +- Avatar + - Supports icon, image and character display, with size and shape configuration; supports dynamic injection of icon and src via slot mechanism. + - Provides placeholder handling: when no icon or image is provided, child nodes can serve as fallback content. +- Avatar.Group + - Implements avatar stacking and masking effects; supports maximum count threshold and popup tooltip; controls overlap spacing via less variables. + - Supports slot-based customization of the popup layer title and content for "overflowed count". +- Badge + - Supports numeric count and text marking; both count and text can inject custom content via slots. + - Supports dot marking and overflow threshold (shows n+ when exceeding the threshold). +- Badge.Ribbon + - Overlays a "ribbon"-style badge on a target element, supporting text slots; typically used to emphasize status or identify features. + +**Section Source** + +- [avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) +- [avatar.group.tsx:1-52](file://frontend/antd/avatar/group/avatar.group.tsx#L1-L52) +- [avatar.group.less:1-12](file://frontend/antd/avatar/group/avatar.group.less#L1-L12) +- [badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) +- [ribbon.badge.tsx:1-22](file://frontend/antd/badge/ribbon/badge.ribbon.tsx#L1-L22) + +## Architecture Overview + +The diagram below shows the call chain from the Svelte entry to specific Ant Design components, as well as key paths for slot and property forwarding. + +```mermaid +sequenceDiagram +participant U as "User Code" +participant S as "Svelte Composite Entry (Index)" +participant C as "Internal Component (tsx)" +participant A as "Ant Design Component" +U->>S : Pass properties and slots +S->>C : Dynamically import and forward properties/slots +C->>A : Forward properties/slots +A-->>U : Render result +``` + +**Diagram Source** + +- [avatar group entry Index.svelte:48-61](file://frontend/antd/avatar/group/Index.svelte#L48-L61) +- [avatar.group.tsx:12-49](file://frontend/antd/avatar/group/avatar.group.tsx#L12-L49) +- [badge ribbon entry Index.svelte:48-61](file://frontend/antd/badge/ribbon/Index.svelte#L48-L61) +- [ribbon.badge.tsx:6-18](file://frontend/antd/badge/ribbon/badge.ribbon.tsx#L6-L18) + +## Detailed Component Analysis + +### Avatar + +- Wrapping approach + - Uses sveltify to wrap Ant Design's Avatar as a Svelte component, while preserving slot capabilities for icon and src. + - When slots exist, slot content takes priority; otherwise falls back to property values; child nodes serve as default content when no slots are provided. +- Placeholder handling + - Through hidden containers and conditional rendering, ensures child nodes can still be rendered as placeholder content when no icon or image is provided. +- Shape and size + - Shape (e.g., circle/square) and size (e.g., small/medium/large) are controlled via Ant Design native properties, following Antd specifications. + +```mermaid +flowchart TD +Start(["Enter Avatar render"]) --> CheckIconSrc["Check if icon or src slot exists"] +CheckIconSrc --> HasSlot{"Slot exists?"} +HasSlot --> |Yes| UseSlot["Use slot content as icon/image"] +HasSlot --> |No| UseProp["Use property value as icon/image"] +UseSlot --> Render["Render Ant Design Avatar"] +UseProp --> Render +Render --> End(["Done"]) +``` + +**Diagram Source** + +- [avatar.tsx:6-25](file://frontend/antd/avatar/avatar.tsx#L6-L25) + +**Section Source** + +- [avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) + +### Avatar.Group + +- Stacking and masking + - Internally uses Ant Design's Group capability for avatar stacking; controls the starting margin of adjacent avatars via less variables to create visual overlap and layering. +- Threshold and popup layer + - Supports setting max.count as the threshold; when exceeded, shows hints like "n more". + - The popup layer title and content can be overridden via slots; if no slots are provided, falls back to property configuration. +- Sub-item rendering + - Maps child items to ReactSlot via useTargets and ReactSlot, ensuring each child avatar renders in order. + +```mermaid +flowchart TD +Enter(["Enter Avatar.Group"]) --> ComputeMax["Calculate max config
including count and popover"] +ComputeMax --> OverLimit{"Exceeds threshold?"} +OverLimit --> |Yes| Popover["Show popup layer (title/content can use slots)"] +OverLimit --> |No| RenderList["Render child avatars one by one"] +Popover --> RenderList +RenderList --> Exit(["Done"]) +``` + +**Diagram Source** + +- [avatar.group.tsx:12-49](file://frontend/antd/avatar/group/avatar.group.tsx#L12-L49) +- [avatar.group.less:1-12](file://frontend/antd/avatar/group/avatar.group.less#L1-L12) + +**Section Source** + +- [avatar group entry Index.svelte:1-62](file://frontend/antd/avatar/group/Index.svelte#L1-L62) +- [avatar.group.tsx:1-52](file://frontend/antd/avatar/group/avatar.group.tsx#L1-L52) +- [avatar.group.less:1-12](file://frontend/antd/avatar/group/avatar.group.less#L1-L12) + +### Badge + +- Count and text + - Both count and text support slot injection, enabling placement of complex content (such as icons, custom text) inside the badge. +- Dot marking + - Implements dot marking via Ant Design native capability; displays a pure dot when count is 0 and numbers are not shown. +- Threshold setting + - Supports setting a maximum value; displays n+ when exceeding the threshold. This capability is provided by the underlying Antd component and the component layer directly forwards the property. + +```mermaid +flowchart TD +Start(["Enter Badge render"]) --> CheckCountText["Check count and text slots"] +CheckCountText --> HasCount{"count has slot?"} +HasCount --> |Yes| UseCountSlot["Use slot count"] +HasCount --> |No| UseCountProp["Use property count"] +CheckCountText --> HasText{"text has slot?"} +HasText --> |Yes| UseTextSlot["Use slot text"] +HasText --> |No| UseTextProp["Use property text"] +UseCountSlot --> Render["Render Ant Design Badge"] +UseCountProp --> Render +UseTextSlot --> Render +UseTextProp --> Render +Render --> End(["Done"]) +``` + +**Diagram Source** + +- [badge.tsx:6-17](file://frontend/antd/badge/badge.tsx#L6-L17) + +**Section Source** + +- [badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) + +### Badge.Ribbon + +- Special effect + - Ribbon draws a "ribbon"-style badge on the parent container, commonly used to highlight status or mark new features; text content can be customized via slots. +- Use cases + - Suitable for adding prominent markings on cards, buttons, list items, and other containers; be careful to avoid conflicts with existing decorations. + +```mermaid +sequenceDiagram +participant U as "User Code" +participant S as "Ribbon Composite Entry" +participant C as "Internal Ribbon Component" +participant A as "Ant Design Ribbon" +U->>S : Pass properties and slots (text) +S->>C : Dynamically import and forward properties/slots +C->>A : Forward properties/slots +A-->>U : Render ribbon badge on container +``` + +**Diagram Source** + +- [badge ribbon entry Index.svelte:48-61](file://frontend/antd/badge/ribbon/Index.svelte#L48-L61) +- [ribbon.badge.tsx:6-18](file://frontend/antd/badge/ribbon/badge.ribbon.tsx#L6-L18) + +**Section Source** + +- [badge ribbon entry Index.svelte:1-62](file://frontend/antd/badge/ribbon/Index.svelte#L1-L62) +- [ribbon.badge.tsx:1-22](file://frontend/antd/badge/ribbon/badge.ribbon.tsx#L1-L22) + +## Dependency Analysis + +- Component wrapping + - All components bridge Ant Design counterparts as Svelte components via sveltify, maintaining consistent property and event forwarding. +- Slot mechanism + - Converts Svelte slots to React Slot via ReactSlot, ensuring compatibility with Antd component slot conventions. +- Dynamic import + - Composite entries use importComponent and import to dynamically import internal implementations, reducing initial bundle size and improving on-demand loading efficiency. +- Style coupling + - Avatar group controls overlap spacing and other style details via less variables, avoiding hardcoding and facilitating unified theme management. + +```mermaid +graph LR +Svelte["Svelte Composite Entry"] --> Sveltify["sveltify Wrapper"] +Sveltify --> Antd["Ant Design Component"] +Svelte --> ReactSlot["ReactSlot Bridge"] +Svelte --> DynamicImport["Dynamic Import Internal Implementation"] +Antd --> Less["less variables control styles"] +``` + +**Diagram Source** + +- [avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) +- [avatar.group.tsx:1-52](file://frontend/antd/avatar/group/avatar.group.tsx#L1-L52) +- [badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) +- [ribbon.badge.tsx:1-22](file://frontend/antd/badge/ribbon/badge.ribbon.tsx#L1-L22) + +**Section Source** + +- [avatar group entry Index.svelte:1-62](file://frontend/antd/avatar/group/Index.svelte#L1-L62) +- [avatar.group.tsx:1-52](file://frontend/antd/avatar/group/avatar.group.tsx#L1-L52) +- [badge ribbon entry Index.svelte:1-62](file://frontend/antd/badge/ribbon/Index.svelte#L1-L62) +- [ribbon.badge.tsx:1-22](file://frontend/antd/badge/ribbon/badge.ribbon.tsx#L1-L22) + +## Performance Considerations + +- On-demand loading + - Composite entries use dynamic import strategy, loading internal implementations only when needed, reducing initial bundle size and first-screen rendering pressure. +- Slot rendering + - Slot content is injected at the rendering stage, avoiding unnecessary pre-processing overhead. +- Style variables + - Manage style details such as overlap spacing centrally via less variables, reducing repeated computation and style jitter. + +[This section provides general performance recommendations and does not require specific file references] + +## Troubleshooting Guide + +- Avatar not showing icon or image + - Check whether the icon or src property is correctly passed in; if using slots, confirm that the slot name and type match. + - If no icon/image is provided, the component falls back to child nodes as placeholder content; confirm that the child nodes are visible. +- Avatar group threshold invalid or popup layer not showing + - Confirm that max.count is a numeric type; when count is a number, the internal code automatically adds one to compensate for its own occupation. + - The popup layer title and content can be overridden via slots; if no slots are provided, falls back to property configuration. +- Badge threshold not working + - Confirm whether the threshold property is correctly forwarded to the underlying component; Antd natively supports n+ display logic. +- Ribbon badge position incorrect + - Confirm that Ribbon's parent container has a positioning context; if necessary, manually set relative positioning on the container to ensure stable overlay effect. + +**Section Source** + +- [avatar.tsx:6-25](file://frontend/antd/avatar/avatar.tsx#L6-L25) +- [avatar.group.tsx:18-40](file://frontend/antd/avatar/group/avatar.group.tsx#L18-L40) +- [badge.tsx:6-17](file://frontend/antd/badge/badge.tsx#L6-L17) +- [ribbon.badge.tsx:6-18](file://frontend/antd/badge/ribbon/badge.ribbon.tsx#L6-L18) + +## Conclusion + +This component system is built on Ant Design, with Svelte wrapping and slot bridging providing flexible avatar and badge capabilities. Avatar group stacking/masking, badge count and threshold, and ribbon badge highlighting effects can all be highly customized without breaking semantics. It is recommended to manage sizes, spacing, and colors uniformly via theme variables and layout specifications in actual projects to achieve a consistent user experience. + +[This section is a summary and does not require specific file references] + +## Appendix + +- Example entries + - Avatar component examples can be found under the demo tab in the docs directory. + - Badge component examples can be found under the demo tab in the docs directory. +- Related documentation + - Avatar component documentation overview: [avatar docs README.md:1-9](file://docs/components/antd/avatar/README.md#L1-L9) + - Badge component documentation overview: [badge docs README.md:1-9](file://docs/components/antd/badge/README.md#L1-L9) + +**Section Source** + +- [avatar docs README.md:1-9](file://docs/components/antd/avatar/README.md#L1-L9) +- [badge docs README.md:1-9](file://docs/components/antd/badge/README.md#L1-L9) diff --git a/.wiki/en/Ant Design Components/Data Display Components/Calendar and Card.md b/.wiki/en/Ant Design Components/Data Display Components/Calendar and Card.md new file mode 100644 index 00000000..e6da0038 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Calendar and Card.md @@ -0,0 +1,359 @@ +# Calendar and Card + + +**Files referenced in this document** +- [frontend/antd/calendar/Index.svelte](file://frontend/antd/calendar/Index.svelte) +- [frontend/antd/calendar/calendar.tsx](file://frontend/antd/calendar/calendar.tsx) +- [frontend/antd/card/Index.svelte](file://frontend/antd/card/Index.svelte) +- [frontend/antd/card/card.tsx](file://frontend/antd/card/card.tsx) +- [frontend/antd/card/grid/Index.svelte](file://frontend/antd/card/grid/Index.svelte) +- [frontend/antd/card/grid/card.grid.tsx](file://frontend/antd/card/grid/card.grid.tsx) +- [frontend/antd/card/meta/Index.svelte](file://frontend/antd/card/meta/Index.svelte) +- [frontend/antd/card/meta/card.meta.tsx](file://frontend/antd/card/meta/card.meta.tsx) +- [frontend/antd/grid/col/col.tsx](file://frontend/antd/grid/col/col.tsx) +- [frontend/antd/grid/row/row.tsx](file://frontend/antd/grid/row/row.tsx) +- [frontend/antd/grid/context.ts](file://frontend/antd/grid/context.ts) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts](file://frontend/antd/config-provider/locales.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +This document covers Calendar and Card components, providing complete instructions from architecture to implementation details. Key topics include: + +- Calendar component: scheduling, event marking, date selection, panel switching, special features of notification calendars (extended via slots and callbacks) +- Card component: basic structure, responsive layout with Card.Grid, content organization with Card.Meta, implementation methods for custom card content +- Localization: multilingual support and date localization based on ConfigProvider +- Interactions and callbacks: event callback handling, value change propagation +- Adaptability: adaptation strategies for different screen sizes and dynamic update mechanisms + +## Project Structure + +Calendar and Card components are located in the frontend Ant Design ecosystem, using Svelte + React wrappers (sveltify) to bridge Svelte components with Ant Design's React implementation. Each component provides: + +- Svelte entry file (Index.svelte): responsible for property forwarding, visibility control, slot collection, and async loading of React implementation +- React wrapper (\*.tsx): uses sveltify to wrap Ant Design components for Svelte use, handling function-type callbacks, slot rendering, and value formatting + +```mermaid +graph TB +subgraph "Calendar Component" +C_Index["calendar/Index.svelte"] +C_Tsx["calendar/calendar.tsx"] +end +subgraph "Card Component" +K_Index["card/Index.svelte"] +K_Tsx["card/card.tsx"] +end +subgraph "Card Sub-components" +G_Index["card/grid/Index.svelte"] +G_Tsx["card/grid/card.grid.tsx"] +M_Index["card/meta/Index.svelte"] +M_Tsx["card/meta/card.meta.tsx"] +end +subgraph "Grid System" +R_Tsx["grid/row/row.tsx"] +C_Tsx2["grid/col/col.tsx"] +Ctx["grid/context.ts"] +end +subgraph "Localization" +CP_Tsx["config-provider/config-provider.tsx"] +Locales["config-provider/locales.ts"] +end +C_Index --> C_Tsx +K_Index --> K_Tsx +G_Index --> G_Tsx +M_Index --> M_Tsx +R_Tsx --> C_Tsx2 +Ctx --> R_Tsx +CP_Tsx --> Locales +``` + +**Diagram Source** + +- [frontend/antd/calendar/Index.svelte:1-85](file://frontend/antd/calendar/Index.svelte#L1-L85) +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [frontend/antd/card/Index.svelte:1-68](file://frontend/antd/card/Index.svelte#L1-L68) +- [frontend/antd/card/card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) +- [frontend/antd/card/grid/Index.svelte:1-63](file://frontend/antd/card/grid/Index.svelte#L1-L63) +- [frontend/antd/card/grid/card.grid.tsx:1-7](file://frontend/antd/card/grid/card.grid.tsx#L1-L7) +- [frontend/antd/card/meta/Index.svelte:1-60](file://frontend/antd/card/meta/Index.svelte#L1-L60) +- [frontend/antd/card/meta/card.meta.tsx:1-32](file://frontend/antd/card/meta/card.meta.tsx#L1-L32) +- [frontend/antd/grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [frontend/antd/grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts:1-800](file://frontend/antd/config-provider/locales.ts#L1-L800) + +**Section Source** + +- [frontend/antd/calendar/Index.svelte:1-85](file://frontend/antd/calendar/Index.svelte#L1-L85) +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [frontend/antd/card/Index.svelte:1-68](file://frontend/antd/card/Index.svelte#L1-L68) +- [frontend/antd/card/card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) +- [frontend/antd/card/grid/Index.svelte:1-63](file://frontend/antd/card/grid/Index.svelte#L1-L63) +- [frontend/antd/card/grid/card.grid.tsx:1-7](file://frontend/antd/card/grid/card.grid.tsx#L1-L7) +- [frontend/antd/card/meta/Index.svelte:1-60](file://frontend/antd/card/meta/Index.svelte#L1-L60) +- [frontend/antd/card/meta/card.meta.tsx:1-32](file://frontend/antd/card/meta/card.meta.tsx#L1-L32) +- [frontend/antd/grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [frontend/antd/grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts:1-800](file://frontend/antd/config-provider/locales.ts#L1-L800) + +## Core Components + +- Calendar + - Supports date value formatting (second-level timestamp and dayjs conversion), disabled date filtering, cell render slots (cellRender/fullCellRender/headerRender), panel switching and selection event callbacks + - Value changes are synced upward via onValueChange for easy integration with Gradio and similar frameworks +- Card + - Provides slot-based rendering for title, extra content, cover image, action area and other regions; supports tab list and tab bar extension (tabProps.\* slots) + - Internally collects child items via context and dynamically composes them into Ant Design's Card component +- Card.Grid + - Serves as a grid container inside the card for holding child content and participating in responsive layout +- Card.Meta + - Provides slot-based rendering for title, description, and avatar, enabling flexible customization of card metadata +- Grid System (Row/Col) + - Row collects column items via context and maps children to Ant Design's Row/Col structure for responsive layout + +**Section Source** + +- [frontend/antd/calendar/calendar.tsx:10-15](file://frontend/antd/calendar/calendar.tsx#L10-L15) +- [frontend/antd/calendar/calendar.tsx:58-98](file://frontend/antd/calendar/calendar.tsx#L58-L98) +- [frontend/antd/card/card.tsx:36-146](file://frontend/antd/card/card.tsx#L36-L146) +- [frontend/antd/card/grid/card.grid.tsx:1-7](file://frontend/antd/card/grid/card.grid.tsx#L1-L7) +- [frontend/antd/card/meta/card.meta.tsx:5-29](file://frontend/antd/card/meta/card.meta.tsx#L5-L29) +- [frontend/antd/grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [frontend/antd/grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) + +## Architecture Overview + +The diagram below shows the bridging relationship between Calendar and Card components in Svelte and Ant Design, as well as key flows for slots and callbacks. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Component
Index.svelte" +participant Wrapper as "React Wrapper
sveltify" +participant Antd as "Ant Design Component" +participant Util as "Utility Functions
useFunction/renderParamsSlot" +Svelte->>Wrapper : Forward properties/visibility/slots +Wrapper->>Util : useFunction wraps callbacks +Wrapper->>Util : renderParamsSlot renders slots +Wrapper->>Antd : Render Antd component and pass props +Antd-->>Wrapper : Callback triggers onChange/onPanelChange/onSelect +Wrapper-->>Svelte : onValueChange syncs value +``` + +**Diagram Source** + +- [frontend/antd/calendar/Index.svelte:65-84](file://frontend/antd/calendar/Index.svelte#L65-L84) +- [frontend/antd/calendar/calendar.tsx:43-98](file://frontend/antd/calendar/calendar.tsx#L43-L98) +- [frontend/antd/card/Index.svelte:53-67](file://frontend/antd/card/Index.svelte#L53-L67) +- [frontend/antd/card/card.tsx:39-146](file://frontend/antd/card/card.tsx#L39-L146) + +## Detailed Component Analysis + +### Calendar + +- Properties and callbacks + - Input value and default value: supports second-level timestamps and dayjs objects, internally unified to dayjs + - Valid range: validRange is also formatted + - Callbacks: onChange/onPanelChange/onSelect convert dates to second-level timestamps before returning + - Slots: cellRender/fullCellRender/headerRender can inject custom rendering via slots +- Event marking and notification calendar + - Inject custom marks or badges via cellRender/fullCellRender slots + - onPanelChange can monitor month/year switching, combined with business logic to implement "notification calendar" scenarios (e.g., highlighting specific dates) +- Date selection and value sync + - onValueChange returns the currently selected date as a second-level timestamp to the parent for state management and persistence + +```mermaid +flowchart TD +Start(["Enter Calendar component"]) --> ParseValue["Parse input value
second-level timestamp -> dayjs"] +ParseValue --> ParseRange["Parse valid range
array -> dayjs[]"] +ParseRange --> RenderCalendar["Render Antd Calendar"] +RenderCalendar --> OnChange{"User selects date?"} +OnChange --> |Yes| ConvertSec["Convert date to second-level timestamp"] +ConvertSec --> CallCb["Trigger onChange/onSelect"] +CallCb --> OnValueChange["Trigger onValueChange to sync value"] +OnValueChange --> End(["Done"]) +OnChange --> |No| End +``` + +**Diagram Source** + +- [frontend/antd/calendar/calendar.tsx:47-98](file://frontend/antd/calendar/calendar.tsx#L47-L98) + +**Section Source** + +- [frontend/antd/calendar/Index.svelte:13-84](file://frontend/antd/calendar/Index.svelte#L13-L84) +- [frontend/antd/calendar/calendar.tsx:10-15](file://frontend/antd/calendar/calendar.tsx#L10-L15) +- [frontend/antd/calendar/calendar.tsx:47-98](file://frontend/antd/calendar/calendar.tsx#L47-L98) + +### Card + +- Basic structure + - Title, extra content, cover image, and action area can all be injected via slots + - Supports tab list tabList and tab bar extension (tabProps.\* slots), including indicator size, more menu, and left/right extra content +- Dynamic content and context + - Collects child items via useTabsItems and useTargets, dynamically injecting tabList and actions + - When Grid child items exist, controls placeholder grid visibility via containsGrid to ensure correct layout +- Custom content implementation + - Uses ReactSlot to render slot content, supporting complex nesting and conditional rendering + - The actions area preferentially uses collected targets, falling back to native props.actions + +```mermaid +classDiagram +class CardWrapper { ++props : AntdCardProps ++slots : Record ++containsGrid : boolean ++tabList : Tab[] ++tabProps : TabProps ++render() +} +class TabsContext { ++useTabsItems(keys) : Items +} +class TargetsContext { ++useTargets(children, slotName) : Target[] +} +CardWrapper --> TabsContext : "get tabList" +CardWrapper --> TargetsContext : "generate actions" +``` + +**Diagram Source** + +- [frontend/antd/card/card.tsx:36-146](file://frontend/antd/card/card.tsx#L36-L146) + +**Section Source** + +- [frontend/antd/card/Index.svelte:12-67](file://frontend/antd/card/Index.svelte#L12-L67) +- [frontend/antd/card/card.tsx:36-146](file://frontend/antd/card/card.tsx#L36-L146) + +### Card.Grid + +- Role + - Acts as a grid container inside the card, holding child content and participating in responsive layout +- Implementation + - Directly wraps Ant Design's Card.Grid, maintaining consistent behavior with Antd + +**Section Source** + +- [frontend/antd/card/grid/Index.svelte:19-59](file://frontend/antd/card/grid/Index.svelte#L19-L59) +- [frontend/antd/card/grid/card.grid.tsx:1-7](file://frontend/antd/card/grid/card.grid.tsx#L1-L7) + +### Card.Meta + +- Content organization + - Title, description, and avatar can all be injected via slots for flexible content organization +- Rendering mechanism + - Renders slots via ReactSlot; falls back to native props if not provided + +**Section Source** + +- [frontend/antd/card/meta/Index.svelte:19-59](file://frontend/antd/card/meta/Index.svelte#L19-L59) +- [frontend/antd/card/meta/card.meta.tsx:5-29](file://frontend/antd/card/meta/card.meta.tsx#L5-L29) + +### Grid System (Row/Col) + +- Responsive layout + - Row collects Col column items via context and maps children to Ant Design's Row/Col structure + - Col acts as ItemHandler, receiving properties from context and rendering +- Context mechanism + - Uses createItemsContext to create items context; Row/Col cooperate via useItems and withItemsContextProvider + +**Section Source** + +- [frontend/antd/grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [frontend/antd/grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) + +## Dependency Analysis + +- Component coupling + - Both Calendar and Card bridge Ant Design components to Svelte via sveltify, reducing direct coupling + - Slots and callbacks are decoupled via useFunction and renderParamsSlot for easy extension +- External dependencies + - dayjs for date formatting and localization + - Ant Design provides UI capabilities and theme/localization resources +- Circular dependencies + - No obvious circular dependencies between components; context is passed in one direction only + +```mermaid +graph LR +Svelte_Index["Svelte Index.svelte"] --> React_Wrapper["React Wrapper sveltify"] +React_Wrapper --> Antd["Ant Design Component"] +React_Wrapper --> Utils["Utility Functions useFunction/renderParamsSlot"] +Antd --> Dayjs["dayjs localization"] +``` + +**Diagram Source** + +- [frontend/antd/calendar/Index.svelte:65-84](file://frontend/antd/calendar/Index.svelte#L65-L84) +- [frontend/antd/calendar/calendar.tsx:3-6](file://frontend/antd/calendar/calendar.tsx#L3-L6) +- [frontend/antd/card/Index.svelte:53-67](file://frontend/antd/card/Index.svelte#L53-L67) +- [frontend/antd/card/card.tsx:2-8](file://frontend/antd/card/card.tsx#L2-L8) + +**Section Source** + +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [frontend/antd/card/card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) + +## Performance Considerations + +- Async loading and lazy rendering + - Svelte Index.svelte asynchronously imports the React implementation to reduce initial bundle size and first-screen blocking +- Callback function optimization + - Use useFunction to wrap callbacks to avoid unnecessary re-renders +- Value computation caching + - Use useMemo to cache dayjs values and valid ranges, reducing repeated computation costs +- Slot rendering + - renderParamsSlot only renders slot content when needed, avoiding unnecessary DOM updates + +**Section Source** + +- [frontend/antd/calendar/Index.svelte:65-84](file://frontend/antd/calendar/Index.svelte#L65-L84) +- [frontend/antd/calendar/calendar.tsx:43-57](file://frontend/antd/calendar/calendar.tsx#L43-L57) +- [frontend/antd/card/card.tsx:105-112](file://frontend/antd/card/card.tsx#L105-L112) + +## Troubleshooting Guide + +- Date not displayed or displayed incorrectly + - Check whether the input value is a second-level timestamp or an object parseable by dayjs + - Confirm whether validRange is a valid dayjs array +- Event callback not triggered + - Confirm whether onChange/onPanelChange/onSelect are correctly bound + - If using slot rendering, ensure slots do not override default behavior +- Slot content not working + - Confirm that slot key names are consistent with the slots supported by the component (e.g., cellRender/fullCellRender/headerRender/title/extra/cover, etc.) +- Localization not working + - Check ConfigProvider's locale settings and browser language environment + - Confirm whether the corresponding language pack exists in locales.ts + +**Section Source** + +- [frontend/antd/calendar/calendar.tsx:47-98](file://frontend/antd/calendar/calendar.tsx#L47-L98) +- [frontend/antd/card/card.tsx:113-132](file://frontend/antd/card/card.tsx#L113-L132) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts:1-800](file://frontend/antd/config-provider/locales.ts#L1-L800) + +## Conclusion + +Calendar and Card components achieve highly extensible UI capabilities through a unified bridging pattern and slot system: + +- Calendar supports date formatting, event callbacks, and slot extension for scheduling and notification calendar scenarios +- Card provides flexible content organization and dynamic layout capabilities, combined with the grid system for responsive design +- Localization and utility functions further improve internationalization and performance + +It is recommended to make full use of slot and callback mechanisms in actual projects, combined with context and utility functions, to build stable and maintainable interfaces. diff --git a/.wiki/en/Ant Design Components/Data Display Components/Carousel and Collapse.md b/.wiki/en/Ant Design Components/Data Display Components/Carousel and Collapse.md new file mode 100644 index 00000000..29a0504e --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Carousel and Collapse.md @@ -0,0 +1,317 @@ +# Carousel and Collapse + + +**Files Referenced in This Document** +- [carousel.tsx](file://frontend/antd/carousel/carousel.tsx) +- [Index.svelte](file://frontend/antd/carousel/Index.svelte) +- [useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [useTargets.ts](file://frontend/utils/hooks/useTargets.ts) +- [renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [collapse.tsx](file://frontend/antd/collapse/collapse.tsx) +- [Index.svelte](file://frontend/antd/collapse/Index.svelte) +- [context.ts](file://frontend/antd/collapse/context.ts) +- [collapse.item/Index.svelte](file://frontend/antd/collapse/item/Index.svelte) +- [__init__.py (carousel backend)](file://backend/modelscope_studio/components/antd/carousel/__init__.py) +- [__init__.py (collapse backend)](file://backend/modelscope_studio/components/antd/collapse/__init__.py) +- [basic.py (carousel demo)](file://docs/components/antd/carousel/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document provides a systematic explanation of the Ant Design **Carousel** and **Collapse** components, covering architecture and implementation details. Key topics include: + +- Carousel: autoplay, transition animations, indicator controls, vertical carousel configuration; recommended approaches for touch swipe, keyboard navigation, and accessibility; and backend parameter mapping. +- Collapse: expand/collapse for individual panels, accordion effect, dynamic loading of panel content, and state persistence; controlled vs. uncontrolled modes, custom panel headers, and animation configuration. + +## Project Structure + +- The frontend Svelte wrapper handles prop processing, slot rendering, and conditional display. +- The React layer bridges Ant Design components to Svelte via sveltify. +- The utility layer provides general capabilities such as function wrapping, target node extraction, and slot rendering. +- The backend Python component handles parameter forwarding and frontend directory resolution. + +```mermaid +graph TB +subgraph "Frontend" +A["carousel/Index.svelte"] +B["carousel/carousel.tsx"] +C["collapse/Index.svelte"] +D["collapse/collapse.tsx"] +E["collapse/item/Index.svelte"] +F["hooks/useFunction.ts"] +G["hooks/useTargets.ts"] +H["utils/renderItems.tsx"] +I["utils/renderParamsSlot.tsx"] +end +subgraph "Backend" +J["backend/.../carousel/__init__.py"] +K["backend/.../collapse/__init__.py"] +end +A --> B +C --> D +E --> D +B --> F +B --> G +D --> F +D --> H +D --> I +J --> A +K --> C +``` + +**Diagram Source** + +- [Index.svelte:1-66](file://frontend/antd/carousel/Index.svelte#L1-L66) +- [carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [Index.svelte:1-66](file://frontend/antd/collapse/Index.svelte#L1-L66) +- [collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [collapse.item/Index.svelte:1-95](file://frontend/antd/collapse/item/Index.svelte#L1-L95) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [**init**.py (carousel backend):45-94](file://backend/modelscope_studio/components/antd/carousel/__init__.py#L45-L94) +- [**init**.py (collapse backend):54-98](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L54-L98) + +**Section Source** + +- [Index.svelte:1-66](file://frontend/antd/carousel/Index.svelte#L1-L66) +- [carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [Index.svelte:1-66](file://frontend/antd/collapse/Index.svelte#L1-L66) +- [collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [collapse.item/Index.svelte:1-95](file://frontend/antd/collapse/item/Index.svelte#L1-L95) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [**init**.py (carousel backend):45-94](file://backend/modelscope_studio/components/antd/carousel/__init__.py#L45-L94) +- [**init**.py (collapse backend):54-98](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L54-L98) + +## Core Components + +- Carousel + - Frontend wrapper: receives props and slots, invokes Ant Design's Carousel, and renders child items via ReactSlot. + - Key points: afterChange/beforeChange are wrapped with useFunction; child item order is extracted and sorted by useTargets. +- Collapse + - Frontend wrapper: injects the items context via withItemsContextProvider, uses renderItems to convert slots into Ant Design's items structure; supports expandIcon as a slot or function. + - Collapse.Item: responsible for cloning and forwarding label/extra/children slots to the underlying component. + +**Section Source** + +- [carousel.tsx:8-29](file://frontend/antd/carousel/carousel.tsx#L8-L29) +- [Index.svelte:48-61](file://frontend/antd/carousel/Index.svelte#L48-L61) +- [collapse.tsx:10-50](file://frontend/antd/collapse/collapse.tsx#L10-L50) +- [collapse.item/Index.svelte:60-88](file://frontend/antd/collapse/item/Index.svelte#L60-L88) + +## Architecture Overview + +The following diagram shows the call chain from the frontend Svelte layer to the React Ant Design component, and the role of key utility functions. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Component" +participant Wrapper as "sveltify Wrapper" +participant UtilF as "useFunction" +participant UtilT as "useTargets" +participant AD as "Ant Design Carousel" +Svelte->>Wrapper : "Render and pass props/slots" +Wrapper->>UtilF : "Wrap afterChange/beforeChange" +Wrapper->>UtilT : "Extract and sort child targets" +Wrapper->>AD : "Render with wrapped callbacks and children" +AD-->>Wrapper : "Trigger callback/transition event" +Wrapper-->>Svelte : "Return result if needed" +``` + +**Diagram Source** + +- [carousel.tsx:9-25](file://frontend/antd/carousel/carousel.tsx#L9-L25) +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) + +## Detailed Component Analysis + +### Carousel Component + +- Autoplay and Transition Animation + - Supports autoplay, autoplaySpeed, speed, easing, effect (e.g., fade), wait_for_animate, and other parameters; see backend initialization parameters for the corresponding backend mappings. + - The afterChange and beforeChange callbacks are wrapped with useFunction to ensure stable execution in the React environment. +- Indicator Controls + - Supports dots, dotPosition, dotPlacement, and other configurations; indicator styles can be controlled via root_class_name or additional class names. +- Vertical Carousel + - Vertical scrolling can be achieved via effect or related layout configurations (depending on Ant Design support and styles). +- Touch Swipe, Keyboard Navigation, and Accessibility + - It is recommended to enable draggable for touch swipe support; keyboard navigation and accessibility labels can be implemented using Ant Design's default behavior combined with custom aria-\* attributes. +- Child Item Rendering + - Child items are extracted by useTargets and sorted by slotIndex/subSlotIndex, then cloned and rendered as ReactSlot, ensuring correct order and visibility. + +```mermaid +flowchart TD +Start(["Start rendering"]) --> Extract["Extract child items
useTargets(children)"] +Extract --> Sort["Sort by index
slotIndex/subSlotIndex"] +Sort --> WrapCallbacks["Wrap callbacks
useFunction(afterChange/beforeChange)"] +WrapCallbacks --> Render["Render Ant Design Carousel"] +Render --> Children["Clone children
ReactSlot"] +Children --> End(["Done"]) +``` + +**Diagram Source** + +- [carousel.tsx:9-25](file://frontend/antd/carousel/carousel.tsx#L9-L25) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) + +**Section Source** + +- [carousel.tsx:8-29](file://frontend/antd/carousel/carousel.tsx#L8-L29) +- [Index.svelte:48-61](file://frontend/antd/carousel/Index.svelte#L48-L61) +- [**init**.py (carousel backend):45-94](file://backend/modelscope_studio/components/antd/carousel/__init__.py#L45-L94) +- [basic.py (carousel demo):40-73](file://docs/components/antd/carousel/demos/basic.py#L40-L73) + +### Collapse Component + +- Single Panel and Accordion + - Use accordion to enable/disable accordion mode; activeKey/defaultActiveKey controls currently expanded panels (supports multiple or single selection). +- Dynamic Panel Content Loading + - Use the items context and renderItems to convert slots into items; destroy_on_hidden/destroy_inactive_panel can control panel destruction when hidden to save resources. +- Collapse State Persistence + - State persistence is implemented via the controlled prop activeKey; the onChange callback can be used to record state changes. +- Controlled and Uncontrolled Modes + - Uncontrolled: use defaultActiveKey; controlled: use activeKey and listen to onChange for updates. +- Custom Panel Header + - The label slot is used for custom headers; the extra slot is used for additional actions on the right; the expandIcon slot or function can customize the expand icon. +- Animation Configuration + - Appearance props such as size, bordered, and ghost can be combined with animation and transition effects; specific animation behavior follows Ant Design's default implementation. + +```mermaid +sequenceDiagram +participant S as "Svelte Collapse" +participant P as "withItemsContextProvider" +participant R as "renderItems" +participant RP as "renderParamsSlot" +participant C as "Ant Design Collapse" +S->>P : "Inject items context" +P->>R : "Convert slots to items" +S->>RP : "Render expandIcon slot" +S->>C : "Pass items, onChange, expandIcon" +C-->>S : "Trigger onChange(key)" +S-->>S : "Update controlled state/persist" +``` + +**Diagram Source** + +- [collapse.tsx:11-49](file://frontend/antd/collapse/collapse.tsx#L11-L49) +- [context.ts:1-7](file://frontend/antd/collapse/context.ts#L1-L7) +- [renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) +- [renderParamsSlot.tsx:5-49](file://frontend/utils/renderParamsSlot.tsx#L5-L49) + +**Section Source** + +- [collapse.tsx:10-50](file://frontend/antd/collapse/collapse.tsx#L10-L50) +- [collapse.item/Index.svelte:60-88](file://frontend/antd/collapse/item/Index.svelte#L60-L88) +- [context.ts:1-7](file://frontend/antd/collapse/context.ts#L1-L7) +- [**init**.py (collapse backend):54-98](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L54-L98) + +## Dependency Analysis + +- Carousel + - carousel.tsx depends on useFunction and useTargets; Index.svelte handles props and visibility. +- Collapse + - collapse.tsx depends on useFunction, renderItems, renderParamsSlot, and the items context; collapse.item/Index.svelte handles slot cloning and forwarding. +- Backend Mapping + - The backend Python components map parameters to frontend components, avoiding duplicated API definitions. + +```mermaid +graph LR +CF["carousel.tsx"] --> UF["useFunction.ts"] +CF --> UT["useTargets.ts"] +CI["Index.svelte(Carousel)"] --> CF +DF["collapse.tsx"] --> UF +DF --> RI["renderItems.tsx"] +DF --> RPS["renderParamsSlot.tsx"] +DI["Index.svelte(Collapse)"] --> DF +DII["collapse.item/Index.svelte"] --> DF +``` + +**Diagram Source** + +- [carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [Index.svelte:1-66](file://frontend/antd/carousel/Index.svelte#L1-L66) +- [Index.svelte:1-66](file://frontend/antd/collapse/Index.svelte#L1-L66) +- [collapse.item/Index.svelte:1-95](file://frontend/antd/collapse/item/Index.svelte#L1-L95) + +**Section Source** + +- [carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [Index.svelte:1-66](file://frontend/antd/carousel/Index.svelte#L1-L66) +- [Index.svelte:1-66](file://frontend/antd/collapse/Index.svelte#L1-L66) +- [collapse.item/Index.svelte:1-95](file://frontend/antd/collapse/item/Index.svelte#L1-L95) + +## Performance Considerations + +- Carousel + - Child item sorting and target extraction are performed inside useMemo to avoid unnecessary re-renders. + - ReactSlot is used for cloning and rendering; be mindful of the number and complexity of child items. +- Collapse + - Use destroy_on_hidden/destroy_inactive_panel to control panel destruction and reduce memory usage. + - renderItems performs recursive rendering of nested slots; avoid excessively deep nesting. +- General + - useFunction wraps callbacks to ensure stable function references and reduce side effects. + +[This section provides general guidance and does not directly analyze specific files; therefore no "Section Source" is included.] + +## Troubleshooting Guide + +- Carousel children not displayed + - Check that children are passed correctly; verify the useTargets filter logic and slotIndex configuration. +- Carousel callbacks not triggered + - Confirm that afterChange/beforeChange are wrapped with useFunction; check Ant Design version compatibility. +- Collapse items not taking effect + - Confirm that items are injected via slots or passed explicitly; check renderItems key generation and slot key names. +- Expand icon not displayed + - If using the expandIcon slot, ensure the slot exists and renderParamsSlot renders correctly; otherwise check that the expandIcon function is passed in. + +**Section Source** + +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) +- [renderParamsSlot.tsx:5-49](file://frontend/utils/renderParamsSlot.tsx#L5-L49) + +## Conclusion + +- Both Carousel and Collapse follow a unified architecture of "Svelte wrapper + Ant Design component + utility functions", offering good extensibility and maintainability. +- Carousel focuses on autoplay, transition animations, and indicator configuration; Collapse emphasizes controlled/uncontrolled modes, dynamic loading, and state persistence. +- It is recommended to combine demo scripts and backend parameter mappings to quickly implement feature requirements in real projects. + +[This section is a summary and does not directly analyze specific files; therefore no "Section Source" is included.] + +## Appendix + +- Parameter Reference + - Carousel: autoplay, autoplaySpeed, adaptiveHeight, dotPosition, dotPlacement, dots, draggable, fade, infinite, speed, easing, effect, afterChange, beforeChange, wait_for_animate, root_class_name. + - Collapse: accordion, activeKey/defaultActiveKey, bordered, collapsible, destroy_on_hidden, destroy_inactive_panel, expand_icon, expand_icon_position, expand_icon_placement, ghost, items, size, root_class_name. + +**Section Source** + +- [**init**.py (carousel backend):45-94](file://backend/modelscope_studio/components/antd/carousel/__init__.py#L45-L94) +- [**init**.py (collapse backend):54-98](file://backend/modelscope_studio/components/antd/collapse/__init__.py#L54-L98) +- [basic.py (carousel demo):40-73](file://docs/components/antd/carousel/demos/basic.py#L40-L73) diff --git a/.wiki/en/Ant Design Components/Data Display Components/Data Display Components.md b/.wiki/en/Ant Design Components/Data Display Components/Data Display Components.md new file mode 100644 index 00000000..9f05e7d7 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Data Display Components.md @@ -0,0 +1,664 @@ +# Data Display Components + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [frontend/antd/package.json](file://frontend/antd/package.json) +- [frontend/antd/avatar/avatar.tsx](file://frontend/antd/avatar/avatar.tsx) +- [frontend/antd/badge/badge.tsx](file://frontend/antd/badge/badge.tsx) +- [frontend/antd/calendar/calendar.tsx](file://frontend/antd/calendar/calendar.tsx) +- [frontend/antd/card/card.tsx](file://frontend/antd/card/card.tsx) +- [frontend/antd/carousel/carousel.tsx](file://frontend/antd/carousel/carousel.tsx) +- [frontend/antd/collapse/collapse.tsx](file://frontend/antd/collapse/collapse.tsx) +- [frontend/antd/descriptions/descriptions.tsx](file://frontend/antd/descriptions/descriptions.tsx) +- [frontend/antd/empty/empty.tsx](file://frontend/antd/empty/empty.tsx) +- [frontend/antd/image/image.tsx](file://frontend/antd/image/image.tsx) +- [frontend/antd/list/list.tsx](file://frontend/antd/list/list.tsx) +- [frontend/antd/popover/popover.tsx](file://frontend/antd/popover/popover.tsx) +- [frontend/antd/qr_code/qr-code.tsx](file://frontend/antd/qr_code/qr-code.tsx) +- [frontend/antd/segmented/segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [frontend/antd/statistic/statistic.tsx](file://frontend/antd/statistic/statistic.tsx) +- [frontend/antd/table/table.tsx](file://frontend/antd/table/table.tsx) +- [frontend/antd/tabs/tabs.tsx](file://frontend/antd/tabs/tabs.tsx) +- [frontend/antd/tag/tag.tsx](file://frontend/antd/tag/tag.tsx) +- [frontend/antd/timeline/timeline.tsx](file://frontend/antd/timeline/timeline.tsx) +- [frontend/antd/tooltip/tooltip.tsx](file://frontend/antd/tooltip/tooltip.tsx) +- [frontend/antd/tour/tour.tsx](file://frontend/antd/tour/tour.tsx) +- [frontend/antd/tree/tree.tsx](file://frontend/antd/tree/tree.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document covers Ant Design data display components, systematically covering Avatar, Badge, Calendar, Card, Carousel, Collapse, Descriptions, Empty, Image, List, Popover, QRCode, Segmented, Statistic, Table, Tabs, Tag, Timeline, Tooltip, Tour, and Tree components and their implementation and usage in this repository. Key topics include: + +- Data rendering: how to map child nodes to Ant Design component children/items via slots and items. +- Interaction behavior: unified handling of event callbacks (such as onChange/onSelect) and function wrapping (useFunction). +- Animation effects: provided by Ant Design natively; the component layer does not add additional animation wrapping. +- Large data optimization: recommended to adopt virtual scrolling, pagination, lazy loading, and other strategies, combined with component extensibility for secondary wrapping. +- Theme customization and style overrides: achieved through Ant Design's theme variable and CSS variable system. +- Responsive and mobile adaptation: follows Ant Design's grid and breakpoint strategies, combined with Svelte component size control. + +## Project Structure + +This repository uses a dual-layer wrapping pattern of "backend Python module + frontend Svelte package": + +- The backend module is responsible for exporting each component class for unified reference in a Python environment. +- The frontend Svelte package bridges Ant Design React components as Svelte components via sveltify, supporting declarative rendering of slots and items. + +```mermaid +graph TB +subgraph "Backend" +PY_API["Python Export Module
__init__.py / components.py"] +end +subgraph "Frontend" +PKG["Svelte Package
package.json"] +AVATAR["Avatar
avatar.tsx"] +BADGE["Badge
badge.tsx"] +CALENDAR["Calendar
calendar.tsx"] +CARD["Card
card.tsx"] +CAROUSEL["Carousel
carousel.tsx"] +COLLAPSE["Collapse
collapse.tsx"] +DESC["Descriptions
descriptions.tsx"] +EMPTY["Empty
empty.tsx"] +IMAGE["Image
image.tsx"] +LIST["List
list.tsx"] +POPOVER["Popover
popover.tsx"] +QRCODE["QRCode
qr-code.tsx"] +SEG["Segmented
segmented.tsx"] +STAT["Statistic
statistic.tsx"] +TABLE["Table
table.tsx"] +TABS["Tabs
tabs.tsx"] +TAG["Tag
tag.tsx"] +TIME["Timeline
timeline.tsx"] +TT["Tooltip
tooltip.tsx"] +TOUR["Tour
tour.tsx"] +TREE["Tree
tree.tsx"] +end +PY_API --> AVATAR +PY_API --> BADGE +PY_API --> CALENDAR +PY_API --> CARD +PY_API --> CAROUSEL +PY_API --> COLLAPSE +PY_API --> DESC +PY_API --> EMPTY +PY_API --> IMAGE +PY_API --> LIST +PY_API --> POPOVER +PY_API --> QRCODE +PY_API --> SEG +PY_API --> STAT +PY_API --> TABLE +PY_API --> TABS +PY_API --> TAG +PY_API --> TIME +PY_API --> TT +PY_API --> TOUR +PY_API --> TREE +PKG --> AVATAR +PKG --> BADGE +PKG --> CALENDAR +PKG --> CARD +PKG --> CAROUSEL +PKG --> COLLAPSE +PKG --> DESC +PKG --> EMPTY +PKG --> IMAGE +PKG --> LIST +PKG --> POPOVER +PKG --> QRCODE +PKG --> SEG +PKG --> STAT +PKG --> TABLE +PKG --> TABS +PKG --> TAG +PKG --> TIME +PKG --> TT +PKG --> TOUR +PKG --> TREE +``` + +Diagram Source + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-144](file://backend/modelscope_studio/components/antd/components.py#L1-L144) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) + +Section Source + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antd/components.py:1-144](file://backend/modelscope_studio/components/antd/components.py#L1-L144) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) + +## Core Components + +This section outlines the bridging approach and key features of each component on the frontend: + +- Unified bridging: all components wrap Ant Design React components as Svelte components via sveltify, supporting declarative rendering of slots and items. +- Function callbacks: use useFunction to wrap callbacks such as onChange/onSelect to ensure correct execution in the Svelte context. +- Date and range: format and convert date-type props to ensure consistency with timestamps passed in from the parent. +- Sub-item rendering: achieve unified mapping of items and children via renderItems and useTargets. + +Section Source + +- [frontend/antd/avatar/avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) +- [frontend/antd/badge/badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [frontend/antd/card/card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) +- [frontend/antd/carousel/carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [frontend/antd/collapse/collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [frontend/antd/descriptions/descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [frontend/antd/empty/empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) + +## Architecture Overview + +The diagram below shows the overall flow from backend export to frontend component bridging, as well as utility functions and contexts shared between components. + +```mermaid +sequenceDiagram +participant Py as "Backend Export Module" +participant Svelte as "Svelte Component" +participant AD as "Ant Design React" +participant Util as "Utility Functions" +Py->>Svelte : Export component class +Svelte->>Util : useFunction/useTargets/renderItems +Svelte->>AD : sveltify wrapping and pass props/slots +AD-->>Svelte : Render result and callback triggers +Svelte-->>Py : Complete data display via slots/items +``` + +Diagram Source + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [frontend/antd/avatar/avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [frontend/antd/card/card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) +- [frontend/antd/carousel/carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [frontend/antd/collapse/collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [frontend/antd/descriptions/descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [frontend/antd/empty/empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) + +## Detailed Component Analysis + +### Avatar + +- Data rendering: supports rendering icon and src via slots; if not provided, falls back to children. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design; component layer does not add additional wrapping. + +```mermaid +flowchart TD +Start(["Enter Avatar"]) --> CheckSlots["Check slots: icon / src"] +CheckSlots --> HasSlots{"Slots exist?"} +HasSlots --> |Yes| RenderSlots["Render slot content"] +HasSlots --> |No| Fallback["Fall back to children"] +RenderSlots --> Render["Render Ant Design Avatar"] +Fallback --> Render +Render --> End(["Done"]) +``` + +Diagram Source + +- [frontend/antd/avatar/avatar.tsx:6-25](file://frontend/antd/avatar/avatar.tsx#L6-L25) + +Section Source + +- [frontend/antd/avatar/avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) + +### Badge + +- Data rendering: count and text support custom slots. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +```mermaid +flowchart TD +Start(["Enter Badge"]) --> CountSlot["count has slot?"] +CountSlot --> |Yes| RenderCount["Render count slot"] +CountSlot --> |No| UseCount["Use props.count"] +TextSlot["text has slot?"] +TextSlot --> |Yes| RenderText["Render text slot"] +TextSlot --> |No| UseText["Use props.text"] +RenderCount --> Render["Render Ant Design Badge"] +UseCount --> Render +RenderText --> Render +UseText --> Render +Render --> End(["Done"]) +``` + +Diagram Source + +- [frontend/antd/badge/badge.tsx:6-18](file://frontend/antd/badge/badge.tsx#L6-L18) + +Section Source + +- [frontend/antd/badge/badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) + +### Calendar + +- Data rendering: value/defaultValue/validRange are formatted with dayjs; cellRender/fullCellRender/headerRender support slots. +- Interaction behavior: onChange/onPanelChange/onSelect callbacks are uniformly wrapped via useFunction; internally converts dates to second-level timestamps before returning to the parent. +- Animation effects: provided by Ant Design. + +```mermaid +sequenceDiagram +participant UI as "User Interface" +participant Comp as "Calendar Component" +participant Util as "useFunction/formatDayjs" +participant AD as "Ant Design Calendar" +UI->>Comp : Pass value/defaultValue/validRange +Comp->>Util : Format date +Comp->>AD : Render and bind callbacks +AD-->>Comp : onChange/onPanelChange/onSelect triggered +Comp->>UI : Convert to second-level timestamp and callback +``` + +Diagram Source + +- [frontend/antd/calendar/calendar.tsx:17-99](file://frontend/antd/calendar/calendar.tsx#L17-L99) + +Section Source + +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) + +### Card + +- Data rendering: title/extra/cover/tabBarExtraContent support slots; actions are auto-collected via useTargets; tabList is rendered via renderItems. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +```mermaid +flowchart TD +Start(["Enter Card"]) --> Actions["Collect actions slots"] +Actions --> Tabs["Parse tabList and tabProps"] +Tabs --> Slots["Parse title/extra/cover and other slots"] +Slots --> Render["Render Ant Design Card"] +Render --> End(["Done"]) +``` + +Diagram Source + +- [frontend/antd/card/card.tsx:37-147](file://frontend/antd/card/card.tsx#L37-L147) + +Section Source + +- [frontend/antd/card/card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) + +### Carousel + +- Data rendering: children are collected via useTargets, then cloned and rendered as ReactSlot. +- Interaction behavior: afterChange/beforeChange are wrapped via useFunction. +- Animation effects: provided by Ant Design. + +```mermaid +sequenceDiagram +participant Comp as "Carousel Component" +participant Util as "useTargets/useFunction" +participant AD as "Ant Design Carousel" +Comp->>Util : Collect children and clone +Comp->>AD : Render and bind callbacks +AD-->>Comp : Before/after switch callbacks +Comp-->>Comp : Execute wrapped callbacks +``` + +Diagram Source + +- [frontend/antd/carousel/carousel.tsx:8-29](file://frontend/antd/carousel/carousel.tsx#L8-L29) + +Section Source + +- [frontend/antd/carousel/carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) + +### Collapse + +- Data rendering: items are rendered via renderItems; expandIcon supports slots. +- Interaction behavior: onChange is wrapped via useFunction. +- Animation effects: provided by Ant Design. + +```mermaid +flowchart TD +Start(["Enter Collapse"]) --> Items["Parse items or slots.default/items"] +Items --> ExpandIcon["expandIcon has slot?"] +ExpandIcon --> |Yes| RenderIcon["Render slot"] +ExpandIcon --> |No| UseIcon["Use props.expandIcon"] +RenderIcon --> Render["Render Ant Design Collapse"] +UseIcon --> Render +Render --> End(["Done"]) +``` + +Diagram Source + +- [frontend/antd/collapse/collapse.tsx:11-50](file://frontend/antd/collapse/collapse.tsx#L11-L50) + +Section Source + +- [frontend/antd/collapse/collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) + +### Descriptions + +- Data rendering: title/extra support slots; items are rendered via renderItems. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +```mermaid +flowchart TD +Start(["Enter Descriptions"]) --> Resolve["Resolve items or slots.default/items"] +Resolve --> Render["Render Ant Design Descriptions"] +Render --> End(["Done"]) +``` + +Diagram Source + +- [frontend/antd/descriptions/descriptions.tsx:10-38](file://frontend/antd/descriptions/descriptions.tsx#L10-L38) + +Section Source + +- [frontend/antd/descriptions/descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) + +### Empty + +- Data rendering: description/image support slots; image supports default value and custom. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +```mermaid +flowchart TD +Start(["Enter Empty"]) --> Desc["description has slot?"] +Desc --> |Yes| RenderDesc["Render slot"] +Desc --> |No| UseDesc["Use props.description"] +Image["image has slot?"] +Image --> |Yes| RenderImg["Render slot"] +Image --> |No| CheckDefault["Determine default or custom"] +RenderDesc --> Render["Render Ant Design Empty"] +UseDesc --> Render +RenderImg --> Render +CheckDefault --> Render +Render --> End(["Done"]) +``` + +Diagram Source + +- [frontend/antd/empty/empty.tsx:6-49](file://frontend/antd/empty/empty.tsx#L6-L49) + +Section Source + +- [frontend/antd/empty/empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) + +### Image + +- Data rendering: supports preview group and slots. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/image/image.tsx:1-200](file://frontend/antd/image/image.tsx#L1-L200) + +### List + +- Data rendering: supports custom item rendering and action areas. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/list/list.tsx:1-200](file://frontend/antd/list/list.tsx#L1-L200) + +### Popover + +- Data rendering: supports slots for trigger and content areas. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/popover/popover.tsx:1-200](file://frontend/antd/popover/popover.tsx#L1-L200) + +### QRCode + +- Data rendering: supports content and style configuration. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/qr_code/qr-code.tsx:1-200](file://frontend/antd/qr_code/qr-code.tsx#L1-L200) + +### Segmented + +- Data rendering: supports options and slots. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/segmented/segmented.tsx:1-200](file://frontend/antd/segmented/segmented.tsx#L1-L200) + +### Statistic + +- Data rendering: supports custom titles and values. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/statistic/statistic.tsx:1-200](file://frontend/antd/statistic/statistic.tsx#L1-L200) + +### Table + +- Data rendering: supports complex structures including column definitions, expandable rows, and row selection. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/table/table.tsx:1-200](file://frontend/antd/table/table.tsx#L1-L200) + +### Tabs + +- Data rendering: supports slots for tab items and extra content. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/tabs/tabs.tsx:1-200](file://frontend/antd/tabs/tabs.tsx#L1-L200) + +### Tag + +- Data rendering: supports checkable tags and slots. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/tag/tag.tsx:1-200](file://frontend/antd/tag/tag.tsx#L1-L200) + +### Timeline + +- Data rendering: supports timeline items and slots. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/timeline/timeline.tsx:1-200](file://frontend/antd/timeline/timeline.tsx#L1-L200) + +### Tooltip + +- Data rendering: supports slots for trigger and content areas. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/tooltip/tooltip.tsx:1-200](file://frontend/antd/tooltip/tooltip.tsx#L1-L200) + +### Tour + +- Data rendering: supports steps and slots. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/tour/tour.tsx:1-200](file://frontend/antd/tour/tour.tsx#L1-L200) + +### Tree + +- Data rendering: supports directory tree and node rendering. +- Interaction behavior: no interaction events. +- Animation effects: provided by Ant Design. + +Section Source + +- [frontend/antd/tree/tree.tsx:1-200](file://frontend/antd/tree/tree.tsx#L1-L200) + +## Dependency Analysis + +- Component coupling: all components depend on Ant Design React version; unified wrapping via sveltify reduces the complexity of directly using React. +- Utility functions: tools such as useFunction/useTargets/renderItems/renderParamsSlot run throughout multiple components, improving reusability and consistency. +- Context: some components (such as Collapse/Descriptions/Tabs) introduce an items context for unified declaration and rendering of items. + +```mermaid +graph LR +Util["Utility Functions
useFunction/useTargets/renderItems"] --> AV["Avatar"] +Util --> BG["Badge"] +Util --> CA["Calendar"] +Util --> CR["Card"] +Util --> CL["Carousel"] +Util --> CP["Collapse"] +Util --> DS["Descriptions"] +Util --> EM["Empty"] +Util --> IM["Image"] +Util --> LI["List"] +Util --> PP["Popover"] +Util --> QC["QRCode"] +Util --> SG["Segmented"] +Util --> ST["Statistic"] +Util --> TB["Table"] +Util --> TS["Tabs"] +Util --> TG["Tag"] +Util --> TM["Timeline"] +Util --> TT["Tooltip"] +Util --> TR["Tree"] +``` + +Diagram Source + +- [frontend/antd/avatar/avatar.tsx:1-28](file://frontend/antd/avatar/avatar.tsx#L1-L28) +- [frontend/antd/badge/badge.tsx:1-21](file://frontend/antd/badge/badge.tsx#L1-L21) +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [frontend/antd/card/card.tsx:1-150](file://frontend/antd/card/card.tsx#L1-L150) +- [frontend/antd/carousel/carousel.tsx:1-32](file://frontend/antd/carousel/carousel.tsx#L1-L32) +- [frontend/antd/collapse/collapse.tsx:1-53](file://frontend/antd/collapse/collapse.tsx#L1-L53) +- [frontend/antd/descriptions/descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [frontend/antd/empty/empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) +- [frontend/antd/image/image.tsx:1-200](file://frontend/antd/image/image.tsx#L1-L200) +- [frontend/antd/list/list.tsx:1-200](file://frontend/antd/list/list.tsx#L1-L200) +- [frontend/antd/popover/popover.tsx:1-200](file://frontend/antd/popover/popover.tsx#L1-L200) +- [frontend/antd/qr_code/qr-code.tsx:1-200](file://frontend/antd/qr_code/qr-code.tsx#L1-L200) +- [frontend/antd/segmented/segmented.tsx:1-200](file://frontend/antd/segmented/segmented.tsx#L1-L200) +- [frontend/antd/statistic/statistic.tsx:1-200](file://frontend/antd/statistic/statistic.tsx#L1-L200) +- [frontend/antd/table/table.tsx:1-200](file://frontend/antd/table/table.tsx#L1-L200) +- [frontend/antd/tabs/tabs.tsx:1-200](file://frontend/antd/tabs/tabs.tsx#L1-L200) +- [frontend/antd/tag/tag.tsx:1-200](file://frontend/antd/tag/tag.tsx#L1-L200) +- [frontend/antd/timeline/timeline.tsx:1-200](file://frontend/antd/timeline/timeline.tsx#L1-L200) +- [frontend/antd/tooltip/tooltip.tsx:1-200](file://frontend/antd/tooltip/tooltip.tsx#L1-L200) +- [frontend/antd/tree/tree.tsx:1-200](file://frontend/antd/tree/tree.tsx#L1-L200) + +Section Source + +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) + +## Performance Considerations + +- Large data display recommendations + - Virtual scrolling: prioritize container components with virtual scrolling capabilities (such as List/Table), rendering only visible area elements. + - Pagination and lazy loading: use pagination or scroll-to-bottom loading for long lists to reduce one-time rendering pressure. + - Event throttling: use throttle/debounce for high-frequency interactions (such as scrolling, zooming) to avoid frequent re-renders. + - Rendering optimization: move complex computations to the backend or cache them; the frontend only does lightweight rendering. +- Animation and transitions + - Ant Design components have built-in smooth transitions; the component layer does not add additional animations to avoid performance degradation from overlapping. +- Theming and styles + - Use Ant Design's theme variables and CSS variable system to reduce repeated style computations. + - Avoid dynamically generating large amounts of inline styles within components; prefer class names and CSS Modules. + +## Troubleshooting Guide + +- Date parameter anomaly + - Symptom: calendar component date display or callback timestamp is inconsistent. + - Diagnosis: confirm whether value/defaultValue/validRange passed in are valid timestamps or values parseable by dayjs; check whether the formatting logic is effective. +- Callback not triggered + - Symptom: callbacks such as onChange/onSelect are not executed. + - Diagnosis: confirm whether useFunction correctly wraps the callback; check the priority relationship between slots and props. +- Slots not working + - Symptom: title/extra/actions, etc. are not rendered as expected. + - Diagnosis: confirm that slot names are consistent with component conventions; check whether renderItems and useTargets are used correctly. +- Style override not working + - Symptom: custom styles do not take effect. + - Diagnosis: confirm CSS scope and !important usage; prefer theme variables and controlled style objects. + +Section Source + +- [frontend/antd/calendar/calendar.tsx:17-99](file://frontend/antd/calendar/calendar.tsx#L17-L99) +- [frontend/antd/card/card.tsx:37-147](file://frontend/antd/card/card.tsx#L37-L147) +- [frontend/antd/carousel/carousel.tsx:8-29](file://frontend/antd/carousel/carousel.tsx#L8-L29) +- [frontend/antd/collapse/collapse.tsx:11-50](file://frontend/antd/collapse/collapse.tsx#L11-L50) +- [frontend/antd/descriptions/descriptions.tsx:10-38](file://frontend/antd/descriptions/descriptions.tsx#L10-L38) +- [frontend/antd/empty/empty.tsx:6-49](file://frontend/antd/empty/empty.tsx#L6-L49) + +## Conclusion + +This repository seamlessly integrates Ant Design React components into the Svelte ecosystem through unified sveltify bridging and utility functions, achieving: + +- Declarative data rendering (slots/items) +- Consistent interaction callbacks (useFunction) +- Easy-to-extend theming and style overrides +- Good performance and maintainability + +For large data scenarios, it is recommended to combine virtual scrolling, pagination, and lazy loading strategies to further improve user experience and performance. + +## Appendix + +- Component list and corresponding file paths + - Avatar: [frontend/antd/avatar/avatar.tsx](file://frontend/antd/avatar/avatar.tsx) + - Badge: [frontend/antd/badge/badge.tsx](file://frontend/antd/badge/badge.tsx) + - Calendar: [frontend/antd/calendar/calendar.tsx](file://frontend/antd/calendar/calendar.tsx) + - Card: [frontend/antd/card/card.tsx](file://frontend/antd/card/card.tsx) + - Carousel: [frontend/antd/carousel/carousel.tsx](file://frontend/antd/carousel/carousel.tsx) + - Collapse: [frontend/antd/collapse/collapse.tsx](file://frontend/antd/collapse/collapse.tsx) + - Descriptions: [frontend/antd/descriptions/descriptions.tsx](file://frontend/antd/descriptions/descriptions.tsx) + - Empty: [frontend/antd/empty/empty.tsx](file://frontend/antd/empty/empty.tsx) + - Image: [frontend/antd/image/image.tsx](file://frontend/antd/image/image.tsx) + - List: [frontend/antd/list/list.tsx](file://frontend/antd/list/list.tsx) + - Popover: [frontend/antd/popover/popover.tsx](file://frontend/antd/popover/popover.tsx) + - QRCode: [frontend/antd/qr_code/qr-code.tsx](file://frontend/antd/qr_code/qr-code.tsx) + - Segmented: [frontend/antd/segmented/segmented.tsx](file://frontend/antd/segmented/segmented.tsx) + - Statistic: [frontend/antd/statistic/statistic.tsx](file://frontend/antd/statistic/statistic.tsx) + - Table: [frontend/antd/table/table.tsx](file://frontend/antd/table/table.tsx) + - Tabs: [frontend/antd/tabs/tabs.tsx](file://frontend/antd/tabs/tabs.tsx) + - Tag: [frontend/antd/tag/tag.tsx](file://frontend/antd/tag/tag.tsx) + - Timeline: [frontend/antd/timeline/timeline.tsx](file://frontend/antd/timeline/timeline.tsx) + - Tooltip: [frontend/antd/tooltip/tooltip.tsx](file://frontend/antd/tooltip/tooltip.tsx) + - Tour: [frontend/antd/tour/tour.tsx](file://frontend/antd/tour/tour.tsx) + - Tree: [frontend/antd/tree/tree.tsx](file://frontend/antd/tree/tree.tsx) +- Backend exports + - [backend/modelscope_studio/components/antd/**init**.py](file://backend/modelscope_studio/components/antd/__init__.py) + - [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- Frontend package info + - [frontend/antd/package.json](file://frontend/antd/package.json) diff --git a/.wiki/en/Ant Design Components/Data Display Components/Descriptions and Empty.md b/.wiki/en/Ant Design Components/Data Display Components/Descriptions and Empty.md new file mode 100644 index 00000000..79aced65 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Descriptions and Empty.md @@ -0,0 +1,350 @@ +# Descriptions and Empty + + +**Files Referenced in This Document** +- [frontend/antd/descriptions/descriptions.tsx](file://frontend/antd/descriptions/descriptions.tsx) +- [frontend/antd/descriptions/item/Index.svelte](file://frontend/antd/descriptions/item/Index.svelte) +- [frontend/antd/descriptions/context.ts](file://frontend/antd/descriptions/context.ts) +- [frontend/antd/empty/empty.tsx](file://frontend/antd/empty/empty.tsx) +- [frontend/antd/grid/row/row.tsx](file://frontend/antd/grid/row/row.tsx) +- [frontend/antd/grid/col/col.tsx](file://frontend/antd/grid/col/col.tsx) +- [frontend/antd/grid/context.ts](file://frontend/antd/grid/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/antd/config-provider/locales.ts](file://frontend/antd/config-provider/locales.ts) +- [docs/components/antd/descriptions/README.md](file://docs/components/antd/descriptions/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on two commonly used UI components: **Descriptions** and **Empty**. It provides an in-depth analysis from the perspectives of system architecture, component relationships, data flow and processing logic, integration points and error handling, and performance characteristics. Based on the existing implementation in the repository, it also provides actionable usage recommendations and best practices. Topics covered include: + +- Descriptions: key-value pair display, responsive layout, label alignment, and custom configuration of description items +- Empty: default icons, custom icons, helper text, and combining action buttons +- Descriptions in form detail pages, multi-language support for labels, and internationalization of empty state +- Grid-based layout for Descriptions and user experience optimization with Empty during data load failures + +## Project Structure + +This project uses a layered and component-based frontend structure. Descriptions and Empty are located under the antd frontend component directory, and use common utilities and context mechanisms to enable flexible slot and child item management. + +```mermaid +graph TB +subgraph "Descriptions" +DRoot["descriptions.tsx"] +DItem["item/Index.svelte"] +DContext["context.ts"] +end +subgraph "Empty" +ERoot["empty.tsx"] +end +subgraph "Grid System" +GRow["grid/row/row.tsx"] +GCol["grid/col/col.tsx"] +GContext["grid/context.ts"] +end +subgraph "Common Utilities" +Ctx["utils/createItemsContext.tsx"] +Locales["config-provider/locales.ts"] +end +DRoot --> DContext +DItem --> DContext +DContext --> Ctx +GRow --> GContext +GCol --> GContext +GContext --> Ctx +ERoot --> Locales +``` + +Diagram Source + +- [frontend/antd/descriptions/descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [frontend/antd/descriptions/item/Index.svelte:1-83](file://frontend/antd/descriptions/item/Index.svelte#L1-L83) +- [frontend/antd/descriptions/context.ts:1-7](file://frontend/antd/descriptions/context.ts#L1-L7) +- [frontend/antd/empty/empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) +- [frontend/antd/grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [frontend/antd/grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) + +Section Source + +- [docs/components/antd/descriptions/README.md:1-9](file://docs/components/antd/descriptions/README.md#L1-L9) + +## Core Components + +- Descriptions + - Responsible for displaying a set of key-value pairs in a read-only grouped format, with support for titles, extra areas, and slot-based content injection. + - Collects internal description items via context and item handlers, and ultimately renders them as an Ant Design Descriptions component. +- Descriptions.Item + - A child item of Descriptions, responsible for receiving visibility, style, ID, class name, and other props, and passing child content to the underlying component via slots. +- Empty + - Provides an empty state placeholder with default, simple, or custom icons; supports custom description text and style functions to improve the experience when data is empty or fails to load. +- Grid System (Grid.Row/Col) + - Uses a context mechanism to collect column children and map them to Ant Design's Row/Col, enabling a grid-based layout for Descriptions. + +Section Source + +- [frontend/antd/descriptions/descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [frontend/antd/descriptions/item/Index.svelte:1-83](file://frontend/antd/descriptions/item/Index.svelte#L1-L83) +- [frontend/antd/empty/empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) +- [frontend/antd/grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [frontend/antd/grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +## Architecture Overview + +Both Descriptions and Empty work based on a unified "slot and child item context" mechanism: + +- The context provider is responsible for collecting structured information (props, slots, elements, etc.) from child items and transforming them into the data structures required by Ant Design during the rendering phase. +- Slots allow users to inject custom content in the form of ReactSlot or Svelte Slot, such as titles, extra areas, and description item content. +- When rendering, the Empty component selects the appropriate icon based on the passed image type or slot, and merges style functions with inline styles. + +```mermaid +sequenceDiagram +participant U as "User Code" +participant D as "Descriptions(React)" +participant Ctx as "ItemsContextProvider" +participant Item as "Descriptions.Item(Svelte)" +participant AD as "Antd.Descriptions" +U->>D : Render Descriptions and pass props/slots +D->>Ctx : Wrap with context provider +U->>Item : Place multiple Items inside Descriptions +Item->>Ctx : Register child items via ItemHandler +Ctx-->>D : Aggregate items list +D->>AD : Pass items, title, extra to Antd.Descriptions +AD-->>U : Rendering complete +``` + +Diagram Source + +- [frontend/antd/descriptions/descriptions.tsx:10-38](file://frontend/antd/descriptions/descriptions.tsx#L10-L38) +- [frontend/antd/descriptions/context.ts:1-7](file://frontend/antd/descriptions/context.ts#L1-L7) +- [frontend/antd/descriptions/item/Index.svelte:56-76](file://frontend/antd/descriptions/item/Index.svelte#L56-L76) +- [frontend/utils/createItemsContext.tsx:171-184](file://frontend/utils/createItemsContext.tsx#L171-L184) + +## Detailed Component Analysis + +### Descriptions Component + +- Key-Value Pair Display + - Child items are collected via context and ultimately generate the items array required by Ant Design Descriptions; supports directly passing items or auto-aggregating from child items. +- Responsive Layout + - Can be combined with the Grid System (Grid.Row/Col) for responsive layout; column children inside a Row are mapped to Antd Col for adaptive arrangement at breakpoints. +- Label Alignment + - The component itself does not directly control label alignment, but can pass through props for Antd Descriptions to handle; alignment is transparently forwarded at the Svelte layer. +- Custom Configuration of Description Items + - Supports visible for controlling display, elem_id/elem_classes/elem_style for setting DOM attributes and styles, additionalProps for additional attributes, and as_item for custom render types. +- Slots, Title, and Extra Area + - Supports title and extra slots for injecting custom titles and extra action areas; falls back to props if not provided. + +```mermaid +classDiagram +class Descriptions { ++props : "Antd Descriptions Props" ++slots : "title, extra, default" ++items : "Array or child item collection" ++render() +} +class DescriptionsItem { ++visible : "Visibility flag" ++elem_id : "DOM ID" ++elem_classes : "CSS classes" ++elem_style : "Inline styles" ++additionalProps : "Additional props" ++as_item : "Render type" ++slots : "children etc." ++itemIndex : "Index" ++itemSlotKey : "Slot key" +} +class ItemsContext { ++items : "Child items grouped by slot" ++setItem() ++initial : "Initialization flag" +} +Descriptions --> ItemsContext : "uses" +DescriptionsItem --> ItemsContext : "registers/collects" +``` + +Diagram Source + +- [frontend/antd/descriptions/descriptions.tsx:10-38](file://frontend/antd/descriptions/descriptions.tsx#L10-L38) +- [frontend/antd/descriptions/item/Index.svelte:18-76](file://frontend/antd/descriptions/item/Index.svelte#L18-L76) +- [frontend/antd/descriptions/context.ts:1-7](file://frontend/antd/descriptions/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:40-95](file://frontend/utils/createItemsContext.tsx#L40-L95) + +Section Source + +- [frontend/antd/descriptions/descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [frontend/antd/descriptions/item/Index.svelte:1-83](file://frontend/antd/descriptions/item/Index.svelte#L1-L83) +- [frontend/antd/descriptions/context.ts:1-7](file://frontend/antd/descriptions/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +### Empty Component + +- Default and Custom Icons + - Supports three built-in icon types as well as custom images; the image slot takes priority when present. +- Helper Text + - The description slot has higher priority than props.description, making it easy to dynamically render localized text or complex content. +- Style and Layout + - Supports passing style functions or objects; internally sets the image style to inline-block to ensure consistent alignment of icons and text. +- Combining Action Buttons + - Interactive elements such as buttons can be combined within the description slot to create a complete "empty state + action" flow. + +```mermaid +flowchart TD +Start(["Enter Empty render"]) --> CheckImage["Check if image slot exists"] +CheckImage --> |Yes| UseSlotImage["Use slot image"] +CheckImage --> |No| SwitchImage["Select type based on props.image"] +SwitchImage --> |Built-in constant| UseAntdDefault["Use Antd default icon"] +SwitchImage --> |Simple built-in| UseAntdSimple["Use Antd simple icon"] +SwitchImage --> |Other| UseCustom["Use custom image"] +UseSlotImage --> RenderDesc["Render description slot or props.description"] +UseAntdDefault --> RenderDesc +UseAntdSimple --> RenderDesc +UseCustom --> RenderDesc +RenderDesc --> MergeStyles["Merge style function and object
ensure icon is inline-block"] +MergeStyles --> End(["Rendering complete"]) +``` + +Diagram Source + +- [frontend/antd/empty/empty.tsx:9-49](file://frontend/antd/empty/empty.tsx#L9-L49) + +Section Source + +- [frontend/antd/empty/empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) + +### Grid-Based Layout (Grid.Row/Col) + +- Row maps collected column children to Antd Col and renders them inside the Row to achieve responsive grid layout. +- Col receives column props and slots via ItemHandler and forwards them to Antd Col. +- When combined with Descriptions, description items can be nested inside Row/Col to form a "grid-based Descriptions". + +```mermaid +sequenceDiagram +participant U as "User Code" +participant R as "Grid.Row(React)" +participant Ctx as "Grid ItemsContext" +participant C as "Grid.Col(React)" +participant AD as "Antd.Row/Col" +U->>R : Render Row +R->>Ctx : Use context provider +U->>C : Place multiple Col inside Row +C->>Ctx : Register column children via ItemHandler +Ctx-->>R : Aggregate column items +R->>AD : Render Row and map Col +AD-->>U : Grid layout complete +``` + +Diagram Source + +- [frontend/antd/grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [frontend/antd/grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:171-184](file://frontend/utils/createItemsContext.tsx#L171-L184) + +Section Source + +- [frontend/antd/grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [frontend/antd/grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) + +## Dependency Analysis + +- Descriptions Dependencies + - Uses the context capability provided by createItemsContext to bridge Svelte slots and React components, enabling items collection and rendering. + - Wraps the component with withItemsContextProvider to ensure child item registration and updates. +- Empty Dependencies + - Depends on Ant Design's Empty component and built-in icon constants; style function and object merging ensures consistent alignment of icons and text. +- Internationalization Dependencies + - Provides multi-language environments through the config-provider's locales, supporting localization switching for both Antd and dayjs. + +```mermaid +graph LR +D["Descriptions"] --> Ctx["createItemsContext"] +DItem["Descriptions.Item"] --> Ctx +E["Empty"] --> AD["Antd.Empty"] +E --> Locales["locales.ts"] +subgraph "Context Utilities" +Ctx +end +subgraph "Antd Components" +AD +end +subgraph "Internationalization" +Locales +end +``` + +Diagram Source + +- [frontend/antd/descriptions/descriptions.tsx:1-10](file://frontend/antd/descriptions/descriptions.tsx#L1-L10) +- [frontend/antd/descriptions/item/Index.svelte:1-15](file://frontend/antd/descriptions/item/Index.svelte#L1-L15) +- [frontend/antd/empty/empty.tsx:1-9](file://frontend/antd/empty/empty.tsx#L1-L9) +- [frontend/antd/config-provider/locales.ts:1-10](file://frontend/antd/config-provider/locales.ts#L1-L10) + +Section Source + +- [frontend/antd/descriptions/descriptions.tsx:1-41](file://frontend/antd/descriptions/descriptions.tsx#L1-L41) +- [frontend/antd/empty/empty.tsx:1-52](file://frontend/antd/empty/empty.tsx#L1-L52) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) + +## Performance Considerations + +- Child Item Collection and Rendering + - Both Descriptions and the Grid System collect child items via context, avoiding unnecessary re-renders; only the corresponding component's recalculation is triggered when items update. +- Slots and Styles + - Slot content is rendered lazily, mounting only when visible; style function and object merging occurs at render time — it is recommended to reuse style objects as much as possible to reduce overhead. +- Icons and Descriptions + - Icon selection and style merging logic for the Empty component is simple with low performance overhead; it is recommended to use built-in icons in scenarios with many empty states to reduce resource loading. + +## Troubleshooting Guide + +- Descriptions shows no content + - Check whether withItemsContextProvider is correctly wrapping Descriptions, and that Descriptions.Item is placed inside it. + - Confirm that child items have been registered via ItemHandler and that the items list is not empty. +- Description items not taking effect + - Check whether visible, elem_id, elem_classes, elem_style, additionalProps, and other props are passed correctly. + - Confirm that the children slot is correctly bound and rendered. +- Empty state icon not displayed + - If passing an image slot, ensure the slot content is valid; otherwise check whether props.image is a built-in constant or a valid custom value. + - Confirm that the object returned by the style function contains the correct image styles. +- Grid layout issues + - Check whether Grid.Row/Col children are correctly registered; confirm that column props and slots are properly forwarded. + +Section Source + +- [frontend/antd/descriptions/descriptions.tsx:10-38](file://frontend/antd/descriptions/descriptions.tsx#L10-L38) +- [frontend/antd/descriptions/item/Index.svelte:56-76](file://frontend/antd/descriptions/item/Index.svelte#L56-L76) +- [frontend/antd/empty/empty.tsx:9-49](file://frontend/antd/empty/empty.tsx#L9-L49) +- [frontend/antd/grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [frontend/antd/grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) + +## Conclusion + +The Descriptions and Empty components achieve flexible content injection and rendering through a unified context and slot mechanism. Descriptions supports key-value pair display and grid-based layout; Empty provides placeholder solutions with both default and custom icons, and can be combined with action buttons to optimize user experience. Combined with internationalization tools, both can operate stably in multi-language environments. It is recommended to prioritize using Descriptions for displaying read-only information in form detail pages, and to use the Empty component to improve usability when data is empty or fails to load. + +## Appendix + +- Usage Scenario Recommendations + - Form detail pages: Use Descriptions to display read-only fields, optionally combined with the Grid System for responsive layout. + - Data load failures: Use the Empty component to display prompts and retry buttons to improve user confidence. +- Multi-language Support + - Switch Antd and dayjs localization through the config-provider's locales to ensure text and formatting in Descriptions and Empty match the target language. +- Best Practices + - Use slots and props appropriately; avoid creating new objects frequently in render functions. + - For scenarios with many empty states, prefer built-in icons to reduce resource overhead. + - In grid-based layouts, divide column widths and breakpoints carefully to ensure readability across different devices. diff --git a/.wiki/en/Ant Design Components/Data Display Components/Image and List.md b/.wiki/en/Ant Design Components/Data Display Components/Image and List.md new file mode 100644 index 00000000..a1dac268 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Image and List.md @@ -0,0 +1,324 @@ +# Image and List + + +**Files Referenced in This Document** +- [frontend/antd/image/image.tsx](file://frontend/antd/image/image.tsx) +- [frontend/antd/image/preview-group/image.preview-group.tsx](file://frontend/antd/image/preview-group/image.preview-group.tsx) +- [frontend/antd/image/preview-group/Index.svelte](file://frontend/antd/image/preview-group/Index.svelte) +- [frontend/antd/list/list.tsx](file://frontend/antd/list/list.tsx) +- [frontend/antd/list/item/list.item.tsx](file://frontend/antd/list/item/list.item.tsx) +- [frontend/antd/list/item/Index.svelte](file://frontend/antd/list/item/Index.svelte) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/utils/hooks/useTargets.ts](file://frontend/utils/hooks/useTargets.ts) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the **Image** and **List** component families, systematically reviewing their encapsulation approach at the frontend layer, capability boundaries, and extension points. Based on the existing repository implementation, it provides actionable usage recommendations and best practices. Key topics include: + +- Image component: batch viewing via preview groups, lazy loading, error handling, and the availability and limitations of image cropping; current state and extension paths for zoom controls, rotation, and download support. +- List component: basic list structure, list item metadata (meta), vertical list layout, and dynamic data binding; current state and extension paths for virtual scrolling, infinite loading, and data filtering; adaptive display and responsive layout design across different devices. + +## Project Structure + +The frontend uses a Svelte + Ant Design combination pattern for Image and List components: + +- Component entry points are exported via Svelte files, with sveltify internally bridging Ant Design's React components into a Svelte-compatible form. +- Preview groups and list items are lazy-loaded via importComponent, combined with the slots mechanism for flexible rendering extensions. +- Utility functions and hooks provide general capabilities: function wrapping, parameterized slot rendering, and target node extraction. + +```mermaid +graph TB +subgraph "Image Component" +IMG_TS["image.tsx
Wraps Ant Design Image"] +PG_IDX["preview-group/Index.svelte
Preview group entry"] +PG_IMPL["preview-group/image.preview-group.tsx
Preview group implementation"] +end +subgraph "List Component" +LIST_TS["list.tsx
Wraps Ant Design List"] +ITEM_IDX["item/Index.svelte
List item entry"] +ITEM_IMPL["item/list.item.tsx
List item implementation"] +end +subgraph "Utilities and Hooks" +USE_FN["useFunction.ts
Function wrapping"] +USE_TGT["useTargets.ts
Target node extraction"] +RENDER_SLOT["renderParamsSlot.tsx
Parameterized slot rendering"] +end +IMG_TS --> PG_IMPL +PG_IDX --> PG_IMPL +LIST_TS --> ITEM_IMPL +ITEM_IDX --> ITEM_IMPL +IMG_TS --> USE_FN +PG_IMPL --> USE_FN +LIST_TS --> USE_FN +ITEM_IMPL --> USE_FN +LIST_TS --> RENDER_SLOT +ITEM_IMPL --> RENDER_SLOT +ITEM_IMPL --> USE_TGT +``` + +**Diagram Source** + +- [frontend/antd/image/image.tsx:1-89](file://frontend/antd/image/image.tsx#L1-L89) +- [frontend/antd/image/preview-group/Index.svelte:1-72](file://frontend/antd/image/preview-group/Index.svelte#L1-L72) +- [frontend/antd/image/preview-group/image.preview-group.tsx:1-55](file://frontend/antd/image/preview-group/image.preview-group.tsx#L1-L55) +- [frontend/antd/list/list.tsx:1-36](file://frontend/antd/list/list.tsx#L1-L36) +- [frontend/antd/list/item/Index.svelte:1-60](file://frontend/antd/list/item/Index.svelte#L1-L60) +- [frontend/antd/list/item/list.item.tsx:1-29](file://frontend/antd/list/item/list.item.tsx#L1-L29) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/hooks/useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +**Section Source** + +- [frontend/antd/image/image.tsx:1-89](file://frontend/antd/image/image.tsx#L1-L89) +- [frontend/antd/image/preview-group/Index.svelte:1-72](file://frontend/antd/image/preview-group/Index.svelte#L1-L72) +- [frontend/antd/image/preview-group/image.preview-group.tsx:1-55](file://frontend/antd/image/preview-group/image.preview-group.tsx#L1-L55) +- [frontend/antd/list/list.tsx:1-36](file://frontend/antd/list/list.tsx#L1-L36) +- [frontend/antd/list/item/Index.svelte:1-60](file://frontend/antd/list/item/Index.svelte#L1-L60) +- [frontend/antd/list/item/list.item.tsx:1-29](file://frontend/antd/list/item/list.item.tsx#L1-L29) + +## Core Components + +- Image: Wraps Ant Design's Image component via sveltify, supporting placeholders, preview configuration, and slot extensions. The preview group provides batch viewing capability, with support for custom masks, close icons, and toolbars. +- List: Wraps Ant Design's List component via sveltify, supporting headers/footers, load-more, and custom render items. List items support extra areas and action collections, with useTargets automatically extracting child nodes carrying specific slotKeys. + +**Section Source** + +- [frontend/antd/image/image.tsx:14-86](file://frontend/antd/image/image.tsx#L14-L86) +- [frontend/antd/image/preview-group/image.preview-group.tsx:13-52](file://frontend/antd/image/preview-group/image.preview-group.tsx#L13-L52) +- [frontend/antd/list/list.tsx:8-33](file://frontend/antd/list/list.tsx#L8-L33) +- [frontend/antd/list/item/list.item.tsx:6-26](file://frontend/antd/list/item/list.item.tsx#L6-L26) + +## Architecture Overview + +The following diagram shows the call chain and slot extension points of the Image and List components at the frontend layer: + +```mermaid +sequenceDiagram +participant U as "User" +participant IMG as "Image Component
image.tsx" +participant PG as "Preview Group
image.preview-group.tsx" +participant LIST as "List Component
list.tsx" +participant ITEM as "ListItem Component
list.item.tsx" +U->>IMG : "Click image" +IMG->>PG : "Trigger preview group" +PG-->>U : "Batch view / toolbar / mask" +U->>LIST : "Render list" +LIST->>ITEM : "Render each item" +ITEM-->>U : "Extra area / action collection" +``` + +**Diagram Source** + +- [frontend/antd/image/image.tsx:24-85](file://frontend/antd/image/image.tsx#L24-L85) +- [frontend/antd/image/preview-group/image.preview-group.tsx:18-51](file://frontend/antd/image/preview-group/image.preview-group.tsx#L18-L51) +- [frontend/antd/list/list.tsx:11-32](file://frontend/antd/list/list.tsx#L11-L32) +- [frontend/antd/list/item/list.item.tsx:9-25](file://frontend/antd/list/item/list.item.tsx#L9-L25) + +## Detailed Component Analysis + +### Image Component + +- Batch Viewing (Preview Group) + - The preview group achieves on-demand loading via lazy imports and conditional rendering, reducing the initial load burden. + - Supports custom masks, close icons, and toolbars; toolbar and image rendering can be injected via slots or function callbacks. + - The mount location of the preview container can be customized via getContainer, making it easy to embed in a specific DOM container. +- Lazy Loading and Error Handling + - The current implementation does not explicitly declare lazy loading and error handling logic; if needed, these can be enhanced at the business layer using native browser attributes or third-party libraries. +- Image Cropping + - This implementation does not expose cropping-related parameters; if cropping is needed, resources can be pre-processed at the business layer or a dedicated cropping library can be introduced. +- Zoom Controls, Rotation, and Download Support + - The current implementation does not have built-in zoom, rotation, or download buttons; corresponding controls can be added via the custom toolbar slot in combination with external libraries. +- Slots and Function Wrapping + - useFunction is used to stabilize passed-in functions; renderParamsSlot supports passing parameters to slot render functions, improving flexibility. + +```mermaid +flowchart TD +Start(["Enter Image render"]) --> CheckPreview["Detect if preview is enabled"] +CheckPreview --> |Yes| BuildPreview["Build preview config
merge slots and functions"] +CheckPreview --> |No| SkipPreview["Disable preview"] +BuildPreview --> SlotsCheck{"Custom slots present?"} +SlotsCheck --> |Yes| RenderSlots["Render custom slots"] +SlotsCheck --> |No| UseDefault["Use default preview behavior"] +RenderSlots --> End(["Done"]) +UseDefault --> End +SkipPreview --> End +``` + +**Diagram Source** + +- [frontend/antd/image/image.tsx:24-85](file://frontend/antd/image/image.tsx#L24-L85) +- [frontend/antd/image/preview-group/image.preview-group.tsx:18-51](file://frontend/antd/image/preview-group/image.preview-group.tsx#L18-L51) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [frontend/utils/renderParamsSlot.tsx:5-50](file://frontend/utils/renderParamsSlot.tsx#L5-L50) + +**Section Source** + +- [frontend/antd/image/image.tsx:14-86](file://frontend/antd/image/image.tsx#L14-L86) +- [frontend/antd/image/preview-group/image.preview-group.tsx:13-52](file://frontend/antd/image/preview-group/image.preview-group.tsx#L13-L52) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +### List Component + +- Basic List Structure and Dynamic Data Binding + - Wraps Ant Design List via sveltify, supporting headers/footers, load-more, and custom render items. + - Render items can be passed via slots or injected as functions, enabling flexible data binding and view rendering. +- List Item and Metadata (meta) + - List items support "extra areas" and "action collections"; action collections are automatically extracted from child nodes carrying specific slotKeys using useTargets, ensuring controllable order and indexing. +- Vertical List Layout + - Uses Ant Design's default vertical layout strategy, suitable for most scenarios; for horizontal or grid layouts, use styles or layout components at the business layer. + +```mermaid +classDiagram +class List_tsx { ++slots : footer/header/loadMore/renderItem ++render() : ReactNode +} +class ListItem_tsx { ++slots : extra/actions ++useTargets(children, slotKey) ++render() : ReactNode +} +List_tsx --> ListItem_tsx : "Renders each item" +``` + +**Diagram Source** + +- [frontend/antd/list/list.tsx:8-33](file://frontend/antd/list/list.tsx#L8-L33) +- [frontend/antd/list/item/list.item.tsx:6-26](file://frontend/antd/list/item/list.item.tsx#L6-L26) +- [frontend/utils/hooks/useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) + +**Section Source** + +- [frontend/antd/list/list.tsx:8-33](file://frontend/antd/list/list.tsx#L8-L33) +- [frontend/antd/list/item/list.item.tsx:6-26](file://frontend/antd/list/item/list.item.tsx#L6-L26) +- [frontend/utils/hooks/useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) + +### Preview Group + +- Batch Viewing and Visibility Control + - The preview group entry uses Svelte lazy imports and visibility checks to render the actual component only when needed, reducing initial overhead. + - Supports controlling preview visibility change events via props, enabling synchronization with parent state. +- Slots and Container Mounting + - Supports custom masks and close icons; container mounting location is customized via getContainer, making it easy to embed in a specified container. + +```mermaid +sequenceDiagram +participant IDX as "Preview Group Entry
Index.svelte" +participant CMP as "Preview Group Implementation
image.preview-group.tsx" +IDX->>IDX : "Check visibility" +IDX->>CMP : "Lazy import and render" +CMP-->>IDX : "Output preview group" +``` + +**Diagram Source** + +- [frontend/antd/image/preview-group/Index.svelte:55-71](file://frontend/antd/image/preview-group/Index.svelte#L55-L71) +- [frontend/antd/image/preview-group/image.preview-group.tsx:18-51](file://frontend/antd/image/preview-group/image.preview-group.tsx#L18-L51) + +**Section Source** + +- [frontend/antd/image/preview-group/Index.svelte:14-71](file://frontend/antd/image/preview-group/Index.svelte#L14-L71) +- [frontend/antd/image/preview-group/image.preview-group.tsx:18-52](file://frontend/antd/image/preview-group/image.preview-group.tsx#L18-L52) + +## Dependency Analysis + +- Components and Utility Functions + - Both Image and List components depend on useFunction for function stabilization, ensuring callbacks are not recreated when props change. + - List items depend on useTargets to extract child nodes with specific slotKeys, enabling automatic assembly of action collections. + - renderParamsSlot provides parameterized slot rendering, supporting parameter passing to slots with forced cloning to ensure rendering consistency across multiple renders. +- Inter-Component Coupling + - Image preview group and Image component are decoupled: the preview group exists as an independent component and collaborates with the Image component via props and slots. + - List items and the List component are decoupled: list items use lazy imports and slots for independent rendering, reducing coupling. + +```mermaid +graph LR +IMG["image.tsx"] --> UF["useFunction.ts"] +PG["image.preview-group.tsx"] --> UF +LIST["list.tsx"] --> UF +ITEM["list.item.tsx"] --> UF +ITEM --> UT["useTargets.ts"] +LIST --> RS["renderParamsSlot.tsx"] +ITEM --> RS +``` + +**Diagram Source** + +- [frontend/antd/image/image.tsx:3-4](file://frontend/antd/image/image.tsx#L3-L4) +- [frontend/antd/image/preview-group/image.preview-group.tsx:3-4](file://frontend/antd/image/preview-group/image.preview-group.tsx#L3-L4) +- [frontend/antd/list/list.tsx:4-5](file://frontend/antd/list/list.tsx#L4-L5) +- [frontend/antd/list/item/list.item.tsx:3-4](file://frontend/antd/list/item/list.item.tsx#L3-L4) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/hooks/useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +**Section Source** + +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/hooks/useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +## Performance Considerations + +- On-Demand Loading and Lazy Imports + - Both preview groups and list items use lazy import strategies, rendering only when visible, which helps reduce initial load and memory usage. +- Function Stabilization + - useFunction memoizes callbacks to avoid recreation due to prop changes, reducing re-render costs. +- Slot Rendering Optimization + - renderParamsSlot enforces cloning and parameter forwarding, ensuring deterministic and reusable slot rendering while reducing unnecessary repeated computation. + +**Section Source** + +- [frontend/antd/image/preview-group/Index.svelte:55-71](file://frontend/antd/image/preview-group/Index.svelte#L55-L71) +- [frontend/antd/list/item/Index.svelte:46-59](file://frontend/antd/list/item/Index.svelte#L46-L59) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [frontend/utils/renderParamsSlot.tsx:23-49](file://frontend/utils/renderParamsSlot.tsx#L23-L49) + +## Troubleshooting Guide + +- Preview group not displayed + - Check the visibility props and the entry component's visibility logic to confirm that the preview group has been lazy-loaded and rendered. + - If using a custom mask or close icon, confirm that the slot is correctly passed in and has not been overridden. +- Toolbar/image rendering not working + - Confirm that passed-in functions are wrapped with useFunction to prevent failures due to function reference changes. + - If using slots, confirm that parameter passing to renderParamsSlot is correct. +- List item action collection is empty + - Check whether child nodes carry the correct slotKey and index information to ensure useTargets can extract them correctly. +- Performance issues + - If frequent re-renders occur, check whether callbacks or slot content are being changed frequently in the parent component; it is recommended to use useFunction or stabilization strategies. + +**Section Source** + +- [frontend/antd/image/preview-group/Index.svelte:55-71](file://frontend/antd/image/preview-group/Index.svelte#L55-L71) +- [frontend/antd/image/preview-group/image.preview-group.tsx:18-51](file://frontend/antd/image/preview-group/image.preview-group.tsx#L18-L51) +- [frontend/antd/list/item/list.item.tsx:10-21](file://frontend/antd/list/item/list.item.tsx#L10-L21) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [frontend/utils/renderParamsSlot.tsx:23-49](file://frontend/utils/renderParamsSlot.tsx#L23-L49) + +## Conclusion + +- The Image component achieves batch viewing and flexible slot extensions via the preview group; the current implementation does not have built-in lazy loading, error handling, cropping, zoom, rotation, or download features, but offers good extensibility. +- The List component provides basic structure and dynamic binding capabilities; list item action collections are automatically assembled via useTargets, making it suitable for combining with styles and layout at the business layer to achieve responsive and adaptive display. +- In terms of performance, components generally adopt lazy import and function stabilization strategies, helping to maintain good runtime efficiency in complex scenarios. + +## Appendix + +- Extension Recommendations + - Image: Introduce lazy loading and error handling strategies at the business layer; for cropping, zoom, rotation, and download, combine external libraries with custom toolbar slots. + - List: Introduce virtual scrolling and infinite loading at the business layer; data filtering can be achieved through external state and render conditions; responsive layout can be adapted for multiple devices via style and breakpoint strategies. diff --git a/.wiki/en/Ant Design Components/Data Display Components/Popover and QRCode.md b/.wiki/en/Ant Design Components/Data Display Components/Popover and QRCode.md new file mode 100644 index 00000000..33d4eecc --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Popover and QRCode.md @@ -0,0 +1,332 @@ +# Popover and QRCode + + +**Files Referenced in This Document** +- [popover.tsx](file://frontend/antd/popover/popover.tsx) +- [Index.svelte (Popover)](file://frontend/antd/popover/Index.svelte) +- [__init__.py (AntdPopover)](file://backend/modelscope_studio/components/antd/popover/__init__.py) +- [README-zh_CN.md (Popover docs)](file://docs/components/antd/popover/README-zh_CN.md) +- [README.md (Popover docs)](file://docs/components/antd/popover/README.md) +- [qr-code.tsx](file://frontend/antd/qr-code/qr-code.tsx) +- [Index.svelte (QRCode)](file://frontend/antd/qr-code/Index.svelte) +- [__init__.py (AntdQRCode)](file://backend/modelscope_studio/components/antd/qr_code/__init__.py) +- [README-zh_CN.md (QRCode docs)](file://docs/components/antd/qr_code/README-zh_CN.md) +- [README.md (QRCode docs)](file://docs/components/antd/qr_code/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document provides a comprehensive explanation of the **Popover** and **QRCode** components, from underlying implementation to usage at the application layer. Topics covered include: + +- Popover: trigger modes, position control, content customization, animation integration, nested usage, delayed display, accessibility support, and more +- QRCode: encoded content, size and margin, color and background, error correction level, icon overlay, dynamic refresh, custom styles, and print optimization +- Complex layout positioning strategies and mobile scanning experience recommendations + +## Project Structure + +Both components follow a unified layered design of "backend component class + frontend Svelte wrapper + React encapsulation": + +- The backend component class handles parameter validation, event binding, example values, and render switches +- The frontend Svelte layer handles prop forwarding, slot processing, and visibility control +- The React encapsulation layer bridges with Ant Design components and supports slot and function callback conversion + +```mermaid +graph TB +subgraph "Backend" +BPY["AntdPopover.__init__"] +BQRY["AntdQRCode.__init__"] +end +subgraph "Frontend Svelte" +PIdx["Popover/Index.svelte"] +QIdx["QRCode/Index.svelte"] +end +subgraph "React Encapsulation" +PR["Popover/popover.tsx"] +QR["QRCode/qr-code.tsx"] +end +subgraph "Ant Design" +ADPop["antd.Popover"] +ADQR["antd.QRCode"] +end +BPY --> PIdx +BQRY --> QIdx +PIdx --> PR +QIdx --> QR +PR --> ADPop +QR --> ADQR +``` + +Diagram Source + +- [**init**.py (AntdPopover):10-124](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L124) +- [Index.svelte (Popover):10-72](file://frontend/antd/popover/Index.svelte#L10-L72) +- [popover.tsx:7-34](file://frontend/antd/popover/popover.tsx#L7-L34) +- [**init**.py (AntdQRCode):10-96](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L10-L96) +- [Index.svelte (QRCode):10-63](file://frontend/antd/qr-code/Index.svelte#L10-L63) +- [qr-code.tsx:6-20](file://frontend/antd/qr-code/qr-code.tsx#L6-L20) + +Section Source + +- [**init**.py (AntdPopover):10-124](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L124) +- [Index.svelte (Popover):10-72](file://frontend/antd/popover/Index.svelte#L10-L72) +- [popover.tsx:7-34](file://frontend/antd/popover/popover.tsx#L7-L34) +- [**init**.py (AntdQRCode):10-96](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L10-L96) +- [Index.svelte (QRCode):10-63](file://frontend/antd/qr-code/Index.svelte#L10-L63) +- [qr-code.tsx:6-20](file://frontend/antd/qr-code/qr-code.tsx#L6-L20) + +## Core Components + +- Popover + - Supports multiple trigger modes: hover, focus, click, context menu + - Supports 12 placement positions: top/bottom/left/right and four corners + - Supports title and content slots for injecting arbitrary content + - Supports open state change event binding + - Supports custom container mount point and delayed display control +- QRCode + - Supports canvas/svg output types + - Supports foreground color, background color, border, icon overlay, and margin + - Supports four error correction levels: L/M/Q/H + - Supports status render slot and refresh event binding + +Section Source + +- [**init**.py (AntdPopover):43-59](file://backend/modelscope_studio/components/antd/popover/__init__.py#L43-L59) +- [**init**.py (AntdQRCode):29-40](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L29-L40) + +## Architecture Overview + +The following diagram shows the call chain from the backend component class to the frontend Svelte wrapper, then to the React encapsulation layer and Ant Design. + +```mermaid +sequenceDiagram +participant Backend as "Backend Component Class" +participant Svelte as "Svelte Wrapper" +participant ReactWrap as "React Encapsulation" +participant AntD as "Ant Design" +Backend->>Svelte : Pass parameters and events +Svelte->>ReactWrap : Forward props/slots/visibility +ReactWrap->>AntD : Render and bind events +AntD-->>ReactWrap : Interaction results/state changes +ReactWrap-->>Svelte : Return callbacks/state +Svelte-->>Backend : Trigger events/update state +``` + +Diagram Source + +- [**init**.py (AntdPopover):14-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L18) +- [Index.svelte (Popover):24-52](file://frontend/antd/popover/Index.svelte#L24-L52) +- [popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) +- [**init**.py (AntdQRCode):15-19](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L15-L19) +- [Index.svelte (QRCode):22-45](file://frontend/antd/qr-code/Index.svelte#L22-L45) +- [qr-code.tsx:6-20](file://frontend/antd/qr-code/qr-code.tsx#L6-L20) + +## Detailed Component Analysis + +### Popover Component + +- Trigger Modes + - Supports hover/focus/click/contextMenu and their combinations + - Entry/leave delays can be controlled via delay parameters +- Position Control + - Supports top/left/right/bottom and all nine grid positions + - Supports overflow auto-adjustment and arrow configuration +- Content Customization + - Supports title/content slots for rendering arbitrary content + - Supports overlay style and inner style +- Animation and Events + - Provides the open_change event for listening to open state changes + - Supports custom container mount points for precise positioning in complex layouts +- Nested Usage + - Avoid z-index conflicts by customizing the container mount point + - Be careful to avoid focus issues caused by multiple layered popovers activating simultaneously +- Delayed Display + - Control the display timing using entry/leave delay parameters +- Accessibility Support + - Recommended to combine with aria-\* attributes and keyboard navigation + - Pay attention to semantic labels and description text in nested scenarios + +```mermaid +classDiagram +class AntdPopover { ++EVENTS ++SLOTS ++placement ++trigger ++mouse_enter_delay ++mouse_leave_delay ++overlay_style ++overlay_inner_style ++get_popup_container ++open_change +} +class PopoverWrapper { ++slots ++afterOpenChange ++getPopupContainer ++children +} +AntdPopover --> PopoverWrapper : "prop forwarding" +``` + +Diagram Source + +- [**init**.py (AntdPopover):14-105](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L105) +- [popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) + +Section Source + +- [**init**.py (AntdPopover):23-105](file://backend/modelscope_studio/components/antd/popover/__init__.py#L23-L105) +- [Index.svelte (Popover):24-52](file://frontend/antd/popover/Index.svelte#L24-L52) +- [popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) +- [README-zh_CN.md (Popover docs):1-8](file://docs/components/antd/popover/README-zh_CN.md#L1-L8) +- [README.md (Popover docs):1-8](file://docs/components/antd/popover/README.md#L1-L8) + +### QRCode Component + +- Encoded Content and Size + - value: the encoded content of the QR code + - size: overall size; margin_size: outer margin; bordered: whether to show a border +- Color and Style + - color: foreground color; bg_color: background color; type: canvas/svg output +- Error Correction and Enhancement + - error_level: four correction levels L/M/Q/H + - boost_level: enhance recognition capability (boolean) +- Icon Overlay and Status + - icon: center icon URL; icon_size: icon size or size configuration + - status: active/expired/loading/scanned states + - statusRender: status render slot +- Dynamic Updates and Events + - refresh event: used to trigger QR code regeneration +- Custom Styles and Print Optimization + - Theme adaptation via styles and class names + - For print scenarios, it is recommended to use fixed sizes and high-contrast colors + +```mermaid +classDiagram +class AntdQRCode { ++EVENTS ++SLOTS ++value ++size ++color ++bg_color ++type ++bordered ++error_level ++boost_level ++icon ++icon_size ++margin_size ++status ++statusRender ++refresh +} +class QRWrapper { ++slots ++statusRender ++value +} +AntdQRCode --> QRWrapper : "prop forwarding" +``` + +Diagram Source + +- [**init**.py (AntdQRCode):15-77](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L15-L77) +- [qr-code.tsx:6-20](file://frontend/antd/qr-code/qr-code.tsx#L6-L20) + +Section Source + +- [**init**.py (AntdQRCode):24-77](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L24-L77) +- [Index.svelte (QRCode):22-45](file://frontend/antd/qr-code/Index.svelte#L22-L45) +- [qr-code.tsx:6-20](file://frontend/antd/qr-code/qr-code.tsx#L6-L20) +- [README-zh_CN.md (QRCode docs):1-8](file://docs/components/antd/qr_code/README-zh_CN.md#L1-L8) +- [README.md (QRCode docs):1-8](file://docs/components/antd/qr_code/README.md#L1-L8) + +## Dependency Analysis + +- Backend Component Class and Frontend Wrapper + - The backend class defines parameters and events; the frontend Svelte layer is responsible for the final assembly of props and slots +- React Encapsulation and Ant Design + - The React encapsulation layer converts slots into renderable nodes and safely passes callback functions to Ant Design components +- Event Binding + - Popover: open_change + - QRCode: refresh + +```mermaid +graph LR +BE["Backend Component Class"] --> FE["Svelte Wrapper"] +FE --> WR["React Encapsulation"] +WR --> AD["Ant Design Component"] +``` + +Diagram Source + +- [**init**.py (AntdPopover):14-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L18) +- [Index.svelte (Popover):24-52](file://frontend/antd/popover/Index.svelte#L24-L52) +- [popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) +- [**init**.py (AntdQRCode):15-19](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L15-L19) +- [Index.svelte (QRCode):22-45](file://frontend/antd/qr-code/Index.svelte#L22-L45) +- [qr-code.tsx:6-20](file://frontend/antd/qr-code/qr-code.tsx#L6-L20) + +Section Source + +- [**init**.py (AntdPopover):14-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L18) +- [Index.svelte (Popover):24-52](file://frontend/antd/popover/Index.svelte#L24-L52) +- [popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) +- [**init**.py (AntdQRCode):15-19](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L15-L19) +- [Index.svelte (QRCode):22-45](file://frontend/antd/qr-code/Index.svelte#L22-L45) +- [qr-code.tsx:6-20](file://frontend/antd/qr-code/qr-code.tsx#L6-L20) + +## Performance Considerations + +- Popover + - Set trigger modes and delays appropriately to avoid frequent re-renders + - For complex content, consider lazy loading or on-demand rendering + - The container mount point should be as close to the target element as possible to reduce DOM nesting depth +- QRCode + - Canvas output may create memory pressure at large sizes; consider using svg or reducing the size if necessary + - Icon overlay increases rendering overhead; lightweight icons are recommended + - The status render slot should only be enabled when needed to avoid unnecessary computation + +## Troubleshooting Guide + +- Popover + - Open state not taking effect: check open_change event binding and the open parameter + - Content not displayed: confirm that the title/content slots are correctly passed + - Positioning issues: check whether get_popup_container returns a valid container +- QRCode + - Cannot refresh: confirm that the refresh event is successfully bound + - Styles not taking effect: check whether color/bg_color and type settings are correct + - Scanning difficulties: increase error_level or enable boost_level + +Section Source + +- [**init**.py (AntdPopover):14-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L18) +- [Index.svelte (Popover):24-52](file://frontend/antd/popover/Index.svelte#L24-L52) +- [**init**.py (AntdQRCode):15-19](file://backend/modelscope_studio/components/antd/qr_code/__init__.py#L15-L19) +- [Index.svelte (QRCode):22-45](file://frontend/antd/qr-code/Index.svelte#L22-L45) + +## Conclusion + +- Both Popover and QRCode follow a consistent three-layer encapsulation pattern, offering good extensibility and controllability +- Popover focuses on interaction and layout; QRCode focuses on data encoding and visual presentation +- It is recommended to combine the strategies and notes in this document when optimizing for complex layouts and mobile scenarios + +## Appendix + +- Demo Entry References + - Popover demo: [README-zh_CN.md (Popover docs)](file://docs/components/antd/popover/README-zh_CN.md#L7) + - QRCode demo: [README-zh_CN.md (QRCode docs)](file://docs/components/antd/qr_code/README-zh_CN.md#L7) diff --git a/.wiki/en/Ant Design Components/Data Display Components/Segmented and Statistic.md b/.wiki/en/Ant Design Components/Data Display Components/Segmented and Statistic.md new file mode 100644 index 00000000..6ff7a19b --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Segmented and Statistic.md @@ -0,0 +1,312 @@ +# Segmented and Statistic + + +**Files Referenced in This Document** +- [frontend/antd/segmented/segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js](file://backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js) +- [backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js](file://backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js) +- [frontend/antd/statistic/statistic.tsx](file://frontend/antd/statistic/statistic.tsx) +- [backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js](file://backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx](file://frontend/antd/statistic/countdown/statistic.countdown.tsx) +- [frontend/antd/statistic/timer/statistic.timer.tsx](file://frontend/antd/statistic/timer/statistic.timer.tsx) +- [docs/components/antd/segmented/README-zh_CN.md](file://docs/components/antd/segmented/README-zh_CN.md) +- [docs/components/antd/statistic/README-zh_CN.md](file://docs/components/antd/statistic/README-zh_CN.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on two frontend components: **Segmented** and **Statistic**. The former is used for selecting among multiple mutually exclusive options; the latter is used for displaying numeric values, titles, prefixes/suffixes, and supports countdown and timer functionality. This document systematically explains the design and usage of these two components from the perspectives of architecture, data flow, processing logic, integration points, error handling, and performance characteristics, with visual diagrams for better understanding. + +## Project Structure + +- Components are composed of a frontend adaptation layer (React wrapper + Svelte pre-processing) and a backend template rendering layer (Svelte runtime bridge). +- Segmented injects option collections via context, supporting combined use with "option" groups; the Statistic component supports flexible extension through slots and function-based formatters. +- The documentation side provides basic demo entry points for quick onboarding. + +```mermaid +graph TB +subgraph "Frontend Adaptation Layer" +S_Tsx["segmented.tsx
React wrapper + render options"] +ST_Tsx["statistic.tsx
React wrapper + slots/formatter"] +CD_Tsx["countdown.tsx
React wrapper + countdown"] +TM_Tsx["timer.tsx
React wrapper + timer"] +end +subgraph "Backend Template Rendering Layer" +S_JS["segmented-Ds7q4Ezu.js
Svelte runtime bridge"] +SO_JS["segmented.option-CS0TqVwO.js
Option item implementation"] +ST_JS["statistic-DvxTRiyV.js
Svelte runtime bridge"] +end +subgraph "External Dependencies" +Antd["Ant Design Component Library"] +end +S_Tsx --> S_JS +ST_Tsx --> ST_JS +CD_Tsx --> Antd +TM_Tsx --> Antd +SO_JS --> S_JS +``` + +**Diagram Source** + +- [frontend/antd/segmented/segmented.tsx:1-47](file://frontend/antd/segmented/segmented.tsx#L1-L47) +- [backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js:695-719](file://backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js#L695-L719) +- [backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js:441-447](file://backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js#L441-L447) +- [frontend/antd/statistic/statistic.tsx:1-34](file://frontend/antd/statistic/statistic.tsx#L1-L34) +- [backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js:685-715](file://backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js#L685-L715) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:1-27](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L1-L27) +- [frontend/antd/statistic/timer/statistic.timer.tsx:1-29](file://frontend/antd/statistic/timer/statistic.timer.tsx#L1-L29) + +**Section Source** + +- [docs/components/antd/segmented/README-zh_CN.md:1-8](file://docs/components/antd/segmented/README-zh_CN.md#L1-L8) +- [docs/components/antd/statistic/README-zh_CN.md:1-9](file://docs/components/antd/statistic/README-zh_CN.md#L1-L9) + +## Core Components + +- Segmented + - Supports passing an options array via props or injecting option collections via "option" slots. + - Provides a combination of the onValueChange callback and the native onChange event. + - Supports disabled state and block-level display (achieved by hiding children). +- Statistic + - Supports combined use of title, prefix, suffix, and formatter as both slots and props. + - Supports custom formatter functions and ReactSlot slot rendering. +- Statistic Sub-components + - Countdown: accepts timestamps or millisecond values and automatically converts them to milliseconds. + - Timer: a timer display based on the current time. + +**Section Source** + +- [frontend/antd/segmented/segmented.tsx:10-44](file://frontend/antd/segmented/segmented.tsx#L10-L44) +- [frontend/antd/statistic/statistic.tsx:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:6-24](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L6-L24) +- [frontend/antd/statistic/timer/statistic.timer.tsx:10-26](file://frontend/antd/statistic/timer/statistic.timer.tsx#L10-L26) + +## Architecture Overview + +The following diagram shows the complete call chain from the Svelte template to the React wrapper and then to the Ant Design component, and how slots and context participate in rendering. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Template" +participant Bridge as "Svelte Runtime Bridge" +participant ReactWrap as "React Wrapper Layer" +participant Antd as "Ant Design Component" +Svelte->>Bridge : "Generate nodes/slot mappings" +Bridge->>ReactWrap : "Create React elements and inject context/slots" +ReactWrap->>Antd : "Pass props/slots/event callbacks" +Antd-->>ReactWrap : "Render result" +ReactWrap-->>Bridge : "Bridge DOM/Portal" +Bridge-->>Svelte : "Complete mount/update" +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js:695-719](file://backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js#L695-L719) +- [backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js:685-715](file://backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js#L685-L715) +- [backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js:441-447](file://backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js#L441-L447) + +## Detailed Component Analysis + +### Segmented Analysis + +- Option Configuration and "Option Group" Combination + - Injects "options/default" slot groups via context; options takes priority, falling back to default. + - Uses useMemo to cache the option list and avoid unnecessary re-renders. +- Controlled and Uncontrolled Modes + - Externally, value/onChange can be passed directly for controlled mode; onValueChange is also provided as an internal value change callback. +- Disabled State and Block-Level Display + - Structural consistency is maintained by hiding children, without affecting the outer layout. +- Dynamic Updates and Style Customization + - Option items achieve dynamic slot and context injection via the bridge runtime, with style and event forwarding support. + +```mermaid +flowchart TD +Start(["Enter Segmented render"]) --> CheckSlots["Check slots: options vs default"] +CheckSlots --> HasOptions{"Has options?"} +HasOptions --> |Yes| UseOptions["Use options option set"] +HasOptions --> |No| UseDefault["Use default option set"] +UseOptions --> Resolve["Render as Antd options array"] +UseDefault --> Resolve +Resolve --> Wrap["Wrap as Antd Segmented and bind onChange/onValueChange"] +Wrap --> End(["Rendering complete"]) +``` + +**Diagram Source** + +- [frontend/antd/segmented/segmented.tsx:15-44](file://frontend/antd/segmented/segmented.tsx#L15-L44) +- [backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js:695-719](file://backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js#L695-L719) + +**Section Source** + +- [frontend/antd/segmented/segmented.tsx:10-44](file://frontend/antd/segmented/segmented.tsx#L10-L44) +- [backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js:695-719](file://backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js#L695-L719) +- [backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js:441-447](file://backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js#L441-L447) + +### Statistic Analysis + +- Value Display, Unit Settings, and Formatting + - Supports dual-channel (slot + prop) for title/prefix/suffix; formatter supports both function and slot forms. +- Countdown and Timer + - Both countdown and timer convert value to milliseconds to ensure consistency with what the Antd component expects. +- Combining Slots and Function-Based Formatters + - When slots.formatter is present, the slot render takes priority; otherwise it falls back to the function-based formatter. + +```mermaid +sequenceDiagram +participant User as "User Code" +participant Stat as "Statistic Wrapper Layer" +participant Slots as "Slot System" +participant Antd as "Antd Statistic" +User->>Stat : "Pass value/title/prefix/suffix/formatter" +Stat->>Slots : "Detect slots.formatter/title/prefix/suffix" +alt slots.formatter exists +Slots-->>Stat : "Return slot render function" +else slots.formatter does not exist +Stat-->>Stat : "Use formatter function" +end +Stat->>Antd : "Pass props and render functions" +Antd-->>User : "Render statistic value" +``` + +**Diagram Source** + +- [frontend/antd/statistic/statistic.tsx:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) +- [backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js:685-715](file://backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js#L685-L715) + +**Section Source** + +- [frontend/antd/statistic/statistic.tsx:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:6-24](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L6-L24) +- [frontend/antd/statistic/timer/statistic.timer.tsx:10-26](file://frontend/antd/statistic/timer/statistic.timer.tsx#L10-L26) + +### Component Class Relationship Diagram (Code Level) + +```mermaid +classDiagram +class SegmentedWrapper { ++props : GetProps ++slots : any ++onValueChange(value) ++onChange(v) +} +class StatisticWrapper { ++props : GetProps ++slots : any ++formatter() +} +class StatisticCountdownWrapper { ++props : GetProps ++slots : any +} +class StatisticTimerWrapper { ++props : GetProps ++slots : any +} +SegmentedWrapper --> "uses" ASegmented : "Antd" +StatisticWrapper --> "uses" AStatistic : "Antd" +StatisticCountdownWrapper --> "uses" AStatistic.Countdown : "Antd" +StatisticTimerWrapper --> "uses" AStatistic.Timer : "Antd" +``` + +**Diagram Source** + +- [frontend/antd/segmented/segmented.tsx:10-44](file://frontend/antd/segmented/segmented.tsx#L10-L44) +- [frontend/antd/statistic/statistic.tsx:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:6-24](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L6-L24) +- [frontend/antd/statistic/timer/statistic.timer.tsx:10-26](file://frontend/antd/statistic/timer/statistic.timer.tsx#L10-L26) + +## Dependency Analysis + +- Inter-Component Coupling + - Segmented and option items establish a loosely-coupled relationship via context; option items do not directly depend on the controller but are uniformly scheduled by the bridge layer. + - The Statistic component and its sub-components (countdown/timer) share the same bridge and slot mechanism. +- External Dependencies + - All components depend on the Ant Design component library to ensure consistent UI behavior and styling. +- Potential Circular Dependencies + - The current structure uses a unidirectional dependency of "bridge layer → React wrapper layer → Antd"; no signs of circular dependencies have been observed. + +```mermaid +graph LR +Segmented["Segmented Wrapper Layer"] --> BridgeS["Segmented Bridge Runtime"] +OptionItem["Option Item Implementation"] --> BridgeS +Statistic["Statistic Wrapper Layer"] --> BridgeSt["Statistic Bridge Runtime"] +Countdown["Countdown Wrapper Layer"] --> AntdCD["Antd Countdown"] +Timer["Timer Wrapper Layer"] --> AntdTM["Antd Timer"] +BridgeS --> AntdSeg["Antd Segmented"] +BridgeSt --> AntdSt["Antd Statistic"] +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js:695-719](file://backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js#L695-L719) +- [backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js:441-447](file://backend/modelscope_studio/components/antd/segmented/option/templates/component/segmented.option-CS0TqVwO.js#L441-L447) +- [backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js:685-715](file://backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js#L685-L715) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:15-21](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L15-L21) +- [frontend/antd/statistic/timer/statistic.timer.tsx:17-23](file://frontend/antd/statistic/timer/statistic.timer.tsx#L17-L23) + +**Section Source** + +- [backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js:695-719](file://backend/modelscope_studio/components/antd/segmented/templates/component/segmented-Ds7q4Ezu.js#L695-L719) +- [backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js:685-715](file://backend/modelscope_studio/components/antd/statistic/templates/component/statistic-DvxTRiyV.js#L685-L715) + +## Performance Considerations + +- Rendering Optimization + - Segmented uses useMemo to cache the options array, reducing unnecessary re-renders. + - The Statistic component uses slot render functions when slots.formatter is present, avoiding extra prop passing overhead. +- DOM Display Strategy + - By setting children to invisible (display: none) and inserting the actual nodes in the bridge layer using "contents", layout jitter risk is reduced. +- Time Parameter Conversion + - Countdown and Timer uniformly convert input values to milliseconds, avoiding performance fluctuations caused by different units from external callers. + +**Section Source** + +- [frontend/antd/segmented/segmented.tsx:30-38](file://frontend/antd/segmented/segmented.tsx#L30-L38) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:17-17](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L17-L17) +- [frontend/antd/statistic/timer/statistic.timer.tsx:19-19](file://frontend/antd/statistic/timer/statistic.timer.tsx#L19-L19) + +## Troubleshooting Guide + +- Options not displayed or not taking effect + - Confirm that the "option group" slots (options/default) are correctly used and that slot elements are properly mounted. + - Check that both onValueChange and onChange are bound to ensure the complete value change event chain. +- Slot content not rendered + - Confirm that slots.formatter/title/prefix/suffix are correctly passed in and that the bridge layer has enabled the corresponding slot rendering. +- Countdown/Timer value anomalies + - Confirm whether the input value unit is in seconds (internally converted to milliseconds) to avoid multiplying by 1000 twice. +- Style or event forwarding issues + - Check the bridge layer context merge logic to confirm that styles and events are not being dropped during the bridge phase. + +**Section Source** + +- [frontend/antd/segmented/segmented.tsx:26-29](file://frontend/antd/segmented/segmented.tsx#L26-L29) +- [frontend/antd/statistic/statistic.tsx:18-28](file://frontend/antd/statistic/statistic.tsx#L18-L28) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:17-20](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L17-L20) +- [frontend/antd/statistic/timer/statistic.timer.tsx:19-22](file://frontend/antd/statistic/timer/statistic.timer.tsx#L19-L22) + +## Conclusion + +The Segmented and Statistic components achieve high consistency with Ant Design components and flexible extensibility through a unified bridge and slot mechanism. Segmented emphasizes dynamic option injection and event callback combinations; Statistic provides powerful flexibility in formatting and slot rendering. With the architecture diagrams and flowcharts in this document, developers can more efficiently apply these two components in form and dashboard scenarios. + +## Appendix + +- Demo Entry Points + - Basic demos for Segmented and Statistic can be found in the documentation, making it easy to quickly verify component behavior. + +**Section Source** + +- [docs/components/antd/segmented/README-zh_CN.md:5-8](file://docs/components/antd/segmented/README-zh_CN.md#L5-L8) +- [docs/components/antd/statistic/README-zh_CN.md:7-9](file://docs/components/antd/statistic/README-zh_CN.md#L7-L9) diff --git a/.wiki/en/Ant Design Components/Data Display Components/Table and Tabs.md b/.wiki/en/Ant Design Components/Data Display Components/Table and Tabs.md new file mode 100644 index 00000000..9fb01c29 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Table and Tabs.md @@ -0,0 +1,345 @@ +# Table and Tabs + + +**Files Referenced in This Document** +- [table.tsx](file://frontend/antd/table/table.tsx) +- [context.ts](file://frontend/antd/table/context.ts) +- [table.column.tsx](file://frontend/antd/table/column/table.column.tsx) +- [table.column-group.tsx](file://frontend/antd/table/column-group/table.column-group.tsx) +- [table.expandable.tsx](file://frontend/antd/table/expandable/table.expandable.tsx) +- [table.row-selection.tsx](file://frontend/antd/table/row-selection/table.row-selection.tsx) +- [tabs.tsx](file://frontend/antd/tabs/tabs.tsx) +- [tabs.context.ts](file://frontend/antd/tabs/context.ts) +- [tabs.item.tsx](file://frontend/antd/tabs/item/tabs.item.tsx) + + +## Table of Contents + +- [Table and Tabs](#table-and-tabs) + - [Table of Contents](#table-of-contents) + - [Introduction](#introduction) + - [Project Structure](#project-structure) + - [Core Components](#core-components) + - [Architecture Overview](#architecture-overview) + - [Detailed Component Analysis](#detailed-component-analysis) + - [Table Component](#table-component) + - [Tabs Component](#tabs-component) + - [Navigation Strategies in Complex Layouts](#navigation-strategies-in-complex-layouts) + - [Dependency Analysis](#dependency-analysis) + - [Performance Considerations](#performance-considerations) + - [Troubleshooting Guide](#troubleshooting-guide) + - [Conclusion](#conclusion) + - [Appendix](#appendix) + +## Introduction + +This document provides a systematic review of the **Table** and **Tabs** component systems, covering their advanced capabilities and engineering implementation. Key topics include: Table's column definitions (column), column groups (column_group), expandable rows (expandable), and row selection (row_selection); Tabs' tab items, position control, disabled state, and dynamic addition/removal. It also provides practical recommendations for large dataset handling, virtual scrolling, sorting, filtering, and pagination integration; as well as extension ideas for Tabs' lazy content loading, tab icons, close buttons, and drag-to-reorder. Finally, it covers navigation strategies for responsive design and complex layouts. + +## Project Structure + +Both components use a layered design of "container component + item handler": + +- The container component handles prop forwarding, slot rendering, context merging, and function wrapping; +- Item handlers (such as TableColumn, TabsItem, etc.) are responsible for injecting child elements into the container and enhancing configuration where necessary (such as menus, dropdowns, icons, etc.). + +```mermaid +graph TB +subgraph "Table Component" +T["Table Container
frontend/antd/table/table.tsx"] +CtxT["Table Context
frontend/antd/table/context.ts"] +Col["Column Handler
frontend/antd/table/column/table.column.tsx"] +ColG["Column Group Handler
frontend/antd/table/column-group/table.column-group.tsx"] +Exp["Expandable Handler
frontend/antd/table/expandable/table.expandable.tsx"] +RSel["Row Selection Handler
frontend/antd/table/row-selection/table.row-selection.tsx"] +end +subgraph "Tabs Component" +Tabs["Tabs Container
frontend/antd/tabs/tabs.tsx"] +CtxTabs["Tabs Context
frontend/antd/tabs/context.ts"] +TabsItem["Tab Item Handler
frontend/antd/tabs/item/tabs.item.tsx"] +end +T --> CtxT +T --> Col +T --> ColG +T --> Exp +T --> RSel +Tabs --> CtxTabs +Tabs --> TabsItem +``` + +**Diagram Source** + +- [table.tsx:28-276](file://frontend/antd/table/table.tsx#L28-L276) +- [context.ts](file://frontend/antd/table/context.ts) +- [table.column.tsx:20-97](file://frontend/antd/table/column/table.column.tsx#L20-L97) +- [table.column-group.tsx:7-19](file://frontend/antd/table/column-group/table.column-group.tsx#L7-L19) +- [table.expandable.tsx:7-11](file://frontend/antd/table/expandable/table.expandable.tsx#L7-L11) +- [table.row-selection.tsx:13-35](file://frontend/antd/table/row-selection/table.row-selection.tsx#L13-L35) +- [tabs.tsx:12-118](file://frontend/antd/tabs/tabs.tsx#L12-L118) +- [tabs.context.ts](file://frontend/antd/tabs/context.ts) +- [tabs.item.tsx:7-11](file://frontend/antd/tabs/item/tabs.item.tsx#L7-L11) + +**Section Source** + +- [table.tsx:28-276](file://frontend/antd/table/table.tsx#L28-L276) +- [tabs.tsx:12-118](file://frontend/antd/tabs/tabs.tsx#L12-L118) + +## Core Components + +- Table Container: handles unified processing and slot rendering for columns, rowSelection, expandable, sticky, showSorterTooltip, pagination, loading, footer, title, and other props. +- Column Handler: enhances column configuration with support for filter dropdown menus, custom popup rendering, menu expand icons, and overflow indicators. +- Column Group Handler: groups a set of columns as a logical unit, facilitating header merging and style control. +- Expandable Handler: injects expandable configuration into the table. +- Row Selection Handler: injects custom selection items (e.g., "Select All", "Invert Selection") into rowSelection. +- Tabs Container: handles unified processing and slot rendering for items, indicator, renderTabBar, more, tabBarExtraContent, addIcon, removeIcon, and other props. +- Tab Item Handler: injects individual tab items into Tabs' items. + +**Section Source** + +- [table.tsx:28-276](file://frontend/antd/table/table.tsx#L28-L276) +- [table.column.tsx:20-97](file://frontend/antd/table/column/table.column.tsx#L20-L97) +- [table.column-group.tsx:7-19](file://frontend/antd/table/column-group/table.column-group.tsx#L7-L19) +- [table.expandable.tsx:7-11](file://frontend/antd/table/expandable/table.expandable.tsx#L7-L11) +- [table.row-selection.tsx:13-35](file://frontend/antd/table/row-selection/table.row-selection.tsx#L13-L35) +- [tabs.tsx:12-118](file://frontend/antd/tabs/tabs.tsx#L12-L118) +- [tabs.item.tsx:7-11](file://frontend/antd/tabs/item/tabs.item.tsx#L7-L11) + +## Architecture Overview + +The following diagram shows the dependency relationships and division of responsibilities between the Table and Tabs containers and their item handlers. + +```mermaid +classDiagram +class Table { ++props : columns,rowSelection,expandable,sticky,showSorterTooltip,pagination,loading,footer,title ++slots : title,footer,loading.tip,loading.indicator,pagination.showQuickJumper.goButton,pagination.itemRender,showSorterTooltip.title,summary +} +class TableColumn { ++enhancement : filterDropdownProps.menu +} +class TableColumnGroup +class TableExpandable +class TableRowSelection +class Tabs { ++props : items,indicator,more,renderTabBar,tabBarExtraContent,addIcon,removeIcon ++slots : renderTabBar,tabBarExtraContent.left,right,more.icon +} +class TabsItem +Table --> TableColumn : "uses" +Table --> TableColumnGroup : "uses" +Table --> TableExpandable : "uses" +Table --> TableRowSelection : "uses" +Tabs --> TabsItem : "uses" +``` + +**Diagram Source** + +- [table.tsx:28-276](file://frontend/antd/table/table.tsx#L28-L276) +- [table.column.tsx:20-97](file://frontend/antd/table/column/table.column.tsx#L20-L97) +- [table.column-group.tsx:7-19](file://frontend/antd/table/column-group/table.column-group.tsx#L7-L19) +- [table.expandable.tsx:7-11](file://frontend/antd/table/expandable/table.expandable.tsx#L7-L11) +- [table.row-selection.tsx:13-35](file://frontend/antd/table/row-selection/table.row-selection.tsx#L13-L35) +- [tabs.tsx:12-118](file://frontend/antd/tabs/tabs.tsx#L12-L118) +- [tabs.item.tsx:7-11](file://frontend/antd/tabs/item/tabs.item.tsx#L7-L11) + +## Detailed Component Analysis + +### Table Component + +- Column Definition (column) + - Supports directly passing columns or injecting via TableColumn; + - Recognizes and converts special placeholders (such as EXPAND_COLUMN, SELECTION_COLUMN); + - Enhances filterDropdownProps with support for menu items, dropdown rendering, popup rendering, menu expand icons, and overflow indicators. +- Column Group (column_group) + - Groups a set of columns as a logical unit for header merging and style control; + - Only the default slot is allowed. +- Expandable Rows (expandable) + - Injects expandable configuration via TableExpandable; + - Supports custom rendering of expanded content. +- Row Selection (row_selection) + - Injects rowSelection via TableRowSelection; + - Supports custom selection items via selections (e.g., "Select All", "Invert Selection"). +- Sorting, Filtering, and Pagination + - Supports slot-based title for showSorterTooltip; + - Supports slot-based jump button and page item rendering for pagination; + - Supports tip and indicator slots for loading; + - Supports container getter function for sticky; + - Supports slot-based rendering for footer and summary. +- Large Datasets and Virtual Scrolling + - It is recommended to combine external virtual scrolling solutions (e.g., fixed height + scrollable container) to reduce DOM node count; + - Use onScroll with pagination/infinite scrolling to avoid rendering large numbers of rows at once. +- Responsive Design + - Use sticky and column width settings to prioritize key columns on small screens; + - Use the column's responsive configuration or a custom breakpoint strategy. + +```mermaid +sequenceDiagram +participant U as "User" +participant T as "Table Container" +participant C as "Column/Expandable/RowSelection Handler" +participant R as "Ant Design Table" +U->>T : Provide columns/rowSelection/expandable/pagination props +T->>C : Inject child items and enhance configuration +C-->>T : Return enhanced configuration +T->>R : Forward props and render slots +R-->>U : Render table UI +``` + +**Diagram Source** + +- [table.tsx:66-271](file://frontend/antd/table/table.tsx#L66-L271) +- [table.column.tsx:28-93](file://frontend/antd/table/column/table.column.tsx#L28-L93) +- [table.expandable.tsx:9-10](file://frontend/antd/table/expandable/table.expandable.tsx#L9-L10) +- [table.row-selection.tsx:21-32](file://frontend/antd/table/row-selection/table.row-selection.tsx#L21-L32) + +**Section Source** + +- [table.tsx:28-276](file://frontend/antd/table/table.tsx#L28-L276) +- [table.column.tsx:20-97](file://frontend/antd/table/column/table.column.tsx#L20-L97) +- [table.column-group.tsx:7-19](file://frontend/antd/table/column-group/table.column-group.tsx#L7-L19) +- [table.expandable.tsx:7-11](file://frontend/antd/table/expandable/table.expandable.tsx#L7-L11) +- [table.row-selection.tsx:13-35](file://frontend/antd/table/row-selection/table.row-selection.tsx#L13-L35) + +### Tabs Component + +- Tab Items + - Inject individual tab items via TabsItem; + - Supports basic props such as disabled, closable, and closeIcon. +- Position Control and Dynamic Add/Remove + - Control tab addition/removal via the dynamic items array; + - indicator controls the bottom bar style with size function support; + - addIcon/removeIcon support slot-based icons. +- Lazy Content Loading + - It is recommended to render only the active panel's content on activation, avoiding rendering all panels at once; + - Load data and components on demand in the onChange event. +- Tab Icons and Close Button + - Customize icons via addIcon/removeIcon slots; + - closable and closeIcon control whether tabs can be closed and the close icon appearance. +- Drag-to-Reorder + - Can be implemented using an external drag library combined with onChange; + - Be careful to maintain consistency between items order and activeKey. +- More Menu and Extra Content + - more.icon supports a slot-based icon; + - tabBarExtraContent supports slot-based content on both the left and right sides. + +```mermaid +sequenceDiagram +participant U as "User" +participant Tabs as "Tabs Container" +participant Item as "TabsItem Handler" +participant AD as "Ant Design Tabs" +U->>Tabs : Provide items/addIcon/removeIcon/more/tabBarExtraContent +Tabs->>Item : Inject tab items and enhance configuration +Item-->>Tabs : Return enhanced tab items +Tabs->>AD : Forward props and render slots +AD-->>U : Render tabs UI +``` + +**Diagram Source** + +- [tabs.tsx:26-115](file://frontend/antd/tabs/tabs.tsx#L26-L115) +- [tabs.item.tsx:9-10](file://frontend/antd/tabs/item/tabs.item.tsx#L9-L10) + +**Section Source** + +- [tabs.tsx:12-118](file://frontend/antd/tabs/tabs.tsx#L12-L118) +- [tabs.item.tsx:7-11](file://frontend/antd/tabs/item/tabs.item.tsx#L7-L11) + +### Navigation Strategies in Complex Layouts + +- Responsive Navigation + - On narrow screens, enable the Tabs more menu to move less-used tabs into a dropdown; + - Use sticky or fixed headers to keep navigation always visible. +- Nested Usage + - When nesting child tabs or subtables inside tabs, be mindful of hierarchy and interaction conflicts; + - Use independent contexts and namespaces to avoid event bubbling and state pollution. +- Navigation Consistency + - Use onChange and activeKey uniformly to manage the current active state; + - For asynchronously loaded data, display a skeleton screen first, then switch to real content. + +## Dependency Analysis + +- Table Side + - The Table container depends on context providers (Column, Expandable, RowSelection) to collect child items; + - TableColumn enhances filterDropdownProps and reuses the menu context; + - TableRowSelection injects selections. +- Tabs Side + - The Tabs container relies on the Items context to collect tab items; + - TabsItem injects individual tab items. + +```mermaid +graph LR +subgraph "Table Dependencies" +CTX["Table Context"] +COL["Column Handler"] +COLG["Column Group Handler"] +EXP["Expandable Handler"] +SEL["Row Selection Handler"] +TBL["Table Container"] +TBL --> CTX +TBL --> COL +TBL --> COLG +TBL --> EXP +TBL --> SEL +end +subgraph "Tabs Dependencies" +CTXS["Tabs Context"] +ITEM["Tab Item Handler"] +TABS["Tabs Container"] +TABS --> CTXS +TABS --> ITEM +end +``` + +**Diagram Source** + +- [context.ts](file://frontend/antd/table/context.ts) +- [table.tsx:41-275](file://frontend/antd/table/table.tsx#L41-L275) +- [tabs.context.ts](file://frontend/antd/tabs/context.ts) +- [tabs.tsx:24-117](file://frontend/antd/tabs/tabs.tsx#L24-L117) + +**Section Source** + +- [table.tsx:41-275](file://frontend/antd/table/table.tsx#L41-L275) +- [tabs.tsx:24-117](file://frontend/antd/tabs/tabs.tsx#L24-L117) + +## Performance Considerations + +- Table + - Large datasets: use fixed height + virtual scrolling (e.g., external library) to reduce DOM node count; + - Pagination/infinite scrolling: combine with backend pagination to avoid rendering everything at once; + - Column rendering: only render necessary columns, hide non-critical ones; + - Event binding: use throttle/debounce for onRow/onHeaderRow. +- Tabs + - Lazy content loading: only render on activation; + - Dynamic add/remove: batch update items to avoid frequent re-renders; + - Icons and slots: use lightweight components and avoid complex computations. + +## Troubleshooting Guide + +- Slots not taking effect + - Confirm that slot key names match container declarations (such as pagination.showQuickJumper.goButton, more.icon, etc.); + - Check that slots are correctly wrapped inside child items. +- Props not taking effect + - Confirm that function-type props are wrapped with useFunction; + - Check that object-type props (such as sticky, showSorterTooltip, pagination) are correctly merged. +- Style anomalies + - Check whether getPopupContainer/getContainer returns the correct mount node; + - Confirm that the ReactSlot render target container inside slots exists and is visible. + +**Section Source** + +- [table.tsx:76-108](file://frontend/antd/table/table.tsx#L76-L108) +- [tabs.tsx:36-39](file://frontend/antd/tabs/tabs.tsx#L36-L39) + +## Conclusion + +This document systematically reviews the capability boundaries and extension points of the Table and Tabs components from an architectural and implementation perspective. Through the collaboration of container components and item handlers, prop forwarding, slot rendering, and configuration enhancement are achieved. Combined with large dataset handling, virtual scrolling, lazy loading, and responsive strategies, they can provide a stable and maintainable navigation experience in complex layouts. + +## Appendix + +- Key Implementation Points + - Table: slotting and function wrapping for columns, rowSelection, expandable, sticky, showSorterTooltip, pagination, loading, footer, and title; + - Tabs: slotting and function wrapping for items, indicator, renderTabBar, more, tabBarExtraContent, addIcon, and removeIcon. +- Extension Recommendations + - Table: introduce virtual scrolling with pagination integration; customize column groups and expandable content based on business scenarios; + - Tabs: combine with routing and state management to implement dynamic add/remove and persistence; support drag-to-reorder and the more menu. diff --git a/.wiki/en/Ant Design Components/Data Display Components/Tag and Timeline.md b/.wiki/en/Ant Design Components/Data Display Components/Tag and Timeline.md new file mode 100644 index 00000000..1e987675 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Tag and Timeline.md @@ -0,0 +1,438 @@ +# Tag and Timeline + + +**Files Referenced in This Document** +- [frontend/antd/tag/tag.tsx](file://frontend/antd/tag/tag.tsx) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx) +- [frontend/antd/tag/checkable-tag/Index.svelte](file://frontend/antd/tag/checkable-tag/Index.svelte) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx) +- [frontend/antd/tag/checkable-tag-group/Index.svelte](file://frontend/antd/tag/checkable-tag-group/Index.svelte) +- [frontend/antd/tag/checkable-tag-group/context.ts](file://frontend/antd/tag/checkable-tag-group/context.ts) +- [frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx](file://frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx) +- [frontend/antd/tag/checkable-tag-group/option/Index.svelte](file://frontend/antd/tag/checkable-tag-group/option/Index.svelte) +- [frontend/antd/timeline/timeline.tsx](file://frontend/antd/timeline/timeline.tsx) +- [frontend/antd/timeline/item/Index.svelte](file://frontend/antd/timeline/item/Index.svelte) +- [frontend/antd/timeline/context.ts](file://frontend/antd/timeline/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/hooks/useTargets.ts](file://frontend/utils/hooks/useTargets.ts) +- [docs/components/antd/tag/demos/checkable_tag.py](file://docs/components/antd/tag/demos/checkable_tag.py) +- [docs/components/antd/timeline/demos/basic.py](file://docs/components/antd/timeline/demos/basic.py) + + +## Update Summary + +**Changes Made** + +- Added the CheckableTagGroup component system, including the CheckableTagGroup main component and CheckableTagGroupOption child component +- Updated Timeline component documentation to reflect the simplified implementation of the Timeline.Item component +- Enhanced batch operation capabilities and dynamic option management for tag groups +- Improved context management and option handling mechanisms for CheckableTagGroup + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the **Tag** and **Timeline** components, systematically explaining their design philosophy, data flow, interaction behavior, and extensibility. Key topics include: + +- Tag: interaction states for regular and checkable tags, color configuration, dynamic tag management, click events, delete functionality, and batch operation recommendations. +- **New**: CheckableTagGroup component system supporting batch tag selection, dynamic option management, and grouped operations. +- Timeline: time nodes (Items), direction control, node customization, and style customization; as well as implementation paths for reversed display, custom icons, and line style adjustments. + +## Project Structure + +- The component layer uses a pattern of "frontend Svelte wrapper + backend Python component bridge"; the frontend adapts Ant Design's React components into Svelte components via sveltify, and introduces the Items context and slot rendering mechanism where necessary. +- The utility layer provides general capabilities such as items context, slot rendering, and target element resolution, supporting dynamic item management for complex container components (such as Timeline). + +```mermaid +graph TB +subgraph "Tag Component" +TAG["Tag
frontend/antd/tag/tag.tsx"] +CTAG["CheckableTag
frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx"] +CTAG_IDX["CheckableTag Wrapper
frontend/antd/tag/checkable-tag/Index.svelte"] +CTAG_GROUP["CheckableTagGroup
frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx"] +CTAG_GROUP_IDX["CheckableTagGroup Wrapper
frontend/antd/tag/checkable-tag-group/Index.svelte"] +CTAG_OPTION["CheckableTagGroupOption
frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx"] +CTAG_OPTION_IDX["CheckableTagGroupOption Wrapper
frontend/antd/tag/checkable-tag-group/option/Index.svelte"] +end +subgraph "Timeline Component" +TL["Timeline
frontend/antd/timeline/timeline.tsx"] +TL_ITEM["Timeline.Item
frontend/antd/timeline/item/Index.svelte"] +TL_CTX["Timeline Context
frontend/antd/timeline/context.ts"] +end +subgraph "Utility Library" +CREATE_ITEMS["createItemsContext
frontend/utils/createItemsContext.tsx"] +RENDER_ITEMS["renderItems
frontend/utils/renderItems.tsx"] +USE_TARGETS["useTargets
frontend/utils/hooks/useTargets.ts"] +end +TAG --> USE_TARGETS +CTAG --> USE_TARGETS +CTAG_GROUP --> CTAG_GROUP_IDX +CTAG_GROUP_IDX --> CTAG_GROUP +CTAG_OPTION --> CTAG_OPTION_IDX +CTAG_OPTION_IDX --> CTAG_OPTION +TL --> TL_CTX +TL_CTX --> CREATE_ITEMS +TL --> RENDER_ITEMS +TL_ITEM --> TL_CTX +``` + +**Diagram Source** + +- [frontend/antd/tag/tag.tsx:1-35](file://frontend/antd/tag/tag.tsx#L1-L35) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:1-35](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L1-L35) +- [frontend/antd/tag/checkable-tag/Index.svelte:1-77](file://frontend/antd/tag/checkable-tag/Index.svelte#L1-L77) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:1-51](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L1-L51) +- [frontend/antd/tag/checkable-tag-group/Index.svelte:1-79](file://frontend/antd/tag/checkable-tag-group/Index.svelte#L1-L79) +- [frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx:1-14](file://frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx#L1-L14) +- [frontend/antd/tag/checkable-tag-group/option/Index.svelte:1-74](file://frontend/antd/tag/checkable-tag-group/option/Index.svelte#L1-L74) +- [frontend/antd/timeline/timeline.tsx:1-50](file://frontend/antd/timeline/timeline.tsx#L1-L50) +- [frontend/antd/timeline/item/Index.svelte:1-65](file://frontend/antd/timeline/item/Index.svelte#L1-L65) +- [frontend/antd/timeline/context.ts:1-7](file://frontend/antd/timeline/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/hooks/useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) + +**Section Source** + +- [frontend/antd/tag/tag.tsx:1-35](file://frontend/antd/tag/tag.tsx#L1-L35) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:1-35](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L1-L35) +- [frontend/antd/tag/checkable-tag/Index.svelte:1-77](file://frontend/antd/tag/checkable-tag/Index.svelte#L1-L77) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:1-51](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L1-L51) +- [frontend/antd/tag/checkable-tag-group/Index.svelte:1-79](file://frontend/antd/tag/checkable-tag-group/Index.svelte#L1-L79) +- [frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx:1-14](file://frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx#L1-L14) +- [frontend/antd/tag/checkable-tag-group/option/Index.svelte:1-74](file://frontend/antd/tag/checkable-tag-group/option/Index.svelte#L1-L74) +- [frontend/antd/timeline/timeline.tsx:1-50](file://frontend/antd/timeline/timeline.tsx#L1-L50) +- [frontend/antd/timeline/item/Index.svelte:1-65](file://frontend/antd/timeline/item/Index.svelte#L1-L65) +- [frontend/antd/timeline/context.ts:1-7](file://frontend/antd/timeline/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/hooks/useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) + +## Core Components + +- Tag + - Regular tag: supports text and icons, closeIcon slot, and value field fallback rendering. + - CheckableTag: two-way binding for checked state, supports label text fallback, icon slot, and change callback. + - **New**: CheckableTagGroup: supports batch tag selection, dynamic option management, and grouped operations. +- Timeline + - Supports dynamic items injection and default slot fallback; supports pending/pendingDot slots; internally collects child items via the Items context and renders them. + +**Section Source** + +- [frontend/antd/tag/tag.tsx:7-32](file://frontend/antd/tag/tag.tsx#L7-L32) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:7-32](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L7-L32) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:8-48](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L8-L48) +- [frontend/antd/timeline/timeline.tsx:9-47](file://frontend/antd/timeline/timeline.tsx#L9-L47) + +## Architecture Overview + +Both Tag and Timeline bridge Ant Design's React components into the Svelte ecosystem via sveltify, while leveraging slots and context to achieve flexible dynamic rendering and prop forwarding. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Svelte as "Svelte Wrapper Layer" +participant Utils as "Utility Library" +participant Antd as "Ant Design Component" +Dev->>Svelte : Pass props and slots +Svelte->>Utils : Parse slots/target elements/context +Utils-->>Svelte : Return processed props and render functions +Svelte->>Antd : Render final component tree +Antd-->>Dev : Output UI result +``` + +**Diagram Source** + +- [frontend/antd/tag/tag.tsx:12-32](file://frontend/antd/tag/tag.tsx#L12-L32) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:13-32](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L13-L32) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:14-46](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L14-L46) +- [frontend/antd/timeline/timeline.tsx:15-46](file://frontend/antd/timeline/timeline.tsx#L15-L46) + +## Detailed Component Analysis + +### Tag Component + +- Regular Tag + - Key points: supports icon/closeIcon slots; when target child nodes are present, child nodes take rendering priority over the children + value fallback. + - Use cases: category labels, status badges, closable temporary tags. +- CheckableTag + - Key points: supports checked/value props and onValueChange callback; supports label text fallback; onChange is triggered in the callback chain. + - Use cases: multi-select filtering, preference settings, category checkboxes. +- **New**: CheckableTagGroup + - Key points: supports an options array or default slot fallback; injects context via ItemHandler, recording each child item's props, slots, and nested children. + - Use cases: batch tag selection, category filtering, multi-option group management. + +```mermaid +classDiagram +class Tag { ++props : All Ant Design Tag supported props ++slots : icon, closeIcon ++value? : string +} +class CheckableTag { ++props : Ant Design Tag.CheckableTag props ++slots : icon ++onValueChange(checked) ++label? : string +} +class CheckableTagGroup { ++props : Ant Design Tag.CheckableTagGroup props ++slots : options, default ++onValueChange(value) ++options? : array +} +class CheckableTagGroupOption { ++props : Single tag option props ++slots : default ++itemIndex : number ++itemSlotKey : string +} +Tag --> "uses" useTargets +CheckableTag --> "uses" useTargets +CheckableTagGroup --> "uses" createItemsContext +CheckableTagGroupOption --> "uses" ItemHandler +``` + +**Diagram Source** + +- [frontend/antd/tag/tag.tsx:7-32](file://frontend/antd/tag/tag.tsx#L7-L32) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:7-32](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L7-L32) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:8-48](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L8-L48) +- [frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx:7-13](file://frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx#L7-L13) +- [frontend/utils/hooks/useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [frontend/antd/tag/checkable-tag-group/context.ts:3-4](file://frontend/antd/tag/checkable-tag-group/context.ts#L3-L4) + +**Section Source** + +- [frontend/antd/tag/tag.tsx:7-32](file://frontend/antd/tag/tag.tsx#L7-L32) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:7-32](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L7-L32) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:8-48](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L8-L48) +- [frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx:7-13](file://frontend/antd/tag/checkable-tag-group/option/checkable-tag-group.option.tsx#L7-L13) +- [frontend/utils/hooks/useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [frontend/antd/tag/checkable-tag-group/context.ts:3-4](file://frontend/antd/tag/checkable-tag-group/context.ts#L3-L4) + +#### Interaction and State + +- Regular Tag + - Click events: handled by Antd native events; onClick and other events can be forwarded via props. + - Delete: achievable by combining the closeIcon slot with the closeIcon prop. +- CheckableTag + - Checked state: two-way binding via value/checked; onValueChange callback for state synchronization. + - Batch operations: manage the value of multiple CheckableTags in a parent container and update them in bulk. +- **New**: CheckableTagGroup + - Checked state: supports single-select and multi-select modes; onValueChange returns a selected value array or a single value. + - Dynamic options: dynamically add/remove tag options via the options prop or default slot. + - Group management: supports nested tag groups and batch operations at the group level. + +**Section Source** + +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:23-26](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L23-L26) +- [frontend/antd/tag/checkable-tag/Index.svelte:69-71](file://frontend/antd/tag/checkable-tag/Index.svelte#L69-L71) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:39-42](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L39-L42) +- [frontend/antd/tag/checkable-tag-group/Index.svelte:71-73](file://frontend/antd/tag/checkable-tag-group/Index.svelte#L71-L73) + +#### Color Configuration and Dynamic Management + +- Color: supports preset color palettes and custom hex values via the color prop. +- Dynamic: combining backend component bridging and frontend prop forwarding enables runtime dynamic switching of colors and text. +- **New**: Tag group color: supports setting a unified color theme for the entire tag group while preserving per-tag color overrides. + +**Section Source** + +- [docs/components/antd/tag/demos/checkable_tag.py:10-15](file://docs/components/antd/tag/demos/checkable_tag.py#L10-L15) + +#### Application in Search Results + +- Recommendation: add Tags to search result entries as category/status identifiers; use CheckableTag for multi-dimensional filtering; use closeIcon to remove filter conditions in one click. +- **New**: Use CheckableTagGroup for advanced filtering: supports multi-dimensional tag combination filtering, batch operations, and saving filter conditions. + +### Timeline Component + +- Timeline Body + - Supports an items array or default slot fallback; pending/pendingDot slots can customize the "in progress" state. + - Internally collects child items via the Items context, then uses renderItems to convert them into the data structure required by Antd. +- **Updated**: Timeline Item (Timeline.Item) + - **Simplified implementation**: removed complex prop handling logic, directly forwarding all props and slots. + - Injects context via ItemHandler, recording each child item's props, slots, and nested children. + - Supports a custom dot slot to replace the timeline node icon. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant TL as "Timeline" +participant Ctx as "Items Context" +participant Item as "Timeline.Item" +participant Render as "renderItems" +Dev->>TL : Set items or fill default slot +TL->>Ctx : Wrap with withItemsContextProvider +TL->>Item : Render child items and inject context +Item->>Ctx : ItemHandler records props/slots/children +TL->>Render : Use renderItems to convert to Antd data structure +Render-->>TL : Return items array +TL-->>Dev : Render timeline +``` + +**Diagram Source** + +- [frontend/antd/timeline/timeline.tsx:13-46](file://frontend/antd/timeline/timeline.tsx#L13-L46) +- [frontend/antd/timeline/context.ts:3-4](file://frontend/antd/timeline/context.ts#L3-L4) +- [frontend/utils/createItemsContext.tsx:171-184](file://frontend/utils/createItemsContext.tsx#L171-L184) +- [frontend/utils/renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) +- [frontend/antd/timeline/item/Index.svelte:49-64](file://frontend/antd/timeline/item/Index.svelte#L49-L64) + +**Section Source** + +- [frontend/antd/timeline/timeline.tsx:13-46](file://frontend/antd/timeline/timeline.tsx#L13-L46) +- [frontend/antd/timeline/context.ts:3-4](file://frontend/antd/timeline/context.ts#L3-L4) +- [frontend/utils/createItemsContext.tsx:171-184](file://frontend/utils/createItemsContext.tsx#L171-L184) +- [frontend/utils/renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) +- [frontend/antd/timeline/item/Index.svelte:49-64](file://frontend/antd/timeline/item/Index.svelte#L49-L64) + +#### Direction Control and Style Customization + +- Direction control: use the mode prop (such as alternate) to control alternating display of timeline nodes. +- Style customization: supports the color prop for node coloring; the dot slot allows custom node icons; pending/pendingDot slots customize the "in progress" state. + +**Section Source** + +- [docs/components/antd/timeline/demos/basic.py:18-38](file://docs/components/antd/timeline/demos/basic.py#L18-L38) + +#### Reversed Display and Timeline Style Adjustments + +- Reversed display: reverse order can be achieved via mode or external layout; for complete reversal, reverse the items array before passing it in at the parent layer. +- Line styles: Antd Timeline's default styles can be adjusted via theme variables or overriding class names; custom styles can also be wrapped in a parent container. + +#### Custom Node Icons + +- Custom icons: inject any icon component via the dot slot in Timeline.Item to achieve personalized visual node expression. + +**Section Source** + +- [docs/components/antd/timeline/demos/basic.py:27-37](file://docs/components/antd/timeline/demos/basic.py#L27-L37) + +#### Visualization in Project Progress + +- Recommendations: express milestones, task nodes, version releases, and other events as Timeline.Items; use color to mark priority/status; use dot slot for status icons; use pending/pendingDot slots to highlight the current phase. + +## Dependency Analysis + +- Tag Component + - useTargets: resolves target elements among child nodes to determine whether to fall back to children + value. + - **New**: createItemsContext: provides context support for tag groups to manage option lists and state. +- Timeline Component + - createItemsContext: provides the Items context responsible for collecting and merging child items. + - renderItems: converts the Item structure in context into the items array required by Antd. + - useItems: reads the collected items in Timeline and passes them to Antd Timeline. + +```mermaid +graph LR +USE_TARGETS["useTargets"] --> TAG["Tag"] +USE_TARGETS --> CTAG["CheckableTag"] +CREATE_ITEMS["createItemsContext"] --> CTAG_GROUP["CheckableTagGroup"] +CREATE_ITEMS --> TL["Timeline"] +TL --> RENDER_ITEMS["renderItems"] +TL --> TL_ITEM["Timeline.Item"] +CTAG_GROUP --> CTAG_OPTION["CheckableTagGroupOption"] +CTAG_OPTION --> CREATE_ITEMS +TL_ITEM --> CREATE_ITEMS +``` + +**Diagram Source** + +- [frontend/utils/hooks/useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [frontend/antd/tag/tag.tsx:12-32](file://frontend/antd/tag/tag.tsx#L12-L32) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:13-32](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L13-L32) +- [frontend/antd/tag/checkable-tag-group/context.ts:1-7](file://frontend/antd/tag/checkable-tag-group/context.ts#L1-L7) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:6-6](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L6-L6) +- [frontend/antd/timeline/timeline.tsx:7-7](file://frontend/antd/timeline/timeline.tsx#L7-L7) +- [frontend/utils/createItemsContext.tsx:97-106](file://frontend/utils/createItemsContext.tsx#L97-L106) +- [frontend/antd/timeline/item/Index.svelte:13-13](file://frontend/antd/timeline/item/Index.svelte#L13-L13) + +**Section Source** + +- [frontend/utils/hooks/useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [frontend/antd/tag/tag.tsx:12-32](file://frontend/antd/tag/tag.tsx#L12-L32) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:13-32](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L13-L32) +- [frontend/antd/tag/checkable-tag-group/context.ts:1-7](file://frontend/antd/tag/checkable-tag-group/context.ts#L1-L7) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:6-6](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L6-L6) +- [frontend/antd/timeline/timeline.tsx:7-7](file://frontend/antd/timeline/timeline.tsx#L7-L7) +- [frontend/utils/createItemsContext.tsx:97-106](file://frontend/utils/createItemsContext.tsx#L97-L106) +- [frontend/antd/timeline/item/Index.svelte:13-13](file://frontend/antd/timeline/item/Index.svelte#L13-L13) + +## Performance Considerations + +- Rendering Optimization + - useTargets only recalculates sorting and filtering of child nodes when children change, avoiding unnecessary re-renders. + - renderItems controls context update frequency via memoizedEqualValue and useMemoizedFn. + - **New**: CheckableTagGroup ensures option cloning via clone: true parameter to avoid state pollution. +- Context Stability + - withItemsContextProvider and useItems keep context references stable via useMemo and useRef, reducing subtree re-renders. + - **New**: Tag group context provides stable option management via createItemsContext. +- Slot Clone Strategy + - renderItems supports clone/forceClone parameters to control node cloning on demand, balancing performance with scope isolation. + +**Section Source** + +- [frontend/utils/hooks/useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [frontend/utils/createItemsContext.tsx:113-156](file://frontend/utils/createItemsContext.tsx#L113-L156) +- [frontend/utils/renderItems.tsx:62-94](file://frontend/utils/renderItems.tsx#L62-L94) +- [frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx:33-36](file://frontend/antd/tag/checkable-tag-group/tag.checkable-tag-group.tsx#L33-L36) + +## Troubleshooting Guide + +- Tag not displaying value + - Check whether children contain recognizable target nodes; if target nodes are present, they will take rendering priority over the value fallback. + - Reference path: [frontend/antd/tag/tag.tsx:22-29](file://frontend/antd/tag/tag.tsx#L22-L29) +- CheckableTag not triggering onValueChange + - Confirm that onValueChange is correctly passed; onChange is triggered before onValueChange, ensure the callback chain is complete. + - Reference path: [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:23-26](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L23-L26) +- **New**: CheckableTagGroup options not displayed + - Confirm that CheckableTagGroupOption is correctly used and content is injected via slots; check that the tag group context is active. + - Reference path: [frontend/antd/tag/checkable-tag-group/option/Index.svelte:55-73](file://frontend/antd/tag/checkable-tag-group/option/Index.svelte#L55-L73) +- **New**: Tag group value not updating + - Confirm that the onValueChange callback correctly handles the return value; check the tag group's value prop binding. + - Reference path: [frontend/antd/tag/checkable-tag-group/Index.svelte:71-73](file://frontend/antd/tag/checkable-tag-group/Index.svelte#L71-L73) +- Timeline not displaying any nodes + - Confirm that Timeline.Item is correctly used and content is injected via slots; check that the Items context is active. + - Reference path: [frontend/antd/timeline/item/Index.svelte:49-64](file://frontend/antd/timeline/item/Index.svelte#L49-L64) +- Custom dot not taking effect + - Ensure the dot slot is correctly declared inside Timeline.Item; check that slotKey matches the context. + - Reference path: [frontend/antd/timeline/item/Index.svelte:58-63](file://frontend/antd/timeline/item/Index.svelte#L58-L63) + +**Section Source** + +- [frontend/antd/tag/tag.tsx:22-29](file://frontend/antd/tag/tag.tsx#L22-L29) +- [frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx:23-26](file://frontend/antd/tag/checkable-tag/tag.checkable-tag.tsx#L23-L26) +- [frontend/antd/tag/checkable-tag-group/option/Index.svelte:55-73](file://frontend/antd/tag/checkable-tag-group/option/Index.svelte#L55-L73) +- [frontend/antd/tag/checkable-tag-group/Index.svelte:71-73](file://frontend/antd/tag/checkable-tag-group/Index.svelte#L71-L73) +- [frontend/antd/timeline/item/Index.svelte:49-64](file://frontend/antd/timeline/item/Index.svelte#L49-L64) +- [frontend/antd/timeline/item/Index.svelte:58-63](file://frontend/antd/timeline/item/Index.svelte#L58-L63) + +## Conclusion + +- The Tag component achieves flexible content fallback and icon extension through slot and target element resolution; CheckableTag provides a concise two-way binding and callback mechanism, suitable for multi-select and filtering scenarios. +- **New**: CheckableTagGroup provides powerful batch tag selection capabilities through a complete context system and option management, suitable for complex filtering and grouping scenarios. +- The Timeline component uses the Items context and renderItems to convert complex nested structures into the array form required by Antd, offering good extensibility and customization capabilities. +- In real business scenarios, combining backend component bridging and frontend prop forwarding can achieve linked display of dynamic tags and progress timelines. + +## Appendix + +- Example References + - CheckableTag demo: [docs/components/antd/tag/demos/checkable_tag.py:1-19](file://docs/components/antd/tag/demos/checkable_tag.py#L1-L19) + - Timeline basic demo: [docs/components/antd/timeline/demos/basic.py:1-41](file://docs/components/antd/timeline/demos/basic.py#L1-L41) +- **New**: CheckableTagGroup Examples + - Tag group basic usage: supports options array and dynamic option management + - Tag group batch operations: supports multi-select mode and batch state management + - Tag group nested usage: supports integrating tag group components in forms and filters diff --git a/.wiki/en/Ant Design Components/Data Display Components/Tooltip and Tour.md b/.wiki/en/Ant Design Components/Data Display Components/Tooltip and Tour.md new file mode 100644 index 00000000..1c61e6cf --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Tooltip and Tour.md @@ -0,0 +1,304 @@ +# Tooltip and Tour + + +**Files Referenced in This Document** +- [tooltip.tsx](file://frontend/antd/tooltip/tooltip.tsx) +- [tour.tsx](file://frontend/antd/tour/tour.tsx) +- [context.ts](file://frontend/antd/tour/context.ts) +- [Index.svelte (Tour)](file://frontend/antd/tour/Index.svelte) +- [Index.svelte (Tour Step)](file://frontend/antd/tour/step/Index.svelte) +- [tour.step.tsx](file://frontend/antd/tour/step/tour.step.tsx) +- [README.md (Tooltip docs)](file://docs/components/antd/tooltip/README.md) +- [README.md (Tour docs)](file://docs/components/antd/tour/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document covers the encapsulation and usage of the **Tooltip** and **Tour** Ant Design components in this repository. Key topics include: + +- Tooltip: trigger modes, position offset, delayed display, multi-line text support, nested usage, HTML content support, and accessibility optimization +- Tour: step configuration, path planning, focus areas, user interaction control, conditional logic, user preference memory, and guided flow customization + +## Project Structure + +This project uses Svelte + React preprocessing (svelte-preprocess-react) to expose Ant Design's React components to the Svelte ecosystem as Svelte components. Tooltip and Tour encapsulations are located under frontend/antd, and Tour's Step subcomponent is located at frontend/antd/tour/step. + +```mermaid +graph TB +subgraph "Ant Design Encapsulation Layer" +T["Tooltip
tooltip.tsx"] +TR["Tour
tour.tsx"] +TS["Tour Step
step/tour.step.tsx"] +end +subgraph "Svelte Wrapper Layer" +TI["Tour Wrapper
tour/Index.svelte"] +TSI["Tour Step Wrapper
step/Index.svelte"] +end +subgraph "Context and Utilities" +CTX["Items Context
tour/context.ts"] +U1["useFunction hook"] +U2["renderItems / renderParamsSlot utilities"] +end +T --> |"calls Antd Tooltip"| T +TR --> |"calls Antd Tour"| TR +TR --> CTX +TR --> U1 +TR --> U2 +TI --> TR +TSI --> TS +``` + +Diagram Source + +- [tooltip.tsx:1-29](file://frontend/antd/tooltip/tooltip.tsx#L1-L29) +- [tour.tsx:1-87](file://frontend/antd/tour/tour.tsx#L1-L87) +- [context.ts:1-7](file://frontend/antd/tour/context.ts#L1-L7) +- [Index.svelte (Tour):1-60](file://frontend/antd/tour/Index.svelte#L1-L60) +- [Index.svelte (Tour Step):1-82](file://frontend/antd/tour/step/Index.svelte#L1-L82) +- [tour.step.tsx:1-14](file://frontend/antd/tour/step/tour.step.tsx#L1-L14) + +Section Source + +- [tooltip.tsx:1-29](file://frontend/antd/tooltip/tooltip.tsx#L1-L29) +- [tour.tsx:1-87](file://frontend/antd/tour/tour.tsx#L1-L87) +- [context.ts:1-7](file://frontend/antd/tour/context.ts#L1-L7) +- [Index.svelte (Tour):1-60](file://frontend/antd/tour/Index.svelte#L1-L60) +- [Index.svelte (Tour Step):1-82](file://frontend/antd/tour/step/Index.svelte#L1-L82) +- [tour.step.tsx:1-14](file://frontend/antd/tour/step/tour.step.tsx#L1-L14) + +## Core Components + +- Tooltip: a lightweight wrapper for Ant Design Tooltip that preserves the title prop and slot-based title rendering capability, and safely injects callback functions into the React component via useFunction. +- Tour: an enhanced wrapper for Ant Design Tour that supports injecting steps, close icons, indicators, and action areas via slots; internally uses the Items context and render utilities to parse the step list; and provides onChange/onClose callback bridging. + +Section Source + +- [tooltip.tsx:7-26](file://frontend/antd/tooltip/tooltip.tsx#L7-L26) +- [tour.tsx:11-84](file://frontend/antd/tour/tour.tsx#L11-L84) + +## Architecture Overview + +The following diagram shows the call chain and data flow for Tooltip and Tour in this repository: + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant SvelteUI as "Svelte Component Wrapper Layer" +participant TourComp as "Tour Component" +participant TourStep as "Tour Step Component" +participant Ctx as "Items Context" +participant Antd as "Ant Design Tour/Tooltip" +Dev->>SvelteUI : Render Tour or Tooltip +SvelteUI->>TourComp : Pass props and slots +TourComp->>Ctx : Read steps/default slot items +TourComp->>Antd : Render Tour and pass steps and callbacks +TourComp->>TourStep : Render each step item +TourStep->>Antd : Render individual TourStep +Dev->>TourComp : Trigger onChange/onClose +TourComp-->>Dev : Callback notification +``` + +Diagram Source + +- [tour.tsx:17-83](file://frontend/antd/tour/tour.tsx#L17-L83) +- [context.ts:1-7](file://frontend/antd/tour/context.ts#L1-L7) +- [Index.svelte (Tour):46-59](file://frontend/antd/tour/Index.svelte#L46-L59) +- [Index.svelte (Tour Step):61-81](file://frontend/antd/tour/step/Index.svelte#L61-L81) +- [tour.step.tsx:7-11](file://frontend/antd/tour/step/tour.step.tsx#L7-L11) + +## Detailed Component Analysis + +### Tooltip Component + +- Trigger Modes + - Supports standard mouse-hover triggering via Ant Design Tooltip's native behavior. + - Dynamic content rendering can be achieved via slot-based titles, making it easy to embed HTML structures or complex components in the title. +- Position Offset + - Fine-tuned using Ant Design Tooltip's native offset parameters to meet different layout requirements. +- Delayed Display + - Use Ant Design Tooltip's delay parameters to avoid flickering or accidental triggers from frequent interactions. +- Multi-line Text Support + - Naturally supports multi-line text and rich text via the slot-based title and Ant Design Tooltip's line-break mechanism. +- Nested Usage + - Other interactive elements (such as buttons or links) can be nested inside Tooltip to achieve composite interactions. +- HTML Content Support + - HTML fragments can be rendered in Tooltip by injecting React nodes into the title via a slot. +- Accessibility Optimization + - Maintain native semantic tags and keyboard reachability; ensure that the title content is readable and understandable. + +```mermaid +flowchart TD +Start(["Enter Tooltip render"]) --> CheckSlot["Check if title slot exists"] +CheckSlot --> |Yes| RenderSlot["Render slot content as title"] +CheckSlot --> |No| UseProp["Use title prop as title"] +RenderSlot --> PassProps["Forward to Antd Tooltip"] +UseProp --> PassProps +PassProps --> End(["Rendering complete"]) +``` + +Diagram Source + +- [tooltip.tsx:17-19](file://frontend/antd/tooltip/tooltip.tsx#L17-L19) + +Section Source + +- [tooltip.tsx:7-26](file://frontend/antd/tooltip/tooltip.tsx#L7-L26) + +### Tour Component + +- Step Configuration + - Supports directly passing a steps array, or injecting steps/default items via slots; internally, render utilities uniformly parse them into the step format required by Ant Design Tour. +- Path Planning + - Step navigation is implemented via Ant Design Tour's built-in navigation logic; the current step index can be obtained via onChange, and combined with business logic to implement conditional decisions and path changes. +- Focus Areas + - Each step can bind a target element selector or function for locating the focus area; dynamic target element computation is supported. +- User Interaction Control + - Provides closeIcon, indicatorsRender, and actionsRender slots for customizing the close icon, indicators, and action area. + - Use the onClose callback to perform cleanup or record user preferences on close. +- Conditional Logic + - In onChange, determine whether to allow the next step or skip certain steps based on the current step and business state. +- User Preference Memory + - Persist user preferences (e.g., "don't show again") in onClose, and decide whether to show the Tour on next initialization based on preferences. +- Guided Flow Customization + - Combine slots and callbacks to implement custom guide text, styles, and interaction behavior. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Tour as "Tour Component" +participant Steps as "Steps List" +participant Ctx as "Items Context" +participant Antd as "Antd Tour" +Dev->>Tour : Pass steps or slot items +Tour->>Ctx : Read steps/default +Tour->>Steps : Use render utilities to parse into Antd steps +Tour->>Antd : Render Tour and pass step list +Dev->>Tour : Trigger onChange/onClose +Tour-->>Dev : Return current step index/close event +``` + +Diagram Source + +- [tour.tsx:33-48](file://frontend/antd/tour/tour.tsx#L33-L48) +- [tour.tsx:49-78](file://frontend/antd/tour/tour.tsx#L49-L78) +- [context.ts:1-7](file://frontend/antd/tour/context.ts#L1-L7) + +Section Source + +- [tour.tsx:11-84](file://frontend/antd/tour/tour.tsx#L11-L84) +- [context.ts:1-7](file://frontend/antd/tour/context.ts#L1-L7) + +#### Tour Step Component + +- Role + - Serves as the container for a single step, responsible for mapping externally passed props and slots to Ant Design TourStep. +- Key Points + - Supports target functions or selectors for locating focus areas. + - Supports bridging interactive props such as next_button_click/prev_button_click. + - Integrates with the Items context via ItemHandler for step item registration and management. + +```mermaid +classDiagram +class TourStep { ++props : TourStepProps ++target : string|function ++itemIndex : number ++slots : object +} +class ItemHandler { ++register(item) ++unregister(id) +} +TourStep --> ItemHandler : "register/manage step items" +``` + +Diagram Source + +- [tour.step.tsx:7-11](file://frontend/antd/tour/step/tour.step.tsx#L7-L11) +- [context.ts:1-7](file://frontend/antd/tour/context.ts#L1-L7) + +Section Source + +- [Index.svelte (Tour Step):1-82](file://frontend/antd/tour/step/Index.svelte#L1-L82) +- [tour.step.tsx:1-14](file://frontend/antd/tour/step/tour.step.tsx#L1-L14) + +## Dependency Analysis + +- Tooltip depends on Ant Design Tooltip, adapted from React component to Svelte via sveltify. +- Tour depends on Ant Design Tour, and also introduces the Items context and render utilities to convert slots into step arrays. +- The Svelte wrapper layer handles prop and slot forwarding, class name and visibility control, and async loading of the underlying component. + +```mermaid +graph LR +A["tooltip.tsx"] --> AD1["Antd Tooltip"] +B["tour.tsx"] --> AD2["Antd Tour"] +B --> C["context.ts"] +D["tour/Index.svelte"] --> B +E["step/Index.svelte"] --> F["step/tour.step.tsx"] +``` + +Diagram Source + +- [tooltip.tsx:1-29](file://frontend/antd/tooltip/tooltip.tsx#L1-L29) +- [tour.tsx:1-87](file://frontend/antd/tour/tour.tsx#L1-L87) +- [context.ts:1-7](file://frontend/antd/tour/context.ts#L1-L7) +- [Index.svelte (Tour):1-60](file://frontend/antd/tour/Index.svelte#L1-L60) +- [Index.svelte (Tour Step):1-82](file://frontend/antd/tour/step/Index.svelte#L1-L82) +- [tour.step.tsx:1-14](file://frontend/antd/tour/step/tour.step.tsx#L1-L14) + +Section Source + +- [tooltip.tsx:1-29](file://frontend/antd/tooltip/tooltip.tsx#L1-L29) +- [tour.tsx:1-87](file://frontend/antd/tour/tour.tsx#L1-L87) +- [context.ts:1-7](file://frontend/antd/tour/context.ts#L1-L7) +- [Index.svelte (Tour):1-60](file://frontend/antd/tour/Index.svelte#L1-L60) +- [Index.svelte (Tour Step):1-82](file://frontend/antd/tour/step/Index.svelte#L1-L82) +- [tour.step.tsx:1-14](file://frontend/antd/tour/step/tour.step.tsx#L1-L14) + +## Performance Considerations + +- Use useMemo to cache the step array and avoid unnecessary re-renders. +- Render Tour and Step only when visible to reduce DOM overhead. +- Use slots and dynamic rendering judiciously to avoid rendering too many complex nodes at once. +- In onChange/onClose, avoid heavy synchronous operations; use async processing where necessary. + +## Troubleshooting Guide + +- Title not displayed or empty + - Check whether title is correctly passed or whether the title slot is used; confirm that the slot content has been correctly rendered. +- Steps not taking effect + - Confirm that the steps or slot items are correctly injected; check whether the Items context is correctly provided. +- Target element cannot be focused + - Check the target selector or function return value; ensure the element is rendered on the page and accessible. +- Callbacks not triggered + - Confirm that onChange/onClose are correctly passed; check whether useFunction is correctly wrapping the callbacks. + +Section Source + +- [tour.tsx:33-48](file://frontend/antd/tour/tour.tsx#L33-L48) +- [tour.tsx:49-78](file://frontend/antd/tour/tour.tsx#L49-L78) +- [Index.svelte (Tour):46-59](file://frontend/antd/tour/Index.svelte#L46-L59) +- [Index.svelte (Tour Step):69-73](file://frontend/antd/tour/step/Index.svelte#L69-L73) + +## Conclusion + +The encapsulation of Tooltip and Tour in this repository follows the principles of "lightweight, extensible, and easy to integrate": while preserving Ant Design's native capabilities, it enhances step configuration, interaction customization, and rendering flexibility through slots and context mechanisms. In practice, it is recommended to configure step paths, target areas, and user preferences based on business scenarios to achieve a better user experience. + +## Appendix + +- Demo and Documentation Entry Points + - Tooltip documentation demo entry: [Tooltip docs:1-8](file://docs/components/antd/tooltip/README.md#L1-L8) + - Tour documentation demo entry: [Tour docs:1-8](file://docs/components/antd/tour/README.md#L1-L8) diff --git a/.wiki/en/Ant Design Components/Data Display Components/Tree.md b/.wiki/en/Ant Design Components/Data Display Components/Tree.md new file mode 100644 index 00000000..7d277088 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Display Components/Tree.md @@ -0,0 +1,348 @@ +# Tree + + +**Files Referenced in This Document** +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [Index.svelte](file://frontend/antd/tree/Index.svelte) +- [context.ts](file://frontend/antd/tree/context.ts) +- [tree.tree-node.tsx](file://frontend/antd/tree/tree-node/tree.tree-node.tsx) +- [directory-tree/Index.svelte](file://frontend/antd/tree/directory-tree/Index.svelte) +- [folder.tsx](file://frontend/antdx/folder/folder.tsx) +- [context.ts (folder context)](file://frontend/antdx/folder/context.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically reviews the design and implementation of the **Tree** component, covering its basic structure, node expand/collapse, DirectoryTree special capabilities, asynchronous data source loading, selection modes and multi-select/half-select, disabled configuration, search filtering, node dragging, right-click context menu, batch operations, virtual scrolling and large dataset optimization, dynamic CRUD operations, as well as typical applications and performance strategies in file management, organizational structures, and classification systems. + +## Project Structure + +The Tree component is composed of a Svelte frontend wrapper layer and a React component bridge layer, and supports declarative nesting and data injection for tree nodes via an "item context" mechanism. DirectoryTree, as a specialized form of Tree, reuses the same bridge layer and enables the directory tree component. + +```mermaid +graph TB +subgraph "Frontend Wrapper Layer" +T_Index["Tree/Index.svelte"] +DT_Index["DirectoryTree/Index.svelte"] +TN_Node["TreeNode/tree.tree-node.tsx"] +end +subgraph "Bridge and Context" +Bridge["Tree/tree.tsx"] +Ctx["Tree/context.ts"] +end +subgraph "External Dependencies" +AntD["Ant Design Tree/DirectoryTree"] +end +T_Index --> Bridge +DT_Index --> Bridge +TN_Node --> Ctx +Bridge --> AntD +``` + +Diagram Source + +- [Index.svelte:1-80](file://frontend/antd/tree/Index.svelte#L1-L80) +- [directory-tree/Index.svelte:1-83](file://frontend/antd/tree/directory-tree/Index.svelte#L1-L83) +- [tree.tree-node.tsx:1-22](file://frontend/antd/tree/tree-node/tree.tree-node.tsx#L1-L22) +- [tree.tsx:1-150](file://frontend/antd/tree/tree.tsx#L1-L150) +- [context.ts:1-7](file://frontend/antd/tree/context.ts#L1-L7) + +Section Source + +- [Index.svelte:1-80](file://frontend/antd/tree/Index.svelte#L1-L80) +- [directory-tree/Index.svelte:1-83](file://frontend/antd/tree/directory-tree/Index.svelte#L1-L83) +- [tree.tsx:1-150](file://frontend/antd/tree/tree.tsx#L1-L150) +- [context.ts:1-7](file://frontend/antd/tree/context.ts#L1-L7) + +## Core Components + +- Tree Wrapper: responsible for bridging Ant Design's Tree/DirectoryTree to the Svelte ecosystem, supporting slot extension, event forwarding, async loading, dragging, and title rendering. +- Tree Node: injects child nodes via ItemHandler as "default" slots, forming a tree structure. +- DirectoryTree: enables directory tree mode on top of Tree, providing folder-style interaction and behavior. +- Item Context: uniformly manages the collection and injection of "items" such as tree nodes and directory icons. + +Section Source + +- [tree.tsx:14-148](file://frontend/antd/tree/tree.tsx#L14-L148) +- [tree.tree-node.tsx:7-18](file://frontend/antd/tree/tree-node/tree.tree-node.tsx#L7-L18) +- [directory-tree/Index.svelte:65-82](file://frontend/antd/tree/directory-tree/Index.svelte#L65-L82) +- [context.ts:3-4](file://frontend/antd/tree/context.ts#L3-L4) + +## Architecture Overview + +The following diagram shows the call chain from Svelte to React, as well as the switching logic between DirectoryTree and regular Tree. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Wrapper Layer" +participant Bridge as "Tree Bridge Layer" +participant AntD as "Ant Design Component Library" +Svelte->>Bridge : Pass props and slots +Bridge->>Bridge : Parse treeData/slots/events +alt Directory Tree Mode +Bridge->>AntD : Use DirectoryTree +else Regular Tree Mode +Bridge->>AntD : Use Tree +end +AntD-->>Bridge : Render results and callbacks +Bridge-->>Svelte : Event forwarding/data return +``` + +Diagram Source + +- [tree.tsx:52-115](file://frontend/antd/tree/tree.tsx#L52-L115) +- [Index.svelte:67-78](file://frontend/antd/tree/Index.svelte#L67-L78) +- [directory-tree/Index.svelte:66-81](file://frontend/antd/tree/directory-tree/Index.svelte#L66-L81) + +## Detailed Component Analysis + +### Basic Structure and Data Model + +- Data Source Origins + - Explicit treeData: directly pass the tree node array required by AntD. + - Slot treeData/default: collect child nodes via item context, automatically converting to treeData. +- Key Fields + - Identification and hierarchy: key/value/title etc. used for identification and display. + - Expanded state: expandedKeys controls initial expansion; onExpand callback responds to user actions. + - Selection and checking: selectedKeys/checkedKeys support single/multi-select; half-select is calculated via internal algorithm. + - Disabled: disabled field disables node interaction. +- Slot Extensions + - switcherIcon/switcherLoadingIcon: custom expand/loading icons. + - showLine.showLeafIcon: custom connection line leaf icon. + - icon: node icon. + - draggable.icon/nodeDraggable: drag icon and node-level draggable toggle. + - titleRender: custom title render function. + +Section Source + +- [tree.tsx:56-126](file://frontend/antd/tree/tree.tsx#L56-L126) +- [context.ts:3-4](file://frontend/antd/tree/context.ts#L3-L4) + +### Expand/Collapse and Async Loading + +- Expand/Collapse + - Get the current expanded set via onExpand, and implement hierarchical expansion combined with treeData's children. +- Async Loading + - Provide lazy loading hooks via loadData/onLoadData, requesting child node data on demand. + - DirectoryTree mode also supports async loading, suitable for large directory scenarios. + +```mermaid +flowchart TD +Start(["User clicks expand"]) --> CheckLoaded{"Child nodes already loaded?"} +CheckLoaded --> |No| Load["Trigger onLoadData/loadData request"] +Load --> Update["Update treeData child nodes"] +CheckLoaded --> |Yes| Render["Render child nodes directly"] +Update --> Render +Render --> End(["Done"]) +``` + +Diagram Source + +- [tree.tsx:114-114](file://frontend/antd/tree/tree.tsx#L114-L114) +- [tree.tsx:137-139](file://frontend/antd/tree/tree.tsx#L137-L139) + +Section Source + +- [tree.tsx:38-42](file://frontend/antd/tree/tree.tsx#L38-L42) +- [tree.tsx:114-114](file://frontend/antd/tree/tree.tsx#L114-L114) + +### DirectoryTree Special Features + +- Mode Switching + - Toggle between Tree and DirectoryTree via the directory prop. +- Event Mapping + - dragStart/dragEnter/dragOver/dragLeave/dragEnd: drag lifecycle events. + - rightClick: right-click context menu trigger. + - loadData: directory tree specific lazy loading hook. +- Folder Style + - More aligned with file system browsing experience, supporting directory hierarchy and icon mapping. + +Section Source + +- [tree.tsx:52-52](file://frontend/antd/tree/tree.tsx#L52-L52) +- [directory-tree/Index.svelte:18-25](file://frontend/antd/tree/directory-tree/Index.svelte#L18-L25) +- [directory-tree/Index.svelte:50-58](file://frontend/antd/tree/directory-tree/Index.svelte#L50-L58) + +### Selection Modes, Multi-select and Half-select + +- Single-select/Multi-select + - Implement single or multi-select via selectedKeys/onChange. +- Multi-select Linkage + - Checking parent nodes affects child nodes; unchecking affects parent node state. +- Half-select State + - When some child nodes are checked, the parent node shows a half-selected state for quick identification of partial selection. +- Disabled Nodes + - The disabled field prevents nodes from being selected or checked. + +Section Source + +- [tree.tsx:134-142](file://frontend/antd/tree/tree.tsx#L134-L142) + +### Search Filtering + +- Filter Function + - filterTreeNode accepts a node and input value, returning a boolean to decide whether to display. +- Practical Recommendations + - Combine expanded state and highlight matching items to improve discoverability. + +Section Source + +- [tree.tsx:132-132](file://frontend/antd/tree/tree.tsx#L132-L132) + +### Node Dragging + +- Drag Toggle + - draggable can be a boolean or object; nodeDraggable supports node-level draggable control. +- Icon Customization + - draggable.icon customizes the drag handle icon. +- Event Forwarding + - dragStart/dragEnd etc. events are triggered by the underlying component for business layer integration. + +Section Source + +- [tree.tsx:102-112](file://frontend/antd/tree/tree.tsx#L102-L112) +- [tree.tsx:48-50](file://frontend/antd/tree/tree.tsx#L48-L50) + +### Right-click Context Menu and Batch Operations + +- Right-click Context Menu + - rightClick event can be used to pop up a context menu. +- Batch Operations + - Combine multi-select and right-click context menu for batch actions like copy, move, and delete. +- Safety + - Intercept disabled nodes to prevent accidental operations. + +Section Source + +- [directory-tree/Index.svelte:23-23](file://frontend/antd/tree/directory-tree/Index.svelte#L23-L23) +- [tree.tsx:134-142](file://frontend/antd/tree/tree.tsx#L134-L142) + +### Dynamic CRUD Operations + +- Add/Modify + - Update treeData or maintain selectedKeys/checkedKeys in controlled mode. +- Delete + - Remove the corresponding node and synchronize cleanup of selection state. +- Query + - Link filterTreeNode with search input for instant filtering. + +Section Source + +- [tree.tsx:59-79](file://frontend/antd/tree/tree.tsx#L59-L79) + +### Virtual Scrolling and Large Dataset Optimization + +- Virtual Scrolling + - Enabling virtual scrolling in super-large trees can significantly reduce DOM count and improve rendering performance. +- Other Optimizations + - Lazy loading (loadData/onLoadData) renders only visible levels. + - Use disabled and hidden nodes judiciously to reduce rendering burden. + - Avoid frequent recalculation of treeData; use shallow comparison and caching where possible. + +Section Source + +- [tree.tsx:114-114](file://frontend/antd/tree/tree.tsx#L114-L114) + +### Application Scenarios and Best Practices + +- File Management + - DirectoryTree + dragging + right-click context menu + async loading to build a file browser-like experience. +- Organizational Structure + - Departments/teams as nodes, supporting collapse and search for easy navigation. +- Classification Systems + - Multi-level classification tree, combined with half-select and batch operations to improve editing efficiency. + +Section Source + +- [directory-tree/Index.svelte:65-82](file://frontend/antd/tree/directory-tree/Index.svelte#L65-L82) +- [tree.tsx:52-52](file://frontend/antd/tree/tree.tsx#L52-L52) + +## Dependency Analysis + +- Component Coupling + - Tree/Index.svelte and DirectoryTree/Index.svelte both depend on the Tree bridge layer. + - Tree nodes inject into the context via ItemHandler, forming a tree structure. +- External Dependencies + - Ant Design Tree/DirectoryTree provides core interaction and rendering. +- Slots and Events + - High customizability is achieved through slots and event forwarding. + +```mermaid +graph LR +T_Index["Tree/Index.svelte"] --> Bridge["Tree/tree.tsx"] +DT_Index["DirectoryTree/Index.svelte"] --> Bridge +TN_Node["TreeNode/tree.tree-node.tsx"] --> Ctx["Tree/context.ts"] +Bridge --> AntD["Ant Design Tree/DirectoryTree"] +``` + +Diagram Source + +- [Index.svelte:10-10](file://frontend/antd/tree/Index.svelte#L10-L10) +- [directory-tree/Index.svelte:10-10](file://frontend/antd/tree/directory-tree/Index.svelte#L10-L10) +- [tree.tsx:1-11](file://frontend/antd/tree/tree.tsx#L1-L11) +- [tree.tree-node.tsx:5-5](file://frontend/antd/tree/tree-node/tree.tree-node.tsx#L5-L5) +- [context.ts:3-4](file://frontend/antd/tree/context.ts#L3-L4) + +Section Source + +- [Index.svelte:1-80](file://frontend/antd/tree/Index.svelte#L1-L80) +- [directory-tree/Index.svelte:1-83](file://frontend/antd/tree/directory-tree/Index.svelte#L1-L83) +- [tree.tsx:1-150](file://frontend/antd/tree/tree.tsx#L1-L150) +- [tree.tree-node.tsx:1-22](file://frontend/antd/tree/tree-node/tree.tree-node.tsx#L1-L22) +- [context.ts:1-7](file://frontend/antd/tree/context.ts#L1-L7) + +## Performance Considerations + +- Rendering Optimization + - Use virtual scrolling and lazy loading to avoid rendering a large number of nodes at once. +- Data Structure + - Keep treeData flat and stable in reference to reduce unnecessary re-renders. +- Event Throttling + - Throttle/debounce high-frequency events (such as drag and scroll). +- Selection and Half-select + - Use checkedKeys and half-select state judiciously to avoid recursive calculations layer by layer. + +## Troubleshooting Guide + +- Cannot expand nodes + - Check whether treeData's children are correctly set or whether async loading is implemented. +- Drag not working + - Confirm that draggable is an object and includes nodeDraggable or that draggable.icon is correctly injected. +- Right-click context menu not appearing + - Confirm that the rightClick event is bound and works in directory tree mode. +- Selection state anomaly + - Check whether selectedKeys/checkedKeys are updated synchronously with treeData. + +Section Source + +- [tree.tsx:102-112](file://frontend/antd/tree/tree.tsx#L102-L112) +- [tree.tsx:134-142](file://frontend/antd/tree/tree.tsx#L134-L142) +- [directory-tree/Index.svelte:23-23](file://frontend/antd/tree/directory-tree/Index.svelte#L23-L23) + +## Conclusion + +This Tree component provides complete encapsulation of Ant Design Tree/DirectoryTree through the combination of a Svelte wrapper layer and React bridge layer, with good extensibility and customizability. Combined with async loading, virtual scrolling, and rich interaction capabilities, it is suitable for complex scenarios such as file management, organizational structures, and classification systems. + +## Appendix + +- Relationship Between DirectoryTree and Folder Component + - DirectoryTree is used for the directory mode of the tree; the folder component (antdx/folder) provides richer file system capabilities (such as icon mapping and content services), and the two can be used complementarily. + +Section Source + +- [directory-tree/Index.svelte:65-82](file://frontend/antd/tree/directory-tree/Index.svelte#L65-L82) +- [folder.tsx:48-86](file://frontend/antdx/folder/folder.tsx#L48-L86) +- [context.ts (folder context):3-13](file://frontend/antdx/folder/context.ts#L3-L13) diff --git a/.wiki/en/Ant Design Components/Data Entry Components/Color and File Components.md b/.wiki/en/Ant Design Components/Data Entry Components/Color and File Components.md new file mode 100644 index 00000000..d9f7205d --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Entry Components/Color and File Components.md @@ -0,0 +1,364 @@ +# Color and File Components + + +**Files referenced in this document** +- [color-picker.tsx](file://frontend/antd/color-picker/color-picker.tsx) +- [context.ts (ColorPicker)](file://frontend/antd/color-picker/context.ts) +- [upload.tsx](file://frontend/antd/upload/upload.tsx) +- [upload.ts (utility functions)](file://frontend/utils/upload.ts) +- [slider.tsx](file://frontend/antd/slider/slider.tsx) +- [context.ts (Slider)](file://frontend/antd/slider/context.ts) +- [form.tsx](file://frontend/antd/form/form.tsx) +- [README.md (ColorPicker docs)](file://docs/components/antd/color_picker/README.md) +- [README.md (Upload docs)](file://docs/components/antd/upload/README.md) +- [README.md (Slider docs)](file://docs/components/antd/slider/README.md) +- [README.md (Form docs)](file://docs/components/antd/form/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on color, file, and advanced input components: ColorPicker, Upload, Slider, and Form. Content covers: + +- Color format conversion (RGB, HEX, HSB), gradient color handling and preset palettes +- Upload configuration, drag-and-drop upload, file preview, progress display and error handling +- Overall form design patterns, field validation, dynamic forms and nested forms +- Accessibility and keyboard navigation support +- Performance optimization strategies such as large file handling, concurrent uploads, and error retry +- Data flow management and best practices for complex form scenarios + +## Project Structure + +These components are located in the frontend Svelte + Ant Design ecosystem, bridging Ant Design components for Svelte use via sveltify, and encapsulating state and callbacks where necessary to adapt to the Gradio data domain. + +```mermaid +graph TB +subgraph "Antd Component Layer" +CP["ColorPicker"] +UP["Upload"] +SL["Slider"] +FM["Form"] +end +subgraph "Utilities and Context" +CTX_CP["ColorPicker Context"] +CTX_SL["Slider Context"] +UT["Upload Utility Functions
URL Parsing and Assembly"] +end +CP --> CTX_CP +SL --> CTX_SL +UP --> UT +``` + +Diagram Source + +- [color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) +- [upload.tsx:1-282](file://frontend/antd/upload/upload.tsx#L1-L282) +- [slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) +- [form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +Section Source + +- [color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) +- [upload.tsx:1-282](file://frontend/antd/upload/upload.tsx#L1-L282) +- [slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) +- [form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +## Core Components + +- ColorPicker + - Supports RGB/HEX/HSB three color format outputs + - Gradient color parsing and multi-point color mapping + - Preset palette rendering and custom panel/text slots +- Upload + - Custom request hook and progress formatting + - File list normalization, maximum count control + - Drag-and-drop/click upload, preview and icon rendering slots +- Slider + - Tick mark rendering (supports label slots) + - Step and tooltip container customization +- Form + - Value domain binding and change notification + - Manually trigger reset/submit/validate actions + - Required mark and feedback icon slots + +Section Source + +- [color-picker.tsx:11-103](file://frontend/antd/color-picker/color-picker.tsx#L11-L103) +- [upload.tsx:21-279](file://frontend/antd/upload/upload.tsx#L21-L279) +- [slider.tsx:37-94](file://frontend/antd/slider/slider.tsx#L37-L94) +- [form.tsx:15-76](file://frontend/antd/form/form.tsx#L15-L76) + +## Architecture Overview + +Components use a "bridge + decoration" architecture: with Ant Design native components as the core, wrapped via sveltify and injected with value change callbacks, slot rendering, and context injection to achieve seamless integration with the Gradio data domain. + +```mermaid +sequenceDiagram +participant U as "User" +participant C as "ColorPicker" +participant A as "Antd ColorPicker" +participant F as "Format Conversion Logic" +U->>C : Select color/drag gradient +C->>A : Trigger onChange(...) +A-->>C : Return color object/gradient info +C->>F : Convert to RGB/HEX/HSB according to value_format +F-->>C : Output unified format array or string +C-->>U : Callback onValueChange(...) +``` + +Diagram Source + +- [color-picker.tsx:71-95](file://frontend/antd/color-picker/color-picker.tsx#L71-L95) + +Section Source + +- [color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) + +## Detailed Component Analysis + +### ColorPicker + +- Key features + - Color format conversion: one of RGB/HEX/HSB, output according to value_format + - Gradient color handling: iterate through gradient points, convert each to the specified format and return as array + - Preset palette: supports passing presets or injecting via context + - Slot extension: slot-based rendering for panelRender and showText +- Key flow + +```mermaid +flowchart TD +Start(["Start"]) --> IsGrad{"Is gradient color?"} +IsGrad --> |Yes| Iterate["Iterate through gradient points"] +Iterate --> Convert["Convert color according to value_format"] +Convert --> EmitGrad["Callback onValueChange(array)"] +IsGrad --> |No| Single["Single color conversion"] +Single --> EmitSingle["Callback onValueChange(string)"] +EmitGrad --> End(["End"]) +EmitSingle --> End +``` + +Diagram Source + +- [color-picker.tsx:71-95](file://frontend/antd/color-picker/color-picker.tsx#L71-L95) + +- Context and preset palette + - Inject marks/presets and other item sets via createItemsContext + - Preset palette prefers externally passed values; otherwise renders from context + +- Accessibility and keyboard navigation + - Based on Ant Design native component, follows its accessibility specifications + - Recommended to supplement aria-label, aria-describedby and other attributes on the business side + +Section Source + +- [color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) +- [context.ts (ColorPicker):1-7](file://frontend/antd/color-picker/context.ts#L1-L7) +- [README.md (ColorPicker docs):1-9](file://docs/components/antd/color_picker/README.md#L1-L9) + +### Upload + +- Key features + - Custom upload: upload(files) -> Promise + - File list normalization: converts non-UploadFile forms to UploadFile structure + - Maximum count control: when maxCount=1, replace; otherwise append + - Progress and icons: supports custom progress formatting and icon rendering slots + - Preview and image recognition: custom previewFile/isImageUrl +- Key flow + +```mermaid +sequenceDiagram +participant U as "User" +participant UI as "Upload" +participant CU as "customRequest/upload" +participant SV as "Server" +U->>UI : Select/drag file +UI->>UI : beforeUpload validation +UI->>UI : Set temporary uploading state and temporary file list +UI->>CU : Call upload(validFiles) +CU->>SV : Send file +SV-->>CU : Return FileData[] +CU-->>UI : Return result +UI->>UI : Merge file list and callback onValueChange/onChange +``` + +Diagram Source + +- [upload.tsx:147-227](file://frontend/antd/upload/upload.tsx#L147-L227) + +- Utility functions: URL retrieval + - getFetchableUrl: concatenates relative paths to accessible URLs + - getFileUrl: returns a usable URL based on FileData/string/other types + +- Performance and reliability + - Disables interaction during upload to avoid repeated triggering + - Temporary file list improves user experience, replaced by real results after completion + - Restores uploading state after error capture + +Section Source + +- [upload.tsx:1-282](file://frontend/antd/upload/upload.tsx#L1-L282) +- [upload.ts (utility functions):1-45](file://frontend/utils/upload.ts#L1-L45) +- [README.md (Upload docs):1-9](file://docs/components/antd/upload/README.md#L1-L9) + +### Slider + +- Key features + - Tick mark rendering: supports label/children slots and property forwarding + - Tooltip container and formatting: tooltip.formatter and getPopupContainer + - Step control: explicitly pass null for step when not set +- Key flow + +```mermaid +flowchart TD +Start(["Start"]) --> RenderMarks["Render tick marks"] +RenderMarks --> SetTooltip["Configure tooltip.formatter/getPopupContainer"] +SetTooltip --> BindStep["step=null if not set"] +BindStep --> OnChange["onChange callback onValueChange(...)"] +OnChange --> End(["End"]) +``` + +Diagram Source + +- [slider.tsx:68-89](file://frontend/antd/slider/slider.tsx#L68-L89) + +Section Source + +- [slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) +- [context.ts (Slider):1-7](file://frontend/antd/slider/context.ts#L1-L7) +- [README.md (Slider docs):1-9](file://docs/components/antd/slider/README.md#L1-L9) + +### Form + +- Key features + - Value domain binding: value -> setFieldsValue; onValuesChange -> onValueChange + - Form actions: trigger corresponding behavior via formAction='reset'|'submit'|'validate' + - Slots: requiredMark, feedbackIcons +- Key flow + +```mermaid +sequenceDiagram +participant V as "External value" +participant F as "Form" +participant AF as "Antd Form Instance" +V->>F : Pass value +F->>AF : setFieldsValue(value) +AF-->>F : onValuesChange(values) +F-->>V : onValueChange(values) +Note over F : Monitor formAction +F->>AF : reset/submit/validate +AF-->>F : Reset formAction after completion +``` + +Diagram Source + +- [form.tsx:32-45](file://frontend/antd/form/form.tsx#L32-L45) + +Section Source + +- [form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [README.md (Form docs):1-14](file://docs/components/antd/form/README.md#L1-L14) + +## Dependency Analysis + +- Inter-component coupling + - ColorPicker/Slider inject item sets via their respective Items contexts, reducing coupling with external data + - Upload relies on utility functions for URL parsing, avoiding scattered logic within the component + - Form only handles bridging and action dispatching, without directly processing business data +- External dependencies + - Ant Design native components as the base UI + - Gradio client types (FileData) for the upload data domain + +```mermaid +graph LR +CP["ColorPicker"] --> CTX_CP["ColorPicker Context"] +SL["Slider"] --> CTX_SL["Slider Context"] +UP["Upload"] --> UT["Upload Utility Functions"] +FM["Form"] --> AF["Antd Form Instance"] +``` + +Diagram Source + +- [color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) +- [slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) +- [upload.tsx:1-282](file://frontend/antd/upload/upload.tsx#L1-L282) +- [form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +Section Source + +- [color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) +- [slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) +- [upload.tsx:1-282](file://frontend/antd/upload/upload.tsx#L1-L282) +- [form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +## Performance Considerations + +- ColorPicker + - Gradient color conversion is completed in onChange to avoid additional rendering overhead + - Preset palette caches rendering results via useMemo +- Upload + - Temporary file list reduces UI jitter + - Disables interaction during upload to prevent concurrent submissions + - Supports custom progress formatting to avoid frequent redraws +- Slider + - Tick marks are rendered on demand to reduce DOM nodes + - step is explicitly passed as null to avoid invalid computation +- Form + - Value changes are only called back in onValuesChange to avoid full synchronization + +[This section provides general performance recommendations and does not require specific file references] + +## Troubleshooting Guide + +- ColorPicker + - If gradient colors are not correctly converted, check whether value_format is consistent with the expectation + - If the preset palette is not displayed, confirm whether context injection or presets property is correctly passed in +- Upload + - Cannot upload: confirm that the upload function's return value is consistent with the FileData structure + - Progress not updating: check whether progress.format is correctly passed in + - Icon/preview anomaly: verify iconRender/itemRender slots and custom functions +- Slider + - Tick marks not displayed: confirm whether marks or context items are correctly injected + - Step invalid: ensure step has not been overridden to undefined +- Form + - Values not syncing: confirm whether two-way binding of value and onValueChange is effective + - Action invalid: check whether formAction has been reset to null + +Section Source + +- [color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) +- [upload.tsx:1-282](file://frontend/antd/upload/upload.tsx#L1-L282) +- [slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) +- [form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +## Conclusion + +The above components are built on Ant Design, combined with context injection and utility functions, to achieve high-performance, extensible and maintainable advanced input capabilities. Through a unified value change callback and slot mechanism, they can meet the needs of complex forms and file handling scenarios. It is recommended to combine error boundaries, loading states, and accessibility attributes in actual projects to further improve stability and user experience. + +[This section is a summary and does not require specific file references] + +## Appendix + +- Examples and documentation entry points + - ColorPicker: see examples and descriptions in the docs directory + - Upload: see examples and descriptions in the docs directory + - Slider: see examples and descriptions in the docs directory + - Form: see examples and descriptions in the docs directory + +Section Source + +- [README.md (ColorPicker docs):1-9](file://docs/components/antd/color_picker/README.md#L1-L9) +- [README.md (Upload docs):1-9](file://docs/components/antd/upload/README.md#L1-L9) +- [README.md (Slider docs):1-9](file://docs/components/antd/slider/README.md#L1-L9) +- [README.md (Form docs):1-14](file://docs/components/antd/form/README.md#L1-L14) diff --git a/.wiki/en/Ant Design Components/Data Entry Components/Data Entry Components.md b/.wiki/en/Ant Design Components/Data Entry Components/Data Entry Components.md new file mode 100644 index 00000000..87a53bc1 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Entry Components/Data Entry Components.md @@ -0,0 +1,520 @@ +# Data Entry Components + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [frontend/antd/auto-complete/auto-complete.tsx](file://frontend/antd/auto-complete/auto-complete.tsx) +- [frontend/antd/cascader/cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [frontend/antd/checkbox/checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [frontend/antd/color-picker/color-picker.tsx](file://frontend/antd/color-picker/color-picker.tsx) +- [frontend/antd/date-picker/date-picker.tsx](file://frontend/antd/date-picker/date-picker.tsx) +- [frontend/antd/radio/radio.tsx](file://frontend/antd/radio/radio.tsx) +- [frontend/antd/rate/rate.tsx](file://frontend/antd/rate/rate.tsx) +- [frontend/antd/slider/slider.tsx](file://frontend/antd/slider/slider.tsx) +- [frontend/antd/switch/switch.tsx](file://frontend/antd/switch/switch.tsx) +- [frontend/antd/time-picker/time-picker.tsx](file://frontend/antd/time-picker/time-picker.tsx) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/form/item/form.item.tsx](file://frontend/antd/form/item/form.item.tsx) +- [frontend/antd/form/item/rule/form.item.rule.tsx](file://frontend/antd/form/item/rule/form.item.rule.tsx) +- [frontend/antd/form/provider/form.provider.tsx](file://frontend/antd/form/provider/form.provider.tsx) +- [frontend/antd/input/input.tsx](file://frontend/antd/input/input.tsx) +- [frontend/antd/input/otp/input.otp.tsx](file://frontend/antd/input/otp/input.otp.tsx) +- [frontend/antd/input/password/input.password.tsx](file://frontend/antd/input/password/input.password.tsx) +- [frontend/antd/input/search/input.search.tsx](file://frontend/antd/input/search/input.search.tsx) +- [frontend/antd/input/textarea/input.textarea.tsx](file://frontend/antd/input/textarea/input.textarea.tsx) +- [frontend/antd/input-number/input-number.tsx](file://frontend/antd/input-number/input-number.tsx) +- [frontend/antd/select/select.tsx](file://frontend/antd/select/select.tsx) +- [frontend/antd/select/option/select.option.tsx](file://frontend/antd/select/option/select.option.tsx) +- [frontend/antd/transfer/transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [frontend/antd/tree-select/tree-select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [frontend/antd/upload/upload.tsx](file://frontend/antd/upload/upload.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Large Data Optimization](#performance-and-large-data-optimization) +8. [Accessibility and Keyboard Navigation](#accessibility-and-keyboard-navigation) +9. [Complex Form Design Patterns and Data Flow](#complex-form-design-patterns-and-data-flow) +10. [Troubleshooting Guide](#troubleshooting-guide) +11. [Conclusion](#conclusion) + +## Introduction + +This document is intended for scenarios where Ant Design components are used for data entry in the frontend. It systematically covers the wrapping and usage of AutoComplete, Cascader, Checkbox, ColorPicker, DatePicker, Form, Input, InputNumber, Mentions, Radio, Rate, Select, Slider, Switch, TimePicker, Transfer, TreeSelect, Upload, and other components. Key areas covered include: + +- Data binding: how to implement controlled/uncontrolled two-way binding via onValueChange +- Validation rules: combining Form.Item with FormItem.Rule +- Formatting options: internal format conversion and unified external output for date/time components +- Complex form design patterns: multi-step, linked fields, dynamic fields, conditional rendering +- Accessibility and keyboard navigation: semantic labels, focus management, keyboard navigation +- Performance optimization: virtual scrolling, lazy loading, debounce/throttle, batch updates + +## Project Structure + +This project uses a dual-layer architecture of "backend component export + frontend Svelte/React wrapping": + +- The backend layer exports Ant Design components as Python classes, enabling unified invocation and documentation generation within the Python ecosystem +- The frontend layer is based on Svelte/React wrapping, providing slot injection, context injection, function hooks, value change bridging, and other capabilities to achieve a consistent API experience with the backend + +```mermaid +graph TB +subgraph "Backend" +A["backend/modelscope_studio/components/antd/__init__.py
Exports Antd* component aliases"] +end +subgraph "Frontend" +B["frontend/antd/*/*.tsx
Component wrappers: sveltify + hooks"] +C["frontend/antd/form/*
Form/FormItem/Rule/Provider"] +D["utils/*
hooks/renderItems/renderParamsSlot etc."] +end +A --> B +B --> D +C --> B +``` + +Diagram Source + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [frontend/antd/auto-complete/auto-complete.tsx:1-151](file://frontend/antd/auto-complete/auto-complete.tsx#L1-L151) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/form/item/form.item.tsx](file://frontend/antd/form/item/form.item.tsx) +- [frontend/antd/form/item/rule/form.item.rule.tsx](file://frontend/antd/form/item/rule/form.item.rule.tsx) +- [frontend/antd/form/provider/form.provider.tsx](file://frontend/antd/form/provider/form.provider.tsx) + +Section Source + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) + +## Core Components + +This section gives an overview of the components covered in this document and their responsibilities: + +- Form system: Form, FormItem, FormItem.Rule, FormProvider +- Input types: Input, Input.TextArea, Input.Search, Input.Password, Input.OTP, InputNumber +- Selection types: Select, Select.Option, Cascader, TreeSelect, Transfer +- Date/time types: DatePicker, TimePicker +- Slider and rating: Slider, Rate +- Toggle and selection: Switch, Radio, Checkbox +- Color: ColorPicker +- Mentions: Mentions (supports keyword mentions and dynamic rendering of options, including the Option sub-component) + +Section Source + +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/form/item/form.item.tsx](file://frontend/antd/form/item/form.item.tsx) +- [frontend/antd/form/item/rule/form.item.rule.tsx](file://frontend/antd/form/item/rule/form.item.rule.tsx) +- [frontend/antd/form/provider/form.provider.tsx](file://frontend/antd/form/provider/form.provider.tsx) +- [frontend/antd/input/input.tsx](file://frontend/antd/input/input.tsx) +- [frontend/antd/input/otp/input.otp.tsx](file://frontend/antd/input/otp/input.otp.tsx) +- [frontend/antd/input/password/input.password.tsx](file://frontend/antd/input/password/input.password.tsx) +- [frontend/antd/input/search/input.search.tsx](file://frontend/antd/input/search/input.search.tsx) +- [frontend/antd/input/textarea/input.textarea.tsx](file://frontend/antd/input/textarea/input.textarea.tsx) +- [frontend/antd/input-number/input-number.tsx](file://frontend/antd/input-number/input-number.tsx) +- [frontend/antd/select/select.tsx](file://frontend/antd/select/select.tsx) +- [frontend/antd/select/option/select.option.tsx](file://frontend/antd/select/option/select.option.tsx) +- [frontend/antd/cascader/cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [frontend/antd/tree-select/tree-select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [frontend/antd/transfer/transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [frontend/antd/date-picker/date-picker.tsx](file://frontend/antd/date-picker/date-picker.tsx) +- [frontend/antd/time-picker/time-picker.tsx](file://frontend/antd/time-picker/time-picker.tsx) +- [frontend/antd/slider/slider.tsx](file://frontend/antd/slider/slider.tsx) +- [frontend/antd/rate/rate.tsx](file://frontend/antd/rate/rate.tsx) +- [frontend/antd/switch/switch.tsx](file://frontend/antd/switch/switch.tsx) +- [frontend/antd/radio/radio.tsx](file://frontend/antd/radio/radio.tsx) +- [frontend/antd/checkbox/checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [frontend/antd/color-picker/color-picker.tsx](file://frontend/antd/color-picker/color-picker.tsx) + +## Architecture Overview + +Frontend components universally use sveltify to wrap Ant Design native components, and complete the following via hooks: + +- Value change bridging: useValueChange bridges onChange and onValueChange to ensure the external side consistently receives value +- Function parameterization: useFunction wraps incoming functions as stable references to avoid closure traps +- Slot rendering: renderItems/renderParamsSlot support flexible combinations of children and slots +- Context injection: withItemsContextProvider injects items into child components (such as Option/Marks/Preset) + +```mermaid +sequenceDiagram +participant U as "User" +participant C as "Wrapped Component (e.g. AutoComplete)" +participant R as "React/antd Component" +participant H as "hooks(onValueChange/useFunction)" +participant P as "Parent Component (Form/Page)" +U->>C : Trigger interaction +C->>R : Call native component event +R-->>C : Callback value +C->>H : onValueChange(value) +H-->>C : Update internal state +C-->>P : onValueChange(value) +Note over C,P : Parent component can combine Form/FormItem for validation and linked fields +``` + +Diagram Source + +- [frontend/antd/auto-complete/auto-complete.tsx:32-148](file://frontend/antd/auto-complete/auto-complete.tsx#L32-L148) +- [frontend/antd/cascader/cascader.tsx:39-204](file://frontend/antd/cascader/cascader.tsx#L39-L204) +- [frontend/antd/checkbox/checkbox.tsx:4-19](file://frontend/antd/checkbox/checkbox.tsx#L4-L19) +- [frontend/antd/color-picker/color-picker.tsx:24-103](file://frontend/antd/color-picker/color-picker.tsx#L24-L103) +- [frontend/antd/date-picker/date-picker.tsx:40-231](file://frontend/antd/date-picker/date-picker.tsx#L40-L231) +- [frontend/antd/radio/radio.tsx:6-29](file://frontend/antd/radio/radio.tsx#L6-L29) +- [frontend/antd/rate/rate.tsx:12-42](file://frontend/antd/rate/rate.tsx#L12-L42) +- [frontend/antd/slider/slider.tsx:37-94](file://frontend/antd/slider/slider.tsx#L37-L94) +- [frontend/antd/switch/switch.tsx:6-39](file://frontend/antd/switch/switch.tsx#L6-L39) +- [frontend/antd/time-picker/time-picker.tsx:37-198](file://frontend/antd/time-picker/time-picker.tsx#L37-L198) + +## Component Details + +### AutoComplete + +- Data binding: receives string value via onValueChange; onChange passes through native callback +- Slots: supports children, dropdownRender, popupRender, notFoundContent, allowClear.clearIcon +- Options: supports rendering via options or slots.children +- Filtering: filterOption can customize filter logic or use default behavior + +```mermaid +flowchart TD +Start(["Start"]) --> Bind["Bind onValueChange"] +Bind --> Render["Render options/slots"] +Render --> UserInput["User input"] +UserInput --> Filter{"Custom filter?"} +Filter -- Yes --> UseFn["Use filterOption function"] +Filter -- No --> Default["Default filtering"] +UseFn --> Change["Trigger onChange and update value"] +Default --> Change +Change --> End(["End"]) +``` + +Diagram Source + +- [frontend/antd/auto-complete/auto-complete.tsx:32-148](file://frontend/antd/auto-complete/auto-complete.tsx#L32-L148) + +Section Source + +- [frontend/antd/auto-complete/auto-complete.tsx:1-151](file://frontend/antd/auto-complete/auto-complete.tsx#L1-L151) + +### Cascader + +- Data binding: onValueChange receives an array (path value); onChange passes through +- Slots: suffixIcon, prefix, removeIcon, expandIcon, displayRender, tagRender, dropdownRender, popupRender, showSearch.render, maxTagPlaceholder +- Search: showSearch supports object configuration and slot rendering +- Dynamic loading: onLoadData corresponds to native loadData + +```mermaid +sequenceDiagram +participant U as "User" +participant C as "Cascader" +participant R as "Antd Cascader" +U->>C : Expand/select node +C->>R : Render panel/search +R-->>C : Return selected value +C-->>U : onValueChange(path array) +``` + +Diagram Source + +- [frontend/antd/cascader/cascader.tsx:19-204](file://frontend/antd/cascader/cascader.tsx#L19-L204) + +Section Source + +- [frontend/antd/cascader/cascader.tsx:1-207](file://frontend/antd/cascader/cascader.tsx#L1-L207) + +### Checkbox + +- Data binding: onValueChange receives a boolean value +- Events: onChange passes through native event + +Section Source + +- [frontend/antd/checkbox/checkbox.tsx:1-22](file://frontend/antd/checkbox/checkbox.tsx#L1-L22) + +### ColorPicker + +- Data binding: onValueChange receives a string or gradient color array; value_format controls the output format (rgb/hex/hsb) +- Slots: panelRender, showText +- Gradient: when isGradient(), outputs each color segment according to value_format + +Section Source + +- [frontend/antd/color-picker/color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) + +### DatePicker + +- Data binding: onValueChange receives a second-level timestamp (including array scenario); onChange/onPanelChange passes through +- Internal format: unified dayjs conversion, external output as second-level timestamp +- Slots: renderExtraFooter, cellRender, panelRender, prevIcon/prefix/nextIcon/suffixIcon/superNextIcon/superPrevIcon, allowClear.clearIcon +- Presets: presets are rendered via renderItems + +```mermaid +flowchart TD +In(["Input date"]) --> Parse["dayjs parse"] +Parse --> Normalize["Normalize to second-level timestamp"] +Normalize --> Emit["onValueChange/onChange"] +Emit --> Out(["Output to parent component"]) +``` + +Diagram Source + +- [frontend/antd/date-picker/date-picker.tsx:14-38](file://frontend/antd/date-picker/date-picker.tsx#L14-L38) +- [frontend/antd/date-picker/date-picker.tsx:126-170](file://frontend/antd/date-picker/date-picker.tsx#L126-L170) + +Section Source + +- [frontend/antd/date-picker/date-picker.tsx:1-234](file://frontend/antd/date-picker/date-picker.tsx#L1-L234) + +### Form / FormItem / FormItem.Rule / FormProvider + +- Form: container that provides Provider injection and layout capability +- FormItem: field container holding label, help, required, validateStatus, etc. +- FormItem.Rule: validation rules supporting required, regex, custom functions, async validation +- FormProvider: global configuration and context + +```mermaid +classDiagram +class Form { ++provider() ++submit() ++resetFields() +} +class FormItem { ++label ++help ++required ++validateStatus +} +class FormItemRule { ++rules ++trigger +} +class FormProvider { ++config +} +Form --> FormItem : "contains" +FormItem --> FormItemRule : "uses" +Form --> FormProvider : "injects" +``` + +Diagram Source + +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/form/item/form.item.tsx](file://frontend/antd/form/item/form.item.tsx) +- [frontend/antd/form/item/rule/form.item.rule.tsx](file://frontend/antd/form/item/rule/form.item.rule.tsx) +- [frontend/antd/form/provider/form.provider.tsx](file://frontend/antd/form/provider/form.provider.tsx) + +Section Source + +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/form/item/form.item.tsx](file://frontend/antd/form/item/form.item.tsx) +- [frontend/antd/form/item/rule/form.item.rule.tsx](file://frontend/antd/form/item/rule/form.item.rule.tsx) +- [frontend/antd/form/provider/form.provider.tsx](file://frontend/antd/form/provider/form.provider.tsx) + +### Input / TextArea / Search / Password / OTP + +- Unified pattern: all receive the latest value via onValueChange; onChange passes through native event +- Extensions: Search, Password, OTP each provide specific behavior and styles + +Section Source + +- [frontend/antd/input/input.tsx](file://frontend/antd/input/input.tsx) +- [frontend/antd/input/otp/input.otp.tsx](file://frontend/antd/input/otp/input.otp.tsx) +- [frontend/antd/input/password/input.password.tsx](file://frontend/antd/input/password/input.password.tsx) +- [frontend/antd/input/search/input.search.tsx](file://frontend/antd/input/search/input.search.tsx) +- [frontend/antd/input/textarea/input.textarea.tsx](file://frontend/antd/input/textarea/input.textarea.tsx) + +### InputNumber + +- Data binding: onValueChange receives a numeric value; onChange passes through +- Use cases: step control, range, precision control + +Section Source + +- [frontend/antd/input-number/input-number.tsx](file://frontend/antd/input-number/input-number.tsx) + +### Select / Option + +- Data binding: onValueChange receives string/number/array; onChange passes through +- Sub-items: Option is injected via renderItems, supporting disabled, grouping, etc. + +Section Source + +- [frontend/antd/select/select.tsx](file://frontend/antd/select/select.tsx) +- [frontend/antd/select/option/select.option.tsx](file://frontend/antd/select/option/select.option.tsx) + +### Slider / Marks + +- Data binding: onValueChange receives number or number[]; onChange passes through +- Marks: rendered via slots.children or slots.label + +Section Source + +- [frontend/antd/slider/slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) + +### Radio + +- Data binding: onValueChange receives a boolean value; onChange passes through +- Theme: style variables injected via token.lineWidth + +Section Source + +- [frontend/antd/radio/radio.tsx:1-32](file://frontend/antd/radio/radio.tsx#L1-L32) + +### Rate + +- Data binding: onValueChange receives a numeric value; onChange passes through +- Slots: character supports custom rating icons + +Section Source + +- [frontend/antd/rate/rate.tsx:1-45](file://frontend/antd/rate/rate.tsx#L1-L45) + +### Switch + +- Data binding: onValueChange receives a boolean value; onChange passes through +- Slots: checkedChildren, unCheckedChildren + +Section Source + +- [frontend/antd/switch/switch.tsx:1-42](file://frontend/antd/switch/switch.tsx#L1-L42) + +### TimePicker + +- Data binding: onValueChange receives a second-level timestamp; onChange/onPanelChange/onCalendarChange passes through +- Internal format: unified dayjs conversion + +Section Source + +- [frontend/antd/time-picker/time-picker.tsx:1-201](file://frontend/antd/time-picker/time-picker.tsx#L1-L201) + +### Transfer + +- Data binding: onValueChange receives target list key values; onChange passes through +- Use cases: multi-select move, sorting, search + +Section Source + +- [frontend/antd/transfer/transfer.tsx](file://frontend/antd/transfer/transfer.tsx) + +### TreeSelect + +- Data binding: onValueChange receives string/array; onChange passes through +- Sub-items: TreeNode is injected via renderItems + +Section Source + +- [frontend/antd/tree-select/tree-select.tsx](file://frontend/antd/tree-select/tree-select.tsx) + +### Upload + +- Data binding: onValueChange receives a file list; onChange passes through +- Use cases: drag and drop, preview, size/type restrictions + +Section Source + +- [frontend/antd/upload/upload.tsx](file://frontend/antd/upload/upload.tsx) + +## Dependency Analysis + +- Inter-component coupling: most components are decoupled through hooks and utility functions, reducing coupling to specific implementations +- Slots and context: withItemsContextProvider and renderItems allow child components to be uniformly injected and rendered +- Event bridging: useValueChange aligns onChange with onValueChange, ensuring parent components subscribe consistently + +```mermaid +graph LR +Utils["utils/*
hooks/renderItems/renderParamsSlot"] --> Auto["AutoComplete"] +Utils --> Cascader +Utils --> ColorPicker +Utils --> DatePicker +Utils --> Slider +Utils --> TimePicker +Form["Form/FormItem/Rule/Provider"] --> Auto +Form --> Cascader +Form --> DatePicker +Form --> TimePicker +``` + +Diagram Source + +- [frontend/antd/auto-complete/auto-complete.tsx:1-151](file://frontend/antd/auto-complete/auto-complete.tsx#L1-L151) +- [frontend/antd/cascader/cascader.tsx:1-207](file://frontend/antd/cascader/cascader.tsx#L1-L207) +- [frontend/antd/color-picker/color-picker.tsx:1-106](file://frontend/antd/color-picker/color-picker.tsx#L1-L106) +- [frontend/antd/date-picker/date-picker.tsx:1-234](file://frontend/antd/date-picker/date-picker.tsx#L1-L234) +- [frontend/antd/slider/slider.tsx:1-97](file://frontend/antd/slider/slider.tsx#L1-L97) +- [frontend/antd/time-picker/time-picker.tsx:1-201](file://frontend/antd/time-picker/time-picker.tsx#L1-L201) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/form/item/form.item.tsx](file://frontend/antd/form/item/form.item.tsx) +- [frontend/antd/form/item/rule/form.item.rule.tsx](file://frontend/antd/form/item/rule/form.item.rule.tsx) +- [frontend/antd/form/provider/form.provider.tsx](file://frontend/antd/form/provider/form.provider.tsx) + +## Performance and Large Data Optimization + +- List rendering + - Use virtual scrolling: in Select/Cascader/TreeSelect, prioritize virtualization solutions to reduce the number of DOM nodes + - Lazy loading: Cascader's onLoadData only requests data when expanded, avoiding loading everything at once +- Input performance + - Debounce/throttle: add debounce to AutoComplete's filterOption or search-type inputs + - Batch updates: use batch submission in Form to reduce re-render counts +- Date and time + - Use dayjs internally, output second-level timestamps externally to avoid repeated parsing + - Render presets and panels with memoization to reduce unnecessary recalculations +- Graphics and colors + - ColorPicker computes output in gradient scenarios according to value_format, avoiding repeated formatting + +## Accessibility and Keyboard Navigation + +- Semantic labels: Radio/Checkbox/Switch, etc. provide clear aria attributes and label associations +- Keyboard navigation: DatePicker/TimePicker/Select/Slider support standard operations such as Tab/Enter/arrow keys +- Focus management: getPopupContainer mounts the overlay inside a container to avoid focus loss +- Screen readers: FormItem provides help/status text to assist in describing errors and prompt information + +## Complex Form Design Patterns and Data Flow + +- Multi-step forms: use FormProvider global configuration combined with onPanelChange and linked fields +- Conditional rendering: dynamically show/hide sections based on field values, combined with FormItem's required and Rule +- Dynamic fields: inject Option/TreeNode/Mark via renderItems to implement dynamic add/edit/delete +- Linked fields and computation: trigger side effects in onValueChange (such as calculating total price, filling in address), and update other fields via Form.setFieldsValue + +```mermaid +sequenceDiagram +participant F as "Form" +participant I1 as "FormItem A" +participant I2 as "FormItem B" +F->>I1 : User input +I1-->>F : onValueChange(newValueA) +F->>I2 : setFieldsValue(linked field) +I2-->>F : onValueChange(newValueB) +F-->>F : Validate and submit +``` + +Diagram Source + +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/antd/form/item/form.item.tsx](file://frontend/antd/form/item/form.item.tsx) +- [frontend/antd/form/item/rule/form.item.rule.tsx](file://frontend/antd/form/item/rule/form.item.rule.tsx) + +## Troubleshooting Guide + +- Event not triggered + - Check whether onValueChange is passed in correctly; confirm whether onChange has been overridden +- Value not updating + - In controlled mode, confirm whether the parent component calls setState in time; check the dependencies of useValueChange +- Slot not working + - Confirm whether slots.key is consistent with the component's contract; check renderParamsSlot's key +- Validation not working + - Check FormItem.Rule's trigger and rules configuration; confirm the timing of Form.validateFields call +- Date anomaly + - Confirm that the input is a second-level timestamp; check the dayjs conversion chain and defaultValue/defaultPickerValue + +Section Source + +- [frontend/antd/auto-complete/auto-complete.tsx:32-148](file://frontend/antd/auto-complete/auto-complete.tsx#L32-L148) +- [frontend/antd/date-picker/date-picker.tsx:126-170](file://frontend/antd/date-picker/date-picker.tsx#L126-L170) +- [frontend/antd/time-picker/time-picker.tsx:109-143](file://frontend/antd/time-picker/time-picker.tsx#L109-L143) +- [frontend/antd/form/item/rule/form.item.rule.tsx](file://frontend/antd/form/item/rule/form.item.rule.tsx) + +## Conclusion + +This project achieves high consistency and strong extensibility for Ant Design components on the frontend through unified wrapping patterns and hooks utilities. With a clear practical path centered on data binding, validation rules, formatting options, and complex form design, it is recommended to combine virtual scrolling, lazy loading, and debounce strategies in actual business scenarios to continuously optimize performance, while improving accessibility and keyboard navigation to enhance the user experience. diff --git a/.wiki/en/Ant Design Components/Data Entry Components/DateTime Components.md b/.wiki/en/Ant Design Components/Data Entry Components/DateTime Components.md new file mode 100644 index 00000000..e599c10b --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Entry Components/DateTime Components.md @@ -0,0 +1,463 @@ +# DateTime Components + + +**Files referenced in this document** +- [frontend/antd/date-picker/date-picker.tsx](file://frontend/antd/date-picker/date-picker.tsx) +- [frontend/antd/date-picker/context.ts](file://frontend/antd/date-picker/context.ts) +- [frontend/antd/date-picker/preset/date-picker.preset.tsx](file://frontend/antd/date-picker/preset/date-picker.preset.tsx) +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx) +- [frontend/antd/time-picker/time-picker.tsx](file://frontend/antd/time-picker/time-picker.tsx) +- [frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx](file://frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx) +- [frontend/antd/calendar/calendar.tsx](file://frontend/antd/calendar/calendar.tsx) +- [frontend/antd/statistic/statistic.tsx](file://frontend/antd/statistic/statistic.tsx) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx](file://frontend/antd/statistic/countdown/statistic.countdown.tsx) +- [frontend/antd/statistic/timer/statistic.timer.tsx](file://frontend/antd/statistic/timer/statistic.timer.tsx) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts](file://frontend/antd/config-provider/locales.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically covers the "date and time" related components and capabilities in the ModelScope Studio frontend, including: + +- DatePicker and DateRangePicker +- TimePicker and TimeRangePicker +- Calendar +- Countdown and Timer within Statistic +- Date formatting, timezone and time unit conversion, range selection, quick options (presets), and disabled date/time +- Localization (ConfigProvider) and internationalization configuration (locales) +- Validation rules and business scenario applications +- Accessibility and keyboard navigation +- Handling patterns and best practices for complex date/time scenarios + +## Project Structure + +The frontend implementation around date/time components is primarily located in the antd-prefixed directory, using Svelte + React wrapping (sveltify) to bridge Ant Design components, with ConfigProvider providing unified theming and internationalization. + +```mermaid +graph TB +subgraph "Date/Time Components" +DP["DatePicker"] +DRP["DateRangePicker"] +TP["TimePicker"] +TRP["TimeRangePicker"] +CAL["Calendar"] +STAT["Statistic"] +CD["Statistic.Countdown"] +TM["Statistic.Timer"] +end +subgraph "Bridge Layer" +Sveltify["sveltify Wrapper"] +Slots["Slot Rendering
renderParamsSlot/ReactSlot"] +Hooks["Utility Hooks
useFunction/useMemo"] +end +subgraph "Internationalization and Theming" +CP["ConfigProvider
Theme/Popup Container/Empty State"] +LOCALES["locales.ts
Multilingual Mapping and On-demand Loading"] +end +DP --> Sveltify +DRP --> Sveltify +TP --> Sveltify +TRP --> Sveltify +CAL --> Sveltify +STAT --> Sveltify +CD --> Sveltify +TM --> Sveltify +Sveltify --> Slots +Sveltify --> Hooks +CP --> LOCALES +CP --> Sveltify +``` + +Diagram Source + +- [frontend/antd/date-picker/date-picker.tsx:40-231](file://frontend/antd/date-picker/date-picker.tsx#L40-L231) +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:29-245](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L29-L245) +- [frontend/antd/time-picker/time-picker.tsx:37-198](file://frontend/antd/time-picker/time-picker.tsx#L37-L198) +- [frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx:26-207](file://frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx#L26-L207) +- [frontend/antd/calendar/calendar.tsx:17-99](file://frontend/antd/calendar/calendar.tsx#L17-L99) +- [frontend/antd/statistic/statistic.tsx:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:6-24](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L6-L24) +- [frontend/antd/statistic/timer/statistic.timer.tsx:10-26](file://frontend/antd/statistic/timer/statistic.timer.tsx#L10-L26) +- [frontend/antd/config-provider/config-provider.tsx:53-151](file://frontend/antd/config-provider/config-provider.tsx#L53-L151) +- [frontend/antd/config-provider/locales.ts:89-863](file://frontend/antd/config-provider/locales.ts#L89-L863) + +Section Source + +- [frontend/antd/date-picker/date-picker.tsx:1-234](file://frontend/antd/date-picker/date-picker.tsx#L1-L234) +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:1-248](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L1-L248) +- [frontend/antd/time-picker/time-picker.tsx:1-201](file://frontend/antd/time-picker/time-picker.tsx#L1-L201) +- [frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx:1-211](file://frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx#L1-L211) +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [frontend/antd/statistic/statistic.tsx:1-34](file://frontend/antd/statistic/statistic.tsx#L1-L34) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:1-27](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L1-L27) +- [frontend/antd/statistic/timer/statistic.timer.tsx:1-29](file://frontend/antd/statistic/timer/statistic.timer.tsx#L1-L29) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) + +## Core Components + +- DatePicker: supports date and time selection, range selection, preset shortcuts, disabled date/time, panel switch callbacks, custom popup containers, etc. +- TimePicker: supports time selection, range selection, disabled time, panel switching, and calendar linked callbacks. +- Calendar: provides a full month view, supports custom cell rendering, header rendering, and valid range restriction. +- Statistic: basic statistic display; both Countdown and Timer accept values in seconds and internally auto-convert to milliseconds to pass to the underlying component. + +Section Source + +- [frontend/antd/date-picker/date-picker.tsx:40-170](file://frontend/antd/date-picker/date-picker.tsx#L40-L170) +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:29-177](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L29-L177) +- [frontend/antd/time-picker/time-picker.tsx:37-143](file://frontend/antd/time-picker/time-picker.tsx#L37-L143) +- [frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx:26-146](file://frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx#L26-L146) +- [frontend/antd/calendar/calendar.tsx:17-94](file://frontend/antd/calendar/calendar.tsx#L17-L94) +- [frontend/antd/statistic/statistic.tsx:8-31](file://frontend/antd/statistic/statistic.tsx#L8-L31) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:6-21](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L6-L21) +- [frontend/antd/statistic/timer/statistic.timer.tsx:10-23](file://frontend/antd/statistic/timer/statistic.timer.tsx#L10-L23) + +## Architecture Overview + +Components are uniformly wrapped through sveltify around Ant Design components, using dayjs for date parsing and formatting. They expose a unified second-level timestamp interface externally, then internally convert to milliseconds to pass to the underlying component. ConfigProvider handles theme algorithms, popup containers, empty state rendering, and internationalization (Antd language packs and dayjs language packs). + +```mermaid +sequenceDiagram +participant U as "User" +participant C as "Component (e.g. DatePicker)" +participant F as "Formatting function (formatDayjs/formatDate)" +participant D as "dayjs" +participant A as "Antd Component" +U->>C : Select date/time +C->>F : Input value (may be seconds/milliseconds/string) +F->>D : Parse to dayjs object +D-->>F : dayjs instance +F-->>C : Format to second-level timestamp +C->>A : Pass millisecond value and callback parameters +A-->>C : Callback triggered (onChange/onPanelChange) +C-->>U : Trigger onValueChange/onChange (second-level timestamp) +``` + +Diagram Source + +- [frontend/antd/date-picker/date-picker.tsx:14-38](file://frontend/antd/date-picker/date-picker.tsx#L14-L38) +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:14-27](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L14-L27) +- [frontend/antd/time-picker/time-picker.tsx:11-35](file://frontend/antd/time-picker/time-picker.tsx#L11-L35) +- [frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx:11-24](file://frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx#L11-L24) + +## Detailed Component Analysis + +### DatePicker + +- Data flow and formatting + - Input supports number (seconds), string, dayjs objects; internally unified to dayjs. + - Output is uniformly a second-level timestamp for easy backend or cross-component passing. +- Key capabilities + - showTime supports object form, and defaultValue will also be formatted. + - disabledDate/disabledTime customize disabled logic. + - presets shortcuts: injected via context, supports dynamic rendering and formatting. + - cellRender/panelRender slot-based rendering. + - getPopupContainer customizes popup container. +- Event callbacks + - onValueChange: unified value change callback (second-level). + - onChange/onPanelChange: both native callback and secondary wrapped callback are available. + +```mermaid +flowchart TD +Start(["Start"]) --> Parse["Parse input to dayjs"] +Parse --> ShowTime{"Time enabled?"} +ShowTime --> |Yes| FormatST["Format default time"] +ShowTime --> |No| SkipST["Skip default time"] +FormatST --> Presets["Merge/format preset items"] +SkipST --> Presets +Presets --> Render["Render component and bind callbacks"] +Render --> End(["End"]) +``` + +Diagram Source + +- [frontend/antd/date-picker/date-picker.tsx:91-161](file://frontend/antd/date-picker/date-picker.tsx#L91-L161) + +Section Source + +- [frontend/antd/date-picker/date-picker.tsx:1-234](file://frontend/antd/date-picker/date-picker.tsx#L1-L234) +- [frontend/antd/date-picker/context.ts:1-7](file://frontend/antd/date-picker/context.ts#L1-L7) +- [frontend/antd/date-picker/preset/date-picker.preset.tsx:1-14](file://frontend/antd/date-picker/preset/date-picker.preset.tsx#L1-L14) + +### DateRangePicker + +- Data flow + - Input/output are both two-element arrays [start, end], with elements as second-level timestamps. + - Default value, current value, and panel value are all formatted and mapped as arrays using dayjs. +- Key capabilities + - showTime's defaultValue supports array mapping. + - presets also support array formatting. + - separator supports slot-based separator. +- Event callbacks + - onValueChange, onChange, onPanelChange, onCalendarChange all return second-level arrays. + +```mermaid +sequenceDiagram +participant U as "User" +participant RP as "DateRangePicker" +participant F as "formatDates" +participant A as "Antd.RangePicker" +U->>RP : Select start and end dates +RP->>F : Input [start, end] (may be dayjs/seconds) +F-->>RP : Return [start, end] (seconds) +RP->>A : Pass millisecond values and callbacks +A-->>RP : Callback triggered +RP-->>U : onValueChange/onChange (second-level array) +``` + +Diagram Source + +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:21-27](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L21-L27) +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:165-177](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L165-L177) + +Section Source + +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:1-248](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L1-L248) + +### TimePicker + +- Data flow + - Input supports number (seconds), string, dayjs; uniformly formatted to dayjs. + - Output is a second-level value (number or string), ensuring consistency via onValueChange. +- Key capabilities + - disabledTime/disabledDate controls available time slots. + - cellRender/panelRender supports slots. + - onCalendarChange and onPanelChange. +- Event callbacks + - onValueChange receives second-level values; onChange/onPanelChange are also formatted before callback. + +```mermaid +flowchart TD +S(["Start"]) --> V["Validate/format input to dayjs"] +V --> DT{"Disabled time?"} +DT --> |Yes| Block["Block selection"] +DT --> |No| RenderT["Render TimePicker"] +RenderT --> Evt["Trigger onChange/onPanelChange/onCalendarChange"] +Evt --> Out["Format to seconds and callback onValueChange"] +Out --> End(["End"]) +``` + +Diagram Source + +- [frontend/antd/time-picker/time-picker.tsx:88-143](file://frontend/antd/time-picker/time-picker.tsx#L88-L143) + +Section Source + +- [frontend/antd/time-picker/time-picker.tsx:1-201](file://frontend/antd/time-picker/time-picker.tsx#L1-L201) + +### TimeRangePicker + +- Data flow + - Input/output are [start, end] arrays with elements as second-level timestamps. + - Default value, current value, and panel value are all formatted as array mappings. +- Key capabilities + - disabledTime/disabledDate controls available time slots. + - separator supports slot-based separator. +- Event callbacks + - onValueChange, onChange, onPanelChange, onCalendarChange all return second-level arrays. + +Section Source + +- [frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx:1-211](file://frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx#L1-L211) + +### Calendar + +- Data flow + - Input/output are uniformly second-level timestamps; internally converted to milliseconds for Antd Calendar. +- Key capabilities + - validRange restricts the valid range. + - cellRender/fullCellRender/headerRender support slots. + - onSelect/onPanelChange/onChange uniformly callback second-level values. +- Note + - disabledDate is not directly exposed; it can be controlled by passing values from external logic. + +Section Source + +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) + +### Statistic / Countdown / Timer + +- Statistic + - Supports slot-based title/prefix/suffix/formatter. +- Statistic.Countdown + - Input value supports seconds or milliseconds; internally converts seconds to milliseconds. + - Supports slot-based title/prefix/suffix. +- Statistic.Timer + - Input value supports seconds or milliseconds; internally converts seconds to milliseconds. + - Supports slot-based title/prefix/suffix. + +```mermaid +sequenceDiagram +participant U as "User" +participant CD as "Countdown" +participant TM as "Timer" +participant A as "Antd.Statistic" +U->>CD : Set target time (seconds) +CD->>CD : Convert seconds to milliseconds +CD->>A : Render countdown +A-->>U : Display remaining time +U->>TM : Set initial value (seconds) +TM->>TM : Convert seconds to milliseconds +TM->>A : Render timer +A-->>U : Display elapsed time +``` + +Diagram Source + +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:11-21](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L11-L21) +- [frontend/antd/statistic/timer/statistic.timer.tsx:13-23](file://frontend/antd/statistic/timer/statistic.timer.tsx#L13-L23) + +Section Source + +- [frontend/antd/statistic/statistic.tsx:1-34](file://frontend/antd/statistic/statistic.tsx#L1-L34) +- [frontend/antd/statistic/countdown/statistic.countdown.tsx:1-27](file://frontend/antd/statistic/countdown/statistic.countdown.tsx#L1-L27) +- [frontend/antd/statistic/timer/statistic.timer.tsx:1-29](file://frontend/antd/statistic/timer/statistic.timer.tsx#L1-L29) + +## Dependency Analysis + +- Components to utilities + - Uses dayjs for date parsing and formatting. + - Uses useFunction/useMemo to stabilize callbacks and computations. + - Uses renderParamsSlot/ReactSlot for slot-based rendering. +- Components to context + - DatePicker presets are injected and consumed via createItemsContext. +- Internationalization and theming + - ConfigProvider is responsible for: + - Theme algorithms (dark/compact). + - Popup containers and target container functions. + - Empty state rendering. + - Internationalization: Antd language packs and dayjs language packs loaded on demand. + - locales.ts provides mapping from language codes to language packs with async loading. + +```mermaid +graph LR +DP["DatePicker"] --> Dayjs["dayjs"] +DRP["DateRangePicker"] --> Dayjs +TP["TimePicker"] --> Dayjs +TRP["TimeRangePicker"] --> Dayjs +CAL["Calendar"] --> Dayjs +DP --> Hooks["useFunction/useMemo"] +DRP --> Hooks +TP --> Hooks +TRP --> Hooks +CAL --> Hooks +DP --> Slots["renderParamsSlot/ReactSlot"] +DRP --> Slots +TP --> Slots +TRP --> Slots +CAL --> Slots +CP["ConfigProvider"] --> LOCALES["locales.ts"] +CP --> Theme["Theme Algorithm/Container/Empty State"] +``` + +Diagram Source + +- [frontend/antd/date-picker/date-picker.tsx:1-11](file://frontend/antd/date-picker/date-picker.tsx#L1-L11) +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:1-7](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L1-L7) +- [frontend/antd/time-picker/time-picker.tsx:1-6](file://frontend/antd/time-picker/time-picker.tsx#L1-L6) +- [frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx:1-6](file://frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx#L1-L6) +- [frontend/antd/calendar/calendar.tsx:1-6](file://frontend/antd/calendar/calendar.tsx#L1-L6) +- [frontend/antd/config-provider/config-provider.tsx:1-11](file://frontend/antd/config-provider/config-provider.tsx#L1-L11) +- [frontend/antd/config-provider/locales.ts:1-10](file://frontend/antd/config-provider/locales.ts#L1-L10) + +Section Source + +- [frontend/antd/date-picker/date-picker.tsx:1-234](file://frontend/antd/date-picker/date-picker.tsx#L1-L234) +- [frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx:1-248](file://frontend/antd/date-picker/range-picker/date-picker.range-picker.tsx#L1-L248) +- [frontend/antd/time-picker/time-picker.tsx:1-201](file://frontend/antd/time-picker/time-picker.tsx#L1-L201) +- [frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx:1-211](file://frontend/antd/time-picker/range-picker/time-picker.range-picker.tsx#L1-L211) +- [frontend/antd/calendar/calendar.tsx:1-102](file://frontend/antd/calendar/calendar.tsx#L1-L102) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) + +## Performance Considerations + +- Formatting and caching + - Use useMemo to cache formatted dayjs values to avoid repeated computation. + - useFunction stabilizes callback references to reduce unnecessary re-renders. +- On-demand loading + - ConfigProvider async-loads Antd and dayjs language resources when locale changes, reducing initial bundle size. +- Rendering optimization + - Slot-based rendering only mounts when needed, reducing irrelevant node overhead. +- Recommendations + - For wide range selection or frequent updates, apply throttle/debounce at the parent level as much as possible. + - When there are many preset items, consider lazy loading and virtualized rendering. + +## Troubleshooting Guide + +- Date not displayed or displayed incorrectly + - Check whether the input is a second-level timestamp; the component internally converts it to milliseconds. + - Confirm that the dayjs language has been correctly set (ConfigProvider sets it automatically). +- Internationalization not taking effect + - Confirm that the locale parameter format conforms to the specification (e.g., zh_CN, en_US); locales.ts contains the corresponding mapping. + - If the language pack fails to load, check network and build configuration. +- Preset items not displayed + - Confirm that preset items have been injected via context, and ensure the value format is dayjs. +- Disabled logic not working + - disabledDate/disabledTime should be functions; ensure stable references by wrapping with useFunction. +- Callback not triggered + - Confirm that using onValueChange and onChange simultaneously does not cause state inconsistency. + - Check whether getPopupContainer correctly returns the container. + +Section Source + +- [frontend/antd/config-provider/config-provider.tsx:96-105](file://frontend/antd/config-provider/config-provider.tsx#L96-L105) +- [frontend/antd/date-picker/date-picker.tsx:86-90](file://frontend/antd/date-picker/date-picker.tsx#L86-L90) +- [frontend/antd/time-picker/time-picker.tsx:83-87](file://frontend/antd/time-picker/time-picker.tsx#L83-L87) + +## Conclusion + +This date/time component system is built on Ant Design and provides complete capabilities from dates and times to calendar, countdown, and timer through a unified formatting and slot-based mechanism. With ConfigProvider's theming and internationalization support, it can meet complex business requirements in multi-language and multi-theme scenarios. It is recommended to follow the "unified second-level timestamp" data contract in actual use, combined with useMemo/useFunction for performance optimization, and extend UI expressiveness through slot-based customization. + +## Appendix + +### Localization and Internationalization Configuration + +- ConfigProvider + - Supports themeMode to switch dark/compact algorithms. + - Supports getPopupContainer/getTargetContainer to customize containers. + - Supports renderEmpty for custom empty state. + - The locale parameter supports language codes; locales.ts provides mapping and async loading. +- locales.ts + - Provides 80+ language code mappings with on-demand loading of Antd and dayjs language packs. + - Default language is en_US; dayjs default language is en. + +Section Source + +- [frontend/antd/config-provider/config-provider.tsx:53-151](file://frontend/antd/config-provider/config-provider.tsx#L53-L151) +- [frontend/antd/config-provider/locales.ts:89-863](file://frontend/antd/config-provider/locales.ts#L89-L863) + +### Accessibility and Keyboard Navigation + +- Recommendations + - Use standard semantic labels and native interactions to ensure keyboard accessibility. + - Mount popup layers inside focusable containers via getPopupContainer. + - Preserve focus management and accessibility attributes in custom cellRender/headerRender. + - For countdown/timer, provide clear titles and unit hints for screen reader recognition. + +### Complex Scenario Handling Patterns and Best Practices + +- Cross-timezone scenarios + - Recommended to uniformly store and transmit UTC second-level timestamps, and perform localized display in the presentation layer based on ConfigProvider's dayjs language and locale settings. +- Range selection + - Use DateRangePicker/TimeRangePicker and validate start/end order and validity at the parent level. +- Preset shortcuts + - Inject preset items via DatePickerPreset, ensure values are in dayjs format to avoid display anomalies from format inconsistencies. +- Validation rules + - Combine disabledDate/disabledTime with min/max date restrictions to form a "disable + validate" dual safeguard. +- Performance + - In large list/high-frequency update scenarios, prioritize useMemo/useCallback to stabilize props and callbacks to reduce re-renders. diff --git a/.wiki/en/Ant Design Components/Data Entry Components/Input Components.md b/.wiki/en/Ant Design Components/Data Entry Components/Input Components.md new file mode 100644 index 00000000..a19ce6e3 --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Entry Components/Input Components.md @@ -0,0 +1,516 @@ +# Input Components + + +**Files referenced in this document** +- [input.tsx](file://frontend/antd/input/input.tsx) +- [input-number.tsx](file://frontend/antd/input-number/input-number.tsx) +- [auto-complete.tsx](file://frontend/antd/auto-complete/auto-complete.tsx) +- [mentions.tsx](file://frontend/antd/mentions/mentions.tsx) +- [input.password.tsx](file://frontend/antd/input/password/input.password.tsx) +- [input.search.tsx](file://frontend/antd/input/search/input.search.tsx) +- [input.textarea.tsx](file://frontend/antd/input/textarea/input.textarea.tsx) +- [input.otp.tsx](file://frontend/antd/input/otp/input.otp.tsx) +- [context.ts](file://frontend/antd/auto-complete/context.ts) +- [hooks/useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [renderItems.ts](file://frontend/utils/renderItems.ts) +- [renderParamsSlot.ts](file://frontend/utils/renderParamsSlot.ts) +- [omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +This section covers the usage and extension of "input-type data entry components", including: Input, InputNumber, AutoComplete, Mentions, InputPassword, InputSearch, InputTextarea, and InputOTP. The document focuses on: + +- How input validation, formatting, debounce, and character limiting are implemented within components, and best practices +- Accessibility and keyboard navigation support +- Integration patterns with form validation +- Performance optimization strategies for large-scale data input scenarios + +## Project Structure + +Input components are all located in the frontend Ant Design wrapper layer, using a unified pattern of "sveltify wrapping + React Slot + Hooks value synchronization" to ensure alignment with Ant Design component properties while providing more flexible slot-based and functional callback capabilities. + +```mermaid +graph TB +subgraph "Antd Input Component Wrappers" +A["Input
Text Input"] +B["InputNumber
Numeric Input"] +C["AutoComplete
Auto Complete"] +D["Mentions
Mentions"] +E["InputPassword
Password Input"] +F["InputSearch
Search Input"] +G["InputTextarea
Multiline Textarea"] +H["InputOTP
One-Time Password Input"] +end +subgraph "Common Utilities and Hooks" +U1["useValueChange
Value Change Sync"] +U2["useFunction
Function Wrapping"] +U3["renderItems
Option Rendering"] +U4["renderParamsSlot
Parameterized Slots"] +U5["omitUndefinedProps
Property Trimming"] +end +A --> U1 +A --> U2 +A --> U4 +A --> U5 +B --> U1 +B --> U2 +B --> U4 +C --> U1 +C --> U2 +C --> U3 +C --> U4 +C --> U5 +C -.-> X["AutoComplete Context"] +D --> U1 +D --> U2 +D --> U3 +D --> U4 +D --> U5 +E --> U1 +E --> U2 +E --> U4 +E --> U5 +F --> U1 +F --> U2 +F --> U4 +F --> U5 +G --> U1 +G --> U2 +G --> U4 +G --> U5 +H --> U1 +H --> U2 +H --> U4 +``` + +Diagram Source + +- [input.tsx:10-116](file://frontend/antd/input/input.tsx#L10-L116) +- [input-number.tsx:7-89](file://frontend/antd/input-number/input-number.tsx#L7-L89) +- [auto-complete.tsx:32-148](file://frontend/antd/auto-complete/auto-complete.tsx#L32-L148) +- [mentions.tsx:11-77](file://frontend/antd/mentions/mentions.tsx#L11-L77) +- [input.password.tsx:10-126](file://frontend/antd/input/password/input.password.tsx#L10-L126) +- [input.search.tsx:10-123](file://frontend/antd/input/search/input.search.tsx#L10-L123) +- [input.textarea.tsx:10-88](file://frontend/antd/input/textarea/input.textarea.tsx#L10-L88) +- [input.otp.tsx:7-54](file://frontend/antd/input/otp/input.otp.tsx#L7-L54) +- [context.ts](file://frontend/antd/auto-complete/context.ts) +- [hooks/useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [renderItems.ts](file://frontend/utils/renderItems.ts) +- [renderParamsSlot.ts](file://frontend/utils/renderParamsSlot.ts) +- [omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + +Section Source + +- [input.tsx:1-119](file://frontend/antd/input/input.tsx#L1-L119) +- [input-number.tsx:1-92](file://frontend/antd/input-number/input-number.tsx#L1-L92) +- [auto-complete.tsx:1-151](file://frontend/antd/auto-complete/auto-complete.tsx#L1-L151) +- [mentions.tsx:1-80](file://frontend/antd/mentions/mentions.tsx#L1-L80) +- [input.password.tsx:1-129](file://frontend/antd/input/password/input.password.tsx#L1-L129) +- [input.search.tsx:1-126](file://frontend/antd/input/search/input.search.tsx#L1-L126) +- [input.textarea.tsx:1-91](file://frontend/antd/input/textarea/input.textarea.tsx#L1-L91) +- [input.otp.tsx:1-57](file://frontend/antd/input/otp/input.otp.tsx#L1-L57) + +## Core Components + +This section outlines the key responsibilities and common design of each component: + +- Value synchronization and callbacks: through the unified useValueChange hook, the controlled value is decoupled from the onValueChange callback, ensuring consistent updates between input events and external state. +- Function wrapping: useFunction converts incoming functions (such as formatter, parser, filterOption) into stable references, avoiding unnecessary re-renders. +- Slot system: ReactSlot and renderParamsSlot support slot-based custom rendering (such as prefix/suffix, clear icon, dropdown items, separators, etc.) and allow parameter passing. +- Property trimming: omitUndefinedProps only passes valid configuration, preventing undefined properties from affecting rendering or behavior. +- Option rendering: renderItems converts option nodes from slots into the options array required by Ant Design, supporting both default and custom option sets. + +Section Source + +- [input.tsx:39-42](file://frontend/antd/input/input.tsx#L39-L42) +- [input-number.tsx:32-35](file://frontend/antd/input-number/input-number.tsx#L32-L35) +- [auto-complete.tsx:63-66](file://frontend/antd/auto-complete/auto-complete.tsx#L63-L66) +- [mentions.tsx:34-37](file://frontend/antd/mentions/mentions.tsx#L34-L37) +- [hooks/useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [renderItems.ts](file://frontend/utils/renderItems.ts) +- [renderParamsSlot.ts](file://frontend/utils/renderParamsSlot.ts) +- [omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + +## Architecture Overview + +The unified architecture of input components consists of "wrapper layer + utility layer + AntD native components", forming clear responsibility boundaries and reuse paths. + +```mermaid +sequenceDiagram +participant U as "User" +participant S as "Svelte Component (Wrapper)" +participant H as "Hooks/Utilities" +participant R as "AntD Native Component" +U->>S : Input/select/keypress +S->>H : Trigger value sync/function wrapping/slot rendering +H-->>S : Return stable value/function/render result +S->>R : Render native component (with value/callbacks/slots) +R-->>S : Trigger onChange/callback +S->>H : Update controlled value (onValueChange) +H-->>S : Complete sync +S-->>U : UI update +``` + +Diagram Source + +- [input.tsx:47-54](file://frontend/antd/input/input.tsx#L47-L54) +- [input-number.tsx:39-46](file://frontend/antd/input-number/input-number.tsx#L39-L46) +- [auto-complete.tsx:76-104](file://frontend/antd/auto-complete/auto-complete.tsx#L76-L104) +- [mentions.tsx:44-61](file://frontend/antd/mentions/mentions.tsx#L44-L61) +- [hooks/useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) + +## Detailed Component Analysis + +### Input + +- Key features + - Controlled value: synchronizes props.value with internal state via useValueChange; triggers onValueChange on onChange. + - Character counting: showCount supports functional formatter; count supports combined configuration of strategy/exceedFormatter/show, using useMemo and omitUndefinedProps to trim invalid fields. + - Slot-based decoration: addonBefore/After, prefix/suffix, allowClear.clearIcon can inject custom nodes via slots. +- Input validation and formatting + - No built-in regex validation; recommended to combine with form validators or perform validation within onValueChange. + - formatter/parser are passed in from the parent; not covered here. +- Debounce and character limits + - No built-in debounce; throttle/debounce can be self-implemented in onValueChange. + - maxLength is natively supported by AntD and used together with showCount. +- Accessibility and keyboard navigation + - Preserves native input behavior, following browser default keyboard interactions. +- Integration with form validation + - Recommended to perform real-time validation in onValueChange and update state via setFieldError/setFieldValue exposed by the form context. +- Performance optimization + - Use useMemo to cache count configuration to reduce re-renders. + - Only render the corresponding decoration node when slots exist, avoiding empty branch overhead. + +Section Source + +- [input.tsx:39-84](file://frontend/antd/input/input.tsx#L39-L84) +- [input.tsx:85-112](file://frontend/antd/input/input.tsx#L85-L112) + +### InputNumber + +- Key features + - Controlled value and callbacks: same as above, using useValueChange to sync values. + - Formatting/parsing: formatter/parser are passed in as functions, wrapped with useFunction for stable references. + - Control icons: controls.upIcon/controls.downIcon support slot injection. + - Decoration and prefix/suffix: addonBefore/After, prefix/suffix support slots. +- Input validation and formatting + - No built-in validation; recommended to perform range and format validation in onChange or onValueChange. + - formatter/parser are used for display and parsing to prevent users from entering non-numeric characters. +- Debounce and character limits + - No built-in debounce; can be implemented in onValueChange. +- Accessibility and keyboard navigation + - Preserves native numeric input behavior, supports up/down arrows to increment/decrement. +- Integration with form validation + - Perform numeric range and precision validation in onValueChange and sync form state. +- Performance optimization + - formatter/parser and control icons are rendered on demand, reducing unnecessary overhead. + +Section Source + +- [input-number.tsx:32-35](file://frontend/antd/input-number/input-number.tsx#L32-L35) +- [input-number.tsx:47-64](file://frontend/antd/input-number/input-number.tsx#L47-L64) +- [input-number.tsx:79-84](file://frontend/antd/input-number/input-number.tsx#L79-L84) + +### AutoComplete + +- Key features + - Value sync: useValueChange syncs value with onValueChange. + - Option rendering: prefers passed-in options; otherwise extracts from slots and converts using renderItems. + - Dropdown rendering: dropdownRender/popupRender support both slot and function forms. + - Filter logic: filterOption supports functions or boolean values; getPopupContainer specifies the popup container. + - Clear and decoration: allowClear.clearIcon, notFoundContent, addonBefore/After, prefix/suffix support slots. +- Input validation and formatting + - No built-in validation; control candidate set via filterOption and validateSearch. + - Recommended to perform secondary validation in onChange/onValueChange. +- Debounce and character limits + - No built-in debounce; can be implemented in onValueChange. +- Accessibility and keyboard navigation + - Supports keyboard up/down selection, Enter to confirm, Tab to switch. +- Integration with form validation + - Use the form context to set error messages in onValueChange. +- Performance optimization + - Use useMemo to cache options; only render decoration nodes when slots exist. + +```mermaid +flowchart TD +Start(["Input event"]) --> Filter["Apply filterOption/validateSearch"] +Filter --> HasOptions{"Matching items?"} +HasOptions -- Yes --> RenderList["Render candidate list
dropdownRender/popupRender"] +HasOptions -- No --> NotFound["Render notFoundContent"] +RenderList --> Select["User selects/Enter to confirm"] +NotFound --> Select +Select --> Sync["useValueChange syncs value"] +Sync --> End(["Done"]) +``` + +Diagram Source + +- [auto-complete.tsx:89-100](file://frontend/antd/auto-complete/auto-complete.tsx#L89-L100) +- [auto-complete.tsx:114-135](file://frontend/antd/auto-complete/auto-complete.tsx#L114-L135) +- [mentions.tsx:48-57](file://frontend/antd/mentions/mentions.tsx#L48-L57) + +Section Source + +- [auto-complete.tsx:63-66](file://frontend/antd/auto-complete/auto-complete.tsx#L63-L66) +- [auto-complete.tsx:89-100](file://frontend/antd/auto-complete/auto-complete.tsx#L89-L100) +- [auto-complete.tsx:114-135](file://frontend/antd/auto-complete/auto-complete.tsx#L114-L135) +- [context.ts](file://frontend/antd/auto-complete/context.ts) + +### Mentions + +- Key features + - Value sync: useValueChange syncs value with onValueChange. + - Option rendering: prefers options; otherwise uses slot renderItems. + - Filter and validation: filterOption, validateSearch support functional forms. + - Popup container: getPopupContainer specifies the container. + - Clear and placeholder: allowClear.clearIcon, notFoundContent support slots. +- Input validation and formatting + - No built-in validation; control input and candidates via validateSearch and filterOption. +- Debounce and character limits + - No built-in debounce; can be implemented in onValueChange. +- Accessibility and keyboard navigation + - Supports keyboard selection and confirmation. +- Integration with form validation + - Perform format and content validation in onValueChange. +- Performance optimization + - useMemo caches options; renders decoration nodes on demand. + +Section Source + +- [mentions.tsx:34-37](file://frontend/antd/mentions/mentions.tsx#L34-L37) +- [mentions.tsx:48-57](file://frontend/antd/mentions/mentions.tsx#L48-L57) +- [mentions.tsx:62-71](file://frontend/antd/mentions/mentions.tsx#L62-L71) + +### InputPassword + +- Key features + - Controlled value: useValueChange syncs value with onValueChange. + - Show/hide toggle: iconRender supports slots and functions. + - Character counting: showCount/formatter and count configuration support functional forms and trimming. + - Decoration and clear: addonBefore/After, prefix/suffix, allowClear.clearIcon support slots. +- Input validation and formatting + - No built-in validation; recommended to perform strength and length validation in onValueChange. +- Debounce and character limits + - No built-in debounce; can be implemented in onValueChange. +- Accessibility and keyboard navigation + - Preserves native password input behavior. +- Integration with form validation + - Perform password policy validation in onValueChange. +- Performance optimization + - Use useMemo to cache count configuration and iconRender. + +Section Source + +- [input.password.tsx:42-45](file://frontend/antd/input/password/input.password.tsx#L42-L45) +- [input.password.tsx:65-79](file://frontend/antd/input/password/input.password.tsx#L65-L79) +- [input.password.tsx:80-94](file://frontend/antd/input/password/input.password.tsx#L80-L94) +- [input.password.tsx:95-122](file://frontend/antd/input/password/input.password.tsx#L95-L122) + +### InputSearch + +- Key features + - Controlled value: useValueChange syncs value with onValueChange. + - Character counting: showCount/formatter and count configuration support functional forms and trimming. + - Search button: enterButton supports slots and text. + - Decoration and clear: addonBefore/After, prefix/suffix, allowClear.clearIcon support slots. +- Input validation and formatting + - No built-in validation; recommended to perform length and content validation in onValueChange. +- Debounce and character limits + - No built-in debounce; can be implemented in onValueChange. +- Accessibility and keyboard navigation + - Supports Enter to trigger search. +- Integration with form validation + - Perform search term validation in onValueChange. +- Performance optimization + - Use useMemo to cache count configuration and enterButton. + +Section Source + +- [input.search.tsx:40-43](file://frontend/antd/input/search/input.search.tsx#L40-L43) +- [input.search.tsx:70-78](file://frontend/antd/input/search/input.search.tsx#L70-L78) +- [input.search.tsx:85-91](file://frontend/antd/input/search/input.search.tsx#L85-L91) +- [input.search.tsx:92-118](file://frontend/antd/input/search/input.search.tsx#L92-L118) + +### InputTextarea + +- Key features + - Controlled value: useValueChange syncs value with onValueChange. + - Character counting: showCount/formatter and count configuration support functional forms and trimming. + - Clear: allowClear.clearIcon supports slots. +- Input validation and formatting + - No built-in validation; recommended to perform length and content validation in onValueChange. +- Debounce and character limits + - No built-in debounce; can be implemented in onValueChange. +- Accessibility and keyboard navigation + - Supports multiline input and scrolling. +- Integration with form validation + - Perform content and length validation in onValueChange. +- Performance optimization + - Use useMemo to cache count configuration. + +Section Source + +- [input.textarea.tsx:32-35](file://frontend/antd/input/textarea/input.textarea.tsx#L32-L35) +- [input.textarea.tsx:62-76](file://frontend/antd/input/textarea/input.textarea.tsx#L62-L76) +- [input.textarea.tsx:77-83](file://frontend/antd/input/textarea/input.textarea.tsx#L77-L83) + +### InputOTP + +- Key features + - Controlled value: useValueChange syncs value with onValueChange. + - Separator: separator supports slots and functions. + - Formatting: formatter supports functions. +- Input validation and formatting + - No built-in validation; recommended to perform length and character type validation in onValueChange. +- Debounce and character limits + - No built-in debounce; can be implemented in onValueChange. +- Accessibility and keyboard navigation + - Supports cell-by-cell input and automatic focus movement. +- Integration with form validation + - Perform OTP validation in onValueChange. +- Performance optimization + - Use useMemo to cache formatter and separator. + +Section Source + +- [input.otp.tsx:25-28](file://frontend/antd/input/otp/input.otp.tsx#L25-L28) +- [input.otp.tsx:38-44](file://frontend/antd/input/otp/input.otp.tsx#L38-L44) +- [input.otp.tsx:46-49](file://frontend/antd/input/otp/input.otp.tsx#L46-L49) + +## Dependency Analysis + +- Component to utility layer + - All input components depend on useValueChange for controlled value synchronization. + - useFunction is used for stable function references to avoid re-renders. + - renderItems/renderParamsSlot are used for slot options and parameterized rendering. + - omitUndefinedProps is used to trim invalid properties. +- Differences between components + - AutoComplete/Mentions rely on context and slot option rendering. + - InputNumber/InputPassword/InputSearch/InputTextarea/InputOTP functionalize and cache configurations such as showCount/count/formatter. + +```mermaid +graph LR +subgraph "Components" +I["Input"] +N["InputNumber"] +AC["AutoComplete"] +M["Mentions"] +P["InputPassword"] +S["InputSearch"] +T["InputTextarea"] +O["InputOTP"] +end +subgraph "Utilities" +V["useValueChange"] +F["useFunction"] +RI["renderItems"] +RP["renderParamsSlot"] +OD["omitUndefinedProps"] +end +I --> V +I --> F +I --> RP +I --> OD +N --> V +N --> F +N --> RP +AC --> V +AC --> F +AC --> RI +AC --> RP +AC --> OD +M --> V +M --> F +M --> RI +M --> RP +M --> OD +P --> V +P --> F +P --> RP +P --> OD +S --> V +S --> F +S --> RP +S --> OD +T --> V +T --> F +T --> RP +T --> OD +O --> V +O --> F +O --> RP +``` + +Diagram Source + +- [input.tsx:39-84](file://frontend/antd/input/input.tsx#L39-L84) +- [input-number.tsx:32-84](file://frontend/antd/input-number/input-number.tsx#L32-L84) +- [auto-complete.tsx:63-100](file://frontend/antd/auto-complete/auto-complete.tsx#L63-L100) +- [mentions.tsx:34-57](file://frontend/antd/mentions/mentions.tsx#L34-L57) +- [input.password.tsx:42-94](file://frontend/antd/input/password/input.password.tsx#L42-L94) +- [input.search.tsx:40-84](file://frontend/antd/input/search/input.search.tsx#L40-L84) +- [input.textarea.tsx:32-76](file://frontend/antd/input/textarea/input.textarea.tsx#L32-L76) +- [input.otp.tsx:25-44](file://frontend/antd/input/otp/input.otp.tsx#L25-L44) +- [hooks/useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [renderItems.ts](file://frontend/utils/renderItems.ts) +- [renderParamsSlot.ts](file://frontend/utils/renderParamsSlot.ts) +- [omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + +## Performance Considerations + +- Controlled value synchronization + - Use useValueChange to uniformly manage the controlled value, avoiding redundant renders caused by inconsistencies between external and internal state. +- Function reference stabilization + - useFunction wraps incoming functions to reduce re-renders caused by prop changes. +- Slot rendering optimization + - Only render the corresponding node when slots exist, avoiding empty branch overhead. +- Configuration caching + - Use useMemo to cache configurations such as showCount/count/formatter to reduce rendering cost. +- Large data input handling + - Avoid heavy computation in onValueChange; if necessary, split into microtasks or use Web Worker. + - For high-frequency inputs (such as search, auto-complete), it is recommended to add debounce/throttle strategies upstream. + - For long text input, prefer TextArea and enable necessary character limits and counting hints. + +## Troubleshooting Guide + +- Input value not syncing + - Check whether onValueChange is correctly passed in and has not been overridden. + - Confirm whether the value in useValueChange is consistent with props.value. +- Slot not working + - Confirm that the slot key name matches the slots supported by the component (such as allowClear.clearIcon, prefix, suffix, enterButton, separator, etc.). + - Check whether the renderParamsSlot key is correct. +- Options not displayed + - AutoComplete/Mentions require providing options or providing options via slots; check the children name and structure in renderItems. +- Formatting anomaly + - Functions such as formatter/parser/filterOption must return the expected type; use useFunction to wrap them for stable references. +- Count configuration invalid + - Confirm that when showCount is an object, provide formatter; use omitUndefinedProps to trim invalid fields in count configuration. + +Section Source + +- [hooks/useValueChange.ts](file://frontend/utils/hooks/useValueChange.ts) +- [hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [renderItems.ts](file://frontend/utils/renderItems.ts) +- [renderParamsSlot.ts](file://frontend/utils/renderParamsSlot.ts) +- [omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + +## Conclusion + +Input components achieve deep compatibility with Ant Design and flexible extensibility through a unified wrapping pattern. With the help of tools such as useValueChange, useFunction, renderItems, renderParamsSlot, and omitUndefinedProps, the components provide powerful slot-based and functional capabilities while ensuring performance. In actual business scenarios, it is recommended to combine with the form validation system to implement input validation, formatting, and debounce strategies in onValueChange, and to employ caching and asynchronous processing for large-scale data input scenarios, to achieve better user experience and stability. diff --git a/.wiki/en/Ant Design Components/Data Entry Components/Selection Components.md b/.wiki/en/Ant Design Components/Data Entry Components/Selection Components.md new file mode 100644 index 00000000..21a22c7a --- /dev/null +++ b/.wiki/en/Ant Design Components/Data Entry Components/Selection Components.md @@ -0,0 +1,673 @@ +# Selection Components + + +**Files referenced in this document** +- [select.tsx](file://frontend/antd/select/select.tsx) +- [option.tsx](file://frontend/antd/select/option/option.tsx) +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [group.tsx](file://frontend/antd/checkbox/group/checkbox.group.tsx) +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [radio.group.tsx](file://frontend/antd/radio/group/radio.group.tsx) +- [switch.tsx](file://frontend/antd/switch/switch.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [option.tsx](file://frontend/antd/segmented/option/segmented.option.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [tree.node.tsx](file://frontend/antd/tree/tree-node/tree.node.tsx) +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [tree.node.tsx](file://frontend/antd/tree-select/tree-node/tree.node.tsx) +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [panel.tsx](file://frontend/antd/cascader/panel/panel.tsx) +- [option.tsx](file://frontend/antd/cascader/option/option.tsx) +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [rate.tsx](file://frontend/antd/rate/rate.tsx) +- [context.ts](file://frontend/antd/select/context.ts) +- [context.ts](file://frontend/antd/checkbox/context.ts) +- [context.ts](file://frontend/antd/radio/context.ts) +- [context.ts](file://frontend/antd/segmented/context.ts) +- [context.ts](file://frontend/antd/tree/context.ts) +- [context.ts](file://frontend/antd/tree-select/context.ts) +- [context.ts](file://frontend/antd/cascader/context.ts) +- [context.ts](file://frontend/antd/rate/context.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Virtual Scrolling](#performance-and-virtual-scrolling) +8. [Accessibility and Keyboard Navigation](#accessibility-and-keyboard-navigation) +9. [Troubleshooting Guide](#troubleshooting-guide) +10. [Conclusion](#conclusion) + +## Introduction + +This document systematically covers the "selection-type" components in the frontend component library: Select, Checkbox, Radio, Switch, Segmented, TreeSelect, Cascader, Transfer, Tree, and Rate. The document covers data binding, option configuration, multi-select mode, and disabled state, combined with design patterns and data flow management for complex scenarios. It also provides accessibility and keyboard navigation recommendations, as well as virtual scrolling and performance optimization strategies for large option sets. + +## Project Structure + +Selection components are primarily located in the frontend Ant Design component directory, organized by functional module: each component is stored in its own directory containing the entry component file and sub-components (such as Option, Group, Panel, etc.), with shared state and configuration managed uniformly through a context file (context.ts). + +```mermaid +graph TB +subgraph "Selection Component Directory" +S["select.tsx"] +C["checkbox.tsx"] +R["radio.tsx"] +SW["switch.tsx"] +SG["segmented.tsx"] +TS["tree-select.tsx"] +CA["cascader.tsx"] +T["tree.tsx"] +TR["transfer.tsx"] +RA["rate.tsx"] +end +subgraph "Sub-components" +SO["option.tsx (select)"] +CO["checkbox.group.tsx"] +RO["radio.group.tsx"] +SGO["segmented.option.tsx"] +TSN["tree.node.tsx (tree-select)"] +TN["tree.node.tsx (tree)"] +CAP["panel.tsx (cascader)"] +CAO["option.tsx (cascader)"] +end +subgraph "Context" +SC["context.ts (select)"] +CC["context.ts (checkbox)"] +RC["context.ts (radio)"] +SGC["context.ts (segmented)"] +TSC["context.ts (tree-select)"] +CAC["context.ts (cascader)"] +TC["context.ts (tree)"] +RAC["context.ts (rate)"] +end +S --> SO +S --> SC +C --> CO +C --> CC +R --> RO +R --> RC +SG --> SGO +SG --> SGC +TS --> TSN +TS --> TSC +T --> TN +T --> TC +CA --> CAP +CA --> CAO +CA --> CAC +TR --> TR +RA --> RAC +``` + +Diagram Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [switch.tsx](file://frontend/antd/switch/switch.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [rate.tsx](file://frontend/antd/rate/rate.tsx) + +Section Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [switch.tsx](file://frontend/antd/switch/switch.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [rate.tsx](file://frontend/antd/rate/rate.tsx) + +## Core Components + +This section outlines the key capabilities and common features of each component: + +- Data binding: controlled/uncontrolled modes, linked to external state via properties such as value/checked. +- Option configuration: declaratively define option sets through child item components (Option/Segmented.Option/Tree.Node, etc.). +- Multi-select mode: Checkbox supports multi-select; Select/Cascader/TreeSelect can be configured for multi-select; Transfer provides a left-right list interaction. +- Disabled state: supports both global disable and per-item disable, ensuring unavailable options do not respond to interaction. +- Controlled updates: onChange callback returns the current selected value, driving upstream state synchronization. + +Section Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [switch.tsx](file://frontend/antd/switch/switch.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [rate.tsx](file://frontend/antd/rate/rate.tsx) + +## Architecture Overview + +Selection components follow a unified "container-item-context" architecture: + +- Container components are responsible for rendering, state management, and event dispatching; +- Item components carry the display and interaction of specific options; +- Context files centrally handle shared logic such as default values, disabled states, and multi-select strategies. + +```mermaid +classDiagram +class Select { ++value ++mode ++disabled ++onChange() +} +class Option { ++label ++value ++disabled +} +class Checkbox { ++checked ++disabled ++onChange() +} +class CheckboxGroup { ++options[] ++value[] ++disabled ++onChange() +} +class Radio { ++checked ++disabled ++onChange() +} +class RadioGroup { ++options[] ++value ++disabled ++onChange() +} +class Switch { ++checked ++disabled ++onChange() +} +class Segmented { ++value ++disabled ++onChange() +} +class SegmentedOption { ++label ++value ++disabled +} +class Tree { ++treeData[] ++expandedKeys[] ++selectedKeys[] ++multiple ++onChange() +} +class TreeNode { ++title ++key ++disabled +} +class TreeSelect { ++treeData[] ++value ++treeDefaultExpandAll ++onChange() +} +class Cascader { ++options[] ++value[] ++onChange() +} +class CascaderPanel { ++options[] ++onChange() +} +class Transfer { ++dataSource[] ++targetKeys[] ++onChange() +} +class Rate { ++value ++allowHalf ++disabled ++onChange() +} +Select --> Option : "contains" +Checkbox --> CheckboxGroup : "combines" +Radio --> RadioGroup : "combines" +Segmented --> SegmentedOption : "contains" +Tree --> TreeNode : "contains" +TreeSelect --> TreeNode : "contains" +Cascader --> CascaderPanel : "contains" +``` + +Diagram Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [option.tsx](file://frontend/antd/select/option/option.tsx) +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [group.tsx](file://frontend/antd/checkbox/group/checkbox.group.tsx) +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [radio.group.tsx](file://frontend/antd/radio/group/radio.group.tsx) +- [switch.tsx](file://frontend/antd/switch/switch.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [option.tsx](file://frontend/antd/segmented/option/segmented.option.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [tree.node.tsx](file://frontend/antd/tree/tree-node/tree.node.tsx) +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [tree.node.tsx](file://frontend/antd/tree-select/tree-node/tree.node.tsx) +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [panel.tsx](file://frontend/antd/cascader/panel/panel.tsx) +- [option.tsx](file://frontend/antd/cascader/option/option.tsx) +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [rate.tsx](file://frontend/antd/rate/rate.tsx) + +## Detailed Component Analysis + +### Select + +- Data binding: supports controlled value and uncontrolled default value; onChange returns the selected value or value array (multi-select). +- Option configuration: declare label/value/disabled via Option child items; supports search filtering and tag backfilling. +- Multi-select mode: when multi-select is enabled, supports tag-style display and clearing individual tags. +- Disabled state: both container and individual items can be disabled; when disabled, cannot be expanded or toggled. +- Context: context.ts centrally handles default values, disabled states, multi-select strategies, and controlled validation. + +```mermaid +sequenceDiagram +participant U as "User" +participant S as "Select" +participant O as "Option" +participant C as "Context" +U->>S : Expand dropdown +S->>C : Read default value/disabled state +U->>O : Click an option +O-->>S : Trigger selection callback +S->>S : Update internal state +S-->>U : Close dropdown and display selected item +S->>C : Trigger onChange(value) +``` + +Diagram Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [option.tsx](file://frontend/antd/select/option/option.tsx) +- [context.ts](file://frontend/antd/select/context.ts) + +Section Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [option.tsx](file://frontend/antd/select/option/option.tsx) +- [context.ts](file://frontend/antd/select/context.ts) + +### Checkbox + +- Data binding: single Checkbox is a controlled checked value; Checkbox.Group receives value[] and syncs via onChange. +- Option configuration: Group's options[] supports passing label/value/disabled directly; child Checkbox items can also be used. +- Multi-select mode: Group defaults to multi-select; supports select all/deselect all and indeterminate state. +- Disabled state: Group-level disable affects all child items; child items can also be individually disabled. +- Context: context.ts is responsible for default values, disabled states, and multi-select strategies. + +```mermaid +flowchart TD +Start(["Enter Checkbox.Group"]) --> LoadOptions["Load options[] or child items"] +LoadOptions --> Render["Render child Checkboxes"] +Render --> Interact{"User interaction?"} +Interact --> |Check/Uncheck| UpdateValue["Update value[]"] +UpdateValue --> Callback["Trigger onChange(value[])"] +Callback --> End(["Done"]) +``` + +Diagram Source + +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [group.tsx](file://frontend/antd/checkbox/group/checkbox.group.tsx) +- [context.ts](file://frontend/antd/checkbox/context.ts) + +Section Source + +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [group.tsx](file://frontend/antd/checkbox/group/checkbox.group.tsx) +- [context.ts](file://frontend/antd/checkbox/context.ts) + +### Radio + +- Data binding: single Radio is a controlled checked value; Radio.Group receives value and syncs via onChange. +- Option configuration: Group's options[] supports label/value/disabled; child Radio items can also be used. +- Multi-select mode: Group is single-select; supports clear and disable. +- Disabled state: Group-level disable affects all child items; child items can also be individually disabled. +- Context: context.ts is responsible for default values, disabled states, and single-select strategies. + +```mermaid +sequenceDiagram +participant U as "User" +participant RG as "Radio.Group" +participant R as "Radio" +participant C as "Context" +U->>R : Click option +R-->>RG : Trigger selection callback +RG->>C : Apply default value/disabled state +RG-->>U : Update selected state and callback onChange(value) +``` + +Diagram Source + +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [radio.group.tsx](file://frontend/antd/radio/group/radio.group.tsx) +- [context.ts](file://frontend/antd/radio/context.ts) + +Section Source + +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [radio.group.tsx](file://frontend/antd/radio/group/radio.group.tsx) +- [context.ts](file://frontend/antd/radio/context.ts) + +### Switch + +- Data binding: controlled checked value; onChange returns the new boolean value. +- Disabled state: disabled disables interaction; supports loading state. +- Use case: suitable for binary selection, such as "enable/disable" or "yes/no". + +Section Source + +- [switch.tsx](file://frontend/antd/switch/switch.tsx) + +### Segmented + +- Data binding: controlled value; onChange returns the selected value. +- Option configuration: supports options[] or child Segmented.Option items; can disable individual items. +- Use case: a compact alternative to Radio.Group, suitable for a small number of discrete options. + +```mermaid +classDiagram +class Segmented { ++value ++options[] ++disabled ++onChange() +} +class SegmentedOption { ++label ++value ++disabled +} +Segmented --> SegmentedOption : "contains" +``` + +Diagram Source + +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [option.tsx](file://frontend/antd/segmented/option/segmented.option.tsx) +- [context.ts](file://frontend/antd/segmented/context.ts) + +Section Source + +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [option.tsx](file://frontend/antd/segmented/option/segmented.option.tsx) +- [context.ts](file://frontend/antd/segmented/context.ts) + +### Tree + +- Data binding: controlled selectedKeys/expandedKeys; onChange returns the selected key set. +- Option configuration: treeData[] supports title/key/children/disabled; supports drag-and-drop, search, and batch selection. +- Multi-select mode: when multiple=true, multi-select is supported; supports both controlled and uncontrolled modes. +- Disabled state: node-level disabled; supports batch disable. + +```mermaid +sequenceDiagram +participant U as "User" +participant T as "Tree" +participant TN as "TreeNode" +participant C as "Context" +U->>TN : Click node +TN-->>T : Trigger selection/expansion +T->>C : Apply multi-select/disable strategy +T-->>U : Update selectedKeys/expandedKeys and callback +``` + +Diagram Source + +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [tree.node.tsx](file://frontend/antd/tree/tree-node/tree.node.tsx) +- [context.ts](file://frontend/antd/tree/context.ts) + +Section Source + +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [tree.node.tsx](file://frontend/antd/tree/tree-node/tree.node.tsx) +- [context.ts](file://frontend/antd/tree/context.ts) + +### TreeSelect + +- Data binding: controlled value; onChange returns the selected key. +- Option configuration: treeData[] with option declaration similar to Select; supports search filtering and tag backfilling. +- Multi-select mode: supports multi-select and parent-child linkage strategies (e.g., leaves only). +- Disabled state: supports global and node-level disable. + +```mermaid +flowchart TD +Open["Expand TreeSelect"] --> Filter["Enter search keyword"] +Filter --> List["Render matching nodes"] +List --> Select["Click node to select"] +Select --> Update["Update value and close panel"] +Update --> Callback["Trigger onChange(value)"] +``` + +Diagram Source + +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [tree.node.tsx](file://frontend/antd/tree-select/tree-node/tree.node.tsx) +- [context.ts](file://frontend/antd/tree-select/context.ts) + +Section Source + +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [tree.node.tsx](file://frontend/antd/tree-select/tree-node/tree.node.tsx) +- [context.ts](file://frontend/antd/tree-select/context.ts) + +### Cascader + +- Data binding: controlled value[]; onChange returns the full path value array. +- Option configuration: options[] supports label/value/children; supports async loading of child levels. +- Multi-select mode: typically single path selection; multiple path selection can be achieved through extensions. +- Disabled state: supports disabling the entire tree and node-level disable. + +```mermaid +sequenceDiagram +participant U as "User" +participant C as "Cascader" +participant P as "CascaderPanel" +participant O as "Option" +participant Ctx as "Context" +U->>C : Open cascade +C->>Ctx : Read default value/disabled state +U->>P : Select level 1 +P-->>C : Notify change +U->>P : Select level 2... +P-->>C : Notify change +C-->>U : Complete path selection and callback onChange(value[]) +``` + +Diagram Source + +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [panel.tsx](file://frontend/antd/cascader/panel/panel.tsx) +- [option.tsx](file://frontend/antd/cascader/option/option.tsx) +- [context.ts](file://frontend/antd/cascader/context.ts) + +Section Source + +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [panel.tsx](file://frontend/antd/cascader/panel/panel.tsx) +- [option.tsx](file://frontend/antd/cascader/option/option.tsx) +- [context.ts](file://frontend/antd/cascader/context.ts) + +### Transfer + +- Data binding: controlled targetKeys[]; onChange returns the target list key set. +- Option configuration: dataSource[] supports title/key; supports search filtering and batch operations. +- Multi-select mode: bidirectional movement from left to right; supports select all/deselect all. +- Disabled state: supports global disable and button disable. + +```mermaid +flowchart TD +Start(["Open Transfer"]) --> SearchLeft["Left side search"] +SearchLeft --> Move["Click move button"] +Move --> UpdateTarget["Update targetKeys[]"] +UpdateTarget --> Callback["Trigger onChange(targetKeys)"] +Callback --> End(["Done"]) +``` + +Diagram Source + +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) + +Section Source + +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) + +### Rate + +- Data binding: controlled value; onChange returns the rating value. +- Option configuration: supports allowHalf half-star, count total, tooltips text. +- Disabled state: disabled disables interaction; supports read-only mode. +- Use case: quick expression of satisfaction or level rating. + +```mermaid +sequenceDiagram +participant U as "User" +participant RA as "Rate" +participant C as "Context" +U->>RA : Mouse hover/click +RA->>C : Apply disabled/read-only strategy +RA-->>U : Update value and callback onChange(value) +``` + +Diagram Source + +- [rate.tsx](file://frontend/antd/rate/rate.tsx) +- [context.ts](file://frontend/antd/rate/context.ts) + +Section Source + +- [rate.tsx](file://frontend/antd/rate/rate.tsx) +- [context.ts](file://frontend/antd/rate/context.ts) + +## Dependency Analysis + +- Low inter-component coupling: container components combine declaratively with child item components, avoiding tight coupling. +- Centralized context: each component's context.ts aggregates default values, disabled states, and multi-select strategies, reducing duplicate logic. +- Clear event chain: from user interaction to container update to callback, forming a stable data flow. + +```mermaid +graph LR +Select["Select"] --> Option["Option"] +Checkbox["Checkbox"] --> CheckboxGroup["Checkbox.Group"] +Radio["Radio"] --> RadioGroup["Radio.Group"] +Segmented["Segmented"] --> SegmentedOption["Segmented.Option"] +Tree["Tree"] --> TreeNode["TreeNode"] +TreeSelect["TreeSelect"] --> TreeNode +Cascader["Cascader"] --> Panel["Cascader.Panel"] +Cascader --> Option +Transfer["Transfer"] +Rate["Rate"] +``` + +Diagram Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [rate.tsx](file://frontend/antd/rate/rate.tsx) + +Section Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [rate.tsx](file://frontend/antd/rate/rate.tsx) + +## Performance and Virtual Scrolling + +- Recommendations for large option sets: + - Use virtual scrolling: for long lists (such as Select/Tree/Transfer), use virtual scroll rendering to only render visible area nodes, significantly reducing DOM count and reflow cost. + - Lazy loading and pagination: for TreeSelect/Cascader, support async loading of child nodes to reduce initial rendering pressure. + - Caching and debounce: debounce search filtering and onChange callbacks to avoid frequent redraws. + - Controlled update optimization: merge multiple state changes in the parent form to reduce unnecessary re-renders. +- Specific implementation points: + - Select: enable virtual scrolling and search filtering for the Option list. + - Tree/TreeSelect: enable virtual scrolling and lazy loading for node rendering. + - Transfer: enable virtual scrolling and batch operation optimization for left and right lists. + +[This section provides general performance guidance and does not require specific file references] + +## Accessibility and Keyboard Navigation + +- Keyboard support: + - Use Tab/Shift+Tab to navigate between options; + - Use Enter/Space to confirm selection; + - Use arrow keys to move among multiple options (such as Tree/Select/Cascader). +- Screen reader friendly: + - Provide semantic labels for each option; + - Disabled and error states provide aria-\* attributes and hint text; + - Provide value reading and tooltips for Rate. +- Recommendations: + - Provide aria-expanded/aria-controls for container components; + - Provide aria-disabled for disabled options; + - Provide aria-required for required fields. + +[This section provides general accessibility guidance and does not require specific file references] + +## Troubleshooting Guide + +- Common issues and diagnosis: + - Selected value not updated: check whether the controlled value and onChange are correctly passed in; confirm consistency of value/checked between container and child items. + - Multi-select not working: confirm the structure of Group's options[] and the type of value[]; check disabled state and indeterminate state. + - Disable not working: verify the disabled attribute hierarchy (container vs. child items); check the disable strategy in context. + - Performance stuttering: enable virtual scrolling for long lists; reduce unnecessary re-renders and deep nesting. +- Debugging recommendations: + - Print the current value in onChange to verify data flow; + - Use browser developer tools to observe DOM count and reflow; + - For TreeSelect/Cascader, check whether async loading is correctly triggered. + +Section Source + +- [select.tsx](file://frontend/antd/select/select.tsx) +- [checkbox.tsx](file://frontend/antd/checkbox/checkbox.tsx) +- [radio.tsx](file://frontend/antd/radio/radio.tsx) +- [segmented.tsx](file://frontend/antd/segmented/segmented.tsx) +- [tree.tsx](file://frontend/antd/tree/tree.tsx) +- [tree.select.tsx](file://frontend/antd/tree-select/tree-select.tsx) +- [cascader.tsx](file://frontend/antd/cascader/cascader.tsx) +- [transfer.tsx](file://frontend/antd/transfer/transfer.tsx) +- [rate.tsx](file://frontend/antd/rate/rate.tsx) + +## Conclusion + +Selection components in this project implement a unified container-item-context architecture with good extensibility and maintainability. Through controlled data binding, clear option configuration, and comprehensive disable strategies, they can meet diverse needs ranging from simple binary selection to complex tree/cascading selection. Combined with virtual scrolling and accessibility design, they can maintain a good experience in large-scale data and accessible scenarios. diff --git a/.wiki/en/Ant Design Components/Feedback Components/Alert.md b/.wiki/en/Ant Design Components/Feedback Components/Alert.md new file mode 100644 index 00000000..162b23f6 --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Alert.md @@ -0,0 +1,287 @@ +# Alert + + +**Files referenced in this document** +- [frontend/antd/alert/alert.tsx](file://frontend/antd/alert/alert.tsx) +- [frontend/antd/alert/Index.svelte](file://frontend/antd/alert/Index.svelte) +- [frontend/antd/alert/error-boundary/alert.error-boundary.tsx](file://frontend/antd/alert/error-boundary/alert.error-boundary.tsx) +- [frontend/antd/alert/error-boundary/Index.svelte](file://frontend/antd/alert/error-boundary/Index.svelte) +- [backend/modelscope_studio/components/antd/alert/__init__.py](file://backend/modelscope_studio/components/antd/alert/__init__.py) +- [backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py](file://backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py) +- [frontend/antd/alert/package.json](file://frontend/antd/alert/package.json) +- [docs/components/antd/alert/README-zh_CN.md](file://docs/components/antd/alert/README-zh_CN.md) +- [docs/components/antd/alert/README.md](file://docs/components/antd/alert/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The Alert component is used to convey information or status feedback that requires user attention, commonly used in form validation hints, operation result feedback, system notifications, and similar scenarios. This component is a wrapper around Ant Design's Alert, providing typed variants (success, info, warning, error), closability, icon and description slots, and error boundary wrapping, ensuring stable presentation even in complex rendering scenarios. + +## Project Structure + +The Alert component is composed of a frontend Svelte wrapper layer and a backend Gradio component layer, with a standalone error boundary version provided to enhance stability. + +```mermaid +graph TB +subgraph "Frontend" +A_Index["frontend/antd/alert/Index.svelte"] +A_Alert["frontend/antd/alert/alert.tsx"] +EB_Index["frontend/antd/alert/error-boundary/Index.svelte"] +EB_Boundary["frontend/antd/alert/error-boundary/alert.error-boundary.tsx"] +Pkg["frontend/antd/alert/package.json"] +end +subgraph "Backend" +Py_Component["backend/modelscope_studio/components/antd/alert/__init__.py"] +Py_EB["backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py"] +end +A_Index --> A_Alert +EB_Index --> EB_Boundary +A_Index --> Py_Component +EB_Index --> Py_EB +Pkg --> A_Index +Pkg --> EB_Index +``` + +Diagram sources + +- [frontend/antd/alert/Index.svelte:10-47](file://frontend/antd/alert/Index.svelte#L10-L47) +- [frontend/antd/alert/alert.tsx:7-43](file://frontend/antd/alert/alert.tsx#L7-L43) +- [frontend/antd/alert/error-boundary/Index.svelte:10-47](file://frontend/antd/alert/error-boundary/Index.svelte#L10-L47) +- [frontend/antd/alert/error-boundary/alert.error-boundary.tsx:6-32](file://frontend/antd/alert/error-boundary/alert.error-boundary.tsx#L6-L32) +- [backend/modelscope_studio/components/antd/alert/**init**.py:11-71](file://backend/modelscope_studio/components/antd/alert/__init__.py#L11-L71) +- [backend/modelscope_studio/components/antd/alert/error_boundary/**init**.py:10-55](file://backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py#L10-L55) +- [frontend/antd/alert/package.json:1-15](file://frontend/antd/alert/package.json#L1-L15) + +Section sources + +- [frontend/antd/alert/Index.svelte:1-66](file://frontend/antd/alert/Index.svelte#L1-L66) +- [frontend/antd/alert/alert.tsx:1-46](file://frontend/antd/alert/alert.tsx#L1-L46) +- [frontend/antd/alert/error-boundary/Index.svelte:1-70](file://frontend/antd/alert/error-boundary/Index.svelte#L1-L70) +- [frontend/antd/alert/error-boundary/alert.error-boundary.tsx:1-35](file://frontend/antd/alert/error-boundary/alert.error-boundary.tsx#L1-L35) +- [backend/modelscope_studio/components/antd/alert/**init**.py:1-89](file://backend/modelscope_studio/components/antd/alert/__init__.py#L1-L89) +- [backend/modelscope_studio/components/antd/alert/error_boundary/**init**.py:1-73](file://backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py#L1-L73) +- [frontend/antd/alert/package.json:1-15](file://frontend/antd/alert/package.json#L1-L15) + +## Core Components + +- Frontend main component: Responsible for wrapping Ant Design's Alert into a Svelte-consumable form, supporting slots (action, closable.closeIcon, description, icon, message), and passing through props and event callbacks. +- Error boundary component: Wraps Alert with an error boundary to ensure that exceptions in the subtree do not crash the entire interface, while retaining slot capabilities for message and description. +- Backend Gradio component: Provides typed parameters (type), slot mapping, event binding (close), and style/class injection capabilities; the error boundary version likewise provides corresponding events and slots. + +Section sources + +- [frontend/antd/alert/alert.tsx:7-43](file://frontend/antd/alert/alert.tsx#L7-L43) +- [frontend/antd/alert/error-boundary/alert.error-boundary.tsx:6-32](file://frontend/antd/alert/error-boundary/alert.error-boundary.tsx#L6-L32) +- [backend/modelscope_studio/components/antd/alert/**init**.py:11-71](file://backend/modelscope_studio/components/antd/alert/__init__.py#L11-L71) +- [backend/modelscope_studio/components/antd/alert/error_boundary/**init**.py:10-55](file://backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py#L10-L55) + +## Architecture Overview + +The following sequence diagram illustrates the call chain from the backend Gradio component through the frontend Svelte wrapper layer to the Ant Design component, including the error boundary wrapping path. + +```mermaid +sequenceDiagram +participant Py as "Backend Component
AntdAlert/AntdAlertErrorBoundary" +participant Svelte as "Frontend Wrapper
Index.svelte" +participant ReactComp as "React Component
alert.tsx / alert.error-boundary.tsx" +participant AntD as "Ant Design Alert" +Py->>Svelte : Render request with props + slots +Svelte->>ReactComp : Pass props and slots +ReactComp->>AntD : Render Alert or ErrorBoundary-wrapped Alert +AntD-->>ReactComp : Visual presentation and interactions (close button, action buttons, etc.) +ReactComp-->>Svelte : Callback afterClose and other events +Svelte-->>Py : Event report (e.g., close) +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/alert/**init**.py:11-71](file://backend/modelscope_studio/components/antd/alert/__init__.py#L11-L71) +- [frontend/antd/alert/Index.svelte:10-47](file://frontend/antd/alert/Index.svelte#L10-L47) +- [frontend/antd/alert/alert.tsx:12-42](file://frontend/antd/alert/alert.tsx#L12-L42) +- [frontend/antd/alert/error-boundary/alert.error-boundary.tsx:17-29](file://frontend/antd/alert/error-boundary/alert.error-boundary.tsx#L17-L29) + +## Detailed Component Analysis + +### Types and Semantics + +- Supported types (type): success, info, warning, error. Each corresponds to a different visual emphasis and semantic meaning, helping users quickly identify the status. +- Semantic guidelines: + - success: Positive feedback for completed operations or finished workflows + - info: General hints or supplementary notes + - warning: Potential issues or operations requiring attention + - error: Failures, exceptions, or issues requiring immediate action + +Section sources + +- [backend/modelscope_studio/components/antd/alert/**init**.py:37-37](file://backend/modelscope_studio/components/antd/alert/__init__.py#L37-L37) + +### Slots and Customization Points + +- Supported slots: + - action: Custom action area (e.g., a "View Details" button) + - closable.closeIcon: Custom close icon + - description: Auxiliary description text / rich content + - icon: Custom icon + - message: Title / main message body +- Prop passthrough: All other props are passed directly to Ant Design Alert, including closable, show_icon, banner, after_close, etc. + +Section sources + +- [backend/modelscope_studio/components/antd/alert/**init**.py:22-23](file://backend/modelscope_studio/components/antd/alert/__init__.py#L22-L23) +- [frontend/antd/alert/alert.tsx:11-43](file://frontend/antd/alert/alert.tsx#L11-L43) + +### Events and Interactions + +- close event: Fired when the user clicks the close button; the backend can bind handling logic via an event listener. +- after_close callback: Fired after the animation ends; can be used to clean up resources or switch states. +- Keyboard operation: Follows Ant Design behavior by default — typically Tab to navigate to the close button, Enter/Space to trigger closing. + +Section sources + +- [backend/modelscope_studio/components/antd/alert/**init**.py:16-20](file://backend/modelscope_studio/components/antd/alert/__init__.py#L16-L20) +- [frontend/antd/alert/alert.tsx:13-13](file://frontend/antd/alert/alert.tsx#L13-L13) + +### Error Boundary + +- Purpose: Captures errors in the Alert subtree to prevent a single slot or content rendering exception from crashing the entire page. +- Use case: When the message/description slots contain dynamic rendering or external data, it is recommended to use the error boundary version. +- Events: Also supports the close event for unified handling of close behavior. + +```mermaid +flowchart TD +Start(["Enter Alert Error Boundary"]) --> RenderMsg["Render message slot"] +RenderMsg --> MsgOK{"Render successful?"} +MsgOK --> |Yes| RenderDesc["Render description slot"] +MsgOK --> |No| Fallback["Display fallback content / empty state"] +RenderDesc --> DescOK{"Render successful?"} +DescOK --> |Yes| Ready["Display normally"] +DescOK --> |No| Fallback +Fallback --> End(["End"]) +Ready --> End +``` + +Diagram sources + +- [frontend/antd/alert/error-boundary/alert.error-boundary.tsx:17-29](file://frontend/antd/alert/error-boundary/alert.error-boundary.tsx#L17-L29) + +Section sources + +- [frontend/antd/alert/error-boundary/alert.error-boundary.tsx:6-32](file://frontend/antd/alert/error-boundary/alert.error-boundary.tsx#L6-L32) +- [backend/modelscope_studio/components/antd/alert/error_boundary/**init**.py:10-55](file://backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py#L10-L55) + +### Styles and Class Names + +- Supports injecting base styles and identifiers via elem_id, elem_classes, elem_style. +- Primary class name prefixes: + - ms-gr-antd-alert: Main Alert component + - ms-gr-antd-alert-error-boundary: Error boundary version +- Can be combined with Ant Design's own type, show_icon, closable, and other props to control appearance. + +Section sources + +- [frontend/antd/alert/Index.svelte:53-53](file://frontend/antd/alert/Index.svelte#L53-L53) +- [frontend/antd/alert/error-boundary/Index.svelte:56-56](file://frontend/antd/alert/error-boundary/Index.svelte#L56-L56) + +### Accessibility and Keyboard Support + +- Accessibility: Follows Ant Design's default accessibility design to ensure screen readers can read the message and description. +- Keyboard: Tab to navigate to the close button, Enter/Space to close; it is recommended to provide explicit accessible names in the action slot. + +Section sources + +- [frontend/antd/alert/alert.tsx:17-40](file://frontend/antd/alert/alert.tsx#L17-L40) + +### Typical Use Cases + +- Form validation hints: Use info/warning/error types, provide specific error information in the description, and offer a "View Details" action. +- Operation feedback: After a successful operation, use the success type to show a brief message with an icon. +- System notifications: Use banner mode with closable to improve visibility and controllability. +- Dynamic content: When message/description comes from external data or async rendering, prefer the error boundary version. + +Section sources + +- [docs/components/antd/alert/README-zh_CN.md:1-8](file://docs/components/antd/alert/README-zh_CN.md#L1-L8) +- [docs/components/antd/alert/README.md:1-8](file://docs/components/antd/alert/README.md#L1-L8) + +## Dependency Analysis + +- Frontend export: package.json points both the Gradio and default entries to Index.svelte, ensuring the backend loads it as expected. +- Component coupling: The frontend wrapper is tightly coupled to the Ant Design component, but maintains high extensibility through slots and prop passthrough. +- Backend integration: The backend component resolves the frontend directory via resolve_frontend_dir; events and slots are declared in the Python layer and executed at runtime by the frontend. + +```mermaid +graph LR +PyMain["Python Component
AntdAlert"] --> FEIndex["Svelte Wrapper
Index.svelte"] +PyEB["Python Component
AntdAlertErrorBoundary"] --> FEIndexEB["Svelte Wrapper
error-boundary/Index.svelte"] +FEIndex --> ReactComp["React Component
alert.tsx"] +FEIndexEB --> ReactCompEB["React Component
alert.error-boundary.tsx"] +ReactComp --> AntD["Ant Design Alert"] +ReactCompEB --> AntDEB["Ant Design ErrorBoundary(Alert)"] +``` + +Diagram sources + +- [frontend/antd/alert/package.json:4-12](file://frontend/antd/alert/package.json#L4-L12) +- [backend/modelscope_studio/components/antd/alert/**init**.py:71-71](file://backend/modelscope_studio/components/antd/alert/__init__.py#L71-L71) +- [backend/modelscope_studio/components/antd/alert/error_boundary/**init**.py:55-55](file://backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py#L55-L55) + +Section sources + +- [frontend/antd/alert/package.json:1-15](file://frontend/antd/alert/package.json#L1-L15) +- [backend/modelscope_studio/components/antd/alert/**init**.py:71-71](file://backend/modelscope_studio/components/antd/alert/__init__.py#L71-L71) +- [backend/modelscope_studio/components/antd/alert/error_boundary/**init**.py:55-55](file://backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py#L55-L55) + +## Performance Considerations + +- Avoid frequent re-renders: Use stable values for message/description/icon and other slots; cache computed results in the parent layer when necessary. +- Control slot complexity: Split complex subtrees into components and use them inside the error boundary to reduce overall rendering pressure. +- Use banner judiciously: Banner mode takes up more space; enable it only for critical alerts. +- Event throttling: Avoid heavy synchronous operations in after_close and close event callbacks; use microtasks or debouncing when necessary. + +## Troubleshooting Guide + +- Slots not working + - Check that slot names are correct (action, closable.closeIcon, description, icon, message). + - Confirm the frontend wrapper has passed slots through to the React component. +- Close event not fired + - Confirm the backend event listener has registered the close event. + - When closable is an object containing a closeIcon slot, check that it is correctly passed through. +- Error boundary not catching exceptions + - Confirm the error boundary version of the component is being used. + - Check that exceptions in the message/description slots are properly wrapped. +- Styles not applied + - Check that elem_id, elem_classes, elem_style are correctly passed in. + - Confirm the class name prefix ms-gr-antd-alert or ms-gr-antd-alert-error-boundary has been applied. + +Section sources + +- [frontend/antd/alert/alert.tsx:11-43](file://frontend/antd/alert/alert.tsx#L11-L43) +- [frontend/antd/alert/error-boundary/alert.error-boundary.tsx:12-29](file://frontend/antd/alert/error-boundary/alert.error-boundary.tsx#L12-L29) +- [backend/modelscope_studio/components/antd/alert/**init**.py:16-23](file://backend/modelscope_studio/components/antd/alert/__init__.py#L16-L23) +- [backend/modelscope_studio/components/antd/alert/error_boundary/**init**.py:14-21](file://backend/modelscope_studio/components/antd/alert/error_boundary/__init__.py#L14-L21) + +## Conclusion + +The Alert component in this project provides a complete set of capabilities: typed variants, slot support, closability, and error boundary protection. Through a clear separation of responsibilities between the frontend and backend, and a stable export convention, it satisfies both standard alerting needs and maintains robustness in complex rendering scenarios. When dynamic or external content is involved, it is recommended to use the error boundary version and combine the event and style system to deliver a consistent user experience. + +## Appendix + +- Example entry reference: The demo provided in the documentation is named `basic`; the demonstration effect can be viewed on the corresponding documentation page. + +Section sources + +- [docs/components/antd/alert/README-zh_CN.md:5-7](file://docs/components/antd/alert/README-zh_CN.md#L5-L7) +- [docs/components/antd/alert/README.md:5-7](file://docs/components/antd/alert/README.md#L5-L7) diff --git a/.wiki/en/Ant Design Components/Feedback Components/Drawer.md b/.wiki/en/Ant Design Components/Feedback Components/Drawer.md new file mode 100644 index 00000000..2a458f3c --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Drawer.md @@ -0,0 +1,348 @@ +# Drawer + + +**Files referenced in this document** +- [frontend/antd/drawer/drawer.tsx](file://frontend/antd/drawer/drawer.tsx) +- [frontend/antd/drawer/Index.svelte](file://frontend/antd/drawer/Index.svelte) +- [backend/modelscope_studio/components/antd/drawer/__init__.py](file://backend/modelscope_studio/components/antd/drawer/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [docs/components/antd/drawer/README.md](file://docs/components/antd/drawer/README.md) +- [docs/components/antd/drawer/README-zh_CN.md](file://docs/components/antd/drawer/README-zh_CN.md) +- [docs/components/antd/watermark/demos/modal_or_drawer.py](file://docs/components/antd/watermark/demos/modal_or_drawer.py) +- [frontend/antd/layout/layout.base.tsx](file://frontend/antd/layout/layout.base.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +Drawer is a panel that slides out from the edge of the screen, commonly used for sidebar navigation, detail panels, settings panels, and similar scenarios. This component is implemented based on Ant Design Drawer and bridged through the Gradio ecosystem, supporting position configuration (left, right, top, bottom), size control, mask behavior, keyboard interaction, and rich slot extension capabilities. This document systematically describes its layout design, interaction patterns, use cases, and best practices, with directly referenceable example paths. + +## Project Structure + +The Drawer component consists of a Svelte frontend wrapper and a Python backend component, working together through Gradio's bridging mechanism. The overall structure is as follows: + +```mermaid +graph TB +subgraph "Backend" +PyInit["AntdDrawer Initialization
Parameter and Event Definitions"] +PySlots["Supported Slot List"] +PyEntry["Register to Component Entry"] +end +subgraph "Frontend" +SvelteIndex["Index.svelte
Conditional Rendering and Prop Passthrough"] +ReactWrapper["drawer.tsx
sveltify Wrapper and Slot Handling"] +AntdDrawer["Ant Design Drawer
Native Component"] +end +PyInit --> PySlots +PyInit --> PyEntry +SvelteIndex --> ReactWrapper +ReactWrapper --> AntdDrawer +``` + +Diagram sources + +- [frontend/antd/drawer/Index.svelte:10-61](file://frontend/antd/drawer/Index.svelte#L10-L61) +- [frontend/antd/drawer/drawer.tsx:14-57](file://frontend/antd/drawer/drawer.tsx#L14-L57) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:10-108](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L10-L108) +- [backend/modelscope_studio/components/antd/components.py:38](file://backend/modelscope_studio/components/antd/components.py#L38) + +Section sources + +- [frontend/antd/drawer/Index.svelte:1-65](file://frontend/antd/drawer/Index.svelte#L1-L65) +- [frontend/antd/drawer/drawer.tsx:1-60](file://frontend/antd/drawer/drawer.tsx#L1-L60) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:1-126](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L1-L126) +- [backend/modelscope_studio/components/antd/components.py:38](file://backend/modelscope_studio/components/antd/components.py#L38) + +## Core Components + +- Backend component: AntdDrawer (Python) + - Supported parameters cover key behaviors such as position, size, mask, keyboard, push, and rendering strategy + - Defines the close event binding mechanism + - Exposes multiple slots to support custom title, footer, extra actions, close icon, etc. +- Frontend wrapper: Index.svelte and drawer.tsx + - Conditional rendering: Loads and mounts the Drawer only when `visible` is true + - Prop passthrough: Merges Gradio props and additional props and passes them to the underlying component + - Slot handling: Supports closeIcon, closable.closeIcon, extra, footer, title, drawerRender slots +- Base layout component: Base (layout.base.tsx) + - Provides the base wrapper for Ant Design Layout, making it easy to build page layouts in conjunction with Drawer + +Section sources + +- [backend/modelscope_studio/components/antd/drawer/**init**.py:10-108](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L10-L108) +- [frontend/antd/drawer/Index.svelte:13-42](file://frontend/antd/drawer/Index.svelte#L13-L42) +- [frontend/antd/drawer/drawer.tsx:14-57](file://frontend/antd/drawer/drawer.tsx#L14-L57) +- [frontend/antd/layout/layout.base.tsx:6-37](file://frontend/antd/layout/layout.base.tsx#L6-L37) + +## Architecture Overview + +The Drawer call chain starts from the backend AntdDrawer, goes through the conditional rendering in the frontend Index.svelte, then uses sveltify in drawer.tsx to bridge the React component to the Svelte environment, and finally renders as an Ant Design Drawer. This flow ensures two-way binding of props and events while preserving all capabilities of Ant Design Drawer. + +```mermaid +sequenceDiagram +participant User as "User" +participant Backend as "AntdDrawer (Backend)" +participant FrontIndex as "Index.svelte (Frontend)" +participant Wrapper as "drawer.tsx (Bridge)" +participant AD as "Antd Drawer (React)" +User->>Backend : Set open/visible and other parameters +Backend->>FrontIndex : Render request +FrontIndex->>FrontIndex : Check visible +FrontIndex->>Wrapper : Pass props and slots +Wrapper->>AD : sveltify wrapper and render +AD-->>User : Display drawer and fire event callbacks +``` + +Diagram sources + +- [frontend/antd/drawer/Index.svelte:48-61](file://frontend/antd/drawer/Index.svelte#L48-L61) +- [frontend/antd/drawer/drawer.tsx:24-56](file://frontend/antd/drawer/drawer.tsx#L24-L56) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:14-18](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L14-L18) + +## Detailed Component Analysis + +### Parameters and Slots Overview + +- Key parameters (excerpt) + - Position and size: placement (left/right/top/bottom), width, height, size (default/large) + - Behavior control: open, keyboard, mask, maskClosable, closable, destroyOnClose, destroyOnHidden, forceRender + - Layout and rendering: getContainer, push, resizable, drawerRender, as_item, visible, elem_id/elem_classes/elem_style +- Slots + - closeIcon, closable.closeIcon, extra, footer, title, drawerRender + +Section sources + +- [backend/modelscope_studio/components/antd/drawer/**init**.py:26-107](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L26-L107) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:20-24](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L20-L24) +- [frontend/antd/drawer/drawer.tsx:14-57](file://frontend/antd/drawer/drawer.tsx#L14-L57) + +### Open/Close Mechanism and Events + +- Visibility control: Index.svelte controls whether the Drawer is rendered via `visible` +- Event binding: The backend defines the close event listener for updating state on close +- Callback functions: Callbacks such as afterOpenChange are converted into safely passable functions via useFunction + +```mermaid +flowchart TD +Start(["Start"]) --> CheckVisible["Check visible"] +CheckVisible --> |false| Skip["Do not render"] +CheckVisible --> |true| Render["Render Drawer component"] +Render --> BindEvents["Bind close and other events"] +BindEvents --> Open["Display drawer"] +Open --> UserAction{"User action?"} +UserAction --> |Click mask / Press ESC| Close["Trigger close"] +Close --> UpdateState["Update open/visible state"] +UpdateState --> Destroy{"Destroy strategy?"} +Destroy --> |Yes| Unmount["Unmount component"] +Destroy --> |No| Hide["Hide but keep DOM"] +Unmount --> End(["End"]) +Hide --> End +Skip --> End +``` + +Diagram sources + +- [frontend/antd/drawer/Index.svelte:48-61](file://frontend/antd/drawer/Index.svelte#L48-L61) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:14-18](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L14-L18) +- [frontend/antd/drawer/drawer.tsx:24-26](file://frontend/antd/drawer/drawer.tsx#L24-L26) + +### Position Configuration and Size Control + +- Position: placement supports left, right, top, bottom +- Size: width/height or size (default/large) controls the drawer dimensions +- Push and container: push can be used with a layout to push content; getContainer specifies the mount container + +Section sources + +- [backend/modelscope_studio/components/antd/drawer/**init**.py:47-50](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L47-L50) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:42-56](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L42-L56) +- [frontend/antd/drawer/drawer.tsx:52-54](file://frontend/antd/drawer/drawer.tsx#L52-L54) + +### Mask Behavior and Keyboard Interaction + +- Mask: `mask` controls whether the mask is displayed; `maskClosable` controls whether clicking the mask closes the drawer +- Keyboard: `keyboard` controls whether ESC closes the drawer +- Auto focus: `autoFocus` can automatically focus the drawer on open + +Section sources + +- [backend/modelscope_studio/components/antd/drawer/**init**.py:44-46](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L44-L46) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:31-32](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L31-L32) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:91](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L91) + +### Animation and Rendering Strategy + +- Animation: Driven by Ant Design Drawer's built-in animation; no additional configuration needed +- Rendering strategy: destroyOnClose, destroyOnHidden, forceRender control the destruction timing and forced rendering + +Section sources + +- [backend/modelscope_studio/components/antd/drawer/**init**.py:36-39](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L36-L39) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:87-89](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L87-L89) + +### Slot and Style Customization + +- Slot mapping: closeIcon, closable.closeIcon, extra, footer, title, drawerRender +- Styles: elem_id, elem_classes, elem_style, styles, class_names, root_style, root_class_name +- Custom rendering: drawerRender can receive parameters and return custom rendered content + +Section sources + +- [backend/modelscope_studio/components/antd/drawer/**init**.py:20-24](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L20-L24) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:33-35](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L33-L35) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:57-60](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L57-L60) +- [frontend/antd/drawer/drawer.tsx:41-51](file://frontend/antd/drawer/drawer.tsx#L41-L51) + +### Coordination with Page Layout and Responsive Adaptation + +- Layout collaboration: Can be combined with Ant Design Layout (Header/Footer/Content/Sider) +- Responsive: Combined with Flex/Grid and other layout components, adjust drawer width or switch placement based on screen size + +Section sources + +- [frontend/antd/layout/layout.base.tsx:6-37](file://frontend/antd/layout/layout.base.tsx#L6-L37) + +### Accessibility and Mobile Optimization + +- Accessibility: The keyboard and focus strategies should be combined with auto-focus and semantic labeling +- Mobile: On small-screen devices, prefer using `bottom` or a smaller `width` to avoid covering main content + +Section sources + +- [backend/modelscope_studio/components/antd/drawer/**init**.py:91](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L91) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:31-32](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L31-L32) + +### Common Use Cases and Example Paths + +- Sidebar navigation: Place menu items in the left drawer; update routes or data when a menu item is clicked +- Detail panel: Display detailed content in the right drawer, supporting scrolling and a bottom action area +- Settings panel: Provide settings in the top or bottom drawer, supporting quick toggling and saving +- Example references: + - Drawer basic usage and extra actions: [docs/components/antd/drawer/README.md](file://docs/components/antd/drawer/README.md) + - Drawer vs. Modal comparison demo: [docs/components/antd/watermark/demos/modal_or_drawer.py](file://docs/components/antd/watermark/demos/modal_or_drawer.py) + +Section sources + +- [docs/components/antd/drawer/README.md:1-9](file://docs/components/antd/drawer/README.md#L1-L9) +- [docs/components/antd/watermark/demos/modal_or_drawer.py:19-26](file://docs/components/antd/watermark/demos/modal_or_drawer.py#L19-L26) + +## Dependency Analysis + +- Component inheritance and context + - AntdDrawer inherits from ModelScopeLayoutComponent, with the general characteristics of a layout component + - AppContext is used to ensure the application context is available +- Component registration + - AntdDrawer is exported from the component entry for unified import and usage + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++bool visible ++str elem_id ++any elem_classes ++dict elem_style ++bool skip_api +} +class AntdDrawer { ++dict additional_props ++str after_open_change ++bool auto_focus ++dict body_style ++str close_icon ++any class_names ++any closable ++bool destroy_on_close ++bool destroy_on_hidden ++bool draggable ++str extra ++str footer ++bool force_render ++any get_container ++num height ++bool keyboard ++bool mask ++bool mask_closable ++str placement ++any push ++bool resizable ++str size ++any styles ++str title ++bool loading ++bool open ++num width ++int z_index ++str drawer_render ++dict root_style ++str root_class_name ++str as_item ++dict _internal ++bool visible ++str elem_id ++any elem_classes ++dict elem_style ++bool render +} +ModelScopeLayoutComponent <|-- AntdDrawer +``` + +Diagram sources + +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:10-108](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L10-L108) + +Section sources + +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [backend/modelscope_studio/components/antd/components.py:38](file://backend/modelscope_studio/components/antd/components.py#L38) + +## Performance Considerations + +- Conditional rendering: Render the Drawer only when `visible` is true to reduce unnecessary DOM overhead +- Rendering strategy: Use destroyOnClose/destroyOnHidden appropriately to balance memory usage and interaction smoothness +- Slots and custom rendering: Avoid heavy computations in drawerRender; use caching or async processing when necessary + +## Troubleshooting Guide + +- Drawer not showing + - Check if visible/open is true + - Confirm the conditional rendering logic in Index.svelte +- Slots not working + - Confirm slot names are correct (closeIcon, closable.closeIcon, extra, footer, title, drawerRender) + - Confirm the slot mapping logic in drawer.tsx +- Close event not fired + - Check the backend event binding and callback function passing +- Mask not working or clicking does not close + - Check mask and maskClosable configuration +- Keyboard close not working + - Check keyboard configuration and auto-focus strategy + +Section sources + +- [frontend/antd/drawer/Index.svelte:48-61](file://frontend/antd/drawer/Index.svelte#L48-L61) +- [frontend/antd/drawer/drawer.tsx:41-51](file://frontend/antd/drawer/drawer.tsx#L41-L51) +- [backend/modelscope_studio/components/antd/drawer/**init**.py:14-18](file://backend/modelscope_studio/components/antd/drawer/__init__.py#L14-L18) + +## Conclusion + +The Drawer component, through its integrated frontend-backend design, preserves the native capabilities of Ant Design Drawer while providing more flexible parameter and slot extensions. With conditional rendering and event binding mechanisms, it can efficiently adapt to various interaction scenarios, including sidebar navigation, detail panels, and settings panels. At the layout level, it can work in conjunction with Ant Design Layout; for accessibility and mobile experience, it is recommended to combine keyboard and size strategies to enhance the user experience. + +## Appendix + +- Example references + - Drawer basic usage and extra actions: [docs/components/antd/drawer/README.md](file://docs/components/antd/drawer/README.md) + - Drawer vs. Modal comparison demo: [docs/components/antd/watermark/demos/modal_or_drawer.py](file://docs/components/antd/watermark/demos/modal_or_drawer.py) +- Related documentation + - Ant Design Drawer official documentation: [Ant Design Drawer](https://ant.design/components/drawer/) diff --git a/.wiki/en/Ant Design Components/Feedback Components/Feedback Components.md b/.wiki/en/Ant Design Components/Feedback Components/Feedback Components.md new file mode 100644 index 00000000..6fa5d009 --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Feedback Components.md @@ -0,0 +1,437 @@ +# Feedback Components + + +**Files referenced in this document** +- [alert.tsx](file://frontend/antd/alert/alert.tsx) +- [drawer.tsx](file://frontend/antd/drawer/drawer.tsx) +- [message.tsx](file://frontend/antd/message/message.tsx) +- [modal.tsx](file://frontend/antd/modal/modal.tsx) +- [notification.tsx](file://frontend/antd/notification/notification.tsx) +- [popconfirm.tsx](file://frontend/antd/popconfirm/popconfirm.tsx) +- [progress.tsx](file://frontend/antd/progress/progress.tsx) +- [result.tsx](file://frontend/antd/result/result.tsx) +- [skeleton.tsx](file://frontend/antd/skeleton/skeleton.tsx) +- [spin.tsx](file://frontend/antd/spin/spin.tsx) +- [watermark.tsx](file://frontend/antd/watermark/watermark.tsx) +- [useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [useTargets.ts](file://frontend/utils/hooks/useTargets.ts) +- [renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically covers the frontend wrappers and usage of Ant Design feedback components, including: Alert, Drawer, Message, Modal, Notification, Popconfirm, Progress, Result, Skeleton, Spin, and Watermark. It focuses on each component's trigger mechanism, display timing, interaction logic, animation and transition state management, error and exception handling strategies, accessibility and keyboard operation support, as well as feedback design patterns for complex interaction scenarios. + +## Project Structure + +All feedback components reside in the frontend directory and follow a unified wrapping pattern: bridging native Ant Design components to Svelte-style components via `sveltify`; implementing slot-based rendering via ReactSlot and renderParamsSlot; and ensuring correct propagation and ordering of callbacks and slot targets through utility hooks such as useFunction and useTargets. + +```mermaid +graph TB +subgraph "Ant Design Feedback Components" +A1["Alert
frontend/antd/alert/alert.tsx"] +A2["Drawer
frontend/antd/drawer/drawer.tsx"] +A3["Message
frontend/antd/message/message.tsx"] +A4["Modal
frontend/antd/modal/modal.tsx"] +A5["Notification
frontend/antd/notification/notification.tsx"] +A6["Popconfirm
frontend/antd/popconfirm/popconfirm.tsx"] +A7["Progress
frontend/antd/progress/progress.tsx"] +A8["Result
frontend/antd/result/result.tsx"] +A9["Skeleton
frontend/antd/skeleton/skeleton.tsx"] +A10["Spin
frontend/antd/spin/spin.tsx"] +A11["Watermark
frontend/antd/watermark/watermark.tsx"] +end +subgraph "Utilities and Hooks" +U1["useFunction
frontend/utils/hooks/useFunction.ts"] +U2["useTargets
frontend/utils/hooks/useTargets.ts"] +U3["renderParamsSlot
frontend/utils/renderParamsSlot.tsx"] +end +A1 --> U1 +A2 --> U1 +A3 --> U1 +A4 --> U1 +A5 --> U1 +A6 --> U1 +A7 --> U1 +A8 --> U2 +A9 --> U1 +A10 --> U2 +A11 --> U1 +A2 --> U3 +A4 --> U3 +``` + +Diagram sources + +- [alert.tsx:1-46](file://frontend/antd/alert/alert.tsx#L1-L46) +- [drawer.tsx:1-60](file://frontend/antd/drawer/drawer.tsx#L1-L60) +- [message.tsx:1-79](file://frontend/antd/message/message.tsx#L1-L79) +- [modal.tsx:1-107](file://frontend/antd/modal/modal.tsx#L1-L107) +- [notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) +- [popconfirm.tsx:1-65](file://frontend/antd/popconfirm/popconfirm.tsx#L1-L65) +- [progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) +- [skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +Section sources + +- [alert.tsx:1-46](file://frontend/antd/alert/alert.tsx#L1-L46) +- [drawer.tsx:1-60](file://frontend/antd/drawer/drawer.tsx#L1-L60) +- [message.tsx:1-79](file://frontend/antd/message/message.tsx#L1-L79) +- [modal.tsx:1-107](file://frontend/antd/modal/modal.tsx#L1-L107) +- [notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) +- [popconfirm.tsx:1-65](file://frontend/antd/popconfirm/popconfirm.tsx#L1-L65) +- [progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) +- [skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +## Core Components + +- Unified wrapping: All feedback components wrap native Ant Design components via `sveltify`, preserving their APIs while extending slot capabilities. +- Slot system: ReactSlot renders named slots (e.g., title, description, icon, footer), with some components supporting parameterized slot rendering (renderParamsSlot). +- Callback adaptation: useFunction wraps incoming functions as stable references, avoiding side effects or duplicate subscriptions caused by re-rendering. +- Target selection: useTargets extracts deliverable target nodes from children, supporting complex layouts and conditional rendering. +- Context holder: Message/Notification obtain context holders via useMessage/useNotification, enabling mounting and destruction of global messages and notifications. + +Section sources + +- [alert.tsx:7-43](file://frontend/antd/alert/alert.tsx#L7-L43) +- [drawer.tsx:14-57](file://frontend/antd/drawer/drawer.tsx#L14-L57) +- [message.tsx:9-76](file://frontend/antd/message/message.tsx#L9-L76) +- [modal.tsx:8-104](file://frontend/antd/modal/modal.tsx#L8-L104) +- [notification.tsx:8-103](file://frontend/antd/notification/notification.tsx#L8-L103) +- [popconfirm.tsx:7-62](file://frontend/antd/popconfirm/popconfirm.tsx#L7-L62) +- [progress.tsx:5-21](file://frontend/antd/progress/progress.tsx#L5-L21) +- [result.tsx:7-30](file://frontend/antd/result/result.tsx#L7-L30) +- [skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [spin.tsx:7-35](file://frontend/antd/spin/spin.tsx#L7-L35) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [renderParamsSlot.tsx:5-50](file://frontend/utils/renderParamsSlot.tsx#L5-L50) + +## Architecture Overview + +The runtime architecture of feedback components revolves around "prop passthrough + slot rendering + callback adaptation". For components that need global mounting (Message/Notification), context holders are obtained via useMessage/useNotification and injected into the DOM upon component mount. For container-type components (Drawer/Modal), the mount target is determined via getContainer or a string selector. For content-type components (Alert/Result/Spin), slots control the title, description, icon, extra content, and more. + +```mermaid +graph TB +C["Application-layer Component"] --> F1["useFunction
Stable Function Reference"] +C --> F2["useTargets
Resolve Slot Targets"] +C --> F3["renderParamsSlot
Parameterized Slot Rendering"] +subgraph "Global Feedback" +M["Message
useMessage"] --> D1["DOM Mount Point"] +N["Notification
useNotification"] --> D2["DOM Mount Point"] +end +subgraph "Container Feedback" +DR["Drawer"] --> G1["getContainer / String"] +MD["Modal"] --> G2["getContainer / String"] +end +subgraph "Content Feedback" +AL["Alert"] +RS["Result"] +SP["Spin"] +end +``` + +Diagram sources + +- [message.tsx:30-33](file://frontend/antd/message/message.tsx#L30-L33) +- [notification.tsx:31-36](file://frontend/antd/notification/notification.tsx#L31-L36) +- [drawer.tsx:52-54](file://frontend/antd/drawer/drawer.tsx#L52-L54) +- [modal.tsx:96-98](file://frontend/antd/modal/modal.tsx#L96-L98) +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [renderParamsSlot.tsx:5-50](file://frontend/utils/renderParamsSlot.tsx#L5-L50) + +## Component Details + +### Alert + +- Trigger mechanism: Triggered by business state changes or user actions; can be closed via `closable`, which fires the `afterClose` callback. +- Display timing: Shown or hidden based on the data source after page initialization; supports dynamic switching of message/description/icon/action slots. +- Interaction logic: Clicking the close button triggers an animated collapse; the `afterClose` callback can be used for resource cleanup or navigation. +- Animation & transitions: Built-in Ant Design animations; slots allow custom icons and action buttons. +- Error handling: Falls back to prop-provided content when slot content is empty; releases resources after closing. +- Accessibility & keyboard: Follows Ant Design default accessibility; it is recommended to provide explicit ARIA labels for the close button. + +Section sources + +- [alert.tsx:7-43](file://frontend/antd/alert/alert.tsx#L7-L43) + +### Drawer + +- Trigger mechanism: Triggered by a button click or route change via `visible`; supports `afterOpenChange` to manage state after opening/closing. +- Display timing: Animates in on first open; animates out on close. +- Interaction logic: Supports custom `closeIcon`, `extra`, `footer`, `title`; `closable.closeIcon` can replace the default close icon. +- Animation & transitions: Controlled by Ant Design's slide-in/slide-out animation; `drawerRender` supports custom rendering logic. +- Error handling: When `getContainer` is a string, it is wrapped via `useFunction`; falls back to the default container on exception. +- Accessibility & keyboard: Maintains native focus order; it is recommended to provide explicit action buttons in the footer. + +Section sources + +- [drawer.tsx:8-57](file://frontend/antd/drawer/drawer.tsx#L8-L57) + +### Message + +- Trigger mechanism: Controlled by the `visible` prop; internally uses `messageApi.open` to open the message. +- Display timing: An effect watches for `visible=true` to open the message; `onClose` is triggered when the `duration` expires or the message is manually closed. +- Interaction logic: `onVisible(false)` and `onClose` are synchronized callbacks; supports deduplication via `key` and `destroy`. +- Animation & transitions: Built-in Ant Design animations; content/icon slots can customize content and icons. +- Error handling: The effect cleanup phase calls `destroy`; ensures the message is only opened once on exception. +- Accessibility & keyboard: Automatically mounted to the context holder; it is recommended to provide readable text and concise descriptions. + +Section sources + +- [message.tsx:19-76](file://frontend/antd/message/message.tsx#L19-L76) + +### Modal + +- Trigger mechanism: `visible` controls display; `afterOpenChange`/`afterClose` manage lifecycle after opening/closing. +- Display timing: Animates in on first open; animates out on close. +- Interaction logic: ok/cancel text and icons can all be customized via slots; `footer` supports a function or a default value. +- Animation & transitions: Built-in Ant Design animations; `modalRender` supports custom rendering. +- Error handling: When `getContainer` is a string, it is wrapped as a function; when `footer` equals `DEFAULT_FOOTER`, it falls back to `undefined`. +- Accessibility & keyboard: Maintains default focus and ESC closing; it is recommended to provide clear confirm/cancel semantics. + +Section sources + +- [modal.tsx:22-104](file://frontend/antd/modal/modal.tsx#L22-L104) + +### Notification + +- Trigger mechanism: `visible` controls display; `open`/`destroy` returned by `useNotification` control the message lifecycle. +- Display timing: An effect watches for `visible=true` to open; `onClose` is triggered when `duration` expires or the notification is manually closed. +- Interaction logic: `onVisible(false)`/`onClose` are synchronized callbacks; supports `placement`, `stack`, `top`/`bottom` positioning. +- Animation & transitions: Built-in Ant Design animations; supports description/icon/actions/btn slots. +- Error handling: The effect cleanup phase calls `destroy`; ensures the notification is only opened once on exception. +- Accessibility & keyboard: It is recommended to provide readable titles and descriptions; supports hover-to-pause and progress bar. + +Section sources + +- [notification.tsx:18-103](file://frontend/antd/notification/notification.tsx#L18-L103) + +### Popconfirm + +- Trigger mechanism: A user click triggers the bubble popup; `afterOpenChange` manages the popup open state. +- Display timing: Pops up immediately after clicking the target element; closes after confirm/cancel. +- Interaction logic: ok/cancel text and icons can all be customized via slots; title/description supports clone rendering. +- Animation & transitions: Bubble animation controlled by Ant Design; `getPopupContainer` supports specifying a mount container. +- Error handling: Falls back to props when slot content is empty; keeps interaction available on exception. +- Accessibility & keyboard: Maintains default focus and ESC closing; it is recommended to provide clear confirm/cancel semantics. + +Section sources + +- [popconfirm.tsx:7-62](file://frontend/antd/popconfirm/popconfirm.tsx#L7-L62) + +### Progress + +- Trigger mechanism: Value changes drive progress updates; `format` and `rounding` support custom formatting. +- Display timing: Value changes are reflected immediately; supports both static and dynamic modes. +- Interaction logic: `format` and `rounding` are wrapped as stable references via `useFunction`. +- Animation & transitions: Built-in Ant Design animations; supports percentage, status, and custom text. +- Error handling: Out-of-bounds values are handled by Ant Design; keeps the component stable on exception. +- Accessibility & keyboard: No interactive input; it is recommended to provide readable text. + +Section sources + +- [progress.tsx:5-21](file://frontend/antd/progress/progress.tsx#L5-L21) + +### Result + +- Trigger mechanism: Displayed after a business operation completes; supports title/subTitle/icon/extra slots. +- Display timing: Rendered immediately once data is ready; children serve as additional content. +- Interaction logic: useTargets resolves slot targets; falls back to children when no slots are provided. +- Animation & transitions: Built-in Ant Design animations; supports multiple status icons and text. +- Error handling: Falls back to props when slot content is empty; keeps content visible on exception. +- Accessibility & keyboard: It is recommended to provide readable titles and descriptions. + +Section sources + +- [result.tsx:7-30](file://frontend/antd/result/result.tsx#L7-L30) + +### Skeleton + +- Trigger mechanism: Displays a skeleton before data loads; switches to real content once loading is complete. +- Display timing: Shown immediately on component mount; switches automatically when real content is ready. +- Interaction logic: No interaction; supports animation and shape configuration. +- Animation & transitions: Built-in Ant Design skeleton animation. +- Error handling: Keeps the skeleton stable on exception; it is recommended to provide a timeout fallback. +- Accessibility & keyboard: No interaction; it is recommended to provide ARIA hints for the loading state. + +Section sources + +- [skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) + +### Spin + +- Trigger mechanism: Shown when an async task starts; hidden when the task ends. +- Display timing: Shown immediately on component mount; wraps real content when children are empty. +- Interaction logic: useTargets resolves slot targets; tip/indicator supports slots. +- Animation & transitions: Built-in Ant Design spinning animation; supports custom indicator and tip text. +- Error handling: Falls back to props when slot content is empty; keeps the loading state on exception. +- Accessibility & keyboard: It is recommended to provide an ARIA label and loading state hint. + +Section sources + +- [spin.tsx:7-35](file://frontend/antd/spin/spin.tsx#L7-L35) + +### Watermark + +- Trigger mechanism: Watermark is generated after page load; supports dynamic updates to text and size. +- Display timing: Takes effect immediately on component mount; suitable for full-screen or localized watermarks. +- Interaction logic: No interaction; supports multi-line text and opacity configuration. +- Animation & transitions: No animation; suitable as a background decoration. +- Error handling: Keeps the watermark stable on exception; it is recommended to provide a fallback solution. +- Accessibility & keyboard: No interaction; does not affect accessibility. + +Section sources + +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) + +## Dependency Analysis + +- Inter-component coupling: Feedback components are independent of one another, sharing only utility hooks. Container-type components share getContainer and renderParamsSlot; global-type components share the context holder. +- External dependencies: Native Ant Design components and styles; React Slot rendering; Svelte Preprocess React bridge. +- Circular dependencies: No circular dependencies found; utility hooks are pure functional wrappers. +- Interface contracts: All components maintain compatibility with the Ant Design API via `sveltify`; slot key names and rendering strategies are consistent. + +```mermaid +graph LR +subgraph "Utility Layer" +UF["useFunction"] +UT["useTargets"] +RPS["renderParamsSlot"] +end +subgraph "Feedback Components" +MSG["Message"] +NOTI["Notification"] +MOD["Modal"] +DRW["Drawer"] +ALERT["Alert"] +POP["Popconfirm"] +PROG["Progress"] +RES["Result"] +SKEL["Skeleton"] +SPIN["Spin"] +WM["Watermark"] +end +UF --> MSG +UF --> NOTI +UF --> MOD +UF --> DRW +UF --> ALERT +UF --> POP +UF --> PROG +UT --> RES +UT --> SPIN +RPS --> MOD +RPS --> DRW +``` + +Diagram sources + +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [renderParamsSlot.tsx:5-50](file://frontend/utils/renderParamsSlot.tsx#L5-L50) +- [message.tsx:29-33](file://frontend/antd/message/message.tsx#L29-L33) +- [notification.tsx:31-36](file://frontend/antd/notification/notification.tsx#L31-L36) +- [modal.tsx:34-35](file://frontend/antd/modal/modal.tsx#L34-L35) +- [drawer.tsx:27-28](file://frontend/antd/drawer/drawer.tsx#L27-L28) +- [alert.tsx:13-20](file://frontend/antd/alert/alert.tsx#L13-L20) +- [popconfirm.tsx:18-20](file://frontend/antd/popconfirm/popconfirm.tsx#L18-L20) +- [progress.tsx:10-12](file://frontend/antd/progress/progress.tsx#L10-L12) +- [result.tsx:11-12](file://frontend/antd/result/result.tsx#L11-L12) +- [spin.tsx:13-14](file://frontend/antd/spin/spin.tsx#L13-L14) + +Section sources + +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [renderParamsSlot.tsx:5-50](file://frontend/utils/renderParamsSlot.tsx#L5-L50) +- [message.tsx:29-33](file://frontend/antd/message/message.tsx#L29-L33) +- [notification.tsx:31-36](file://frontend/antd/notification/notification.tsx#L31-L36) +- [modal.tsx:34-35](file://frontend/antd/modal/modal.tsx#L34-L35) +- [drawer.tsx:27-28](file://frontend/antd/drawer/drawer.tsx#L27-L28) +- [alert.tsx:13-20](file://frontend/antd/alert/alert.tsx#L13-L20) +- [popconfirm.tsx:18-20](file://frontend/antd/popconfirm/popconfirm.tsx#L18-L20) +- [progress.tsx:10-12](file://frontend/antd/progress/progress.tsx#L10-L12) +- [result.tsx:11-12](file://frontend/antd/result/result.tsx#L11-L12) +- [spin.tsx:13-14](file://frontend/antd/spin/spin.tsx#L13-L14) + +## Performance Considerations + +- Stable function references: useFunction wraps callbacks as useMemo references, reducing unnecessary re-renders and side effects. +- Slot rendering optimization: ReactSlot and renderParamsSlot clone and render only when necessary, avoiding full re-layouts. +- Lifecycle management: Message/Notification proactively call `destroy` in the effect cleanup phase to prevent memory leaks. +- Container mounting: When `getContainer` for Drawer/Modal is a string, a wrapper function is used to avoid repeated bindings. +- Conditional rendering: Spin/Result use useTargets and conditional branches to render real content only when slots are present, reducing DOM overhead. + +## Troubleshooting Guide + +- Slots not working + - Check that slot key names match the component declarations; confirm that ReactSlot is correctly wrapping them. + - Reference paths: [alert.tsx:17-40](file://frontend/antd/alert/alert.tsx#L17-L40), [result.tsx:17-27](file://frontend/antd/result/result.tsx#L17-L27), [spin.tsx:20-32](file://frontend/antd/spin/spin.tsx#L20-L32) +- Callbacks not fired or firing repeatedly + - Use useFunction to wrap callbacks to ensure stable references; check the effect dependency array. + - Reference paths: [message.tsx:35-68](file://frontend/antd/message/message.tsx#L35-L68), [notification.tsx:38-95](file://frontend/antd/notification/notification.tsx#L38-L95) +- Global message not displayed + - Confirm the context holder has been rendered; verify that `visible` and `key` are configured correctly; set a reasonable `duration`. + - Reference paths: [message.tsx:30-33](file://frontend/antd/message/message.tsx#L30-L33), [notification.tsx:31-36](file://frontend/antd/notification/notification.tsx#L31-L36) +- Container mount exception + - When `getContainer` is a string, ensure it is wrapped as a function; check selector validity. + - Reference paths: [drawer.tsx:52-54](file://frontend/antd/drawer/drawer.tsx#L52-L54), [modal.tsx:96-98](file://frontend/antd/modal/modal.tsx#L96-L98) +- Animation stuttering or flickering + - Check if slot content is changing frequently; avoid heavy DOM operations during animations. + - Reference paths: [progress.tsx:10-12](file://frontend/antd/progress/progress.tsx#L10-L12), [spin.tsx:13-14](file://frontend/antd/spin/spin.tsx#L13-L14) + +Section sources + +- [alert.tsx:17-40](file://frontend/antd/alert/alert.tsx#L17-L40) +- [result.tsx:17-27](file://frontend/antd/result/result.tsx#L17-L27) +- [spin.tsx:20-32](file://frontend/antd/spin/spin.tsx#L20-L32) +- [message.tsx:30-33](file://frontend/antd/message/message.tsx#L30-L33) +- [notification.tsx:31-36](file://frontend/antd/notification/notification.tsx#L31-L36) +- [drawer.tsx:52-54](file://frontend/antd/drawer/drawer.tsx#L52-L54) +- [modal.tsx:96-98](file://frontend/antd/modal/modal.tsx#L96-L98) +- [progress.tsx:10-12](file://frontend/antd/progress/progress.tsx#L10-L12) + +## Conclusion + +This repository provides a systematic wrapper for Ant Design feedback components, unifying slot rendering, callback adaptation, and lifecycle management. Through stable function references, conditional rendering, and context holders, it achieves a highly available and maintainable feedback system. It is recommended to select the appropriate component and trigger strategy based on your business scenario in practice, and to pay attention to accessibility and performance details. + +## Appendix + +- Best practices + - Use `visible` and `key` to manage the uniqueness and lifecycle of global messages. + - Provide clear confirm/cancel semantics and keyboard support for important operations. + - In complex layouts, prefer renderParamsSlot and useTargets to manage slot targets. + - Provide clear text and visual cues for loading states and error states. +- Complex interaction scenarios + - Multi-step flows: Use Result to display the final state; Progress to show progress; Spin to wrap critical areas. + - Global notifications: Place Notification in the top-right or bottom-right corner, supporting stacking and pause-on-hover. + - Modal confirmation: Use Modal/Popconfirm for critical deletions and dangerous operations to provide a second confirmation. + - Drawer navigation: Use Drawer as a secondary panel for long lists or settings pages; pay attention to getContainer and z-index management. diff --git a/.wiki/en/Ant Design Components/Feedback Components/Interactive Feedback.md b/.wiki/en/Ant Design Components/Feedback Components/Interactive Feedback.md new file mode 100644 index 00000000..a711d684 --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Interactive Feedback.md @@ -0,0 +1,301 @@ +# Interactive Feedback + + +**Files referenced in this document** +- [frontend/antd/popconfirm/popconfirm.tsx](file://frontend/antd/popconfirm/popconfirm.tsx) +- [frontend/antd/popover/popover.tsx](file://frontend/antd/popover/popover.tsx) +- [frontend/antd/popconfirm/Index.svelte](file://frontend/antd/popconfirm/Index.svelte) +- [frontend/antd/popover/Index.svelte](file://frontend/antd/popover/Index.svelte) +- [backend/modelscope_studio/components/antd/popconfirm/__init__.py](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py) +- [backend/modelscope_studio/components/antd/popover/__init__.py](file://backend/modelscope_studio/components/antd/popover/__init__.py) +- [docs/components/antd/popconfirm/README-zh_CN.md](file://docs/components/antd/popconfirm/README-zh_CN.md) +- [docs/components/antd/popover/README-zh_CN.md](file://docs/components/antd/popover/README-zh_CN.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on two types of components in the interactive feedback component group: Popconfirm (Bubble Confirmation) and Popover (Bubble Card). It provides a systematic explanation from design philosophy, interaction patterns, confirmation flow, content delivery, trigger and positioning strategies, props and events, style customization, and common use cases, along with source-traceable reference paths to help developers quickly understand and correctly use these components. + +## Project Structure + +These two components use a "Svelte wrapper layer + React component library bridge" pattern on the frontend, with the backend exposing a Python API through Gradio component wrapping. Their organization is as follows: + +- Frontend layer: Svelte components handle prop passthrough, slot rendering, and event mapping; the TypeScript bridge layer adapts Ant Design's React components for use in Svelte. +- Backend layer: Python component classes define props, events, slots, and default values, and declare frontend directory mappings so the runtime can load the corresponding frontend components. + +```mermaid +graph TB +subgraph "Frontend" +IDX_PCF["Index.svelte
popconfirm"] --> BRG_PCF["popconfirm.tsx
Bridge Layer"] +IDX_POV["Index.svelte
popover"] --> BRG_POV["popover.tsx
Bridge Layer"] +end +subgraph "Backend" +PY_PCF["AntdPopconfirm
Python Component"] --> FE_DIR_PCF["resolve_frontend_dir('popconfirm')"] +PY_POV["AntdPopover
Python Component"] --> FE_DIR_POV["resolve_frontend_dir('popover')"] +end +BRG_PCF --> ANT_PCF["Ant Design Popconfirm"] +BRG_POV --> ANT_POV["Ant Design Popover"] +PY_PCF --> IDX_PCF +PY_POV --> IDX_POV +``` + +Diagram sources + +- [frontend/antd/popconfirm/Index.svelte:1-76](file://frontend/antd/popconfirm/Index.svelte#L1-L76) +- [frontend/antd/popover/Index.svelte:1-76](file://frontend/antd/popover/Index.svelte#L1-L76) +- [frontend/antd/popconfirm/popconfirm.tsx:1-65](file://frontend/antd/popconfirm/popconfirm.tsx#L1-L65) +- [frontend/antd/popover/popover.tsx:1-37](file://frontend/antd/popover/popover.tsx#L1-L37) +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:138-138](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L138-L138) +- [backend/modelscope_studio/components/antd/popover/**init**.py:106-106](file://backend/modelscope_studio/components/antd/popover/__init__.py#L106-L106) + +Section sources + +- [frontend/antd/popconfirm/Index.svelte:1-76](file://frontend/antd/popconfirm/Index.svelte#L1-L76) +- [frontend/antd/popover/Index.svelte:1-76](file://frontend/antd/popover/Index.svelte#L1-L76) +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:138-138](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L138-L138) +- [backend/modelscope_studio/components/antd/popover/**init**.py:106-106](file://backend/modelscope_studio/components/antd/popover/__init__.py#L106-L106) + +## Core Components + +- Popconfirm + - Design philosophy: Provides a second confirmation for dangerous or irreversible operations to reduce accidental operation risk. + - Key interactions: Supports hover/focus/click/contextMenu triggers; provides confirm/cancel dual buttons with text/icon slots. + - Confirmation flow: Clicking confirm fires the callback; cancel closes the popup; supports controlled `open` state and controlled event callbacks. +- Popover + - Design philosophy: Provides contextual information hints or lightweight action entry points for target elements without changing the page layout. + - Key interactions: Supports hover/focus/click/contextMenu triggers; title and content can be slotted, with automatic collision avoidance and positioning. + +Section sources + +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:10-27](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L10-L27) +- [backend/modelscope_studio/components/antd/popover/**init**.py:10-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L18) + +## Architecture Overview + +The following diagram shows the call chain and data flow from the frontend Svelte to the backend Python component. + +```mermaid +sequenceDiagram +participant Py as "Python Component
AntdPopconfirm/AntdPopover" +participant Idx as "Svelte Wrapper Layer
Index.svelte" +participant Br as "Bridge Layer
popconfirm.tsx / popover.tsx" +participant AD as "Ant Design Component" +Py->>Idx : "Instantiate and pass props/events/slots" +Idx->>Br : "Render bridge component, pass through props and slots" +Br->>AD : "Call Ant Design component, inject events and container" +AD-->>Br : "State change (openChange)" +Br-->>Idx : "Callback fired" +Idx-->>Py : "Event report (e.g., open_change/popup_click)" +``` + +Diagram sources + +- [frontend/antd/popconfirm/Index.svelte:24-55](file://frontend/antd/popconfirm/Index.svelte#L24-L55) +- [frontend/antd/popover/Index.svelte:24-52](file://frontend/antd/popover/Index.svelte#L24-L52) +- [frontend/antd/popconfirm/popconfirm.tsx:17-62](file://frontend/antd/popconfirm/popconfirm.tsx#L17-L62) +- [frontend/antd/popover/popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:14-27](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L14-L27) +- [backend/modelscope_studio/components/antd/popover/**init**.py:14-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L18) + +## Detailed Component Analysis + +### Popconfirm + +- Design philosophy and interaction pattern + - Targeting "high-risk operations", reduces accidental trigger cost through a second confirmation. + - Supports multiple trigger modes; the popup provides confirm/cancel buttons with an optional icon. +- Props and events + - Key props: title, description, confirm text/button props, cancel text/button props, trigger type, positioning and collision avoidance, container mount point, delay, z-index, etc. + - Key events: open_change, cancel, confirm, popup_click. + - Key slots: title, description, okText, okButtonProps.icon, cancelText, cancelButtonProps.icon. +- Callbacks and state + - Get open/close state changes via `afterOpenChange`. + - Customize the mount container via `getPopupContainer` for positioning and z-index control in complex layouts. +- Use cases + - Delete confirmation, edit confirmation, batch operation confirmation, etc. + +```mermaid +flowchart TD +Start(["User trigger"]) --> Trigger{"Trigger type"} +Trigger --> |click/hover/focus/contextMenu| Open["Open confirmation popup"] +Open --> Action{"User choice"} +Action --> |Confirm| Confirm["Fire confirm callback"] +Action --> |Cancel| Cancel["Fire cancel callback"] +Confirm --> Close["Close popup"] +Cancel --> Close +Close --> End(["End"]) +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:14-27](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L14-L27) +- [frontend/antd/popconfirm/popconfirm.tsx:17-62](file://frontend/antd/popconfirm/popconfirm.tsx#L17-L62) + +Section sources + +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:10-137](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L10-L137) +- [frontend/antd/popconfirm/popconfirm.tsx:7-62](file://frontend/antd/popconfirm/popconfirm.tsx#L7-L62) +- [frontend/antd/popconfirm/Index.svelte:24-75](file://frontend/antd/popconfirm/Index.svelte#L24-L75) + +### Popover + +- Design philosophy and interaction pattern + - Provides non-intrusive information display and lightweight action entry points. + - Supports title and content slots, with automatic collision avoidance and multi-directional positioning. +- Props and events + - Key props: title, content, trigger type, placement, arrow, color, container mount point, delay, z-index, etc. + - Key events: open_change. + - Key slots: title, content. +- Use cases + - Information hints, action menus, supplementary explanations, etc. + +```mermaid +sequenceDiagram +participant U as "User" +participant P as "Popover" +participant C as "Content Slot" +participant D as "Positioning and Collision Avoidance" +U->>P : "Trigger (click/hover/focus/right-click)" +P->>D : "Calculate optimal position and collision avoidance" +P->>C : "Render title/content slots" +P-->>U : "Display floating layer" +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/popover/**init**.py:14-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L18) +- [frontend/antd/popover/popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) + +Section sources + +- [backend/modelscope_studio/components/antd/popover/**init**.py:10-104](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L104) +- [frontend/antd/popover/popover.tsx:7-34](file://frontend/antd/popover/popover.tsx#L7-L34) +- [frontend/antd/popover/Index.svelte:24-72](file://frontend/antd/popover/Index.svelte#L24-L72) + +### Component Classes and Bridge Layer Relationships + +```mermaid +classDiagram +class AntdPopconfirm { ++EVENTS ++SLOTS ++props and methods... +} +class PopconfirmBridge { ++slots : title, description, okText, okButtonProps.icon, cancelText, cancelButtonProps.icon ++afterOpenChange() ++getPopupContainer() +} +class AntdPopover { ++EVENTS ++SLOTS ++props and methods... +} +class PopoverBridge { ++slots : title, content ++afterOpenChange() ++getPopupContainer() +} +AntdPopconfirm --> PopconfirmBridge : "Instantiate and render" +AntdPopover --> PopoverBridge : "Instantiate and render" +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:10-37](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L10-L37) +- [frontend/antd/popconfirm/popconfirm.tsx:7-17](file://frontend/antd/popconfirm/popconfirm.tsx#L7-L17) +- [backend/modelscope_studio/components/antd/popover/**init**.py:10-21](file://backend/modelscope_studio/components/antd/popover/__init__.py#L10-L21) +- [frontend/antd/popover/popover.tsx:7-12](file://frontend/antd/popover/popover.tsx#L7-L12) + +## Dependency Analysis + +- Frontend dependencies + - The Svelte wrapper layer depends on the bridge layer; the bridge layer depends on the Ant Design React component library. + - Events and slots are passed across frameworks through function wrapping and ReactSlot rendering. +- Backend dependencies + - Python component classes map the component name to the frontend directory via resolve_frontend_dir, ensuring the runtime can load it. +- Coupling and cohesion + - Component responsibilities are clear: Python handles prop/event/slot definitions, Svelte handles prop passthrough and event mapping, and the TS bridge layer handles slot rendering and callback wrapping. + +```mermaid +graph LR +PY_PCF["Python: AntdPopconfirm"] --> IDX_PCF["Svelte: popconfirm/Index.svelte"] +IDX_PCF --> BRG_PCF["TS: popconfirm.tsx"] +BRG_PCF --> AD_PCF["Ant Design Popconfirm"] +PY_POV["Python: AntdPopover"] --> IDX_POV["Svelte: popover/Index.svelte"] +IDX_POV --> BRG_POV["TS: popover.tsx"] +BRG_POV --> AD_POV["Ant Design Popover"] +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:138-138](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L138-L138) +- [frontend/antd/popconfirm/Index.svelte:10-10](file://frontend/antd/popconfirm/Index.svelte#L10-L10) +- [frontend/antd/popconfirm/popconfirm.tsx:1-5](file://frontend/antd/popconfirm/popconfirm.tsx#L1-L5) +- [backend/modelscope_studio/components/antd/popover/**init**.py:106-106](file://backend/modelscope_studio/components/antd/popover/__init__.py#L106-L106) +- [frontend/antd/popover/Index.svelte:10-10](file://frontend/antd/popover/Index.svelte#L10-L10) +- [frontend/antd/popover/popover.tsx:1-5](file://frontend/antd/popover/popover.tsx#L1-L5) + +Section sources + +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:138-138](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L138-L138) +- [backend/modelscope_studio/components/antd/popover/**init**.py:106-106](file://backend/modelscope_studio/components/antd/popover/__init__.py#L106-L106) +- [frontend/antd/popconfirm/Index.svelte:10-10](file://frontend/antd/popconfirm/Index.svelte#L10-L10) +- [frontend/antd/popover/Index.svelte:10-10](file://frontend/antd/popover/Index.svelte#L10-L10) +- [frontend/antd/popconfirm/popconfirm.tsx:1-5](file://frontend/antd/popconfirm/popconfirm.tsx#L1-L5) +- [frontend/antd/popover/popover.tsx:1-5](file://frontend/antd/popover/popover.tsx#L1-L5) + +## Performance Considerations + +- Lazy loading and lazy rendering + - The Svelte wrapper layer uses dynamic component imports to avoid an oversized initial bundle. +- Slot rendering optimization + - Slot content is rendered only when needed, reducing unnecessary virtual DOM updates. +- Container mounting and z-index management + - Mount the popup to an appropriate container via `getPopupContainer` to avoid z-index conflicts and reflows. +- Delay and destruction strategy + - Set appropriate mouse enter/leave delays to avoid frequent flickering; choose hide-then-destroy strategy based on the scenario to save memory. + +## Troubleshooting Guide + +- Cannot open/close + - Check that the trigger type and `open` state are consistent; confirm `open_change` event is correctly bound. + - Reference paths: [frontend/antd/popconfirm/Index.svelte:24-55](file://frontend/antd/popconfirm/Index.svelte#L24-L55), [frontend/antd/popover/Index.svelte:24-52](file://frontend/antd/popover/Index.svelte#L24-L52) +- Content not displayed or misaligned + - Confirm slot names and rendering logic; check if getPopupContainer returns a valid container. + - Reference paths: [frontend/antd/popconfirm/popconfirm.tsx:17-62](file://frontend/antd/popconfirm/popconfirm.tsx#L17-L62), [frontend/antd/popover/popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) +- Events not fired + - Confirm backend event listeners match frontend event mapping; check that callback function wrapping is effective. + - Reference paths: [backend/modelscope_studio/components/antd/popconfirm/**init**.py:14-27](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L14-L27), [backend/modelscope_studio/components/antd/popover/**init**.py:14-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L18) + +Section sources + +- [frontend/antd/popconfirm/Index.svelte:24-55](file://frontend/antd/popconfirm/Index.svelte#L24-L55) +- [frontend/antd/popover/Index.svelte:24-52](file://frontend/antd/popover/Index.svelte#L24-L52) +- [frontend/antd/popconfirm/popconfirm.tsx:17-62](file://frontend/antd/popconfirm/popconfirm.tsx#L17-L62) +- [frontend/antd/popover/popover.tsx:10-34](file://frontend/antd/popover/popover.tsx#L10-L34) +- [backend/modelscope_studio/components/antd/popconfirm/**init**.py:14-27](file://backend/modelscope_studio/components/antd/popconfirm/__init__.py#L14-L27) +- [backend/modelscope_studio/components/antd/popover/**init**.py:14-18](file://backend/modelscope_studio/components/antd/popover/__init__.py#L14-L18) + +## Conclusion + +Popconfirm and Popover are implemented in this project through a unified architecture of "Python component + Svelte wrapper + TS bridge + Ant Design component", ensuring behavioral consistency with Ant Design while providing flexible slot and event extension capabilities. By making proper use of triggers, positioning, container mounting, and event callbacks, stable and user-friendly interaction experiences can be achieved in complex interfaces. + +## Appendix + +- Example entries + - Popconfirm example entry: [docs/components/antd/popconfirm/README-zh_CN.md:5-8](file://docs/components/antd/popconfirm/README-zh_CN.md#L5-L8) + - Popover example entry: [docs/components/antd/popover/README-zh_CN.md:5-8](file://docs/components/antd/popover/README-zh_CN.md#L5-L8) diff --git a/.wiki/en/Ant Design Components/Feedback Components/Message and Notification.md b/.wiki/en/Ant Design Components/Feedback Components/Message and Notification.md new file mode 100644 index 00000000..58757a54 --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Message and Notification.md @@ -0,0 +1,332 @@ +# Message and Notification + + +**Files referenced in this document** +- [frontend/antd/message/message.tsx](file://frontend/antd/message/message.tsx) +- [frontend/antd/notification/notification.tsx](file://frontend/antd/notification/notification.tsx) +- [frontend/antd/message/Index.svelte](file://frontend/antd/message/Index.svelte) +- [frontend/antd/notification/Index.svelte](file://frontend/antd/notification/Index.svelte) +- [backend/modelscope_studio/components/antd/message/__init__.py](file://backend/modelscope_studio/components/antd/message/__init__.py) +- [backend/modelscope_studio/components/antd/notification/__init__.py](file://backend/modelscope_studio/components/antd/notification/__init__.py) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/antd/message/package.json](file://frontend/antd/message/package.json) +- [frontend/antd/notification/package.json](file://frontend/antd/notification/package.json) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Memory Management](#performance-and-memory-management) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document systematically covers the message notification component group, focusing on two types of global feedback components: Message and Notification. It provides a complete explanation covering design philosophy, use cases, comparison of differences, configuration options and dynamic behavior, lifecycle and memory cleanup, accessibility and experience optimization, along with source-traceable path references to help developers get started quickly and use the components correctly. + +## Project Structure + +The message notification components are built from three layers: "backend Python component + frontend Svelte wrapper + React/antd implementation": + +- The backend component is responsible for parameter validation, event binding, rendering control, and frontend package export declarations. +- The frontend Svelte layer is responsible for prop passthrough, slot mapping, and visibility state synchronization. +- The React layer implements the specific message popup, stacking, and destruction logic based on the antd message/notification API. + +```mermaid +graph TB +subgraph "Backend" +PY_MSG["AntdMessage
Python Component"] +PY_NOTI["AntdNotification
Python Component"] +end +subgraph "Frontend Svelte" +SV_MSG["message/Index.svelte"] +SV_NOTI["notification/Index.svelte"] +end +subgraph "React/antd" +TSX_MSG["message.tsx
useMessage-driven"] +TSX_NOTI["notification.tsx
useNotification-driven"] +end +PY_MSG --> SV_MSG --> TSX_MSG +PY_NOTI --> SV_NOTI --> TSX_NOTI +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/message/**init**.py:10-91](file://backend/modelscope_studio/components/antd/message/__init__.py#L10-L91) +- [backend/modelscope_studio/components/antd/notification/**init**.py:10-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L10-L109) +- [frontend/antd/message/Index.svelte:10-78](file://frontend/antd/message/Index.svelte#L10-L78) +- [frontend/antd/notification/Index.svelte:10-80](file://frontend/antd/notification/Index.svelte#L10-L80) +- [frontend/antd/message/message.tsx:9-79](file://frontend/antd/message/message.tsx#L9-L79) +- [frontend/antd/notification/notification.tsx:8-106](file://frontend/antd/notification/notification.tsx#L8-L106) + +Section sources + +- [frontend/antd/message/package.json:1-15](file://frontend/antd/message/package.json#L1-L15) +- [frontend/antd/notification/package.json:1-15](file://frontend/antd/notification/package.json#L1-L15) + +## Core Components + +- Message + - Design goal: Provide immediate, concise feedback for user actions, commonly used for submit success/failure, warning, or loading hints. + - Key features: Lightweight, no mask, auto-dismiss, configurable duration, key-based uniqueness and override control. +- Notification + - Design goal: Pop up richer content in a page corner, suitable for reminders that need to carry a title, description, buttons, actions, etc. + - Key features: Supports multiple placement positions (top/bottom/left/right), stacking management, progress bar, hover-to-pause, customizable buttons and actions. + +Section sources + +- [backend/modelscope_studio/components/antd/message/**init**.py:10-91](file://backend/modelscope_studio/components/antd/message/__init__.py#L10-L91) +- [backend/modelscope_studio/components/antd/notification/**init**.py:10-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L10-L109) + +## Architecture Overview + +The message component call chain is: backend component instantiation → frontend Svelte rendering → React/antd executes open/destroy → lifecycle callbacks trigger state propagation back. + +```mermaid +sequenceDiagram +participant Py as "Backend Component" +participant S as "Svelte Wrapper" +participant R as "React/antd" +participant UI as "Browser Interface" +Py->>S : Pass props and slots +S->>R : Pass through props and slots +R->>R : Initialize useMessage/useNotification +alt Visible and open +R->>UI : open({key, content, duration, ...}) +else Close or destroy +R->>UI : destroy(key) +end +UI-->>R : User interaction (click/close) +R-->>S : Fire onVisible(false) callback +S-->>Py : Update visible state +``` + +Diagram sources + +- [frontend/antd/message/message.tsx:30-68](file://frontend/antd/message/message.tsx#L30-L68) +- [frontend/antd/notification/notification.tsx:31-95](file://frontend/antd/notification/notification.tsx#L31-L95) +- [frontend/antd/message/Index.svelte:58-77](file://frontend/antd/message/Index.svelte#L58-L77) +- [frontend/antd/notification/Index.svelte:59-79](file://frontend/antd/notification/Index.svelte#L59-L79) + +## Detailed Component Analysis + +### Message Component + +- Responsibilities and behavior + - Provides global message capabilities based on antd's `message.useMessage`; + - Supports controlling visibility via `visible` and uniqueness via `messageKey`; + - Supports `slots.content` and `slots.icon` for custom content and icons; + - Fires `onVisible(false)` on close and destroys the corresponding key when the component unmounts. +- Key configuration options (excerpt) + - Content and type: content, type (success/info/warning/error/loading) + - Display duration: duration (seconds) + - Container mount point: getContainer (function) + - Text and styles: className, style, rootClassName + - Key and visibility: messageKey, visible +- Dynamic updates and batch operations + - Use messageKey to override and update the same message position; + - Multiple messages can coexist without interfering with each other; + - Use `destroy(key)` or `destroyAll()` for batch cleanup. +- Lifecycle and memory + - Registered on open; destroyed on close/unmount; avoids residual DOM and event listeners. + +```mermaid +flowchart TD +Start(["Enter Effect"]) --> CheckVisible{"visible is true?"} +CheckVisible -- No --> Destroy["destroy(key) and return"] +CheckVisible -- Yes --> Open["messageApi.open({...})"] +Open --> OnClose["onClose callback fires onVisible(false)"] +OnClose --> End(["End"]) +Destroy --> End +``` + +Diagram sources + +- [frontend/antd/message/message.tsx:35-68](file://frontend/antd/message/message.tsx#L35-L68) + +Section sources + +- [frontend/antd/message/message.tsx:9-79](file://frontend/antd/message/message.tsx#L9-L79) +- [frontend/antd/message/Index.svelte:19-77](file://frontend/antd/message/Index.svelte#L19-L77) +- [backend/modelscope_studio/components/antd/message/**init**.py:26-72](file://backend/modelscope_studio/components/antd/message/__init__.py#L26-L72) + +### Notification Component + +- Responsibilities and behavior + - Provides global notification capabilities based on antd's `notification.useNotification`; + - Supports multiple positions (top/bottom/left/right and combinations) and stacking management; + - Supports rich slots: slots.message/description/icon/actions/btn/closeIcon; + - Fires `onVisible(false)` on close and destroys the corresponding key on unmount. +- Key configuration options (excerpt) + - Position and stacking: placement, stack, top, bottom, rtl + - Content and interaction: message, description, btn, actions, closeIcon, icon + - Behavior and experience: duration, showProgress, pauseOnHover, role (alert/status) + - Key and visibility: notificationKey, visible +- Dynamic updates and batch operations + - Use notificationKey to override the same notification; + - Supports `destroyAll()` for batch cleanup; + - In stacking mode, controls the arrangement and override strategy for new and old notifications. +- Lifecycle and memory + - Registered on open; destroyed on close/unmount; avoids memory leaks. + +```mermaid +sequenceDiagram +participant S as "Svelte Wrapper" +participant R as "React/antd" +participant N as "notificationApi" +participant U as "User" +S->>R : visible=true and pass props +R->>N : open({key, message, description, actions, ...}) +U-->>N : Click/close +N-->>R : onClose callback +R-->>S : onVisible(false) +S-->>S : updateProps({visible : false}) +R->>N : destroy(key) or destroyAll() +``` + +Diagram sources + +- [frontend/antd/notification/notification.tsx:38-95](file://frontend/antd/notification/notification.tsx#L38-L95) +- [frontend/antd/notification/Index.svelte:59-79](file://frontend/antd/notification/Index.svelte#L59-L79) + +Section sources + +- [frontend/antd/notification/notification.tsx:8-106](file://frontend/antd/notification/notification.tsx#L8-L106) +- [frontend/antd/notification/Index.svelte:19-79](file://frontend/antd/notification/Index.svelte#L19-L79) +- [backend/modelscope_studio/components/antd/notification/**init**.py:26-90](file://backend/modelscope_studio/components/antd/notification/__init__.py#L26-L90) + +### Differences and Use Cases + +- Use cases + - Message: Lightweight feedback, short text hints, no need for complex interaction; + - Notification: Requires a title/description/buttons/actions, multiple position display, emphasizes important information. +- Display position and stacking + - Message: Appears at the top of the container or in a specified container by default; does not support multiple positions; + - Notification: Supports top/bottom/left/right and combinations, with stacking management and progress bar. +- Interaction and accessibility + - Notification: Supports `role` (alert/status) for screen reader identification; + - Message: More oriented toward one-time hints with minimal interaction. +- Dynamic and batch operations + - Both support key-based uniqueness and override; Notification makes it easier to implement batch cleanup and stacking strategies. + +Section sources + +- [backend/modelscope_studio/components/antd/message/**init**.py:26-72](file://backend/modelscope_studio/components/antd/message/__init__.py#L26-L72) +- [backend/modelscope_studio/components/antd/notification/**init**.py:26-90](file://backend/modelscope_studio/components/antd/notification/__init__.py#L26-L90) + +## Dependency Analysis + +- Component export and entry + - Both message and notification expose Gradio-compatible entry points via package.json; +- Frontend bridge + - The Svelte wrapper handles prop and slot passthrough, and writes back the `visible` state; + - The React layer safely injects functions like getContainer into the antd API via useFunction; +- Events and slots + - The backend declares click/close events; the Svelte side binds them via the `_internal` flag; + - Slot mapping: Message (content/icon), Notification (actions/btn/closeIcon/description/icon/message/title). + +```mermaid +graph LR +PkgMsg["message/package.json"] --> SMsg["message/Index.svelte"] +PkgNoti["notification/package.json"] --> SNoti["notification/Index.svelte"] +SMsg --> TMsg["message.tsx"] +SNoti --> TNoti["notification.tsx"] +TMsg --> Hook["useFunction.ts"] +TNoti --> Hook +``` + +Diagram sources + +- [frontend/antd/message/package.json:1-15](file://frontend/antd/message/package.json#L1-L15) +- [frontend/antd/notification/package.json:1-15](file://frontend/antd/notification/package.json#L1-L15) +- [frontend/antd/message/Index.svelte:10](file://frontend/antd/message/Index.svelte#L10) +- [frontend/antd/notification/Index.svelte:10](file://frontend/antd/notification/Index.svelte#L10) +- [frontend/antd/message/message.tsx:29](file://frontend/antd/message/message.tsx#L29) +- [frontend/antd/notification/notification.tsx:31](file://frontend/antd/notification/notification.tsx#L31) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) + +Section sources + +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) + +## Performance and Memory Management + +- Performance characteristics + - Message: Lightweight, no mask, small DOM count — suitable for high-frequency hints; + - Notification: Supports stacking and progress bar with stronger visual feedback, but DOM count may increase. +- Memory cleanup strategy + - Uniformly call `destroy(key)`/`destroyAll()` on close and unmount; + - Use key to precisely control resource reclamation, avoiding duplicate rendering and event accumulation; + - Use getContainer to mount messages to the minimum necessary container, reducing reflow and repaint. +- Best practices + - Set a unique key for each independent message; + - Set a reasonable `duration` to avoid too many messages persisting for too long; + - Use `destroyAll()` in batch operations to clean up expired messages; + - For frequently triggered operations, prefer Message; introduce Notification only when necessary. + +Section sources + +- [frontend/antd/message/message.tsx:51-58](file://frontend/antd/message/message.tsx#L51-L58) +- [frontend/antd/notification/notification.tsx:74-77](file://frontend/antd/notification/notification.tsx#L74-L77) + +## Troubleshooting Guide + +- Common issues + - Message not displayed: Check if `visible` is true and that `messageKey` is correctly passed in; + - Cannot be closed: Confirm the `onClose` callback has not been overridden; ensure the `onVisible` callback chain is functioning correctly; + - Duplicate messages: Set a unique key for each message to avoid being overridden by subsequent `open` calls; + - Position is wrong: Confirm the mount node returned by `getContainer` exists and is visible. +- Debugging steps + - Print props and visible state in the Svelte layer; + - Confirm messageApi/notificationApi has been initialized in the React layer; + - Use `destroyAll()` to quickly clear the slate and verify whether any DOM remains; + - Check that the getContainer function consistently returns the same node. + +Section sources + +- [frontend/antd/message/message.tsx:35-68](file://frontend/antd/message/message.tsx#L35-L68) +- [frontend/antd/notification/notification.tsx:38-95](file://frontend/antd/notification/notification.tsx#L38-L95) + +## Conclusion + +The message notification component group implements highly available and extensible global feedback capabilities through a layered design of "backend parameters + frontend bridge + React/antd driver". Message is suitable for lightweight hints; Notification is suitable for rich notifications. By applying reasonable key strategies, duration configuration, and destruction mechanisms, excellent performance and memory health can be maintained while ensuring a great user experience. + +## Appendix: Usage Examples and Best Practices + +- Success hint (Message) + - Set `type` to `success`, use an appropriate `duration`, and make `messageKey` unique; + - Toggle display via `visible`; synchronize visible state with `onClose`. + - Example path reference: [frontend/antd/message/message.tsx:35-50](file://frontend/antd/message/message.tsx#L35-L50) +- Error alert (Notification) + - Set `type` to `error`, enrich content with `message`/`description`, and provide operations via `actions`; + - Use `destroyAll()` to clean up historical error messages and prevent accumulation. + - Example path reference: [frontend/antd/notification/notification.tsx:38-69](file://frontend/antd/notification/notification.tsx#L38-L69) +- Info notification (Notification) + - Use `placement` to specify position (e.g., topRight); set `role` to `status`; + - Control stacking with `stack`; improve readability with `pauseOnHover`. + - Example path reference: [frontend/antd/notification/notification.tsx:31-36](file://frontend/antd/notification/notification.tsx#L31-L36) +- Manual close + - Proactively close via `onVisible(false)`, or call `destroy(key)` externally; + - Example path reference: [frontend/antd/message/message.tsx:46-50](file://frontend/antd/message/message.tsx#L46-L50), [frontend/antd/notification/notification.tsx:65-69](file://frontend/antd/notification/notification.tsx#L65-L69) +- Dynamic updates and batch operations + - Use `messageKey` to override an existing message; + - Use `destroyAll()` for batch cleanup to avoid memory leaks. + - Example path reference: [frontend/antd/message/message.tsx:51-58](file://frontend/antd/message/message.tsx#L51-L58), [frontend/antd/notification/notification.tsx:74-77](file://frontend/antd/notification/notification.tsx#L74-L77) + +Accessibility and experience optimization recommendations + +- Set `role` (alert/status) on Notification to improve accessibility; +- Set a reasonable `duration` to avoid interrupting user tasks; +- Provide clear feedback text and action buttons for key operations; +- In dark themes or high-contrast environments, ensure message colors and icons are clearly distinguishable. + +Section sources + +- [backend/modelscope_studio/components/antd/notification/**init**.py:40-44](file://backend/modelscope_studio/components/antd/notification/__init__.py#L40-L44) +- [frontend/antd/notification/notification.tsx:65-69](file://frontend/antd/notification/notification.tsx#L65-L69) diff --git a/.wiki/en/Ant Design Components/Feedback Components/Modal.md b/.wiki/en/Ant Design Components/Feedback Components/Modal.md new file mode 100644 index 00000000..1492d5e7 --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Modal.md @@ -0,0 +1,322 @@ +# Modal + + +**Files referenced in this document** +- [frontend/antd/modal/modal.tsx](file://frontend/antd/modal/modal.tsx) +- [frontend/antd/modal/static/modal.static.tsx](file://frontend/antd/modal/static/modal.static.tsx) +- [backend/modelscope_studio/components/antd/modal/__init__.py](file://backend/modelscope_studio/components/antd/modal/__init__.py) +- [backend/modelscope_studio/components/antd/modal/static/__init__.py](file://backend/modelscope_studio/components/antd/modal/static/__init__.py) +- [frontend/antd/modal/static/Index.svelte](file://frontend/antd/modal/static/Index.svelte) +- [docs/components/antd/modal/README.md](file://docs/components/antd/modal/README.md) +- [docs/components/antd/modal/demos/basic.py](file://docs/components/antd/modal/demos/basic.py) +- [docs/components/antd/modal/demos/custom_footer.py](file://docs/components/antd/modal/demos/custom_footer.py) +- [docs/components/antd/modal/demos/static.py](file://docs/components/antd/modal/demos/static.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Animation](#performance-and-animation) +8. [Accessibility and Keyboard Interaction](#accessibility-and-keyboard-interaction) +9. [Troubleshooting](#troubleshooting) +10. [Conclusion](#conclusion) +11. [Appendix: Common Scenario Examples](#appendix-common-scenario-examples) + +## Introduction + +This document systematically covers the "Modal" component group, including the design principles, use cases, z-index management, focus control, keyboard interaction, event and style customization, animation and transitions, performance optimization, and accessibility support for both regular Modal and Static Modal. The document also provides practical guidance based on repository examples to help developers efficiently integrate and extend the components in the Gradio/ModelScope ecosystem. + +## Project Structure + +This component is positioned between the frontend Ant Design wrapper layer and the backend Python component bridge layer, using a layered design of "Frontend Svelte + React Slot + Backend LayoutComponent": + +- Frontend layer: Wraps Ant Design's Modal as a slottable component via `sveltify`; the static modal dynamically renders via the useModal API. +- Backend layer: Python components encapsulate AntdModal/AntdModalStatic, exposing a unified property and event interface and declaring supported slots. +- Documentation and examples: Provides three types of examples — basic, custom footer, and static call — for quick onboarding. + +```mermaid +graph TB +subgraph "Backend" +PY_API["AntdModal
AntdModalStatic"] +end +subgraph "Frontend" +F_Svelte["Index.svelte
Static Wrapper"] +F_Modal["Modal.tsx
Regular Dialog"] +F_Static["ModalStatic.tsx
Static Dialog"] +end +subgraph "Third-party" +AntD["Ant Design Modal"] +end +PY_API --> F_Svelte +F_Svelte --> F_Modal +F_Svelte --> F_Static +F_Modal --> AntD +F_Static --> AntD +``` + +Diagram sources + +- [frontend/antd/modal/modal.tsx:1-107](file://frontend/antd/modal/modal.tsx#L1-L107) +- [frontend/antd/modal/static/modal.static.tsx:1-132](file://frontend/antd/modal/static/modal.static.tsx#L1-L132) +- [frontend/antd/modal/static/Index.svelte:1-69](file://frontend/antd/modal/static/Index.svelte#L1-L69) +- [backend/modelscope_studio/components/antd/modal/**init**.py:1-136](file://backend/modelscope_studio/components/antd/modal/__init__.py#L1-L136) +- [backend/modelscope_studio/components/antd/modal/static/**init**.py:1-133](file://backend/modelscope_studio/components/antd/modal/static/__init__.py#L1-L133) + +Section sources + +- [docs/components/antd/modal/README.md:1-13](file://docs/components/antd/modal/README.md#L1-L13) + +## Core Components + +- Regular Modal (AntdModal) + - Design positioning: Rendered directly as a component, suitable for scenarios that need to explicitly manage the lifecycle and z-index in the layout tree. + - Key capabilities: Supports slottable title, footer, button icons and text, close icon, custom renderer, container mount point, keyboard and mask behavior, etc. +- Static Modal (AntdModalStatic) + - Design positioning: Dynamically triggered via useModal without needing to be declared in the layout tree, suitable for one-time dialogs such as message hints and confirmation flows. + - Key capabilities: Supports info/success/error/warning/confirm types, auto-focus buttons, controlled visibility, onOk/onCancel callback linkage. + +Section sources + +- [backend/modelscope_studio/components/antd/modal/**init**.py:11-136](file://backend/modelscope_studio/components/antd/modal/__init__.py#L11-L136) +- [backend/modelscope_studio/components/antd/modal/static/**init**.py:10-133](file://backend/modelscope_studio/components/antd/modal/static/__init__.py#L10-L133) + +## Architecture Overview + +The following diagram shows the key call chain from user trigger to dialog presentation, including both regular and static modes: + +```mermaid +sequenceDiagram +participant U as "User" +participant PY as "Backend Component (AntdModal/Static)" +participant FE as "Frontend Wrapper (Index.svelte)" +participant MOD as "Modal/ModalStatic" +participant ANT as "Ant Design Modal" +U->>PY : Trigger display (e.g., click a button) +PY->>FE : Pass props and visibility +alt Regular mode +FE->>MOD : Render Modal component +MOD->>ANT : Render regular dialog +else Static mode +FE->>MOD : Pass visible/type etc. +MOD->>ANT : Call useModal(type) to create instance +end +ANT-->>U : Display dialog and respond to interactions +``` + +Diagram sources + +- [frontend/antd/modal/static/Index.svelte:54-68](file://frontend/antd/modal/static/Index.svelte#L54-L68) +- [frontend/antd/modal/modal.tsx:36-102](file://frontend/antd/modal/modal.tsx#L36-L102) +- [frontend/antd/modal/static/modal.static.tsx:46-128](file://frontend/antd/modal/static/modal.static.tsx#L46-L128) + +## Component Details + +### Regular Modal + +- Slot and prop mapping + - Supported slots: okText, okButtonProps.icon, cancelText, cancelButtonProps.icon, closable.closeIcon, closeIcon, footer, title, modalRender. + - Prop passthrough: afterOpenChange, afterClose, getContainer, keyboard, mask, maskClosable, width, zIndex, wrapClassName, etc. +- Event binding + - ok/cancel events are bound via event listeners to trigger callbacks or update visibility. +- Container mount and z-index + - getContainer can specify the mount node to avoid the z-index being blocked by a local container; defaults to mounting to body. +- Focus and keyboard + - `keyboard` controls whether Esc is allowed to close; `autoFocusButton` and similar props affect the initial focus. +- Custom rendering + - `modalRender` can replace the entire rendering logic; `footer` supports function-based slots for complex footer layouts. + +```mermaid +flowchart TD +Start(["Enter render"]) --> CheckSlots["Check if slots exist"] +CheckSlots --> |Exist| RenderSlot["Render slot content"] +CheckSlots --> |Do not exist| UseProp["Use prop value"] +RenderSlot --> Combine["Merge into final props"] +UseProp --> Combine +Combine --> Mount["Mount to target container"] +Mount --> Focus["Set focus/keyboard behavior based on config"] +Focus --> End(["Complete"]) +``` + +Diagram sources + +- [frontend/antd/modal/modal.tsx:36-99](file://frontend/antd/modal/modal.tsx#L36-L99) + +Section sources + +- [frontend/antd/modal/modal.tsx:1-107](file://frontend/antd/modal/modal.tsx#L1-L107) +- [backend/modelscope_studio/components/antd/modal/**init**.py:18-32](file://backend/modelscope_studio/components/antd/modal/__init__.py#L18-L32) + +### Static Modal + +- Dynamic creation and destruction + - Obtains the API via `useModal`; creates the corresponding type instance when `visible` is true, otherwise destroys the current instance. + - Auto-focus on buttons is disabled by default unless explicitly passed in. +- Event and visibility linkage + - onOk/onCancel internally synchronize `onVisible(false)`, implementing the consistent behavior of "confirm/cancel = close". +- Slots and props + - Supports title, content, footer, okText, okButtonProps.icon, cancelText, cancelButtonProps.icon, closable.closeIcon, closeIcon, modalRender, etc. +- Usage restrictions + - Not declared in the layout tree; driven only by props such as visible/type; suitable for one-time hints and confirmation flows. + +```mermaid +sequenceDiagram +participant C as "Caller" +participant MS as "ModalStatic" +participant API as "useModal" +participant D as "Dialog Instance" +C->>MS : visible=true, type=info/success/... +MS->>API : Call corresponding type method (type) +API-->>MS : Return instance reference +MS->>D : Render and apply slots/props +D-->>MS : User action (confirm/cancel) +MS->>C : Fire onVisible(false) +MS->>API : Destroy instance +``` + +Diagram sources + +- [frontend/antd/modal/static/modal.static.tsx:46-128](file://frontend/antd/modal/static/modal.static.tsx#L46-L128) + +Section sources + +- [frontend/antd/modal/static/modal.static.tsx:1-132](file://frontend/antd/modal/static/modal.static.tsx#L1-L132) +- [backend/modelscope_studio/components/antd/modal/static/**init**.py:14-28](file://backend/modelscope_studio/components/antd/modal/static/__init__.py#L14-L28) + +### Component Relationships and Inheritance + +- The backend component classes AntdModal and AntdModalStatic both inherit from ModelScopeLayoutComponent, which unifies event, slot, prop, and lifecycle handling. +- The frontend Index.svelte serves as the dynamic loading entry point, responsible for passing props and slots to Modal or ModalStatic. + +```mermaid +classDiagram +class ModelScopeLayoutComponent +class AntdModal { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class AntdModalStatic { ++EVENTS ++SLOTS ++FRONTEND_DIR +} +class Modal_tsx +class ModalStatic_tsx +class Index_svelte +ModelScopeLayoutComponent <|-- AntdModal +ModelScopeLayoutComponent <|-- AntdModalStatic +Index_svelte --> Modal_tsx : "Render regular" +Index_svelte --> ModalStatic_tsx : "Render static" +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/modal/**init**.py:11-16](file://backend/modelscope_studio/components/antd/modal/__init__.py#L11-L16) +- [backend/modelscope_studio/components/antd/modal/static/**init**.py:10-13](file://backend/modelscope_studio/components/antd/modal/static/__init__.py#L10-L13) +- [frontend/antd/modal/static/Index.svelte:10-68](file://frontend/antd/modal/static/Index.svelte#L10-L68) + +## Dependency Analysis + +- Frontend dependencies + - sveltify: Bridges React components to Svelte. + - useFunction: Stabilizes callback functions to avoid side effects from repeated rendering. + - renderParamsSlot: Supports slot rendering with parameters. + - Ant Design Modal: Core UI behavior and styles. +- Backend dependencies + - Gradio event system: Binds ok/cancel via event listeners. + - Component base class ModelScopeLayoutComponent: Unifies lifecycle and prop handling. + +```mermaid +graph LR +A["Modal.tsx"] --> B["Ant Design Modal"] +C["ModalStatic.tsx"] --> B +D["Index.svelte"] --> A +D --> C +E["AntdModal"] --> D +F["AntdModalStatic"] --> D +``` + +Diagram sources + +- [frontend/antd/modal/modal.tsx:1-107](file://frontend/antd/modal/modal.tsx#L1-L107) +- [frontend/antd/modal/static/modal.static.tsx:1-132](file://frontend/antd/modal/static/modal.static.tsx#L1-L132) +- [frontend/antd/modal/static/Index.svelte:1-69](file://frontend/antd/modal/static/Index.svelte#L1-L69) +- [backend/modelscope_studio/components/antd/modal/**init**.py:1-136](file://backend/modelscope_studio/components/antd/modal/__init__.py#L1-L136) +- [backend/modelscope_studio/components/antd/modal/static/**init**.py:1-133](file://backend/modelscope_studio/components/antd/modal/static/__init__.py#L1-L133) + +## Performance and Animation + +- Rendering strategy + - Regular mode: Rendered on demand; when open=false, use destroyOnClose/destroyOnHidden to reduce memory usage. + - Static mode: Instances are dynamically created/destroyed when visible toggles, avoiding persistent DOM. +- Animation and transitions + - Ant Design Modal provides open/close animations and mask transitions; visual z-index and size can be adjusted via width, zIndex, wrapClassName, etc. +- Performance recommendations + - For scenarios with many dialogs, prefer the static mode to reduce the number of nodes in the layout tree. + - For frequently toggled dialogs, set getContainer appropriately to avoid unnecessary reflows. + - When using modalRender for custom rendering, minimize deep nesting and expensive computations. + +[This section provides general guidance and does not directly analyze specific files] + +## Accessibility and Keyboard Interaction + +- Keyboard interaction + - `keyboard` controls whether Esc is allowed to close; `maskClosable` controls whether clicking the mask closes the dialog. + - Static mode disables auto-focus on buttons by default to avoid interrupting user actions; can be explicitly specified via `autoFocusButton`. +- Focus management + - After opening, focus should move to the first interactive element (e.g., the confirm button); after closing, focus should return to the trigger source (`focusTriggerAfterClose`). +- Screen readers + - Provide clear title and content; supplement semantics with aria-\* attributes when necessary. + - Avoid hints in modalRender that rely solely on color; ensure text is readable. + +[This section provides general guidance and does not directly analyze specific files] + +## Troubleshooting + +- Issue: Dialog not displayed + - Check that visible/open is correctly passed in; for static mode, ensure visible switches from false to true. + - Confirm getContainer points to a valid node that is not clipped by a parent. +- Issue: Clicking the mask does not close + - Check maskClosable and keyboard settings; confirm no external events are intercepting. +- Issue: Static dialog does not disappear + - Ensure onOk/onCancel callbacks call `onVisible(false)`; or directly update visible to false. +- Issue: Slots not working + - Confirm slot names match the component's supported list; regular mode uses slots, static mode is driven by visible/type. + +Section sources + +- [frontend/antd/modal/static/modal.static.tsx:107-114](file://frontend/antd/modal/static/modal.static.tsx#L107-L114) +- [backend/modelscope_studio/components/antd/modal/**init**.py:18-32](file://backend/modelscope_studio/components/antd/modal/__init__.py#L18-L32) + +## Conclusion + +- Regular Modal is suitable for scenarios requiring fine-grained lifecycle and z-index control in the layout tree; Static Modal is suitable for one-time hints and confirmation flows. +- Through flexible combination of slots and props, rich interaction and style customization can be achieved; combining useModal with the event system enables a consistent user experience. +- For performance and accessibility, it is recommended to prefer static mode for high-frequency dialogs, set focus and keyboard behavior appropriately, and ensure content is screen-reader-friendly. + +[This section is a summary and does not directly analyze specific files] + +## Appendix: Common Scenario Examples + +The following examples come from the repository documentation and demos, showcasing different usage patterns and typical scenarios. + +- Basic dialog + - Scenario: Open/close, confirm/cancel. + - Example path: [docs/components/antd/modal/demos/basic.py:1-19](file://docs/components/antd/modal/demos/basic.py#L1-L19) +- Custom footer + - Scenario: Custom bottom buttons, link navigation, combined interactions. + - Example path: [docs/components/antd/modal/demos/custom_footer.py:1-31](file://docs/components/antd/modal/demos/custom_footer.py#L1-L31) +- Static dialog (info/success/error/warning/confirm) + - Scenario: Message hints, confirmation dialogs. + - Example path: [docs/components/antd/modal/demos/static.py:1-74](file://docs/components/antd/modal/demos/static.py#L1-L74) + +Section sources + +- [docs/components/antd/modal/demos/basic.py:1-19](file://docs/components/antd/modal/demos/basic.py#L1-L19) +- [docs/components/antd/modal/demos/custom_footer.py:1-31](file://docs/components/antd/modal/demos/custom_footer.py#L1-L31) +- [docs/components/antd/modal/demos/static.py:1-74](file://docs/components/antd/modal/demos/static.py#L1-L74) diff --git a/.wiki/en/Ant Design Components/Feedback Components/Progress and Result.md b/.wiki/en/Ant Design Components/Feedback Components/Progress and Result.md new file mode 100644 index 00000000..c37ef21f --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Progress and Result.md @@ -0,0 +1,289 @@ +# Progress and Result + + +**Files referenced in this document** +- [frontend/antd/progress/progress.tsx](file://frontend/antd/progress/progress.tsx) +- [frontend/antd/progress/Index.svelte](file://frontend/antd/progress/Index.svelte) +- [docs/components/antd/progress/README.md](file://docs/components/antd/progress/README.md) +- [docs/components/antd/progress/demos/basic.py](file://docs/components/antd/progress/demos/basic.py) +- [frontend/antd/result/result.tsx](file://frontend/antd/result/result.tsx) +- [frontend/antd/result/Index.svelte](file://frontend/antd/result/Index.svelte) +- [docs/components/antd/result/README.md](file://docs/components/antd/result/README.md) +- [docs/components/antd/result/demos/basic.py](file://docs/components/antd/result/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the progress and result component group, systematically covering the functional characteristics, shape variants, status semantics, property configuration, animation and style customization methods for both the Progress and Result components, combined with demo examples from the repository to provide practical recommendations for typical application scenarios such as file upload progress, task execution status, and operation result feedback. It also covers key points for user experience optimization and accessibility support, helping developers use progress and result components efficiently and consistently in the Gradio ecosystem. + +## Project Structure + +- Component implementations reside in the frontend layer: each component has a Svelte entry file for property handling and slot rendering, and a TypeScript wrapper for interfacing with the native Ant Design component. +- Documentation and demos reside under docs/components/antd, providing component descriptions and runnable examples. +- The relationship between component entries and wrappers is shown in the following diagram: + +```mermaid +graph TB +subgraph "Frontend Implementation" +PIndex["progress/Index.svelte"] +PWrap["progress/progress.tsx"] +RIndex["result/Index.svelte"] +RWrap["result/result.tsx"] +end +subgraph "Third-party Library" +AntD["Ant Design Progress/Result"] +end +PIndex --> PWrap +RIndex --> RWrap +PWrap --> AntD +RWrap --> AntD +``` + +Diagram sources + +- [frontend/antd/progress/Index.svelte:1-64](file://frontend/antd/progress/Index.svelte#L1-L64) +- [frontend/antd/progress/progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [frontend/antd/result/Index.svelte:1-64](file://frontend/antd/result/Index.svelte#L1-L64) +- [frontend/antd/result/result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) + +Section sources + +- [frontend/antd/progress/Index.svelte:1-64](file://frontend/antd/progress/Index.svelte#L1-L64) +- [frontend/antd/progress/progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [frontend/antd/result/Index.svelte:1-64](file://frontend/antd/result/Index.svelte#L1-L64) +- [frontend/antd/result/result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) + +## Core Components + +- Progress + - Supports three shapes — line, circle, and dashboard (controlled via `type`) — and can add step segments (`steps`), info display toggle (`show_info`), and status color (`stroke_color`). + - Provides a percentage value (`percent`) and a format callback (`format`) for flexible text display control; supports a custom rounding function (`rounding`). + - Common statuses: default, active (`status='active'`), exception (`status='exception'`), success (`status='success'`). +- Result + - Used to display the final result of a series of operations, supporting success, info, warning, and error statuses. + - Supports title, sub_title, icon, and extra slots for extending buttons, links, or complex content. + +Section sources + +- [docs/components/antd/progress/README.md:1-8](file://docs/components/antd/progress/README.md#L1-L8) +- [docs/components/antd/result/README.md:1-8](file://docs/components/antd/result/README.md#L1-L8) +- [docs/components/antd/progress/demos/basic.py:1-39](file://docs/components/antd/progress/demos/basic.py#L1-L39) +- [docs/components/antd/result/demos/basic.py:1-57](file://docs/components/antd/result/demos/basic.py#L1-L57) + +## Architecture Overview + +The following diagram shows the call chain and slot passing mechanism from the Svelte entry to the native Ant Design component: + +```mermaid +sequenceDiagram +participant UI as "Page/Layout" +participant PIdx as "progress/Index.svelte" +participant PWrap as "progress/progress.tsx" +participant RIdx as "result/Index.svelte" +participant RWrap as "result/result.tsx" +participant Ant as "Ant Design Component" +UI->>PIdx : Pass props and slots +PIdx->>PIdx : Handle visibility/styles/additional props +PIdx->>PWrap : Render wrapper and pass through props +PWrap->>Ant : Call Ant Design Progress +Ant-->>UI : Render progress bar +UI->>RIdx : Pass props and slots +RIdx->>RIdx : Handle visibility/styles/additional props +RIdx->>RWrap : Render wrapper and pass through slots +RWrap->>Ant : Call Ant Design Result +Ant-->>UI : Render result panel +``` + +Diagram sources + +- [frontend/antd/progress/Index.svelte:10-61](file://frontend/antd/progress/Index.svelte#L10-L61) +- [frontend/antd/progress/progress.tsx:5-21](file://frontend/antd/progress/progress.tsx#L5-L21) +- [frontend/antd/result/Index.svelte:10-59](file://frontend/antd/result/Index.svelte#L10-L59) +- [frontend/antd/result/result.tsx:7-30](file://frontend/antd/result/result.tsx#L7-L30) + +## Detailed Component Analysis + +### Progress Component + +- Shapes and behavior + - Line progress bar: Default type, suitable for long-running tasks. + - Circle progress bar: `type="circle"`, suitable for emphasizing completion rate or as a card-level metric. + - Dashboard progress bar: `type="dashboard"`, suitable for threshold judgment and interval visualization. + - Step segments: The `steps` parameter splits the progress into multiple stages, commonly used for multi-stage tasks. +- Value display and formatting + - `percent` is the percentage input; `show_info` controls whether the number or status icon is displayed. + - The `format` callback can customize text content, such as showing "Done" text on completion. + - `rounding` allows customizing the rounding strategy for the percentage. +- Color and status + - `stroke_color` supports a single color or gradient array, coloring by step or overall. + - `status` controls the status color and animation: default, active, exception, success. +- Props and slots + - Props: percent, type, steps, stroke_color, status, show_info, format, rounding, etc. + - Slots: No built-in slots; text is mainly customized via `format`. +- Use cases + - File upload progress: Line progress bar showing real-time percentage, switching to success status on completion. + - Task execution status: Circle progress bar as a card-level metric; dashboard for threshold reminders. + - Multi-step flow: `steps` breaks down complex flows into multiple stages to improve perceived progress. + +```mermaid +flowchart TD +Start(["Start"]) --> SetType["Set type
type=linear/circle/dashboard"] +SetType --> SetPercent["Set percentage
percent"] +SetPercent --> ShowInfo{"Show info?"} +ShowInfo --> |Yes| FormatText["Format text
format callback"] +ShowInfo --> |No| SkipFormat["Skip text display"] +FormatText --> Color["Set color
stroke_color/status"] +SkipFormat --> Color +Color --> Steps{"Use steps?"} +Steps --> |Yes| StepSeg["Draw by step
steps"] +Steps --> |No| SingleSeg["Draw as whole"] +StepSeg --> Render["Render progress bar"] +SingleSeg --> Render +Render --> End(["End"]) +``` + +Diagram sources + +- [frontend/antd/progress/progress.tsx:5-21](file://frontend/antd/progress/progress.tsx#L5-L21) +- [docs/components/antd/progress/demos/basic.py:9-35](file://docs/components/antd/progress/demos/basic.py#L9-L35) + +Section sources + +- [frontend/antd/progress/progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [frontend/antd/progress/Index.svelte:10-61](file://frontend/antd/progress/Index.svelte#L10-L61) +- [docs/components/antd/progress/README.md:1-8](file://docs/components/antd/progress/README.md#L1-L8) +- [docs/components/antd/progress/demos/basic.py:1-39](file://docs/components/antd/progress/demos/basic.py#L1-L39) + +### Result Component + +- Status and semantics + - success: The operation completed successfully; encourage the user to proceed to the next step. + - info: Provides a neutral hint; guides the user to view details. + - warning: A risk or issue requiring attention; recommend the user confirm. + - error: The operation failed; the user needs to correct the issue and retry. +- Visual and content + - A title and sub_title clearly convey the result and context. + - The icon can be customized, combined with status colors to enhance recognition. + - The extra slot places action buttons, links, or supplementary notes. +- Props and slots + - Props: status, title, sub_title, icon, extra, etc. + - Slots: extra, icon, subTitle, title. +- Use cases + - Operation result feedback: A unified feedback interface after submitting a form or purchasing a service. + - Error diagnosis: Displaying the specific issue and repair guidance in an error state. + - Conversion guidance: Providing actions such as "Go to Console" or "Buy Again" after a success. + +```mermaid +sequenceDiagram +participant App as "Application" +participant R as "Result Component" +participant Slot as "Slot Content" +participant Ant as "Ant Design Result" +App->>R : Pass status/title/subTitle/icon +App->>Slot : Provide extra/icon/subTitle/title slots +R->>R : Parse slots and pass through to wrapper +R->>Ant : Render Result +Ant-->>App : Display result panel and action area +``` + +Diagram sources + +- [frontend/antd/result/result.tsx:7-30](file://frontend/antd/result/result.tsx#L7-L30) +- [frontend/antd/result/Index.svelte:10-59](file://frontend/antd/result/Index.svelte#L10-L59) + +Section sources + +- [frontend/antd/result/result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) +- [frontend/antd/result/Index.svelte:1-64](file://frontend/antd/result/Index.svelte#L1-L64) +- [docs/components/antd/result/README.md:1-8](file://docs/components/antd/result/README.md#L1-L8) +- [docs/components/antd/result/demos/basic.py:1-57](file://docs/components/antd/result/demos/basic.py#L1-L57) + +## Dependency Analysis + +- Component coupling and responsibilities + - The Svelte entry handles prop collection, visibility control, style concatenation, and slot parsing. + - The TypeScript wrapper interfaces with the Ant Design component, passing through props and callbacks (format, rounding). + - The slot system is implemented via ReactSlot and useTargets, ensuring dynamic rendering and fallback of slots. +- External dependencies + - Ant Design Progress/Result: Provides core UI and interaction behavior. + - @svelte-preprocess-react: Bridges React components with the Svelte context. + - @utils/hooks: Provides utility functions such as useFunction and useTargets. + +```mermaid +graph LR +PIdx["progress/Index.svelte"] --> PWrap["progress/progress.tsx"] +RIdx["result/Index.svelte"] --> RWrap["result/result.tsx"] +PWrap --> AntD["Ant Design Progress"] +RWrap --> AntD2["Ant Design Result"] +PWrap --> Hooks["@utils/hooks"] +RWrap --> Hooks +``` + +Diagram sources + +- [frontend/antd/progress/Index.svelte:1-64](file://frontend/antd/progress/Index.svelte#L1-L64) +- [frontend/antd/progress/progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [frontend/antd/result/Index.svelte:1-64](file://frontend/antd/result/Index.svelte#L1-L64) +- [frontend/antd/result/result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) + +Section sources + +- [frontend/antd/progress/progress.tsx:1-24](file://frontend/antd/progress/progress.tsx#L1-L24) +- [frontend/antd/result/result.tsx:1-33](file://frontend/antd/result/result.tsx#L1-L33) + +## Performance Considerations + +- Rendering overhead + - Progress bar: Line and circle rendering costs are similar; step segments (`steps`) increase path drawing times; it is recommended to reduce unnecessary re-renders in high-frequency update scenarios. + - Result: Content is relatively static; slot rendering is only triggered when content changes. +- Animation and smoothness + - Avoid complex computations when using the `format` callback; try to return lightweight strings. + - Circle/dashboard progress bars may impose GPU pressure at high refresh rates; use large circular progress bars with caution on mobile. +- Styles and theming + - When injecting styles via elem_style/elem_classes, prefer atomic classes or theme variables to reduce inline style jitter. + +## Troubleshooting Guide + +- Slots not working + - Confirm slot names are correct (extra, icon, subTitle, title), and that slots are explicitly passed through in the wrapper. + - If no slot content is provided, the wrapper will fall back to the corresponding prop field. +- Percentage not updating + - Ensure the `percent` prop updates as data changes; avoid expensive computations in `format` that cause lag. + - If custom rounding is needed, check the input/output types and boundary values of the `rounding` function. +- Status color anomaly + - When `status` and `stroke_color` are used simultaneously, note the status priority and color override order. + - When `steps` is an array, ensure its length matches the number of stages to avoid out-of-bounds errors. +- Accessibility + - Provide semantic labels and screen-reader-friendly text for key states (success/error). + - Provide alternative descriptions for invisible text in circle progress bars to ensure assistive technologies can understand the progress meaning. + +Section sources + +- [frontend/antd/result/result.tsx:10-30](file://frontend/antd/result/result.tsx#L10-L30) +- [frontend/antd/progress/progress.tsx:9-21](file://frontend/antd/progress/progress.tsx#L9-L21) + +## Conclusion + +The Progress and Result components in the Gradio ecosystem fulfill the dual responsibilities of "process visibility" and "result feedback". Through Ant Design's mature capabilities and this project's Svelte wrapper, developers can obtain a consistent, extensible, and customizable progress and result experience at minimal cost. It is recommended to choose the appropriate shape and status based on your business scenario in practice, and to follow accessibility and performance best practices to improve user satisfaction and maintainability. + +## Appendix + +- Example references + - Progress basic demo: [docs/components/antd/progress/demos/basic.py:1-39](file://docs/components/antd/progress/demos/basic.py#L1-L39) + - Result basic demo: [docs/components/antd/result/demos/basic.py:1-57](file://docs/components/antd/result/demos/basic.py#L1-L57) +- Component documentation + - Progress documentation: [docs/components/antd/progress/README.md:1-8](file://docs/components/antd/progress/README.md#L1-L8) + - Result documentation: [docs/components/antd/result/README.md:1-8](file://docs/components/antd/result/README.md#L1-L8) diff --git a/.wiki/en/Ant Design Components/Feedback Components/Spin and Skeleton.md b/.wiki/en/Ant Design Components/Feedback Components/Spin and Skeleton.md new file mode 100644 index 00000000..42e492a3 --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Spin and Skeleton.md @@ -0,0 +1,327 @@ +# Spin and Skeleton + + +**Files referenced in this document** +- [frontend/antd/skeleton/skeleton.tsx](file://frontend/antd/skeleton/skeleton.tsx) +- [frontend/antd/skeleton/avatar/skeleton.avatar.tsx](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx) +- [frontend/antd/skeleton/button/skeleton.button.tsx](file://frontend/antd/skeleton/button/skeleton.button.tsx) +- [frontend/antd/skeleton/image/skeleton.image.tsx](file://frontend/antd/skeleton/image/skeleton.image.tsx) +- [frontend/antd/skeleton/input/skeleton.input.tsx](file://frontend/antd/skeleton/input/skeleton.input.tsx) +- [frontend/antd/skeleton/node/skeleton.node.tsx](file://frontend/antd/skeleton/node/skeleton.node.tsx) +- [frontend/antd/spin/spin.tsx](file://frontend/antd/spin/spin.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Common Use Cases and Best Practices](#appendix-common-use-cases-and-best-practices) + +## Introduction + +This document focuses on the loading skeleton component group, systematically explaining the implementation patterns, usage strategies, and UX design considerations for Skeleton and Spin in this repository. Topics covered include: + +- Skeleton placeholder types, animation effects, and content layout simulation +- Spin loading indicator size variations and state management +- Component property configuration, custom animations, and style customization +- Practical recommendations for common scenarios such as list loading, image placeholders, form loading, and page transitions +- Timing and transition effects for switching between skeleton and real content +- Performance optimization recommendations and network condition adaptation strategies + +## Project Structure + +The loading skeleton component group resides in the frontend Ant Design component layer, following a unified "adapter" wrapping pattern that bridges Ant Design's React components to the Svelte ecosystem via preprocessing tools, ensuring a consistent invocation experience within this project's component system. + +```mermaid +graph TB +subgraph "Antd Skeleton Sub-components" +SA["Skeleton.Avatar
avatar/skeleton.avatar.tsx"] +SB["Skeleton.Button
button/skeleton.button.tsx"] +SI["Skeleton.Image
image/skeleton.image.tsx"] +SIN["Skeleton.Input
input/skeleton.input.tsx"] +SN["Skeleton.Node
node/skeleton.node.tsx"] +end +SMain["Skeleton
skeleton.tsx"] +subgraph "Antd Loading Indicator" +SP["Spin
spin.tsx"] +end +SMain --> SA +SMain --> SB +SMain --> SI +SMain --> SIN +SMain --> SN +``` + +Diagram sources + +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/skeleton/avatar/skeleton.avatar.tsx:1-9](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx#L1-L9) +- [frontend/antd/skeleton/button/skeleton.button.tsx:1-9](file://frontend/antd/skeleton/button/skeleton.button.tsx#L1-L9) +- [frontend/antd/skeleton/image/skeleton.image.tsx:1-9](file://frontend/antd/skeleton/image/skeleton.image.tsx#L1-L9) +- [frontend/antd/skeleton/input/skeleton.input.tsx:1-9](file://frontend/antd/skeleton/input/skeleton.input.tsx#L1-L9) +- [frontend/antd/skeleton/node/skeleton.node.tsx:1-9](file://frontend/antd/skeleton/node/skeleton.node.tsx#L1-L9) +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) + +Section sources + +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/skeleton/avatar/skeleton.avatar.tsx:1-9](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx#L1-L9) +- [frontend/antd/skeleton/button/skeleton.button.tsx:1-9](file://frontend/antd/skeleton/button/skeleton.button.tsx#L1-L9) +- [frontend/antd/skeleton/image/skeleton.image.tsx:1-9](file://frontend/antd/skeleton/image/skeleton.image.tsx#L1-L9) +- [frontend/antd/skeleton/input/skeleton.input.tsx:1-9](file://frontend/antd/skeleton/input/skeleton.input.tsx#L1-L9) +- [frontend/antd/skeleton/node/skeleton.node.tsx:1-9](file://frontend/antd/skeleton/node/skeleton.node.tsx#L1-L9) +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) + +## Core Components + +- Skeleton + - Main entry: Bridges Ant Design's Skeleton component to the Svelte environment in a unified way + - Sub-components: Avatar, Button, Image, Input, Node — each corresponding to a placeholder skeleton for a different element type +- Spin + - Main entry: Bridges Ant Design's Spin component to the Svelte environment in a unified way, with support for slottable `tip` and `indicator` customization + +Section sources + +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/skeleton/avatar/skeleton.avatar.tsx:1-9](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx#L1-L9) +- [frontend/antd/skeleton/button/skeleton.button.tsx:1-9](file://frontend/antd/skeleton/button/skeleton.button.tsx#L1-L9) +- [frontend/antd/skeleton/image/skeleton.image.tsx:1-9](file://frontend/antd/skeleton/image/skeleton.image.tsx#L1-L9) +- [frontend/antd/skeleton/input/skeleton.input.tsx:1-9](file://frontend/antd/skeleton/input/skeleton.input.tsx#L1-L9) +- [frontend/antd/skeleton/node/skeleton.node.tsx:1-9](file://frontend/antd/skeleton/node/skeleton.node.tsx#L1-L9) +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) + +## Architecture Overview + +The overall architecture uses a combination of "adapter + slots": + +- Adapter: The unified `sveltify` tool bridges Ant Design's React components as Svelte-usable components +- Slottable: Spin supports `tip` and `indicator` slots for custom tip text and indicator styles +- Target selection: Spin internally converts children into a locatable set of targets via a target selection hook, ensuring correct wrapping logic + +```mermaid +sequenceDiagram +participant U as "User Code" +participant S as "Spin Component" +participant Hook as "useTargets Hook" +participant AD as "Antd Spin" +U->>S : Pass children and props +S->>Hook : useTargets(children) +Hook-->>S : Return target set +S->>AD : Render Antd Spin(props, slots) +AD-->>U : Display loading indicator (with optional custom tip/indicator) +``` + +Diagram sources + +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) + +Section sources + +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) + +## Detailed Component Analysis + +### Skeleton Component Family + +- Design goals + - Provide stable content layout placeholders before data is ready, avoiding page jumps and layout jitter + - Improve perceived speed and usability by simulating real content with appropriate animations and shapes +- Placeholder types + - Avatar: Avatar placeholder + - Button: Button placeholder + - Image: Image placeholder + - Input: Input field placeholder + - Node: General-purpose node placeholder +- Animation and layout + - Based on Ant Design's Skeleton animation mechanism, typically manifests as a shimmer (gradient flash) effect + - Simulate complex layouts such as text, cards, and lists by setting different shapes (circle/square/rectangle) and row counts +- Usage recommendations + - List loading: Prefer Node or multiple Input rows to simulate list items + - Image placeholders: Use Image with dimensions matching the real image + - Form loading: Use Input/Button to simulate fields and action areas + - Page transitions: Wrap the container with Skeleton during route transitions to reduce the perception of a white screen + +```mermaid +classDiagram +class Skeleton { ++Main Entry +} +class SkeletonAvatar { ++Avatar Placeholder +} +class SkeletonButton { ++Button Placeholder +} +class SkeletonImage { ++Image Placeholder +} +class SkeletonInput { ++Input Placeholder +} +class SkeletonNode { ++General Node Placeholder +} +Skeleton --> SkeletonAvatar : "Contains" +Skeleton --> SkeletonButton : "Contains" +Skeleton --> SkeletonImage : "Contains" +Skeleton --> SkeletonInput : "Contains" +Skeleton --> SkeletonNode : "Contains" +``` + +Diagram sources + +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/skeleton/avatar/skeleton.avatar.tsx:1-9](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx#L1-L9) +- [frontend/antd/skeleton/button/skeleton.button.tsx:1-9](file://frontend/antd/skeleton/button/skeleton.button.tsx#L1-L9) +- [frontend/antd/skeleton/image/skeleton.image.tsx:1-9](file://frontend/antd/skeleton/image/skeleton.image.tsx#L1-L9) +- [frontend/antd/skeleton/input/skeleton.input.tsx:1-9](file://frontend/antd/skeleton/input/skeleton.input.tsx#L1-L9) +- [frontend/antd/skeleton/node/skeleton.node.tsx:1-9](file://frontend/antd/skeleton/node/skeleton.node.tsx#L1-L9) + +Section sources + +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/skeleton/avatar/skeleton.avatar.tsx:1-9](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx#L1-L9) +- [frontend/antd/skeleton/button/skeleton.button.tsx:1-9](file://frontend/antd/skeleton/button/skeleton.button.tsx#L1-L9) +- [frontend/antd/skeleton/image/skeleton.image.tsx:1-9](file://frontend/antd/skeleton/image/skeleton.image.tsx#L1-L9) +- [frontend/antd/skeleton/input/skeleton.input.tsx:1-9](file://frontend/antd/skeleton/input/skeleton.input.tsx#L1-L9) +- [frontend/antd/skeleton/node/skeleton.node.tsx:1-9](file://frontend/antd/skeleton/node/skeleton.node.tsx#L1-L9) + +### Spin Component + +- Design goals + - Provide clear feedback during async operations to prevent users from thinking the page is unresponsive + - Supports custom tip text and indicator to meet the visual needs of different scenarios +- Key features + - Slottable: Supports `tip` and `indicator` slots for injecting custom text and icons + - Target selection: Internally converts children into a target set via a target selection hook, ensuring correct wrapping logic + - Prop passthrough: All props are passed directly to Ant Design's Spin except for additional extensions +- Usage recommendations + - List loading: Use Spin as the list container with children as list items; `tip` indicates "Loading" + - Image placeholder: Wrap images with Spin before they finish loading; use a simple rotating icon for `indicator` + - Form submission: Disable interactions and display Spin during submission; `tip` indicates "Submitting" + - Page transitions: Wrap the entire page with Spin during route transitions to provide global loading feedback + +```mermaid +flowchart TD +Start(["Enter Spin render"]) --> Targets["useTargets(children)
Resolve target set"] +Targets --> HasTargets{"Targets exist?"} +HasTargets --> |No| HideChildren["Hide children (render placeholder only)"] +HasTargets --> |Yes| ShowChildren["Show children"] +HideChildren --> RenderAD["Render Antd Spin(props, slots)"] +ShowChildren --> RenderAD +RenderAD --> End(["End"]) +``` + +Diagram sources + +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) + +Section sources + +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) + +## Dependency Analysis + +- Component coupling + - The Skeleton family all depend on Ant Design's Skeleton implementation, bridged via sveltify + - Spin depends on Ant Design's Spin implementation, and introduces a target selection hook and ReactSlot slot mechanism +- External dependencies + - @svelte-preprocess-react: Provides sveltify and ReactSlot capabilities + - Ant Design: Provides the concrete implementations of Skeleton and Spin +- Potential issues + - Slot names and prop naming must be consistent with Ant Design to avoid runtime errors + - Target selection logic must ensure the children structure is reasonable to avoid wrapping anomalies + +```mermaid +graph LR +Spin["Spin Component"] --> AD_Spin["Antd Spin"] +Spin --> RS["ReactSlot"] +Spin --> UT["useTargets Hook"] +Skeleton["Skeleton Component"] --> AD_Skeleton["Antd Skeleton"] +Skeleton --> SA["Skeleton.Avatar"] +Skeleton --> SB["Skeleton.Button"] +Skeleton --> SI["Skeleton.Image"] +Skeleton --> SIN["Skeleton.Input"] +Skeleton --> SN["Skeleton.Node"] +``` + +Diagram sources + +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/skeleton/avatar/skeleton.avatar.tsx:1-9](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx#L1-L9) +- [frontend/antd/skeleton/button/skeleton.button.tsx:1-9](file://frontend/antd/skeleton/button/skeleton.button.tsx#L1-L9) +- [frontend/antd/skeleton/image/skeleton.image.tsx:1-9](file://frontend/antd/skeleton/image/skeleton.image.tsx#L1-L9) +- [frontend/antd/skeleton/input/skeleton.input.tsx:1-9](file://frontend/antd/skeleton/input/skeleton.input.tsx#L1-L9) +- [frontend/antd/skeleton/node/skeleton.node.tsx:1-9](file://frontend/antd/skeleton/node/skeleton.node.tsx#L1-L9) + +Section sources + +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) + +## Performance Considerations + +- Skeleton rendering cost + - The number and depth of skeleton placeholder elements should approximate the real content to avoid excessive rendering causing lag + - For long lists, use Skeleton.Node or a small number of input rows as placeholders to reduce DOM count +- Loading indicator feedback + - Spin's `tip` and `indicator` should be as lightweight as possible to avoid additional repaints and reflows + - In high-frequency refresh scenarios, it is recommended to use throttling or debouncing to control the frequency of loading state transitions +- Network condition adaptation + - For poor network conditions, it is recommended to extend the Skeleton display time threshold to avoid frequent flickering + - For high-latency scenarios, Spin's `tip` text should clearly inform the user why they are waiting (e.g., "Connecting to server") + +## Troubleshooting Guide + +- Issue: Spin cannot correctly wrap children + - Debug: Confirm whether children have a recognizable target structure; check the return value of useTargets + - Reference implementation: [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- Issue: tip/indicator slots not working + - Debug: Confirm slot names are `tip` and `indicator`; ensure the slots object has the corresponding keys + - Reference implementation: [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- Issue: Skeleton sub-component style anomalies + - Debug: Confirm sub-components are correctly importing the corresponding Ant Design modules; check theme and style overrides + - Reference implementations: + - [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) + - [frontend/antd/skeleton/avatar/skeleton.avatar.tsx:1-9](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx#L1-L9) + - [frontend/antd/skeleton/button/skeleton.button.tsx:1-9](file://frontend/antd/skeleton/button/skeleton.button.tsx#L1-L9) + - [frontend/antd/skeleton/image/skeleton.image.tsx:1-9](file://frontend/antd/skeleton/image/skeleton.image.tsx#L1-L9) + - [frontend/antd/skeleton/input/skeleton.input.tsx:1-9](file://frontend/antd/skeleton/input/skeleton.input.tsx#L1-L9) + - [frontend/antd/skeleton/node/skeleton.node.tsx:1-9](file://frontend/antd/skeleton/node/skeleton.node.tsx#L1-L9) + +Section sources + +- [frontend/antd/spin/spin.tsx:1-38](file://frontend/antd/spin/spin.tsx#L1-L38) +- [frontend/antd/skeleton/skeleton.tsx:1-7](file://frontend/antd/skeleton/skeleton.tsx#L1-L7) +- [frontend/antd/skeleton/avatar/skeleton.avatar.tsx:1-9](file://frontend/antd/skeleton/avatar/skeleton.avatar.tsx#L1-L9) +- [frontend/antd/skeleton/button/skeleton.button.tsx:1-9](file://frontend/antd/skeleton/button/skeleton.button.tsx#L1-L9) +- [frontend/antd/skeleton/image/skeleton.image.tsx:1-9](file://frontend/antd/skeleton/image/skeleton.image.tsx#L1-L9) +- [frontend/antd/skeleton/input/skeleton.input.tsx:1-9](file://frontend/antd/skeleton/input/skeleton.input.tsx#L1-L9) +- [frontend/antd/skeleton/node/skeleton.node.tsx:1-9](file://frontend/antd/skeleton/node/skeleton.node.tsx#L1-L9) + +## Conclusion + +The loading skeleton component group in this repository achieves seamless integration of Ant Design Skeleton and Spin through a unified adapter and slottable design. In practice, the appropriate skeleton type and loading indicator form should be chosen based on the business scenario, and props and slots should be used for customization to meet branding and interaction needs. At the same time, pay attention to rendering performance and network condition adaptation to ensure a consistent, smooth user experience across different devices and environments. + +## Appendix: Common Use Cases and Best Practices + +- List loading + - Use Skeleton.Node or multiple Input rows to simulate list item placeholders + - Wrap the list container with Spin; `tip` indicates "Loading", `indicator` uses the default spinning icon +- Image placeholder + - Use Skeleton.Image to simulate image dimensions and placeholders + - When an image fails to load, switch to a skeleton placeholder or error hint +- Form loading + - Use Skeleton.Input and Skeleton.Button to simulate input fields and action areas + - Disable interactions and display Spin during submission; `tip` indicates "Submitting" +- Page transitions + - During route transitions, wrap the page body with Skeleton to reduce the perception of a white screen + - For high-latency scenarios, Spin's `tip` text should clearly inform the user why they are waiting diff --git a/.wiki/en/Ant Design Components/Feedback Components/Watermark.md b/.wiki/en/Ant Design Components/Feedback Components/Watermark.md new file mode 100644 index 00000000..c4429c60 --- /dev/null +++ b/.wiki/en/Ant Design Components/Feedback Components/Watermark.md @@ -0,0 +1,434 @@ +# Watermark + + +**Files referenced in this document** +- [watermark.tsx](file://frontend/antd/watermark/watermark.tsx) +- [Index.svelte](file://frontend/antd/watermark/Index.svelte) +- [__init__.py](file://backend/modelscope_studio/components/antd/watermark/__init__.py) +- [watermark-wBOVRUhz.js](file://backend/modelscope_studio/components/antd/watermark/templates/component/watermark-wBOVRUhz.js) +- [basic.py](file://docs/components/antd/watermark/demos/basic.py) +- [modal_or_drawer.py](file://docs/components/antd/watermark/demos/modal_or_drawer.py) +- [README.md](file://docs/components/antd/watermark/README.md) +- [README-zh_CN.md](file://docs/components/antd/watermark/README-zh_CN.md) +- [app.py](file://docs/components/antd/watermark/app.py) +- [component.py](file://backend/modelscope_studio/utils/dev/component.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The Watermark component is used to overlay text or image watermarks on a page or container, commonly used for copyright protection, version identification, customer differentiation, and similar scenarios. The Watermark component in this repository is based on Ant Design's Watermark implementation and is used within the Gradio ecosystem through a Svelte/React bridge layer. + +- Features + - Text watermark: Supports single-line or multi-line text watermarks. + - Image watermark: Supports a custom image as the watermark source. + - Position and layout: Controls repetition and arrangement through width, height, gap, and offset parameters. + - Rotation and scaling: Supports rotation angle and scale configuration. + - Opacity and z-index: Supports opacity and z-index control. + - Embedded usage: Can wrap any child element and automatically takes effect as the container changes. + - Event binding: Supports removal event binding for dynamic control. + +- Application scenarios + - Copyright protection: Add a "Copyright Protected" watermark to preview images or reports. + - Version identification: Add a "DEVELOPMENT" or "TEST" watermark in development/test environments. + - Customer differentiation: Add a dedicated watermark per customer or tenant for identification and auditing. + - Sensitive data protection: Add a watermark on export or display interfaces to reduce the risk of inadvertent propagation. + +- Implementation principles + - Frontend bridge: Wraps Ant Design's Watermark component as a Svelte-usable component via `sveltify`. + - Prop passthrough: Merges Gradio props (such as elem_id, elem_classes, elem_style, visible) with additional props and passes them to the underlying component. + - Render control: Controls whether to render based on `visible`; supports slots and children. + - Backend encapsulation: The Python layer provides the AntdWatermark class, carrying props and declaring the frontend directory mapping, while also declaring event listeners. + +- Usage notes + - Text and image: Set via `content` or `image` parameters; multi-line text can use array form. + - Repeat pattern: Control repetition and offset via width, height, gap, and offset. + - Rotation and scaling: `rotate` controls the angle; `z_index` controls the z-index. + - Dynamic updates: Watermark content and styles can be dynamically switched via Gradio's update mechanism. + - Style customization: Extend styles via elem_style, elem_classes, and additional props. + +**Section sources** + +- [README.md:1-9](file://docs/components/antd/watermark/README.md#L1-L9) +- [README-zh_CN.md:1-9](file://docs/components/antd/watermark/README-zh_CN.md#L1-L9) + +## Project Structure + +The organization of the Watermark component in the repository is as follows: + +- Frontend + - Svelte wrapper layer: Index.svelte handles prop processing, visibility control, and child node rendering. + - React bridge layer: watermark.tsx wraps Ant Design's Watermark as a Svelte component using `sveltify`. + - Runtime template: watermark-wBOVRUhz.js is the component runtime template, responsible for React component mounting and bridging logic. +- Backend + - Python encapsulation: The AntdWatermark class carries props and events, and declares the frontend directory mapping. +- Examples and documentation + - Basic example: basic.py demonstrates the basic usage of text and image watermarks. + - Dialog example: modal_or_drawer.py demonstrates how to use watermarks inside Modal/Drawer. + - Documentation pages: README/README-zh_CN.md provides example placeholders and links. + +```mermaid +graph TB +subgraph "Frontend" +IDX["Index.svelte
Prop handling and render control"] +WRAP["watermark.tsx
sveltify wrapper"] +RT["watermark-wBOVRUhz.js
Runtime template and bridge"] +end +subgraph "Backend" +PY["__init__.py
AntdWatermark class and props"] +DEV["component.py
ModelScopeLayoutComponent base class"] +end +subgraph "Examples and Documentation" +DEMO1["basic.py"] +DEMO2["modal_or_drawer.py"] +DOC["README.md / README-zh_CN.md"] +end +IDX --> WRAP --> RT +PY --> IDX +PY --> WRAP +PY --> RT +DEV --> PY +DEMO1 --> PY +DEMO2 --> PY +DOC --> DEMO1 +DOC --> DEMO2 +``` + +**Diagram sources** + +- [Index.svelte:1-64](file://frontend/antd/watermark/Index.svelte#L1-L64) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [watermark-wBOVRUhz.js:1-442](file://backend/modelscope_studio/components/antd/watermark/templates/component/watermark-wBOVRUhz.js#L1-L442) +- [**init**.py:1-83](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L1-L83) +- [component.py:1-169](file://backend/modelscope_studio/utils/dev/component.py#L1-L169) +- [basic.py:1-23](file://docs/components/antd/watermark/demos/basic.py#L1-L23) +- [modal_or_drawer.py:1-30](file://docs/components/antd/watermark/demos/modal_or_drawer.py#L1-L30) +- [README.md:1-9](file://docs/components/antd/watermark/README.md#L1-L9) +- [README-zh_CN.md:1-9](file://docs/components/antd/watermark/README-zh_CN.md#L1-L9) + +**Section sources** + +- [Index.svelte:1-64](file://frontend/antd/watermark/Index.svelte#L1-L64) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [watermark-wBOVRUhz.js:1-442](file://backend/modelscope_studio/components/antd/watermark/templates/component/watermark-wBOVRUhz.js#L1-L442) +- [**init**.py:1-83](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L1-L83) +- [component.py:1-169](file://backend/modelscope_studio/utils/dev/component.py#L1-L169) +- [README.md:1-9](file://docs/components/antd/watermark/README.md#L1-L9) +- [README-zh_CN.md:1-9](file://docs/components/antd/watermark/README-zh_CN.md#L1-L9) + +## Core Components + +- AntdWatermark (Backend) + - Responsibility: Carries the watermark component's props and events, declares the frontend directory mapping, and skips API calls. + - Key props (from constructor): content, width, height, inherit, rotate, z_index, image, font, gap, offset, root_class_name, etc. + - Events: remove (binds the removal event). + - Other: `skip_api` returns True, indicating this component does not participate in the standard API flow. + +- Watermark (Frontend Bridge) + - Responsibility: Wraps Ant Design's Watermark component as a Svelte component via `sveltify` for use in Gradio. + - Behavior: Directly exports Watermark as the default export. + +- Index.svelte (Frontend Wrapper) + - Responsibility: Handles Gradio props (elem_id, elem_classes, elem_style, visible), merges additional props, and controls visibility and child node rendering. + - Behavior: When `visible` is true, asynchronously loads Watermark and renders it; supports slots and children. + +- Runtime template (watermark-wBOVRUhz.js) + - Responsibility: Provides React component bridging, context merging, Portal rendering, and effect registration to ensure the component is correctly mounted and updated in the browser environment. + +**Section sources** + +- [**init**.py:8-83](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L8-L83) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [Index.svelte:1-64](file://frontend/antd/watermark/Index.svelte#L1-L64) +- [watermark-wBOVRUhz.js:330-442](file://backend/modelscope_studio/components/antd/watermark/templates/component/watermark-wBOVRUhz.js#L330-L442) + +## Architecture Overview + +The following diagram shows the overall call chain and responsibilities from Python to the frontend and then to the runtime: + +```mermaid +sequenceDiagram +participant Py as "Python Backend
AntdWatermark" +participant Wrap as "Frontend Wrapper
Index.svelte" +participant Bridge as "Bridge Layer
watermark.tsx" +participant Runtime as "Runtime Template
watermark-wBOVRUhz.js" +Py->>Wrap : "Declare component and props" +Wrap->>Bridge : "Import and wrap Watermark" +Bridge->>Runtime : "Create React component instance" +Runtime-->>Wrap : "Return renderable React component" +Wrap-->>Py : "Render or hide based on visible" +``` + +**Diagram sources** + +- [**init**.py:66-66](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L66-L66) +- [Index.svelte:10-63](file://frontend/antd/watermark/Index.svelte#L10-L63) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [watermark-wBOVRUhz.js:330-442](file://backend/modelscope_studio/components/antd/watermark/templates/component/watermark-wBOVRUhz.js#L330-L442) + +## Detailed Component Analysis + +### Props and Configuration + +- Text watermark + - content: A string or array of strings for setting watermark text; supports multi-line text. + - font: Font-related configuration (e.g., color, font size), supported by the underlying Ant Design. +- Image watermark + - image: An image URL for setting the image watermark source. +- Repetition and layout + - width, height: The width and height of the watermark unit. + - gap: The horizontal and vertical spacing between watermarks. + - offset: The initial offset of the watermark (typically used to control the starting position). +- Rotation and scaling + - rotate: Watermark rotation angle. + - inherit: Whether to inherit parent styles. +- Z-index and opacity + - z_index: Watermark z-index. + - Other styles: Control opacity, background, etc. via elem_style and elem_classes. +- Other + - root_class_name: Root node class name prefix. + - additional_props: Extra prop passthrough. + +- Dynamic updates and style customization + - visible: Controls whether the component is rendered. + - elem_id, elem_classes, elem_style: Used for positioning and style customization. + - slots and children: Supports slot and child node rendering. + +**Section sources** + +- [**init**.py:50-64](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L50-L64) +- [Index.svelte:21-44](file://frontend/antd/watermark/Index.svelte#L21-L44) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) + +### Usage Flow and Examples + +- Basic text watermark + - Nest Watermark inside a container and set `content` to a string or array. + - Reference example: basic.py. +- Image watermark + - Set `image` to an image URL; use width and height to control watermark dimensions. + - Reference example: basic.py. +- Usage inside dialogs/drawers + - Wrap Modal/Drawer with Watermark to achieve watermark coverage inside the dialog. + - Reference example: modal_or_drawer.py. + +```mermaid +sequenceDiagram +participant Demo as "Example Script
basic.py / modal_or_drawer.py" +participant Py as "AntdWatermark
Backend" +participant Wrap as "Index.svelte" +participant Bridge as "watermark.tsx" +participant RT as "watermark-wBOVRUhz.js" +Demo->>Py : "Create Watermark component and pass props" +Py->>Wrap : "Declare component and props" +Wrap->>Bridge : "Import and wrap" +Bridge->>RT : "Create React instance" +RT-->>Wrap : "Return renderable component" +Wrap-->>Demo : "Render result" +``` + +**Diagram sources** + +- [basic.py:1-23](file://docs/components/antd/watermark/demos/basic.py#L1-L23) +- [modal_or_drawer.py:1-30](file://docs/components/antd/watermark/demos/modal_or_drawer.py#L1-L30) +- [**init**.py:8-83](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L8-L83) +- [Index.svelte:50-63](file://frontend/antd/watermark/Index.svelte#L50-L63) +- [watermark.tsx:1-6](file://frontend/antd/watermark/watermark.tsx#L1-L6) +- [watermark-wBOVRUhz.js:330-442](file://backend/modelscope_studio/components/antd/watermark/templates/component/watermark-wBOVRUhz.js#L330-L442) + +**Section sources** + +- [basic.py:1-23](file://docs/components/antd/watermark/demos/basic.py#L1-L23) +- [modal_or_drawer.py:1-30](file://docs/components/antd/watermark/demos/modal_or_drawer.py#L1-L30) + +### Events and Lifecycle + +- remove event + - Bound via event listeners; can be used to remove the watermark when needed. + - The event callback updates internal state to enable the removal behavior. + +**Section sources** + +- [**init**.py:12-16](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L12-L16) + +### Class Relationship Diagram + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__init__() ++__exit__() +} +class AntdWatermark { ++EVENTS ++content ++width ++height ++inherit ++rotate ++z_index ++image ++font ++gap ++offset ++root_class_name ++FRONTEND_DIR ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +ModelScopeLayoutComponent <|-- AntdWatermark +``` + +**Diagram sources** + +- [component.py:11-127](file://backend/modelscope_studio/utils/dev/component.py#L11-L127) +- [**init**.py:8-83](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L8-L83) + +## Dependency Analysis + +- Component coupling + - AntdWatermark depends on the frontend directory mapping and runtime template to ensure correct rendering in the browser. + - Index.svelte depends on the wrapper layer and runtime template, responsible for prop processing and visibility control. + - watermark.tsx is responsible only for bridging, with low coupling, making it easy to maintain. +- External dependencies + - Ant Design Watermark: Underlying implementation. + - Svelte/React bridge tools: sveltify, @svelte-preprocess-react, etc. +- Potential issues + - If FRONTEND_DIR is not set correctly, it may cause frontend resources to fail to load. + - When `visible` is false, the component is not rendered; be aware of side effects when dynamically toggling. + +```mermaid +graph LR +PY["AntdWatermark
Backend"] --> IDX["Index.svelte
Frontend Wrapper"] +IDX --> WRAP["watermark.tsx
Bridge"] +WRAP --> RT["watermark-wBOVRUhz.js
Runtime Template"] +PY --> AD["Ant Design Watermark
External Dependency"] +``` + +**Diagram sources** + +- [**init**.py:66-66](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L66-L66) +- [Index.svelte:10-10](file://frontend/antd/watermark/Index.svelte#L10-L10) +- [watermark.tsx:1-1](file://frontend/antd/watermark/watermark.tsx#L1-L1) +- [watermark-wBOVRUhz.js:330-330](file://backend/modelscope_studio/components/antd/watermark/templates/component/watermark-wBOVRUhz.js#L330-L330) + +**Section sources** + +- [**init**.py:66-66](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L66-L66) +- [Index.svelte:10-10](file://frontend/antd/watermark/Index.svelte#L10-L10) +- [watermark.tsx:1-1](file://frontend/antd/watermark/watermark.tsx#L1-L1) +- [watermark-wBOVRUhz.js:330-330](file://backend/modelscope_studio/components/antd/watermark/templates/component/watermark-wBOVRUhz.js#L330-L330) + +## Performance Considerations + +- Rendering overhead + - Watermarks are essentially a background layer overlaid on a container, with minimal impact on the rendering of main content; however, a large number of repeating units may increase painting costs. +- Repaint and reflow + - Frequently changing props such as content, image, rotate, and z_index may trigger repaints; it is recommended to batch updates or reduce change frequency. +- Image watermark + - Image loading and decoding incur additional overhead; use appropriately sized and formatted images to avoid large images causing lag. +- Visibility control + - Controlling render timing via `visible` can effectively reduce unnecessary overhead. +- Recommendations + - Set width, height, and gap reasonably to avoid overly dense repetition. + - For frequently toggled scenarios, prioritize caching and throttling strategies. + - When using inside dialogs/drawers, pay attention to the rendering timing during dialog open/close. + +[This section provides general performance recommendations and does not require specific file sources] + +## Troubleshooting Guide + +- Watermark not displayed + - Check if `visible` is true; confirm props are correctly passed through to the component. + - Confirm FRONTEND_DIR correctly points to the frontend directory. +- Image watermark not displayed + - Check if the `image` URL is accessible; confirm image dimensions and format are reasonable. + - Adjust width and height to fit the container. +- Rotation or z-index anomaly + - Check that `rotate` and `z_index` settings match expectations; confirm no other styles are overriding them. +- Dynamic updates not working + - Confirm the update logic is correct; use a re-render strategy if necessary. +- Events not working + - Confirm the `remove` event has been bound; check that the event callback is executing correctly. + +**Section sources** + +- [Index.svelte:50-63](file://frontend/antd/watermark/Index.svelte#L50-L63) +- [**init**.py:66-66](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L66-L66) + +## Conclusion + +The Watermark component provides flexible watermarking capabilities in the Gradio ecosystem through a concise prop system and a stable bridging mechanism. It supports text and image watermarks, repeat layouts, rotation and scaling, and z-index control, applicable to a variety of scenarios including copyright protection, version identification, and customer differentiation. Combined with visibility control and event binding, a dynamic and maintainable watermarking solution can be achieved. + +[This section is a summary and does not require specific file sources] + +## Appendix + +### Common Use Case Example Paths + +- Copyright protection: Add a "Copyright Protected" text or image watermark to preview image or report containers. +- Version identification: Add a "DEVELOPMENT" or "TEST" watermark in development/test environments. +- Customer differentiation: Add a dedicated watermark per customer or tenant for identification and auditing. +- Export protection: Add a watermark on export interfaces or print preview to reduce the risk of inadvertent propagation. + +**Section sources** + +- [basic.py:1-23](file://docs/components/antd/watermark/demos/basic.py#L1-L23) +- [modal_or_drawer.py:1-30](file://docs/components/antd/watermark/demos/modal_or_drawer.py#L1-L30) + +### Quick Reference for Props + +- Text watermark: content (string or array), font +- Image watermark: image, width, height +- Repetition and layout: gap, offset +- Rotation and z-index: rotate, z_index +- Styles and visibility: elem_style, elem_classes, elem_id, visible +- Other: root_class_name, additional_props + +**Section sources** + +- [**init**.py:50-64](file://backend/modelscope_studio/components/antd/watermark/__init__.py#L50-L64) +- [Index.svelte:21-44](file://frontend/antd/watermark/Index.svelte#L21-L44) + +### Security and Anti-tampering Recommendations + +- Trustworthy content sources: Ensure content and image come from trusted sources to avoid injecting malicious content. +- Access control: Restrict modification permissions for the watermark component to prevent it from being bypassed or removed. +- Audit logging: Record watermark change logs for tracking and auditing. +- Principle of least privilege: Grant only the necessary watermark configuration permissions to avoid over-authorization. + +[This section provides general security recommendations and does not require specific file sources] + +### Accessibility and Screen Reader Compatibility + +- Text watermark + - Ensure text semantics are clear; avoid using decorative text. + - Provide alternative text or titles for key information. +- Image watermark + - Provide descriptive alt text for image watermarks to help screen readers identify them. +- Interaction and focus + - Watermarks should not interfere with user operations; ensure focusable elements are not obscured. +- Styles and contrast + - Ensure the watermark has sufficient contrast with the background to avoid affecting readability. +- Accessibility testing + - Test with screen readers and keyboard navigation to verify the accessibility experience. + +[This section provides general accessibility recommendations and does not require specific file sources] diff --git a/.wiki/en/Ant Design Components/General Components/Button.md b/.wiki/en/Ant Design Components/General Components/Button.md new file mode 100644 index 00000000..140f9ce8 --- /dev/null +++ b/.wiki/en/Ant Design Components/General Components/Button.md @@ -0,0 +1,312 @@ +# Button + + +**Files referenced in this document** +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [frontend/antd/button/group/button.group.tsx](file://frontend/antd/button/group/button.group.tsx) +- [frontend/antd/button/group/Index.svelte](file://frontend/antd/button/group/Index.svelte) +- [backend/modelscope_studio/components/antd/button/__init__.py](file://backend/modelscope_studio/components/antd/button/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [docs/components/antd/button/README-zh_CN.md](file://docs/components/antd/button/README-zh_CN.md) +- [docs/components/antd/button/demos/basic.py](file://docs/components/antd/button/demos/basic.py) +- [docs/components/antd/button/app.py](file://docs/components/antd/button/app.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically introduces the Button component, covering its core functionality, property configuration, and event handling mechanism. It focuses on explaining configuration items such as type (variant), size, and state; explains the usage and layout control of button groups; provides example paths for various scenarios (such as basic buttons, icon buttons, ghost buttons, dashed buttons, etc.); elaborates on handling special states like disabled, loading, and danger; explains style customization, theme adaptation, and responsive design points; and provides best practice recommendations for accessibility and keyboard navigation. + +## Project Structure + +The Button component consists of backend Python component class and frontend Svelte/React wrapper layer, following Gradio ecosystem's "component as context" pattern, supporting custom rendering of icons and loading state icons through the Slot mechanism. + +```mermaid +graph TB +subgraph "Backend" +PY_BTN["AntdButton
Python Component Class"] +PY_GROUP["AntdButtonGroup
Python Component Class"] +end +subgraph "Frontend" +IDX["Index.svelte
Component Entry"] +BTN["button.tsx
React Wrapper"] +SLOT["Slot Processing
icon / loading.icon"] +GROUP_IDX["group/Index.svelte
Button Group Entry"] +GROUP_BTN["group/button.group.tsx
Antd Button.Group Wrapper"] +end +PY_BTN --> IDX +PY_GROUP --> GROUP_IDX +IDX --> BTN +GROUP_IDX --> GROUP_BTN +BTN --> SLOT +``` + +Diagram Source + +- [backend/modelscope_studio/components/antd/button/**init**.py:15-138](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L138) +- [frontend/antd/button/Index.svelte:10-73](file://frontend/antd/button/Index.svelte#L10-L73) +- [frontend/antd/button/button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) +- [frontend/antd/button/group/Index.svelte:10-61](file://frontend/antd/button/group/Index.svelte#L10-L61) +- [frontend/antd/button/group/button.group.tsx:6-24](file://frontend/antd/button/group/button.group.tsx#L6-L24) + +Section Source + +- [backend/modelscope_studio/components/antd/button/**init**.py:15-138](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L138) +- [frontend/antd/button/Index.svelte:10-73](file://frontend/antd/button/Index.svelte#L10-L73) +- [frontend/antd/button/button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) +- [frontend/antd/button/group/Index.svelte:10-61](file://frontend/antd/button/group/Index.svelte#L10-L61) +- [frontend/antd/button/group/button.group.tsx:6-24](file://frontend/antd/button/group/button.group.tsx#L6-L24) + +## Core Components + +- Backend Component Class: AntdButton provides all property and event definitions for buttons, supporting type, variant, size, color, shape, state, and other configurations, and declares supported slots (icon, loading.icon). +- Frontend Wrapper Layer: Index.svelte maps Python properties to React components, injecting styles and IDs; button.tsx uses sveltify to wrap Ant Design's Button, parsing and passing slots. +- Button Group: AntdButtonGroup corresponds to the frontend Button.Group wrapper, supporting group-level styles and theme variable injection. + +Section Source + +- [backend/modelscope_studio/components/antd/button/**init**.py:15-138](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L138) +- [frontend/antd/button/Index.svelte:10-73](file://frontend/antd/button/Index.svelte#L10-L73) +- [frontend/antd/button/button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) +- [frontend/antd/button/group/Index.svelte:10-61](file://frontend/antd/button/group/Index.svelte#L10-L61) +- [frontend/antd/button/group/button.group.tsx:6-24](file://frontend/antd/button/group/button.group.tsx#L6-L24) + +## Architecture Overview + +The diagram below shows the call chain from Python component to frontend rendering, and the processing flow of Slot in loading state and icon state. + +```mermaid +sequenceDiagram +participant Py as "Python : AntdButton" +participant Svelte as "Svelte : Index.svelte" +participant Wrap as "React : button.tsx" +participant AD as "Antd : Button" +participant Slot as "Slot Resolution" +Py->>Svelte : Pass properties and values +Svelte->>Wrap : Render React wrapper component +Wrap->>AD : Pass props including icon, loading +Wrap->>Slot : Parse slots.icon / slots["loading.icon"] +Slot-->>Wrap : Return React node +Wrap-->>AD : Inject icon/loading icon +AD-->>Svelte : Render final button +``` + +Diagram Source + +- [frontend/antd/button/button.tsx:11-36](file://frontend/antd/button/button.tsx#L11-L36) +- [frontend/antd/button/Index.svelte:59-73](file://frontend/antd/button/Index.svelte#L59-L73) +- [backend/modelscope_studio/components/antd/button/**init**.py:41-49](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L49) + +## Detailed Component Analysis + +### Properties and Configuration + +- Type and Variant + - type: Supports primary, dashed, link, text, default + - variant: Supports outlined, dashed, solid, filled, text, link + - color: Supports default, primary, danger and a set of preset color names +- Size and Shape + - size: large, middle, small + - shape: default, circle, round +- State and Behavior + - disabled: Disabled state + - danger: Danger state + - ghost: Ghost button (transparent background) + - loading: Boolean or loading object with delay + - block: Block-level width + - html_type: button, submit, reset + - href/target: Link button and jump target +- Icon and Slots + - icon: Icon name or node + - loading.icon: Loading state custom icon +- Style and Identity + - elem_id, elem_classes, elem_style + - class_names, styles, root_class_name + +Section Source + +- [backend/modelscope_studio/components/antd/button/**init**.py:51-138](file://backend/modelscope_studio/components/antd/button/__init__.py#L51-L138) +- [frontend/antd/button/button.tsx:18-30](file://frontend/antd/button/button.tsx#L18-L30) + +### Event Handling Mechanism + +- click event: Bound through event listener, when triggered can update internal state to drive UI changes. +- Typical Usage: In the example, register click callback for button to output logs or trigger business logic. + +Section Source + +- [backend/modelscope_studio/components/antd/button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46) +- [docs/components/antd/button/demos/basic.py:9-10](file://docs/components/antd/button/demos/basic.py#L9-L10) + +### Slots and Icon Processing + +- Slot Definition: icon, loading.icon +- Rendering Strategy: + - If slots.icon exists, render with ReactSlot and clone + - When loading.icon exists, use that node as loading icon and preserve loading.delay value (when loading is an object) + - If no slot, fall back to props.icon or props.loading + +```mermaid +flowchart TD +Start(["Enter rendering"]) --> HasIcon{"Does slots.icon exist?"} +HasIcon --> |Yes| RenderIcon["Render slots.icon (cloned)"] +HasIcon --> |No| UseIcon["Use props.icon"] +RenderIcon --> Next1["Continue processing loading"] +UseIcon --> Next1 +Next1 --> HasLoadIcon{"Does slots['loading.icon'] exist?"} +HasLoadIcon --> |Yes| BuildLoadObj["Build loading object
containing icon and delay"] +HasLoadIcon --> |No| UseLoad["Use props.loading"] +BuildLoadObj --> End(["Complete"]) +UseLoad --> End +``` + +Diagram Source + +- [frontend/antd/button/button.tsx:18-30](file://frontend/antd/button/button.tsx#L18-L30) + +Section Source + +- [frontend/antd/button/button.tsx:11-36](file://frontend/antd/button/button.tsx#L11-L36) + +### Button Group (Button.Group) + +- Component Entry: group/Index.svelte +- Wrapper Implementation: group/button.group.tsx +- Theme Adaptation: Injects CSS variables through Ant Design's theme.token.lineWidth, unifying in-group borders and spacing +- Applicable Scenarios: Multiple buttons combined arrangement, sharing the same theme style + +```mermaid +sequenceDiagram +participant Py as "Python : AntdButtonGroup" +participant Svelte as "Svelte : group/Index.svelte" +participant Wrap as "React : group/button.group.tsx" +participant AD as "Antd : Button.Group" +Py->>Svelte : Pass properties +Svelte->>Wrap : Render wrapper component +Wrap->>AD : Pass props and inject theme variables +AD-->>Svelte : Render button group +``` + +Diagram Source + +- [frontend/antd/button/group/Index.svelte:48-61](file://frontend/antd/button/group/Index.svelte#L48-L61) +- [frontend/antd/button/group/button.group.tsx:10-24](file://frontend/antd/button/group/button.group.tsx#L10-L24) + +Section Source + +- [frontend/antd/button/group/Index.svelte:10-61](file://frontend/antd/button/group/Index.svelte#L10-L61) +- [frontend/antd/button/group/button.group.tsx:6-24](file://frontend/antd/button/group/button.group.tsx#L6-L24) + +### Examples and Usage Scenarios + +The following examples are from documentation demo scripts, demonstrating button usage with different variants and states: + +- Basic Buttons: Primary button, default button, dashed button, text button, link button +- Variants and Colors: Filled variant combined with default/danger color +- Loading State and Icons: Setting icon slot in loading state +- Block Buttons: block=True makes button fill container width + +Example Path + +- [docs/components/antd/button/demos/basic.py:9-22](file://docs/components/antd/button/demos/basic.py#L9-L22) + +Section Source + +- [docs/components/antd/button/demos/basic.py:5-25](file://docs/components/antd/button/demos/basic.py#L5-L25) + +### Style Customization, Theme Adaptation and Responsive Design + +- Style Injection: Add custom styles for individual buttons or button groups through elem_id, elem_classes, elem_style +- Theme Variables: Button groups inject CSS variables through Ant Design theme tokens, ensuring consistent in-group borders +- Responsive: Combined with Flex/Space and other layout components, buttons can automatically wrap and align under different screen sizes + +Section Source + +- [frontend/antd/button/group/button.group.tsx:10-24](file://frontend/antd/button/group/button.group.tsx#L10-L24) +- [docs/components/antd/button/demos/basic.py](file://docs/components/antd/button/demos/basic.py#L8) + +### Accessibility and Keyboard Navigation + +- Keyboard Accessibility: Buttons natively support Enter/Space triggering, recommend providing clear focus indicators in complex interactions +- Text and Icons: Provide readable text alternatives for icon buttons (aria-label), avoid relying solely on icons to convey critical information +- Disabled and Loading States: Disabled and loading states should maintain visual consistency, ensuring users perceive the current non-interactive state +- Combined Buttons: In button groups, recommend providing clear grouping semantics, adding titles or dividers when necessary + +## Dependency Analysis + +- Component Registration: AntdButton and AntdButtonGroup are centrally exported in backend component collection, facilitating unified import and usage +- Component Base Class: ModelScopeLayoutComponent provides common layout capabilities and event hooks +- Frontend Bridge: Bridges Ant Design's React components to Svelte environment through sveltify while preserving Slot capabilities + +```mermaid +graph LR +Export["components.py Export"] --> Btn["AntdButton"] +Export --> BtnGroup["AntdButtonGroup"] +Btn --> Base["ModelScopeLayoutComponent"] +BtnGroup --> Base +``` + +Diagram Source + +- [backend/modelscope_studio/components/antd/components.py:14-15](file://backend/modelscope_studio/components/antd/components.py#L14-L15) +- [backend/modelscope_studio/utils/dev/component.py:11-27](file://backend/modelscope_studio/utils/dev/component.py#L11-L27) + +Section Source + +- [backend/modelscope_studio/components/antd/components.py:14-15](file://backend/modelscope_studio/components/antd/components.py#L14-L15) +- [backend/modelscope_studio/utils/dev/component.py:11-27](file://backend/modelscope_studio/utils/dev/component.py#L11-L27) + +## Performance Considerations + +- Button Group Theme Variable Injection: Token is calculated only once during group component initialization, avoiding repeated calculation overhead +- Slot Rendering: Prioritize using slots.icon and slots["loading.icon"], reducing unnecessary props passing +- Delayed Loading: loading object supports delay field, avoiding flicker caused by frequent switching + +Section Source + +- [frontend/antd/button/group/button.group.tsx:10-24](file://frontend/antd/button/group/button.group.tsx#L10-L24) +- [frontend/antd/button/button.tsx:21-29](file://frontend/antd/button/button.tsx#L21-L29) + +## Troubleshooting Guide + +- Slot Not Working + - Check whether ms.Slot("icon") or ms.Slot("loading.icon") is correctly used to wrap icon component + - Confirm slots are correctly passed in frontend +- Loading Icon Not Displaying + - Ensure slots["loading.icon"] exists and is a valid node + - When loading is an object, confirm whether delay field is set as expected +- Button Group Style Abnormal + - Check whether theme token is available, confirm CSS variables are injected +- Event Not Triggered + - Confirm click event listener is bound and callback function is executable + +Section Source + +- [frontend/antd/button/button.tsx:18-30](file://frontend/antd/button/button.tsx#L18-L30) +- [frontend/antd/button/group/button.group.tsx:10-24](file://frontend/antd/button/group/button.group.tsx#L10-L24) +- [backend/modelscope_studio/components/antd/button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46) + +## Conclusion + +The Button component in this project achieves complete wrapping of Ant Design, with rich type, variant, size, and state configurations, while flexibly supporting icon and loading state customization through the Slot mechanism. Button groups provide good extensibility in theme adaptation and layout control. Combined with example scripts and best practices, developers can quickly build button interactions that meet design specifications and accessibility requirements. + +## Appendix + +- Documentation Entry and Examples + - [docs/components/antd/button/README-zh_CN.md:1-8](file://docs/components/antd/button/README-zh_CN.md#L1-L8) + - [docs/components/antd/button/demos/basic.py:1-26](file://docs/components/antd/button/demos/basic.py#L1-L26) + - [docs/components/antd/button/app.py:1-7](file://docs/components/antd/button/app.py#L1-L7) diff --git a/.wiki/en/Ant Design Components/General Components/FloatButton.md b/.wiki/en/Ant Design Components/General Components/FloatButton.md new file mode 100644 index 00000000..cfaff72f --- /dev/null +++ b/.wiki/en/Ant Design Components/General Components/FloatButton.md @@ -0,0 +1,351 @@ +# FloatButton + + +**Files referenced in this document** +- [Index.svelte](file://frontend/antd/float-button/Index.svelte) +- [float-button.tsx](file://frontend/antd/float-button/float-button.tsx) +- [group/Index.svelte](file://frontend/antd/float-button/group/Index.svelte) +- [group/float-button.group.tsx](file://frontend/antd/float-button/group/float-button.group.tsx) +- [back-top/Index.svelte](file://frontend/antd/float-button/back-top/Index.svelte) +- [back-top/float-button.back-top.tsx](file://frontend/antd/float-button/back-top/float-button.back-top.tsx) +- [__init__.py](file://backend/modelscope_studio/components/antd/float_button/__init__.py) +- [README-zh_CN.md](file://docs/components/antd/float_button/README-zh_CN.md) +- [app.py](file://docs/components/antd/float_button/app.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +FloatButton is a "floating button" component used to provide globally accessible function entries at any position on the page. It is implemented based on Ant Design's FloatButton and presented as a unified component form in the model domain through Gradio frontend bridge layer. This component supports extension capabilities such as icons, description text, tooltip popups, and badge count; meanwhile, it provides two enhanced sub-features: "FloatButton Group" and "Back to Top", used for combining multiple actions and quickly returning to the top of the page respectively. + +Design Goals: + +- Remain visible at any scroll state on the page, improving user accessibility +- Provide flexible layout position and size control, meeting different page styles +- Support slot-based extensions (such as custom icons, descriptions, tooltips, badges) +- Collaborate with scroll containers and content areas to avoid blocking critical information +- Cover mobile and responsive scenarios, ensuring consistent interaction experience + +## Project Structure + +FloatButton component consists of backend Python component class and frontend Svelte/React wrapper layer, with documentation examples demonstrated through the docs layer. + +```mermaid +graph TB +subgraph "Backend" +PY["AntdFloatButton.__init__.py"] +end +subgraph "Frontend" +IDX["float-button/Index.svelte"] +CMP["float-button.tsx"] +GRP_IDX["float-button/group/Index.svelte"] +GRP_CMP["float-button/group/float-button.group.tsx"] +BT_IDX["float-button/back-top/Index.svelte"] +BT_CMP["float-button/back-top/float-button.back-top.tsx"] +end +subgraph "Documentation" +DOC_README["docs/.../float_button/README-zh_CN.md"] +DOC_APP["docs/.../float_button/app.py"] +end +PY --> IDX +PY --> GRP_IDX +PY --> BT_IDX +IDX --> CMP +GRP_IDX --> GRP_CMP +BT_IDX --> BT_CMP +DOC_README --> DOC_APP +``` + +Diagram Source + +- [**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) +- [Index.svelte:1-70](file://frontend/antd/float-button/Index.svelte#L1-L70) +- [float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [group/Index.svelte:1-72](file://frontend/antd/float-button/group/Index.svelte#L1-L72) +- [group/float-button.group.tsx:1-70](file://frontend/antd/float-button/group/float-button.group.tsx#L1-L70) +- [back-top/Index.svelte:1-73](file://frontend/antd/float-button/back-top/Index.svelte#L1-L73) +- [back-top/float-button.back-top.tsx:1-47](file://frontend/antd/float-button/back-top/float-button.back-top.tsx#L1-L47) +- [README-zh_CN.md:1-8](file://docs/components/antd/float_button/README-zh_CN.md#L1-L8) +- [app.py:1-7](file://docs/components/antd/float_button/app.py#L1-L7) + +Section Source + +- [**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) +- [README-zh_CN.md:1-8](file://docs/components/antd/float_button/README-zh_CN.md#L1-L8) +- [app.py:1-7](file://docs/components/antd/float_button/app.py#L1-L7) + +## Core Components + +- AntdFloatButton: Backend component class, declares events, slots, and properties, responsible for mapping frontend components to Gradio ecosystem. +- FloatButton: Frontend wrapper, interfaces with Ant Design's FloatButton, supporting slot injection and function-type callback handling. +- FloatButton.Group: Frontend wrapper, used to combine multiple floating buttons, supporting close icon, shape, theme variables, etc. +- FloatButton.BackTop: Frontend wrapper, provides "back to top" capability, supporting custom scroll container retrieval logic. + +Section Source + +- [**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) +- [float-button.tsx:14-75](file://frontend/antd/float-button/float-button.tsx#L14-L75) +- [group/float-button.group.tsx:10-70](file://frontend/antd/float-button/group/float-button.group.tsx#L10-L70) +- [back-top/float-button.back-top.tsx:7-47](file://frontend/antd/float-button/back-top/float-button.back-top.tsx#L7-L47) + +## Architecture Overview + +The diagram below shows the overall call chain from backend component class to frontend wrapper and then to Ant Design component. + +```mermaid +sequenceDiagram +participant Py as "Backend AntdFloatButton" +participant Svelte as "Svelte Entry Index.svelte" +participant Wrap as "React Wrapper float-button.tsx" +participant AD as "Ant Design FloatButton" +Py->>Svelte : Render component and pass properties/slots +Svelte->>Wrap : Dynamic import and pass props +Wrap->>AD : Inject icon/description/tooltip/badge slots +AD-->>Wrap : Return render result +Wrap-->>Svelte : Rendering complete +Svelte-->>Py : Component mounted +``` + +Diagram Source + +- [**init**.py:92-96](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L92-L96) +- [Index.svelte:10-69](file://frontend/antd/float-button/Index.svelte#L10-L69) +- [float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) + +## Detailed Component Analysis + +### Component 1: FloatButton + +- Design Concept + - As a global page entry, ensuring clickable trigger at any scroll position + - Supports extensions like icons, descriptions, tooltips, and badges through slot system +- Key Features + - Slot Support: icon, description, tooltip, tooltip.title, badge.count + - Callback Function Safety Handling: Wraps function-type properties like tooltip.afterOpenChange, tooltip.getPopupContainer + - Visibility Control: Controls rendering through visible +- Usage Scenarios + - Quick action entries (like "Back to Top", "Share", "Feedback") + - Entry buttons for multi-state switching or conditional display +- Configuration Points + - Icon and Shape: icon, shape + - Type and Style: type, root_class_name, class_names, styles + - Link and Native Properties: href, href_target, html_type + - Badge and Tooltip: badge, tooltip +- Interaction Behavior + - Supports click event binding + - Tooltip supports delayed open/close callbacks and popup container selection + +```mermaid +classDiagram +class AntdFloatButton { ++EVENTS ++SLOTS ++__init__(...) ++FRONTEND_DIR +} +class FloatButton { ++Slots : icon, description, tooltip, tooltip.title, badge.count ++Function Wrapping : afterOpenChange, getPopupContainer +} +AntdFloatButton --> FloatButton : "Backend drives frontend" +``` + +Diagram Source + +- [**init**.py:12-32](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L32) +- [float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) + +Section Source + +- [**init**.py:12-110](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L12-L110) +- [Index.svelte:13-51](file://frontend/antd/float-button/Index.svelte#L13-L51) +- [float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) + +### Component 2: FloatButton.Group + +- Design Concept + - Combines multiple floating buttons into one group, forming a compound entry, reducing page element count + - Supports close icon, shape (circle/square), and theme variable injection +- Key Features + - Slot Support: icon, closeIcon, description, tooltip, badge.count + - Shape and Style: shape, className, inline style overriding theme variables + - Child Item Rendering: Separates slots from regular child nodes through useSlotsChildren +- Usage Scenarios + - Multi-function entry aggregation (like "Edit/Favorite/Share/More") + - Expandable/collapsible compound action areas +- Configuration Points + - Group Shape: shape (circle/square) + - Theme Variables: Inject border radius, etc. through CSS variables + - Slot-based Icons and Tooltips: Supports independent configuration for each child item + +```mermaid +classDiagram +class FloatButtonGroup { ++Slots : icon, closeIcon, description, tooltip, badge.count ++Properties : shape, className, style ++Theme : useToken() ++Children : useSlotsChildren() +} +``` + +Diagram Source + +- [group/float-button.group.tsx:10-67](file://frontend/antd/float-button/group/float-button.group.tsx#L10-L67) + +Section Source + +- [group/Index.svelte:14-50](file://frontend/antd/float-button/group/Index.svelte#L14-L50) +- [group/float-button.group.tsx:10-67](file://frontend/antd/float-button/group/float-button.group.tsx#L10-L67) + +### Component 3: FloatButton.BackTop + +- Design Concept + - Provides one-click back to top capability in long pages, improving navigation efficiency + - Supports custom scroll container retrieval logic, adapting to complex layouts +- Key Features + - Slot Support: icon, description, tooltip, badge.count + - Custom Target Container: target function wrapping, supports dynamic selection of scroll container +- Usage Scenarios + - Long content pages like content pages, list pages, detail pages + - Scenarios requiring frequent up/down scrolling +- Configuration Points + - Icon and Tooltip: icon, tooltip + - Badge and Description: badge, description + - Scroll Container: target (function), returns scroll container DOM node + +```mermaid +sequenceDiagram +participant User as "User" +participant BackTop as "BackTop Component" +participant Target as "target function" +participant Scroll as "Scroll Container" +User->>BackTop : Click "Back to Top" +BackTop->>Target : Get scroll container +Target-->>BackTop : Return DOM node +BackTop->>Scroll : Smooth scroll to top +Scroll-->>User : Page returns to top +``` + +Diagram Source + +- [back-top/float-button.back-top.tsx:7-44](file://frontend/antd/float-button/back-top/float-button.back-top.tsx#L7-L44) + +Section Source + +- [back-top/Index.svelte:14-50](file://frontend/antd/float-button/back-top/Index.svelte#L14-L50) +- [back-top/float-button.back-top.tsx:7-44](file://frontend/antd/float-button/back-top/float-button.back-top.tsx#L7-L44) + +### Component 4: Backend Bridge and Event Binding + +- Backend Component Class + - Defines events: click (binds internal event handler) + - Defines slots: icon, description, tooltip, tooltip.title, badge.count + - Frontend directory mapping: resolve_frontend_dir("float-button") +- Documentation and Examples + - README contains basic example placeholder + - app.py used to start documentation site + +Section Source + +- [**init**.py:22-32](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L22-L32) +- [**init**.py:92-96](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L92-L96) +- [README-zh_CN.md:1-8](file://docs/components/antd/float_button/README-zh_CN.md#L1-L8) +- [app.py:1-7](file://docs/components/antd/float_button/app.py#L1-L7) + +## Dependency Analysis + +- Component Coupling + - Backend AntdFloatButton only handles property and event declaration, does not directly render, reducing coupling + - Frontend achieves on-demand loading and decoupling through Svelte dynamic import wrapper +- Slots and Themes + - Group component introduces Ant Design theme token, injecting CSS variables to adapt border radius, etc. +- Function-type Properties + - Wraps tooltip callbacks and target through useFunction, ensuring stable operation in React/Svelte environments + +```mermaid +graph LR +PY["Backend AntdFloatButton"] --> IDX["Svelte Entry"] +IDX --> WRAP["React Wrapper"] +WRAP --> AD["Ant Design Component"] +WRAP --> THEME["Theme Token Injection"] +WRAP --> FN["useFunction Wrapped Callback"] +``` + +Diagram Source + +- [**init**.py:92-96](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L92-L96) +- [Index.svelte:10-69](file://frontend/antd/float-button/Index.svelte#L10-L69) +- [float-button.tsx:20-28](file://frontend/antd/float-button/float-button.tsx#L20-L28) +- [group/float-button.group.tsx:16-31](file://frontend/antd/float-button/group/float-button.group.tsx#L16-L31) +- [back-top/float-button.back-top.tsx:11](file://frontend/antd/float-button/back-top/float-button.back-top.tsx#L11) + +Section Source + +- [**init**.py:92-96](file://backend/modelscope_studio/components/antd/float_button/__init__.py#L92-L96) +- [float-button.tsx:20-28](file://frontend/antd/float-button/float-button.tsx#L20-L28) +- [group/float-button.group.tsx:16-31](file://frontend/antd/float-button/group/float-button.group.tsx#L16-L31) +- [back-top/float-button.back-top.tsx:11](file://frontend/antd/float-button/back-top/float-button.back-top.tsx#L11) + +## Performance Considerations + +- On-demand Loading + - Svelte avoids initial bundle bloat through dynamic import wrapper +- Rendering Overhead + - Slot content is hidden by default, only injected into Ant Design component when needed +- Callback Functions + - Use useFunction to wrap function-type properties, reducing unnecessary re-renders +- Theme Injection + - Group component injects theme tokens through CSS variables, avoiding repeated style calculations + +Section Source + +- [Index.svelte:10-10](file://frontend/antd/float-button/Index.svelte#L10-L10) +- [float-button.tsx:30-71](file://frontend/antd/float-button/float-button.tsx#L30-L71) +- [group/float-button.group.tsx:16-31](file://frontend/antd/float-button/group/float-button.group.tsx#L16-L31) + +## Troubleshooting Guide + +- FloatButton Not Displaying + - Check whether visible is true + - Confirm FRONTEND_DIR mapping is correct +- Slot Not Working + - Ensure slot names match the component support list (icon, description, tooltip, tooltip.title, badge.count) + - Group component additionally supports closeIcon, badge.count +- Back to Top Not Working + - Check whether target function returns a valid scroll container DOM node +- Tooltip Callback Not Triggered + - Confirm tooltip.afterOpenChange, tooltip.getPopupContainer are wrapped through useFunction + +Section Source + +- [Index.svelte:56-69](file://frontend/antd/float-button/Index.svelte#L56-L69) +- [float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) +- [group/float-button.group.tsx:10-67](file://frontend/antd/float-button/group/float-button.group.tsx#L10-L67) +- [back-top/float-button.back-top.tsx:7-44](file://frontend/antd/float-button/back-top/float-button.back-top.tsx#L7-L44) + +## Conclusion + +The FloatButton component achieves seamless integration and extension with Ant Design through the collaboration of backend bridge and frontend wrapper. Its slot-based design, theme injection, and function-type property wrapping maintain good maintainability and extensibility even in complex page layouts. Combined with the enhanced capabilities of "FloatButton Group" and "Back to Top", it can cover various common interaction scenarios, improving user experience and development efficiency. + +## Appendix + +- Examples and Documentation + - Documentation example entry: docs/components/antd/float_button/README-zh_CN.md + - Documentation site startup: docs/components/antd/float_button/app.py + +Section Source + +- [README-zh_CN.md:1-8](file://docs/components/antd/float_button/README-zh_CN.md#L1-L8) +- [app.py:1-7](file://docs/components/antd/float_button/app.py#L1-L7) diff --git a/.wiki/en/Ant Design Components/General Components/General Components.md b/.wiki/en/Ant Design Components/General Components/General Components.md new file mode 100644 index 00000000..05e30fd1 --- /dev/null +++ b/.wiki/en/Ant Design Components/General Components/General Components.md @@ -0,0 +1,375 @@ +# General Components + + +**Files referenced in this document** +- [button.tsx](file://frontend/antd/button/button.tsx) +- [float-button.tsx](file://frontend/antd/float-button/float-button.tsx) +- [icon.tsx](file://frontend/antd/icon/icon.tsx) +- [typography.base.tsx](file://frontend/antd/typography/typography.base.tsx) +- [basic.py (Button)](file://docs/components/antd/button/demos/basic.py) +- [basic.py (FloatButton)](file://docs/components/antd/float_button/demos/basic.py) +- [basic.py (Icon)](file://docs/components/antd/icon/demos/basic.py) +- [basic.py (Typography)](file://docs/components/antd/typography/demos/basic.py) +- [README-zh_CN.md (Button)](file://docs/components/antd/button/README-zh_CN.md) +- [README-zh_CN.md (FloatButton)](file://docs/components/antd/float_button/README-zh_CN.md) +- [README-zh_CN.md (Icon)](file://docs/components/antd/icon/README-zh_CN.md) +- [README-zh_CN.md (Typography)](file://docs/components/antd/typography/README-zh_CN.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This chapter covers the implementation and usage of Ant Design general components in this repository, focusing on the following basic general components: Button, FloatButton, Icon, and Typography. The documentation provides in-depth analysis from aspects including system architecture, component responsibilities, data and event flow, accessibility and keyboard navigation, style and theme customization, best practices for combined usage, and performance optimization, with example paths to guide readers in getting started quickly. + +## Project Structure + +This project uses an organization of "frontend Svelte component wrapping + backend Gradio example demonstration": + +- Frontend components are located under frontend/antd, where each component consists of a svelte file and a tsx wrapper layer. The tsx layer is responsible for bridging Ant Design's React components to the Svelte ecosystem, and extending child content like icons, tooltips, and badges through the slots mechanism. +- Documentation examples are located under docs/components/antd, where each component provides multiple demo scripts (basic.py, etc.) to demonstrate different properties and interaction scenarios. + +```mermaid +graph TB +subgraph "Frontend Components" +BTN["Button
button.tsx"] +FBTN["FloatButton
float-button.tsx"] +ICON["Icon
icon.tsx"] +TYPO["Typography.Base
typography.base.tsx"] +end +subgraph "Documentation Examples" +DEMO_BTN["Button Example
button/demos/basic.py"] +DEMO_FBTN["FloatButton Example
float_button/demos/basic.py"] +DEMO_ICON["Icon Example
icon/demos/basic.py"] +DEMO_TYPO["Typography Example
typography/demos/basic.py"] +end +BTN --> DEMO_BTN +FBTN --> DEMO_FBTN +ICON --> DEMO_ICON +TYPO --> DEMO_TYPO +``` + +Diagram Source + +- [button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [typography.base.tsx:1-170](file://frontend/antd/typography/typography.base.tsx#L1-L170) +- [basic.py (Button):1-26](file://docs/components/antd/button/demos/basic.py#L1-L26) +- [basic.py (FloatButton):1-30](file://docs/components/antd/float_button/demos/basic.py#L1-L30) +- [basic.py (Icon):1-24](file://docs/components/antd/icon/demos/basic.py#L1-L24) +- [basic.py (Typography):1-23](file://docs/components/antd/typography/demos/basic.py#L1-L23) + +Section Source + +- [README-zh_CN.md (Button):1-8](file://docs/components/antd/button/README-zh_CN.md#L1-L8) +- [README-zh_CN.md (FloatButton):1-8](file://docs/components/antd/float_button/README-zh_CN.md#L1-L8) +- [README-zh_CN.md (Icon):1-10](file://docs/components/antd/icon/README-zh_CN.md#L1-L10) +- [README-zh_CN.md (Typography):1-8](file://docs/components/antd/typography/README-zh_CN.md#L1-L8) + +## Core Components + +- Button + - Responsibility: Wraps Ant Design's Button, supports injecting icon and custom loading icon through slots; supports dual entry rendering via value and children. + - Key Points: Uses useTargets to extract slot targets, dynamically determining render content; conditionally merges loading configuration, compatible with both objects and booleans. +- FloatButton + - Responsibility: Wraps Ant Design's FloatButton, supports slot-based configuration for icon, description, tooltip, badge, etc.; wraps function-type configuration items with useFunction to maintain reactivity. + - Key Points: tooltip supports title and overall configuration object; badge supports count slot; description supports slot. +- Icon + - Responsibility: Supports Ant Design built-in icon name mapping and IconFont rendering; supports custom component slot as SVG component. + - Key Points: slots.component has highest priority; otherwise maps to built-in icon by value; finally falls back to IconFont type. +- Typography.Base + - Responsibility: Unifies and aggregates four typography component types: Title, Text, Paragraph, Link, supporting slot-based configuration for copyable, editable, and ellipsis. + - Key Points: Dynamically selects specific Typography sub-component based on component; processes multiple slots with useTargets and renderParamsSlot, ensuring flexibility and extensibility. + +Section Source + +- [button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [typography.base.tsx:1-170](file://frontend/antd/typography/typography.base.tsx#L1-L170) + +## Architecture Overview + +The diagram below shows the call chain for general components: documentation examples start through Gradio application, internally use ConfigProvider for global theme configuration, then render each component; components internally bridge Ant Design's React components to Svelte components through sveltify, and inject icons, tooltips, badges, etc. using the slots mechanism. + +```mermaid +sequenceDiagram +participant Demo as "Example Script" +participant App as "Gradio Application" +participant Provider as "ConfigProvider" +participant Comp as "Component Wrapper Layer" +participant Antd as "Ant Design Component" +Demo->>App : "Build Blocks and start" +App->>Provider : "Apply global configuration" +App->>Comp : "Render component instance" +Comp->>Antd : "Pass properties and slots" +Antd-->>Comp : "Render result" +Comp-->>App : "Return Svelte wrapped node" +App-->>Demo : "Complete one render" +``` + +Diagram Source + +- [basic.py (Button):5-25](file://docs/components/antd/button/demos/basic.py#L5-L25) +- [basic.py (FloatButton):5-29](file://docs/components/antd/float_button/demos/basic.py#L5-L29) +- [basic.py (Icon):5-23](file://docs/components/antd/icon/demos/basic.py#L5-L23) +- [basic.py (Typography):10-22](file://docs/components/antd/typography/demos/basic.py#L10-L22) +- [button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) +- [float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) +- [icon.tsx:12-52](file://frontend/antd/icon/icon.tsx#L12-L52) +- [typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) + +## Detailed Component Analysis + +### Button + +- Design Points + - Supports multiple types and variants: such as primary, dashed, text, link, filled, etc.; supports block layout and size control. + - Slot Capabilities: Inject icons through slots.icon; inject loading state icons through slots.loading.icon, supporting delay configuration. + - Content Entry: Supports directly passing text (children) or value field; when slots exist, slot content is rendered first. +- Events and Interaction + - click event: The example demonstrates click callback binding. + - Loading State: Can be configured via loading=true or passing an object to configure delay time. +- Styles and Themes + - Global theme takes effect through ConfigProvider; supports color and variant combinations. +- Usage Examples (Reference Path) + - Basic usage and variants: [basic.py (Button):8-22](file://docs/components/antd/button/demos/basic.py#L8-L22) + - Slot icons and loading state: [basic.py (Button):18-22](file://docs/components/antd/button/demos/basic.py#L18-L22) + +```mermaid +sequenceDiagram +participant U as "User" +participant Btn as "Button Wrapper Layer" +participant RBtn as "Antd Button" +U->>Btn : "Click triggers click event" +Btn->>RBtn : "Forward click event" +RBtn-->>U : "Execute callback and update interface" +Note over Btn,RBtn : "Slots icon/ loading.icon injected by slots" +``` + +Diagram Source + +- [button.tsx:11-36](file://frontend/antd/button/button.tsx#L11-L36) +- [basic.py (Button):10-10](file://docs/components/antd/button/demos/basic.py#L10-L10) + +Section Source + +- [button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) +- [basic.py (Button):8-22](file://docs/components/antd/button/demos/basic.py#L8-L22) + +### FloatButton + +- Design Points + - Supports sub-components like Group and BackTop; supports slot-based configuration for icon, description, tooltip, badge, etc. + - tooltip supports title and overall configuration object; badge supports count slot; description supports slot. + - Uses useFunction to wrap function-type configuration items (like afterOpenChange, getPopupContainer), ensuring reactive updates. +- Events and Interaction + - Supports click, visibility control (BackTop's visibility_height), etc. +- Styles and Themes + - Customize position and layout through elem_style; combine with Group to implement multi-button grouping. +- Usage Examples (Reference Path) + - Basic usage and grouping: [basic.py (FloatButton):8-13](file://docs/components/antd/float_button/demos/basic.py#L8-L13) + - Badge and icon: [basic.py (FloatButton):10-12](file://docs/components/antd/float_button/demos/basic.py#L10-L12) + - BackTop and Tooltip slots: [basic.py (FloatButton):13-13](file://docs/components/antd/float_button/demos/basic.py#L13-L13), [basic.py (FloatButton):23-27](file://docs/components/antd/float_button/demos/basic.py#L23-L27) + +```mermaid +sequenceDiagram +participant U as "User" +participant F as "FloatButton Wrapper Layer" +participant FB as "Antd FloatButton" +U->>F : "Click float button" +F->>FB : "Forward click event" +FB-->>U : "Execute callback and show/hide" +Note over F,FB : "tooltip.title/tooltip slot and badge.count slot injected by slots" +``` + +Diagram Source + +- [float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) +- [basic.py (FloatButton):13-13](file://docs/components/antd/float_button/demos/basic.py#L13-L13) +- [basic.py (FloatButton):23-27](file://docs/components/antd/float_button/demos/basic.py#L23-L27) + +Section Source + +- [float-button.tsx:7-72](file://frontend/antd/float-button/float-button.tsx#L7-L72) +- [basic.py (FloatButton):8-27](file://docs/components/antd/float_button/demos/basic.py#L8-L27) + +### Icon + +- Design Points + - Supports built-in icon name mapping (like HomeOutlined, SettingFilled, etc.); supports spin, rotate, twoTone, etc. properties. + - Supports IconFont fallback rendering; supports slots.component to inject custom SVG components. +- Events and Interaction + - The example demonstrates click event binding. +- Styles and Themes + - Supports style controls like color, rotation angle, two-tone icons, etc. +- Usage Examples (Reference Path) + - Basic icons and two-tone icons: [basic.py (Icon):9-16](file://docs/components/antd/icon/demos/basic.py#L9-L16) + - Custom component slots: [basic.py (Icon):19-21](file://docs/components/antd/icon/demos/basic.py#L19-L21) + +```mermaid +flowchart TD +Start(["Enter Icon rendering"]) --> CheckSlot["Check if slots.component exists"] +CheckSlot --> |Yes| RenderCustom["Render custom component"] +CheckSlot --> |No| CheckValue["Look up built-in icon by value"] +CheckValue --> Found{"Found built-in icon?"} +Found --> |Yes| RenderBuiltIn["Render built-in icon"] +Found --> |No| CheckIconFont["Check IconFont context"] +CheckIconFont --> HasFont{"Has IconFont?"} +HasFont --> |Yes| RenderIconFont["Render using IconFont"] +HasFont --> |No| Empty["Do not render empty"] +RenderCustom --> End(["End"]) +RenderBuiltIn --> End +RenderIconFont --> End +Empty --> End +``` + +Diagram Source + +- [icon.tsx:12-52](file://frontend/antd/icon/icon.tsx#L12-L52) +- [basic.py (Icon):9-16](file://docs/components/antd/icon/demos/basic.py#L9-L16) +- [basic.py (Icon):19-21](file://docs/components/antd/icon/demos/basic.py#L19-L21) + +Section Source + +- [icon.tsx:12-52](file://frontend/antd/icon/icon.tsx#L12-L52) +- [basic.py (Icon):9-21](file://docs/components/antd/icon/demos/basic.py#L9-L21) + +### Typography.Base + +- Design Points + - Unifies and aggregates four component types: Title, Text, Paragraph, Link, switching via component parameter. + - Supports slot-based configuration for copyable, editable, and ellipsis, enhancing customizability. + - Uses useSlotsChildren and useTargets to separate slot content from regular children, avoiding duplicate rendering. +- Events and Interaction + - editable_change event: The example demonstrates binding for edit change event and output update. +- Styles and Themes + - Generates class names through className and component name prefix, facilitating theme override. +- Usage Examples (Reference Path) + - Basic titles and text: [basic.py (Typography):13-15](file://docs/components/antd/typography/demos/basic.py#L13-L15) + - Copyable paragraphs and edit events: [basic.py (Typography):16-19](file://docs/components/antd/typography/demos/basic.py#L16-L19) + +```mermaid +sequenceDiagram +participant U as "User" +participant T as "Typography.Base" +participant TT as "Antd Typography.*" +U->>T : "Start editing" +T->>TT : "Trigger editable event" +TT-->>T : "Return edit result" +T-->>U : "Update content and close edit" +Note over T,TT : "copyable/ editable/ ellipsis slots injected by slots" +``` + +Diagram Source + +- [typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) +- [basic.py (Typography):16-19](file://docs/components/antd/typography/demos/basic.py#L16-L19) + +Section Source + +- [typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) +- [basic.py (Typography):13-19](file://docs/components/antd/typography/demos/basic.py#L13-L19) + +## Dependency Analysis + +- Inter-component Coupling + - Button, FloatButton, Icon, and Typography.Base all bridge Ant Design's React components to Svelte through sveltify, independent of each other with low coupling. + - The slot mechanism (slots) runs through all components, used to inject child content like icons, tooltips, badges, etc., enhancing extensibility. +- External Dependencies + - Ant Design React component library: Provides basic UI capabilities. + - @svelte-preprocess-react: Provides sveltify and ReactSlot, implementing Svelte and React interoperability. + - lodash-es: Provides utility functions (like isObject). + - @utils/\*: Provides useTargets, useFunction, renderParamsSlot, and other utilities, enhancing slot and event handling capabilities. +- Potential Circular Dependencies + - No circular dependencies found in the current structure; components all collaborate through utility functions and contexts, maintaining one-way dependencies. + +```mermaid +graph LR +BTN["Button.tsx"] --> AD["Ant Design Button"] +FBTN["FloatButton.tsx"] --> AD_FB["Ant Design FloatButton"] +ICON["Icon.tsx"] --> AD_Icons["Ant Design Icons"] +TYPO["Typography.Base.tsx"] --> AD_Typo["Ant Design Typography"] +BTN --> Utils["@utils/*"] +FBTN --> Utils +ICON --> Utils +TYPO --> Utils +Utils --> SveltePreprocess["@svelte-preprocess-react"] +AD --> React["React"] +AD_FB --> React +AD_Icons --> React +AD_Typo --> React +``` + +Diagram Source + +- [button.tsx:1-6](file://frontend/antd/button/button.tsx#L1-L6) +- [float-button.tsx:1-5](file://frontend/antd/float-button/float-button.tsx#L1-L5) +- [icon.tsx:1-6](file://frontend/antd/icon/icon.tsx#L1-L6) +- [typography.base.tsx:1-10](file://frontend/antd/typography/typography.base.tsx#L1-L10) + +Section Source + +- [button.tsx:1-6](file://frontend/antd/button/button.tsx#L1-L6) +- [float-button.tsx:1-5](file://frontend/antd/float-button/float-button.tsx#L1-L5) +- [icon.tsx:1-6](file://frontend/antd/icon/icon.tsx#L1-L6) +- [typography.base.tsx:1-10](file://frontend/antd/typography/typography.base.tsx#L1-L10) + +## Performance Considerations + +- Slot Rendering Optimization + - Uses useTargets and useSlotsChildren to separate slots from regular children, reducing unnecessary rendering overhead. + - Conditionally injects loading.icon, copyable.icon, editable.icon, etc., avoiding useless node mounting. +- Function-type Configuration Wrapping + - Uses useFunction to wrap function-type configurations for tooltip (like afterOpenChange, getPopupContainer), ensuring reactive updates without closure jitter. +- Conditional Merging + - Merges copyable, editable, ellipsis, etc. configurations through getConfig and omitUndefinedProps, only enabling corresponding capabilities when needed, reducing runtime burden. +- Theme and Styles + - Unifies theme through ConfigProvider, avoiding repeated calculations and style conflicts; reasonably uses className prefix for precise override. + +## Troubleshooting Guide + +- Slot Not Working + - Confirm whether slot names are correct (like icon, loading.icon, copyable.icon, editable.icon, ellipsis.symbol, etc.). + - Confirm slots.component has higher priority than built-in icon mapping; if provided, it will override default behavior. +- Tooltip Cannot Open or Callback Invalid + - Check whether tooltip is an object configuration; ensure function-type configuration items are wrapped through useFunction. +- Icon Not Displaying + - If slots.component is not provided, confirm whether value is a built-in icon name; otherwise, need to correctly configure IconFont context. +- Edit/Copy/Ellipsis Configuration Not Working + - Confirm that editable, copyable, or ellipsis enable corresponding capability if any exists; if it's an object configuration, ensure fields are complete. + +Section Source + +- [float-button.tsx:14-72](file://frontend/antd/float-button/float-button.tsx#L14-L72) +- [icon.tsx:12-52](file://frontend/antd/icon/icon.tsx#L12-L52) +- [typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) + +## Conclusion + +This repository seamlessly integrates Ant Design's React components into the Svelte/Gradio ecosystem through unified sveltify wrapping and slot mechanism, achieving high customizability and ease of use for general components like Button, FloatButton, Icon, and Typography. With ConfigProvider, slots, and utility functions, developers can flexibly implement style customization, interaction extension, and accessibility requirements. It is recommended to follow slot naming conventions, reasonably use function-type configuration wrapping and conditional rendering strategies in actual projects for better performance and maintainability. + +## Appendix + +- Quick Example Paths + - Button: [basic.py (Button):8-22](file://docs/components/antd/button/demos/basic.py#L8-L22) + - FloatButton: [basic.py (FloatButton):8-27](file://docs/components/antd/float_button/demos/basic.py#L8-L27) + - Icon: [basic.py (Icon):9-21](file://docs/components/antd/icon/demos/basic.py#L9-L21) + - Typography: [basic.py (Typography):13-19](file://docs/components/antd/typography/demos/basic.py#L13-L19) +- Component Documentation Entry + - Button: [README-zh_CN.md (Button):1-8](file://docs/components/antd/button/README-zh_CN.md#L1-L8) + - FloatButton: [README-zh_CN.md (FloatButton):1-8](file://docs/components/antd/float_button/README-zh_CN.md#L1-L8) + - Icon: [README-zh_CN.md (Icon):1-10](file://docs/components/antd/icon/README-zh_CN.md#L1-L10) + - Typography: [README-zh_CN.md (Typography):1-8](file://docs/components/antd/typography/README-zh_CN.md#L1-L8) diff --git a/.wiki/en/Ant Design Components/General Components/Icon.md b/.wiki/en/Ant Design Components/General Components/Icon.md new file mode 100644 index 00000000..db7c8238 --- /dev/null +++ b/.wiki/en/Ant Design Components/General Components/Icon.md @@ -0,0 +1,360 @@ +# Icon + + +**Files referenced in this document** +- [frontend/antd/icon/Index.svelte](file://frontend/antd/icon/Index.svelte) +- [frontend/antd/icon/icon.tsx](file://frontend/antd/icon/icon.tsx) +- [frontend/antd/icon/iconfont-provider/Index.svelte](file://frontend/antd/icon/iconfont-provider/Index.svelte) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx) +- [backend/modelscope_studio/components/antd/icon/__init__.py](file://backend/modelscope_studio/components/antd/icon/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [docs/components/antd/icon/README-zh_CN.md](file://docs/components/antd/icon/README-zh_CN.md) +- [docs/components/antd/icon/demos/basic.py](file://docs/components/antd/icon/demos/basic.py) +- [docs/components/antd/icon/demos/iconfont.py](file://docs/components/antd/icon/demos/iconfont.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Optimization](#performance-and-optimization) +8. [Accessibility](#accessibility) +9. [Troubleshooting](#troubleshooting) +10. [Conclusion](#conclusion) +11. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document systematically introduces the Icon component in ModelScope Studio's frontend ecosystem, covering: + +- Usage guidelines and common scenarios (inline icons, button icons, navigation icons) +- Supported icon libraries and icon font integration (Ant Design built-in icons, iconfont.cn) +- Size, color, style, and other configuration options +- IconFontProvider configuration and usage +- Performance optimization, lazy loading, and caching strategies +- Accessibility, semantic markup, and screen reader compatibility +- Custom icon library integration solutions and best practices + +## Project Structure + +The Icon component consists of "backend Gradio component layer" and "frontend Svelte/React presentation layer", and supports custom rendering through the Slot mechanism. + +```mermaid +graph TB +subgraph "Backend" +PY_ICON["AntdIcon
Python Component"] +PY_PROVIDER["AntdIconIconfontProvider
Python Component"] +end +subgraph "Frontend" +SV_INDEX["Index.svelte
Component Entry (Svelte)"] +TS_ICON["icon.tsx
React Implementation (Ant Design Icons)"] +SV_PROVIDER_INDEX["iconfont-provider/Index.svelte
Provider Entry (Svelte)"] +TS_PROVIDER["iconfont-provider.tsx
React Provider (IconFont)"] +end +PY_ICON --> SV_INDEX +PY_PROVIDER --> SV_PROVIDER_INDEX +SV_INDEX --> TS_ICON +SV_PROVIDER_INDEX --> TS_PROVIDER +``` + +Diagram Source + +- [backend/modelscope_studio/components/antd/icon/**init**.py:9-88](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L88) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) +- [frontend/antd/icon/icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [frontend/antd/icon/iconfont-provider/Index.svelte:1-53](file://frontend/antd/icon/iconfont-provider/Index.svelte#L1-L53) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:1-44](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L1-L44) + +Section Source + +- [backend/modelscope_studio/components/antd/icon/**init**.py:9-88](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L88) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) +- [frontend/antd/icon/icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [frontend/antd/icon/iconfont-provider/Index.svelte:1-53](file://frontend/antd/icon/iconfont-provider/Index.svelte#L1-L53) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:1-44](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L1-L44) + +## Core Components + +- AntdIcon (Backend): Provides properties such as value, spin, rotate, twoToneColor, component, etc.; supports click event binding; supports a Slot named "component" to inject custom rendering. +- AntdIconIconfontProvider (Backend): Provides IconFont context, used to render icons by type in icon font libraries like iconfont.cn. +- Frontend Svelte Entry: Responsible for forwarding backend-passed properties and Slots to React implementation. +- Frontend React Implementation: Selects built-in Ant Design icons based on value or renders custom icon types through IconFont context. + +Section Source + +- [backend/modelscope_studio/components/antd/icon/**init**.py:9-88](file://backend/modelscope_studio/components/antd/icon/__init__.py#L9-L88) +- [frontend/antd/icon/Index.svelte:1-67](file://frontend/antd/icon/Index.svelte#L1-L67) +- [frontend/antd/icon/icon.tsx:1-55](file://frontend/antd/icon/icon.tsx#L1-L55) +- [frontend/antd/icon/iconfont-provider/Index.svelte:1-53](file://frontend/antd/icon/iconfont-provider/Index.svelte#L1-L53) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:1-44](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L1-L44) + +## Architecture Overview + +The diagram below shows the key call chain from backend to frontend and then to icon rendering: + +```mermaid +sequenceDiagram +participant Py as "Backend AntdIcon" +participant S as "Frontend Index.svelte" +participant R as "React Icon Implementation" +participant Ctx as "IconFont Context" +Py->>S : Pass value/props/Slots +S->>R : Render Icon and pass through properties +alt Using custom component Slot +R->>R : Render using custom component +else Using built-in or IconFont +R->>Ctx : Read IconFont context +alt IconFont exists +R->>Ctx : Call IconFont(type, props) +else Not exists +R->>R : Render Ant Design built-in icon +end +end +``` + +Diagram Source + +- [frontend/antd/icon/Index.svelte:52-66](file://frontend/antd/icon/Index.svelte#L52-L66) +- [frontend/antd/icon/icon.tsx:17-52](file://frontend/antd/icon/icon.tsx#L17-L52) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:36-41](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L36-L41) + +## Component Details + +### AntdIcon (Backend) + +- Supported Properties + - value: String, specifies icon name (like built-in icon name or IconFont type name) + - spin: Boolean, whether to rotate animation + - rotate: Numeric angle, icon rotation angle + - twoToneColor: Two-tone icon primary color + - component: Root node component placeholder (used to replace default container) + - Element-level styles and class names: elem_style, elem_classes + - Visibility and rendering: visible, render +- Events + - click: Bind click event +- Slot + - component: Used to inject custom rendering (such as text emoticons, SVG components) + +Section Source + +- [backend/modelscope_studio/components/antd/icon/**init**.py:27-68](file://backend/modelscope_studio/components/antd/icon/__init__.py#L27-L68) +- [backend/modelscope_studio/components/antd/icon/**init**.py:18-22](file://backend/modelscope_studio/components/antd/icon/__init__.py#L18-L22) + +### Frontend Svelte Entry (Index.svelte) + +- Passes backend-provided value, additionalProps, elem\_\*, and other properties to React Icon +- Gets and forwards to React Icon through Slot +- Conditional rendering: Only renders when visible is true + +Section Source + +- [frontend/antd/icon/Index.svelte:13-66](file://frontend/antd/icon/Index.svelte#L13-L66) + +### React Implementation (icon.tsx) + +- Key Logic Points + - Prioritizes custom component injected through "component" Slot for rendering + - Otherwise, if built-in icon name exists, renders corresponding Ant Design icon + - If no built-in icon and IconFont context exists, renders through IconFont(type, props) +- Key Context + - useIconFontContext: Gets IconFont context instance + +Section Source + +- [frontend/antd/icon/icon.tsx:17-52](file://frontend/antd/icon/icon.tsx#L17-L52) + +### AntdIconIconfontProvider (Backend) + +- Provides IconFont context, enabling child-level Icons to render custom icon fonts by type +- Common Usage: Wraps a set of icons that need to use iconfont.cn + +Section Source + +- [backend/modelscope_studio/components/antd/icon/**init**.py:16-16](file://backend/modelscope_studio/components/antd/icon/__init__.py#L16-L16) + +### Frontend Provider (iconfont-provider.tsx) + +- Functionality + - Creates IconFont instance based on createFromIconfontCN + - Instance Caching: Reuses same instance when scriptUrl and extraCommonProps are unchanged + - Exposes to subtree through IconFontContext.Provider +- Parameters + - scriptUrl: Icon font script address (can be an array) + - extraCommonProps: Extra common properties (like color, fontSize, etc.) + +Section Source + +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:12-41](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L12-L41) + +### Provider Frontend Entry (iconfont-provider/Index.svelte) + +- Passes backend-provided Provider properties to React Provider component +- Acts as parent context container for Icons + +Section Source + +- [frontend/antd/icon/iconfont-provider/Index.svelte:42-52](file://frontend/antd/icon/iconfont-provider/Index.svelte#L42-L52) + +## Dependency Analysis + +- Component Coupling + - AntdIcon and AntdIconIconfontProvider are associated through classes in backend + - Frontend Svelte entry and React implementation are decoupled, communicating through properties and Slots + - React Icon depends on Ant Design Icons and IconFont context +- External Dependencies + - @ant-design/icons: Built-in icon library + - lodash-es isEqual: Used for Provider instance cache comparison + +```mermaid +graph LR +PY_ICON["Backend AntdIcon"] --> SV_ICON["Svelte Entry"] +PY_PROVIDER["Backend IconFontProvider"] --> SV_PROVIDER["Svelte Provider Entry"] +SV_ICON --> REACT_ICON["React Icon Implementation"] +SV_PROVIDER --> REACT_PROVIDER["React Provider Implementation"] +REACT_ICON --> AD["@ant-design/icons"] +REACT_PROVIDER --> ADIF["createFromIconfontCN"] +``` + +Diagram Source + +- [backend/modelscope_studio/components/antd/icon/**init**.py:5-6](file://backend/modelscope_studio/components/antd/icon/__init__.py#L5-L6) +- [frontend/antd/icon/icon.tsx:5-5](file://frontend/antd/icon/icon.tsx#L5-L5) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:4-6](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L4-L6) + +Section Source + +- [backend/modelscope_studio/components/antd/icon/**init**.py:5-6](file://backend/modelscope_studio/components/antd/icon/__init__.py#L5-L6) +- [frontend/antd/icon/icon.tsx:5-5](file://frontend/antd/icon/icon.tsx#L5-L5) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:4-6](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L4-L6) + +## Performance and Optimization + +- Lazy Loading and Async Rendering + - Svelte entry uses async import for Icon and Provider, avoiding first-screen blocking +- Instance Caching + - Provider internally caches IconFont instances based on scriptUrl and extraCommonProps equality, reducing repeated initialization +- Render Path Short-circuit + - When custom Slot exists, directly renders custom component, skipping built-in icon resolution +- Recommendations + - For pages with many icons, prioritize using IconFont and centrally managing scriptUrl + - Reasonably set extraCommonProps to avoid frequent instance rebuilding + - Avoid mixing too many different script sources under the same Provider, reducing context switching cost + +Section Source + +- [frontend/antd/icon/Index.svelte:10-10](file://frontend/antd/icon/Index.svelte#L10-L10) +- [frontend/antd/icon/iconfont-provider/Index.svelte:8-9](file://frontend/antd/icon/iconfont-provider/Index.svelte#L8-L9) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:18-35](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L18-L35) + +## Accessibility + +- Semantic Recommendations + - If the icon carries interactive semantics (like "delete", "search"), it should be accompanied by readable text or aria-label + - For decorative icons, use aria-hidden or add no extra semantics +- Screen Readers + - Keep icons with alternative text (for example, through adjacent text or title attribute) + - Avoid relying solely on color to convey information +- Styles and Focus + - Click-type icons need to ensure focusable and keyboard accessible + - Rotation/animation should not affect accessibility experience + +[This section provides general guidance, no specific file references needed] + +## Troubleshooting + +- Icon Not Displaying + - Check whether value is a valid built-in icon name or IconFont type name + - If using Provider, confirm scriptUrl is correct and network accessible +- Custom Component Not Working + - Confirm that custom rendering is correctly injected using "component" Slot + - Check Slot name case and passing path +- Repeated Requests or Instance Jitter + - Frequent changes to Provider's extraCommonProps or scriptUrl will cause instance rebuilding + - Recommend fixing parameters or merging multiple script sources + +Section Source + +- [frontend/antd/icon/icon.tsx:32-51](file://frontend/antd/icon/icon.tsx#L32-L51) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:18-35](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L18-L35) + +## Conclusion + +This component uses a "backend component + frontend async rendering" pattern, balancing unified access to both Ant Design built-in icons and custom icon fonts like iconfont.cn. Through Slot mechanism and context caching, it satisfies both flexible extension and ensures performance and maintainability. It is recommended to centrally manage icon font resources and style parameters in projects, combining with accessibility guidelines to improve user experience. + +[This section is a summary, no specific file references needed] + +## Appendix: Usage Examples and Best Practices + +### Basic Usage and Built-in Icons + +- Scenarios: Inline icons, button icons, status icons +- Example Reference + - [docs/components/antd/icon/demos/basic.py:9-17](file://docs/components/antd/icon/demos/basic.py#L9-L17) + +Best Practices + +- Provide click callbacks and readable text for interactive icons +- Use twoToneColor to control two-tone icon primary color, maintaining brand consistency + +Section Source + +- [docs/components/antd/icon/demos/basic.py:9-17](file://docs/components/antd/icon/demos/basic.py#L9-L17) + +### Using iconfont.cn + +- Scenarios: Enterprise icon libraries, third-party icon fonts +- Example Reference + - [docs/components/antd/icon/demos/iconfont.py:9-18](file://docs/components/antd/icon/demos/iconfont.py#L9-L18) + +Best Practices + +- Merge multiple script sources into an array to reduce request count +- Set common properties like color, fontSize uniformly through extraCommonProps +- Wrap the set of icons that need to use the font outside the Provider + +Section Source + +- [docs/components/antd/icon/demos/iconfont.py:9-18](file://docs/components/antd/icon/demos/iconfont.py#L9-L18) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:29-33](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L29-L33) + +### Custom Icon Library Integration + +- Option 1: Use "component" Slot to inject any custom rendering (text, SVG, components) + - Example Reference + - [docs/components/antd/icon/demos/basic.py:19-21](file://docs/components/antd/icon/demos/basic.py#L19-L21) +- Option 2: Connect custom fonts through IconFontProvider + - Example Reference + - [docs/components/antd/icon/demos/iconfont.py:9-18](file://docs/components/antd/icon/demos/iconfont.py#L9-L18) + +Best Practices + +- Keep Slot rendering lightweight, avoid executing complex logic on icons +- Prefer localizing font resources or using stable CDN to reduce loading failure risk + +Section Source + +- [docs/components/antd/icon/demos/basic.py:19-21](file://docs/components/antd/icon/demos/basic.py#L19-L21) +- [docs/components/antd/icon/demos/iconfont.py:9-18](file://docs/components/antd/icon/demos/iconfont.py#L9-L18) + +### Configuration Quick Reference + +- AntdIcon (Backend) + - value: Icon name + - spin: Rotation animation + - rotate: Rotation angle + - twoToneColor: Two-tone primary color + - component: Root node component placeholder + - elem_style/elem_classes: Element styles and class names + - visible/render: Visibility and rendering control +- AntdIconIconfontProvider (Backend) + - script_url: Icon font script address (array) + - extra_common_props: Common properties (like color, fontSize) + +Section Source + +- [backend/modelscope_studio/components/antd/icon/**init**.py:27-68](file://backend/modelscope_studio/components/antd/icon/__init__.py#L27-L68) +- [frontend/antd/icon/iconfont-provider/iconfont-provider.tsx:12-12](file://frontend/antd/icon/iconfont-provider/iconfont-provider.tsx#L12-L12) diff --git a/.wiki/en/Ant Design Components/General Components/Typography.md b/.wiki/en/Ant Design Components/General Components/Typography.md new file mode 100644 index 00000000..3fef6aa3 --- /dev/null +++ b/.wiki/en/Ant Design Components/General Components/Typography.md @@ -0,0 +1,251 @@ +# Typography + + +**Files referenced in this document** +- [frontend/antd/typography/Base.svelte](file://frontend/antd/typography/Base.svelte) +- [frontend/antd/typography/typography.base.tsx](file://frontend/antd/typography/typography.base.tsx) +- [frontend/antd/typography/title/Index.svelte](file://frontend/antd/typography/title/Index.svelte) +- [frontend/antd/typography/paragraph/Index.svelte](file://frontend/antd/typography/paragraph/Index.svelte) +- [frontend/antd/typography/text/Index.svelte](file://frontend/antd/typography/text/Index.svelte) +- [frontend/antd/typography/link/Index.svelte](file://frontend/antd/typography/link/Index.svelte) +- [docs/components/antd/typography/README.md](file://docs/components/antd/typography/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The Typography component is used to present text content such as headings, paragraphs, inline text, and links in the interface, unifying text hierarchy, readability, and consistency in the design system. This component is wrapped based on Ant Design's Typography capabilities, providing interactive features such as copyable, editable, and ellipsis, and integrates with Gradio through the Svelte component system, supporting dynamic values and slot-based extensions. + +## Project Structure + +Typography uses an organization of "sub-components + base bridge layer" on the frontend side: + +- Base.svelte: Svelte layer entry, responsible for property processing, slot pass-through, and rendering condition control +- typography.base.tsx: React bridge layer, uniformly scheduling Ant Design Typography component types, and injecting advanced capabilities like copyable/editable/ellipsis +- title/paragraph/text/link: Four specific semantic sub-components, mapping to Ant Design's Title/Paragraph/Text/Link respectively + +```mermaid +graph TB +subgraph "Svelte Layer" +Base["Base.svelte"] +Title["title/Index.svelte"] +Paragraph["paragraph/Index.svelte"] +Text["text/Index.svelte"] +Link["link/Index.svelte"] +end +subgraph "React Bridge Layer" +Bridge["typography.base.tsx"] +end +subgraph "Ant Design" +ADT["Typography.Title/Paragraph/Text/Link"] +end +Title --> Base +Paragraph --> Base +Text --> Base +Link --> Base +Base --> Bridge +Bridge --> ADT +``` + +Diagram Source + +- [frontend/antd/typography/Base.svelte:11-84](file://frontend/antd/typography/Base.svelte#L11-L84) +- [frontend/antd/typography/typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) + +Section Source + +- [frontend/antd/typography/Base.svelte:1-85](file://frontend/antd/typography/Base.svelte#L1-L85) +- [frontend/antd/typography/typography.base.tsx:1-170](file://frontend/antd/typography/typography.base.tsx#L1-L170) + +## Core Components + +- Base.svelte: Responsible for extracting from Gradio properties and converting to React-consumable props; handling visibility, DOM ID/class names, extra properties, and slots; rendering base bridge layer on demand +- typography.base.tsx: Selects corresponding Ant Design component based on component type; uniformly handles copyable, editable, and ellipsis configuration and slots; injects component instance and style class names to output +- Four semantic sub-components: title, paragraph, text, link, all using Base as carrier, only needing to specify component + +Section Source + +- [frontend/antd/typography/Base.svelte:15-62](file://frontend/antd/typography/Base.svelte#L15-L62) +- [frontend/antd/typography/typography.base.tsx:19-80](file://frontend/antd/typography/typography.base.tsx#L19-L80) +- [frontend/antd/typography/title/Index.svelte:1-12](file://frontend/antd/typography/title/Index.svelte#L1-L12) +- [frontend/antd/typography/paragraph/Index.svelte:1-12](file://frontend/antd/typography/paragraph/Index.svelte#L1-L12) +- [frontend/antd/typography/text/Index.svelte:1-12](file://frontend/antd/typography/text/Index.svelte#L1-L12) +- [frontend/antd/typography/link/Index.svelte:1-12](file://frontend/antd/typography/link/Index.svelte#L1-L12) + +## Architecture Overview + +The diagram below shows the call chain from Svelte to React and then to Ant Design Typography, as well as the assembly process of copyable/editable/ellipsis. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Sub-component
title/paragraph/text/link" +participant Base as "Base.svelte" +participant Bridge as "typography.base.tsx" +participant AD as "Ant Design Typography" +Svelte->>Base : Pass props + slots +Base->>Bridge : Convert and merge props +Bridge->>Bridge : Parse copyable/editable/ellipsis config and slots +Bridge->>AD : Render corresponding component (Title/Paragraph/Text/Link) +AD-->>Bridge : Return component with assembled interactive capabilities +Bridge-->>Base : Output final node +Base-->>Svelte : Render result +``` + +Diagram Source + +- [frontend/antd/typography/Base.svelte:65-84](file://frontend/antd/typography/Base.svelte#L65-L84) +- [frontend/antd/typography/typography.base.tsx:69-163](file://frontend/antd/typography/typography.base.tsx#L69-L163) + +## Detailed Component Analysis + +### Base Bridge Layer (typography.base.tsx) + +- Component Selection Logic: Switches among Title/Paragraph/Text/Link based on component value +- Capability Assembly: + - Copy (copyable): Supports custom icons, tooltips, or injection through slots + - Edit (editable): Supports edit icon, tooltip, and enter icon slot-based replacement + - Ellipsis (ellipsis): Supports ellipsis symbol and tooltip slot-based replacement; has special toggle behavior for link component +- Slot and Target Resolution: Uses useTargets to identify targets with specific slot markers in children, then renders with ReactSlot +- Class Name and Style: Appends namespace class name on top of original className, facilitating theme and override + +```mermaid +flowchart TD +Start(["Enter bridge layer"]) --> Choose["Select Ant Design component based on component"] +Choose --> Copyable{"Enable copy capability?"} +Copyable --> |Yes| BuildCopy["Merge config and inject icon/tooltip slots"] +Copyable --> |No| SkipCopy["Skip copy config"] +Choose --> Editable{"Enable edit capability?"} +Editable --> |Yes| BuildEdit["Inject edit icon/tooltip/enter icon slots"] +Editable --> |No| SkipEdit["Skip edit config"] +Choose --> Ellipsis{"Enable ellipsis capability?"} +Ellipsis --> |Yes| BuildEllipsis["Inject ellipsis symbol/tooltip slots"] +Ellipsis --> |No| SkipEllipsis["Skip ellipsis config"] +BuildCopy --> Render["Render final component"] +BuildEdit --> Render +BuildEllipsis --> Render +SkipCopy --> Render +SkipEdit --> Render +SkipEllipsis --> Render +Render --> End(["Return render result"]) +``` + +Diagram Source + +- [frontend/antd/typography/typography.base.tsx:40-167](file://frontend/antd/typography/typography.base.tsx#L40-L167) + +Section Source + +- [frontend/antd/typography/typography.base.tsx:19-167](file://frontend/antd/typography/typography.base.tsx#L19-L167) + +### Svelte Entry (Base.svelte) + +- Property Processing: Gets component properties from Gradio, filters internal fields, preserves externally available props +- Slot Processing: Collects and passes through slots, while distinguishing value and children for rendering +- Conditional Rendering: Controls display based on visible; supports directly rendering children in layout mode +- DOM Properties: Injects elem_id, elem_classes, elem_style, etc. + +Section Source + +- [frontend/antd/typography/Base.svelte:15-62](file://frontend/antd/typography/Base.svelte#L15-L62) +- [frontend/antd/typography/Base.svelte:65-84](file://frontend/antd/typography/Base.svelte#L65-L84) + +### Semantic Sub-components (title/paragraph/text/link) + +- All render through Base.svelte, only needing to set component to switch semantics and hierarchy +- Support both children slot and value dynamic value as content sources +- Have independent toggle logic for link component's ellipsis behavior + +Section Source + +- [frontend/antd/typography/title/Index.svelte:1-12](file://frontend/antd/typography/title/Index.svelte#L1-L12) +- [frontend/antd/typography/paragraph/Index.svelte:1-12](file://frontend/antd/typography/paragraph/Index.svelte#L1-L12) +- [frontend/antd/typography/text/Index.svelte:1-12](file://frontend/antd/typography/text/Index.svelte#L1-L12) +- [frontend/antd/typography/link/Index.svelte:1-12](file://frontend/antd/typography/link/Index.svelte#L1-L12) + +## Dependency Analysis + +- Component Coupling + - Sub-components only depend on Base.svelte, maintaining low coupling and high cohesion + - Base.svelte depends on bridge layer, responsible for cross-framework (Svelte → React) adaptation + - Bridge layer depends on Ant Design Typography, centrally handling interactive capabilities +- Slot and Target Resolution + - Uses useTargets and ReactSlot to implement slot-based capability injection, avoiding hardcoding +- External Dependencies + - Ant Design Typography: Provides basic capabilities for headings, paragraphs, text, and links + - Gradio/Svelte preprocessing tools: Provide property processing, slot context, and async component loading + +```mermaid +graph LR +Title["title/Index.svelte"] --> Base["Base.svelte"] +Paragraph["paragraph/Index.svelte"] --> Base +Text["text/Index.svelte"] --> Base +Link["link/Index.svelte"] --> Base +Base --> Bridge["typography.base.tsx"] +Bridge --> AD["Ant Design Typography"] +``` + +Diagram Source + +- [frontend/antd/typography/title/Index.svelte:9](file://frontend/antd/typography/title/Index.svelte#L9) +- [frontend/antd/typography/paragraph/Index.svelte:9](file://frontend/antd/typography/paragraph/Index.svelte#L9) +- [frontend/antd/typography/text/Index.svelte:9](file://frontend/antd/typography/text/Index.svelte#L9) +- [frontend/antd/typography/link/Index.svelte:9](file://frontend/antd/typography/link/Index.svelte#L9) +- [frontend/antd/typography/Base.svelte:11-13](file://frontend/antd/typography/Base.svelte#L11-L13) +- [frontend/antd/typography/typography.base.tsx:8](file://frontend/antd/typography/typography.base.tsx#L8) + +Section Source + +- [frontend/antd/typography/Base.svelte:11-13](file://frontend/antd/typography/Base.svelte#L11-L13) +- [frontend/antd/typography/typography.base.tsx:8](file://frontend/antd/typography/typography.base.tsx#L8) + +## Performance Considerations + +- Async Component Loading: Base.svelte loads bridge layer lazily through importComponent, reducing first-screen size +- Conditional Rendering: Only renders when visible is true; assembles ellipsis tooltip on demand, reducing unnecessary overhead +- Slot Rendering: Through useTargets and ReactSlot, only renders actually matched slot content, avoiding full traversal + +Section Source + +- [frontend/antd/typography/Base.svelte:11-13](file://frontend/antd/typography/Base.svelte#L11-L13) +- [frontend/antd/typography/typography.base.tsx:51-64](file://frontend/antd/typography/typography.base.tsx#L51-L64) + +## Troubleshooting Guide + +- Text Not Displaying + - Check whether Base.svelte's visible field is true + - Confirm whether children or value is correctly passed in +- Copy/Edit/Ellipsis Button Not Working + - Confirm whether copyable/editable/ellipsis configuration object or slots are correctly passed in + - For link component, confirm ellipsis enable condition +- Slot Icon/Tooltip Not Appearing + - Check whether slot key names match (like copyable.icon, copyable.tooltips, editable.icon, etc.) + - Confirm useTargets can correctly identify slot markers in children +- Style Abnormal + - Confirm whether elem_classes and elem_style are correctly injected + - Check whether namespace class names are overridden + +Section Source + +- [frontend/antd/typography/Base.svelte:30-62](file://frontend/antd/typography/Base.svelte#L30-L62) +- [frontend/antd/typography/typography.base.tsx:40-167](file://frontend/antd/typography/typography.base.tsx#L40-L167) + +## Conclusion + +The Typography component effectively connects Svelte with Ant Design capabilities through clear layered design, ensuring both semantics and maintainability, while providing rich interactive capabilities like copy, edit, and ellipsis. Its slot-based and conditional assembly mechanism enables good extensibility and performance in different scenarios. + +## Appendix + +- Usage examples and instructions can be found in the documentation page's example placeholder + - [docs/components/antd/typography/README.md:5-8](file://docs/components/antd/typography/README.md#L5-L8) diff --git a/.wiki/en/Ant Design Components/Layout Components/Divider.md b/.wiki/en/Ant Design Components/Layout Components/Divider.md new file mode 100644 index 00000000..5bcfcfde --- /dev/null +++ b/.wiki/en/Ant Design Components/Layout Components/Divider.md @@ -0,0 +1,291 @@ +# Divider + + +**Files referenced in this document** +- [divider.tsx](file://frontend/antd/divider/divider.tsx) +- [Index.svelte](file://frontend/antd/divider/Index.svelte) +- [__init__.py](file://backend/modelscope_studio/components/antd/divider/__init__.py) +- [components.py](file://backend/modelscope_studio/components/antd/components.py) +- [README.md](file://docs/components/antd/divider/README.md) +- [README-zh_CN.md](file://docs/components/antd/divider/README-zh_CN.md) +- [basic.py](file://docs/components/antd/divider/demos/basic.py) +- [basic.py (form)](file://docs/components/antd/form/demos/basic.py) +- [basic.py (layout)](file://docs/components/antd/layout/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Accessibility](#performance-and-accessibility) +8. [Usage Scenarios and Examples](#usage-scenarios-and-examples) +9. [Troubleshooting](#troubleshooting) +10. [Conclusion](#conclusion) + +## Introduction + +The Divider component creates visual separation between content sections, helping users quickly identify information blocks. Based on Ant Design's Divider, it supports horizontal and vertical orientations, multiple line styles (solid, dashed, dotted), centered and left/right-aligned title text, plain text style, and provides a flexible style override interface for consistent styling across different layouts and themes. + +## Project Structure + +The Divider component consists of a backend Python component class and a frontend Svelte wrapper. Props are passed in a Gradio-style through to the Ant Design React component, which is ultimately rendered as a visible divider in the browser. + +```mermaid +graph TB +subgraph "Backend" +PY_INIT["AntdDivider.__init__()
Python component class"] +PY_EXPORT["components.py export"] +end +subgraph "Frontend" +SVELTE_INDEX["Index.svelte
Prop handling and rendering"] +TS_WRAPPER["divider.tsx
sveltify wrapper"] +ANTD_REACT["antd.Divider
Ant Design React component"] +end +PY_INIT --> PY_EXPORT +PY_EXPORT --> SVELTE_INDEX +SVELTE_INDEX --> TS_WRAPPER +TS_WRAPPER --> ANTD_REACT +``` + +Diagram sources + +- [**init**.py:1-95](file://backend/modelscope_studio/components/antd/divider/__init__.py#L1-L95) +- [components.py:37-37](file://backend/modelscope_studio/components/antd/components.py#L37-L37) +- [Index.svelte:1-75](file://frontend/antd/divider/Index.svelte#L1-L75) +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) + +Section sources + +- [**init**.py:1-95](file://backend/modelscope_studio/components/antd/divider/__init__.py#L1-L95) +- [components.py:37-37](file://backend/modelscope_studio/components/antd/components.py#L37-L37) +- [Index.svelte:1-75](file://frontend/antd/divider/Index.svelte#L1-L75) +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) + +## Core Components + +- Backend component class: `AntdDivider`, responsible for defining props, default values, styles, and rendering strategy, and declaring frontend resource paths. +- Frontend wrapper: `Index.svelte` handles prop merging, style injection, and conditional rendering. `divider.tsx` uses `sveltify` to bridge Ant Design's React Divider as a Svelte-compatible component. + +Key responsibilities + +- Prop mapping: Maps Python-layer props (`dashed`, `variant`, `orientation`, `orientation_margin`, `plain`, `type`, `size`, `value`, `elem_style`, `elem_classes`, etc.) to the React Divider. +- Rendering branch: Determines whether to render a divider with text or a plain line based on whether `children` or `value` is provided. +- Style injection: Injects custom styles and class names via `elem_style` and `elem_classes`. + +Section sources + +- [**init**.py:21-76](file://backend/modelscope_studio/components/antd/divider/__init__.py#L21-L76) +- [Index.svelte:23-57](file://frontend/antd/divider/Index.svelte#L23-L57) +- [divider.tsx:5-12](file://frontend/antd/divider/divider.tsx#L5-L12) + +## Architecture Overview + +The diagram below shows the call chain and data flow from the Python component to the browser rendering. + +```mermaid +sequenceDiagram +participant Py as "Python Backend
AntdDivider" +participant Svelte as "Frontend
Index.svelte" +participant Wrapper as "Wrapper
divider.tsx" +participant AD as "Ant Design React
Divider" +Py->>Svelte : Pass props and value +Svelte->>Svelte : Process visible, styles, additional props +Svelte->>Wrapper : Render React Divider +Wrapper->>AD : Pass props including children/value +AD-->>Wrapper : Render DOM +Wrapper-->>Svelte : Return node +Svelte-->>Py : Complete one render +``` + +Diagram sources + +- [**init**.py:77-77](file://backend/modelscope_studio/components/antd/divider/__init__.py#L77-L77) +- [Index.svelte:60-74](file://frontend/antd/divider/Index.svelte#L60-L74) +- [divider.tsx:5-12](file://frontend/antd/divider/divider.tsx#L5-L12) + +## Detailed Component Analysis + +### Props and Configuration + +- Type and orientation + - `type`: horizontal | vertical — controls horizontal or vertical divider. + - `size`: small | middle | large (horizontal only) — affects the overall visual size. +- Line style + - `variant`: dashed | dotted | solid — controls the line style. + - `dashed`: boolean toggle (legacy compatibility), equivalent to `variant=dashed`. +- Text and alignment + - `value` or slot content: text displayed on the divider. + - `orientation`: left | right | center | start | end — controls text position. + - `orientation_margin`: number or string (parsed with unit if provided, as px otherwise) — sets the margin between text and edge. + - `plain`: whether to display text in plain style. +- Style and appearance + - `elem_style`: inject inline styles (e.g., `borderColor`). + - `elem_classes`: inject additional CSS classes. + - `root_class_name`: root element class name (passed by parent container). + - `additional_props`: other passthrough props. +- Layout and visibility + - `visible`: controls whether the component is rendered. + - `as_item`, `_internal`, `render`, etc.: framework-internal props that affect rendering context. + +Section sources + +- [**init**.py:21-76](file://backend/modelscope_studio/components/antd/divider/__init__.py#L21-L76) +- [Index.svelte:13-57](file://frontend/antd/divider/Index.svelte#L13-L57) + +### Rendering Logic and Branches + +- When children or `value` is present, renders a divider with text. +- Otherwise renders a plain line divider. +- Supports direct child node rendering in inner layout mode. + +```mermaid +flowchart TD +Start(["Enter render"]) --> CheckVisible{"visible is true?"} +CheckVisible --> |No| EndHidden["Do not render"] +CheckVisible --> |Yes| CheckInternal{"Inner layout mode?"} +CheckInternal --> |Yes| RenderWithChildren["Render Divider with children"] +CheckInternal --> |No| CheckValue{"Has value?"} +CheckValue --> |Yes| RenderWithValue["Render Divider with value"] +CheckValue --> |No| RenderPlain["Render plain line Divider"] +RenderWithChildren --> End(["Done"]) +RenderWithValue --> End +RenderPlain --> End +EndHidden --> End +``` + +Diagram sources + +- [Index.svelte:60-74](file://frontend/antd/divider/Index.svelte#L60-L74) + +### Text Centering and Alignment + +- Use `orientation=center` (or equivalent `start`/`end`) to center text. +- Use `orientation=left`/`right` or `orientation=start`/`end` combined with `orientation_margin` to control the spacing between text and edge. +- With `plain=True`, text is rendered in a lighter style, suitable for smaller font sizes or subtle hints. + +Section sources + +- [**init**.py:27-32](file://backend/modelscope_studio/components/antd/divider/__init__.py#L27-L32) +- [basic.py:11-26](file://docs/components/antd/divider/demos/basic.py#L11-L26) + +### Style Customization and Color Configuration + +- Inject `borderColor`, `borderWidth`, and other styles via `elem_style` for color and thickness customization. +- Inject custom CSS classes via `elem_classes` for complex theming needs. +- `variant` and `dashed` provide line style switching (solid/dashed/dotted). + +Section sources + +- [basic.py:11-26](file://docs/components/antd/divider/demos/basic.py#L11-L26) +- [**init**.py:26-32](file://backend/modelscope_studio/components/antd/divider/__init__.py#L26-L32) + +### Responsive Behavior and Screen Adaptation + +- The component does not have built-in media query logic, but responsive behavior can be achieved through `elem_style` and layout containers (such as Flex and Layout). +- In horizontal layouts, `size` can subtly adjust the overall visual size; in vertical layouts, `size` has no effect. +- On narrow screens, adjust `orientation` and margin in combination with container width and text length to avoid text truncation. + +Section sources + +- [**init**.py:32-34](file://backend/modelscope_studio/components/antd/divider/__init__.py#L32-L34) +- [basic.py (layout):42-88](file://docs/components/antd/layout/demos/basic.py#L42-L88) + +## Dependency Analysis + +- Backend export: `AntdDivider` is exported in the antd component collection for modular usage. +- Frontend bridging: `Index.svelte` dynamically loads `divider.tsx` via `importComponent`. The latter uses `sveltify` to wrap Ant Design's React Divider as a Svelte component. +- Prop passthrough: All props except framework-reserved fields are passed through to the React Divider, maintaining consistency with the Ant Design API. + +```mermaid +graph LR +A["components.py"] --> B["AntdDivider.__init__"] +B --> C["FRONTEND_DIR=resolve_frontend_dir('divider')"] +C --> D["Index.svelte"] +D --> E["divider.tsx"] +E --> F["antd.Divider"] +``` + +Diagram sources + +- [components.py:37-37](file://backend/modelscope_studio/components/antd/components.py#L37-L37) +- [**init**.py:77-77](file://backend/modelscope_studio/components/antd/divider/__init__.py#L77-L77) +- [Index.svelte:10-10](file://frontend/antd/divider/Index.svelte#L10-L10) +- [divider.tsx:3-3](file://frontend/antd/divider/divider.tsx#L3-L3) + +Section sources + +- [components.py:37-37](file://backend/modelscope_studio/components/antd/components.py#L37-L37) +- [**init**.py:77-77](file://backend/modelscope_studio/components/antd/divider/__init__.py#L77-L77) +- [Index.svelte:10-10](file://frontend/antd/divider/Index.svelte#L10-L10) +- [divider.tsx:3-3](file://frontend/antd/divider/divider.tsx#L3-L3) + +## Performance and Accessibility + +- Rendering overhead: The component is a lightweight pure display element. Dynamic import and conditional rendering avoid unnecessary repaints. +- Accessibility: Text content is rendered with semantic tags. For important dividers, providing a short description (e.g., `aria-label`) is recommended to improve screen reader experience. +- Theme consistency: Unify styles via `elem_style` and `elem_classes` to reduce redundant computations and style conflicts. + +[This section contains general recommendations and does not require specific file references] + +## Usage Scenarios and Examples + +### Form Grouping + +- Use dividers to group different business domains within a form, improving readability. +- Example reference: The form demo shows dividers used between form controls. + +Section sources + +- [basic.py (form):16-90](file://docs/components/antd/form/demos/basic.py#L16-L90) + +### Content Area Separation + +- Use horizontal dividers in articles or pages to separate paragraphs. Use `orientation=center` for title-style separators. +- Example reference: The basic demo shows different variants and dividers with text. + +Section sources + +- [basic.py:5-29](file://docs/components/antd/divider/demos/basic.py#L5-L29) + +### Navigation Menu Separation + +- Use vertical or horizontal dividers to separate menu items in navigation lists. On narrow screens, adjust `orientation` and margin to avoid text overflow. +- Recommendation: Prefer vertical dividers for side navigation and horizontal dividers for top or bottom navigation. + +[This subsection is conceptual; no specific file references required] + +### Behavior in Responsive Layouts + +- Use layout components like Flex and Layout to adjust divider orientation and text length at different screen sizes. +- Recommendation: On mobile, prefer horizontal dividers with shorter text. If necessary, hide the text and keep only the line. + +Section sources + +- [basic.py (layout):42-88](file://docs/components/antd/layout/demos/basic.py#L42-L88) + +## Troubleshooting + +- Text not displayed + - Check whether `value` or child content has been passed. If not, the component renders a plain line. + - Confirm that `visible` is `True`. +- Text position incorrect + - When `orientation` is set to left/right/start/end, use `orientation_margin` to adjust spacing. + - `plain` affects the visual weight of the text. Remove it if stronger separation is needed. +- Line style not applied + - `dashed` and `variant=dashed` are equivalent. Ensure no conflicting props are set simultaneously. + - `borderColor`, `borderWidth`, and other styles in `elem_style` must be compatible with the target platform. +- Vertical divider size not working + - `size` only applies to horizontal dividers. For vertical dividers, control the visual size via container width and border properties. + +Section sources + +- [Index.svelte:60-74](file://frontend/antd/divider/Index.svelte#L60-L74) +- [**init**.py:26-34](file://backend/modelscope_studio/components/antd/divider/__init__.py#L26-L34) + +## Conclusion + +The Divider component provides rich visual expression through a clean API, capable of both basic line separation and title-style dividers with text. Through multi-dimensional configuration of type, line style, alignment, and styling, it reliably implements information hierarchy and spatial separation across different layouts and themes. In practice, it is recommended to combine layout containers with responsive strategies, choose `orientation` and `size` appropriately, and use `elem_style`/`elem_classes` for brand and theme customization. diff --git a/.wiki/en/Ant Design Components/Layout Components/Flex.md b/.wiki/en/Ant Design Components/Layout Components/Flex.md new file mode 100644 index 00000000..8bb5cf98 --- /dev/null +++ b/.wiki/en/Ant Design Components/Layout Components/Flex.md @@ -0,0 +1,291 @@ +# Flex + + +**Files referenced in this document** +- [frontend/antd/flex/flex.tsx](file://frontend/antd/flex/flex.tsx) +- [frontend/antd/flex/Index.svelte](file://frontend/antd/flex/Index.svelte) +- [backend/modelscope_studio/components/antd/flex/__init__.py](file://backend/modelscope_studio/components/antd/flex/__init__.py) +- [docs/components/antd/flex/README.md](file://docs/components/antd/flex/README.md) +- [docs/components/antd/flex/demos/basic.py](file://docs/components/antd/flex/demos/basic.py) +- [docs/components/antd/flex/demos/align.py](file://docs/components/antd/flex/demos/align.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document provides a systematic description of the Flex layout component and its implementation and usage in ModelScope Studio. The Flex component is based on Ant Design's Flex container, offering main axis and cross axis alignment, layout direction, wrapping control, spacing configuration, and is bridged between frontend and backend via the Gradio ecosystem. The document covers the following topics from concept to practice: + +- Core concepts: main axis/cross axis, and correspondence to justify-content, align-items, align-content +- Key props: orientation/vertical, wrap, justify, align, flex, gap +- Practical scenarios: button group alignment, content area distribution, responsive card layouts +- Complex nested layouts and best practices +- Compatibility and cross-browser considerations + +## Project Structure + +The Flex component in this repository uses a layered design of "backend Python component + frontend Svelte wrapper + Ant Design Flex container": + +- Backend: Python class responsible for parameter validation, rendering strategy, and frontend resource location +- Frontend: Svelte component responsible for dynamic import, prop passthrough, and style concatenation +- Dependencies: React/Ant Design components are bridged to Svelte via `svelte-preprocess-react` + +```mermaid +graph TB +subgraph "Backend" +PY["AntdFlex
Python component"] +DEV["ModelScopeLayoutComponent
Base layout component"] +end +subgraph "Frontend" +IDX["Index.svelte
Dynamic import wrapper"] +FLEX_TS["flex.tsx
sveltify wrapper"] +ANTDFLEX["Ant Design Flex
Container"] +end +subgraph "Docs and Examples" +DOC["README.md"] +DEMO1["basic.py example"] +DEMO2["align.py example"] +end +PY --> IDX +DEV --> PY +IDX --> FLEX_TS +FLEX_TS --> ANTDFLEX +DOC --> DEMO1 +DOC --> DEMO2 +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/flex/**init**.py:8-98](file://backend/modelscope_studio/components/antd/flex/__init__.py#L8-L98) +- [frontend/antd/flex/Index.svelte:10-61](file://frontend/antd/flex/Index.svelte#L10-L61) +- [frontend/antd/flex/flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) +- [docs/components/antd/flex/README.md:1-9](file://docs/components/antd/flex/README.md#L1-L9) + +Section sources + +- [backend/modelscope_studio/components/antd/flex/**init**.py:8-98](file://backend/modelscope_studio/components/antd/flex/__init__.py#L8-L98) +- [frontend/antd/flex/Index.svelte:1-62](file://frontend/antd/flex/Index.svelte#L1-L62) +- [frontend/antd/flex/flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) +- [docs/components/antd/flex/README.md:1-9](file://docs/components/antd/flex/README.md#L1-L9) + +## Core Components + +- AntdFlex (backend) + - Receives and validates all Flex-related parameters (direction, wrapping, main axis/cross axis alignment, flex shorthand, gap, etc.) and maps them to frontend-consumable props. + - Provides `FRONTEND_DIR` pointing to the frontend flex directory, ensuring the frontend component is loaded correctly at runtime. + - Follows the layout semantics of `ModelScopeLayoutComponent` and participates in the application-level layout context. + +- Index.svelte (frontend wrapper) + - Dynamically imports the frontend flex component via `importComponent`, avoiding first-screen blocking. + - Retrieves and processes component props via `getProps`/`processProps`, supporting additional prop passthrough and visibility control. + - Injects generic props like `elem_id`, `elem_classes`, and `elem_style` into the final render node. + +- flex.tsx (Svelte wrapper) + - Uses `sveltify` to convert Ant Design's Flex container into a Svelte-compatible component, passing props and children through directly. + +- Docs and examples + - `README.md` provides basic description and example placeholders. + - `basic.py` and `align.py` demonstrate interactive examples for vertical/horizontal direction switching and main axis/cross axis alignment. + +Section sources + +- [backend/modelscope_studio/components/antd/flex/**init**.py:21-79](file://backend/modelscope_studio/components/antd/flex/__init__.py#L21-L79) +- [frontend/antd/flex/Index.svelte:13-42](file://frontend/antd/flex/Index.svelte#L13-L42) +- [frontend/antd/flex/flex.tsx:4-8](file://frontend/antd/flex/flex.tsx#L4-L8) +- [docs/components/antd/flex/README.md:1-9](file://docs/components/antd/flex/README.md#L1-L9) +- [docs/components/antd/flex/demos/basic.py:8-23](file://docs/components/antd/flex/demos/basic.py#L8-L23) +- [docs/components/antd/flex/demos/align.py:8-41](file://docs/components/antd/flex/demos/align.py#L8-L41) + +## Architecture Overview + +The diagram below shows the call chain from user code to the final render, illustrating the collaboration between the Flex component's frontend and backend: + +```mermaid +sequenceDiagram +participant U as "User code" +participant PY as "AntdFlex (backend)" +participant IDX as "Index.svelte (frontend wrapper)" +participant F as "flex.tsx (Svelte wrapper)" +participant AD as "Ant Design Flex" +U->>PY : Create AntdFlex and pass params +PY->>IDX : Resolve FRONTEND_DIR and render +IDX->>F : Dynamically import Antd Flex component +F->>AD : Pass through props and children +AD-->>U : Rendered flexible layout container +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/flex/**init**.py:81-81](file://backend/modelscope_studio/components/antd/flex/__init__.py#L81-L81) +- [frontend/antd/flex/Index.svelte:10-10](file://frontend/antd/flex/Index.svelte#L10-L10) +- [frontend/antd/flex/flex.tsx:4-8](file://frontend/antd/flex/flex.tsx#L4-L8) + +## Detailed Component Analysis + +### Backend Class: AntdFlex Props and Behavior + +- Key props + - `orientation`/`vertical`: controls layout direction (horizontal/vertical) + - `wrap`: controls single-line or multi-line display + - `justify`: main axis alignment (start/end/center/flex-start/flex-end/space-\* etc.) + - `align`: cross axis alignment (start/end/center/flex-start/flex-end/baseline/stretch etc.) + - `flex`: flex shorthand property + - `gap`: element spacing (small/middle/large or numeric value) + - `component`/`root_class_name`/`class_names`/`styles`/`as_item`/`_internal`: generic props and style injection + - Visibility and DOM injection: `elem_id`/`elem_classes`/`elem_style`/`visible`/`render` + +- Behavioral characteristics + - `skip_api=True`: not exposed as a standard API component; suitable for internal layout use + - `FRONTEND_DIR` points to the frontend flex directory, ensuring component availability at runtime + - Inherits from `ModelScopeLayoutComponent`, providing layout context capabilities + +Section sources + +- [backend/modelscope_studio/components/antd/flex/**init**.py:21-79](file://backend/modelscope_studio/components/antd/flex/__init__.py#L21-L79) +- [backend/modelscope_studio/utils/dev/component.py:11-52](file://backend/modelscope_studio/utils/dev/component.py#L11-L52) + +### Frontend Wrapper: Index.svelte + +- Dynamic import: lazy-loads `flex.tsx` via `importComponent`, reducing first-screen overhead +- Prop processing: `getProps`/`processProps` extracts and merges component props, additional props, visibility, and DOM injection +- Style concatenation: `elem_classes` combined with fixed class names; `elem_id`/`elem_style` injected into the root node +- Conditional rendering: controls rendering based on `visible` + +Section sources + +- [frontend/antd/flex/Index.svelte:13-42](file://frontend/antd/flex/Index.svelte#L13-L42) +- [frontend/antd/flex/Index.svelte:48-61](file://frontend/antd/flex/Index.svelte#L48-L61) + +### Svelte Wrapper: flex.tsx + +- Uses `sveltify` to bridge Ant Design's Flex container as a Svelte component +- Passes props and children through directly, maintaining consistent semantics with Antd Flex + +Section sources + +- [frontend/antd/flex/flex.tsx:4-8](file://frontend/antd/flex/flex.tsx#L4-L8) + +### Examples: Basic and Alignment + +- `basic.py`: demonstrates vertical/horizontal direction switching and spacing configuration +- `align.py`: demonstrates main axis/cross axis alignment options and interactive updates + +Section sources + +- [docs/components/antd/flex/demos/basic.py:8-23](file://docs/components/antd/flex/demos/basic.py#L8-L23) +- [docs/components/antd/flex/demos/align.py:8-41](file://docs/components/antd/flex/demos/align.py#L8-L41) + +### Key Props and CSS Flex Correspondence + +- Main axis and cross axis + - Main axis: determined by layout direction (horizontal/vertical corresponds to row/column) + - Cross axis: perpendicular to the main axis +- Alignment mapping + - `justify-content` ↔ `justify` (main axis alignment) + - `align-items` ↔ `align` (cross axis alignment) + - `align-content` ↔ cross axis distribution for multi-line (effective when `wrap` is `wrap`/`wrap-reverse`) + +Section sources + +- [backend/modelscope_studio/components/antd/flex/**init**.py:52-58](file://backend/modelscope_studio/components/antd/flex/__init__.py#L52-L58) + +### Practical Application Scenarios + +- Button group alignment: use `justify`/`align` to quickly achieve horizontal or vertical centering, space-between, etc. +- Content area distribution: use `gap` and `wrap` for responsive grids with wrapping +- Responsive card layouts: combine `orientation`/`vertical` with `justify`/`align` for card flow arrangement + +Section sources + +- [docs/components/antd/flex/demos/basic.py:8-23](file://docs/components/antd/flex/demos/basic.py#L8-L23) +- [docs/components/antd/flex/demos/align.py:8-41](file://docs/components/antd/flex/demos/align.py#L8-L41) + +### Complex Nested Layouts and Best Practices + +- Nesting strategy + - Outer containers set main axis alignment and wrapping; inner containers focus on cross axis alignment + - Use `gap` to control spacing between levels, avoiding hard-coded margin/padding +- Best practices + - First use `vertical`/`orientation` to control direction, then fine-tune with `justify`/`align` + - In multi-line scenarios, choose `wrap` and `align-content` combinations carefully + - Combine with interactive components (such as Segmented) to dynamically switch alignment, improving discoverability + +Section sources + +- [docs/components/antd/flex/demos/align.py:8-41](file://docs/components/antd/flex/demos/align.py#L8-L41) + +## Dependency Analysis + +- Component coupling + - `AntdFlex` only depends on the frontend flex directory, resolved via `FRONTEND_DIR`, reducing coupling + - `Index.svelte` and `flex.tsx` are loosely coupled; the former handles runtime loading, the latter handles bridging +- External dependencies + - Ant Design Flex: provides core layout capability + - svelte-preprocess-react: provides `sveltify` and dynamic import utilities +- Potential circular dependencies + - No obvious circular dependencies in the current structure. Avoid inter-referencing backend components if extending in the future. + +```mermaid +graph LR +PY["AntdFlex (backend)"] --> |FRONTEND_DIR| FE["flex frontend directory"] +IDX["Index.svelte"] --> |dynamic import| FLEX_TS["flex.tsx"] +FLEX_TS --> |sveltify| AD["Ant Design Flex"] +``` + +Diagram sources + +- [backend/modelscope_studio/components/antd/flex/**init**.py:81-81](file://backend/modelscope_studio/components/antd/flex/__init__.py#L81-L81) +- [frontend/antd/flex/Index.svelte:10-10](file://frontend/antd/flex/Index.svelte#L10-L10) +- [frontend/antd/flex/flex.tsx:4-8](file://frontend/antd/flex/flex.tsx#L4-L8) + +Section sources + +- [backend/modelscope_studio/components/antd/flex/**init**.py:81-81](file://backend/modelscope_studio/components/antd/flex/__init__.py#L81-L81) +- [frontend/antd/flex/Index.svelte:10-10](file://frontend/antd/flex/Index.svelte#L10-L10) +- [frontend/antd/flex/flex.tsx:4-8](file://frontend/antd/flex/flex.tsx#L4-L8) + +## Performance Considerations + +- Dynamic import optimization: `Index.svelte` uses `importComponent` for lazy loading, reducing first-screen bundle size and render time +- Minimal prop passthrough: only necessary props are passed, avoiding redundant computation and reflow +- Spacing and wrapping: use `gap` and `wrap` appropriately to avoid complex layout reflows caused by excessive nesting + +## Troubleshooting Guide + +- Component not visible + - Check if `visible` is `true` + - Confirm that `elem_style`/`elem_classes` are not causing overflow or hidden behavior +- Direction and alignment issues + - Confirm that the combination of `orientation`/`vertical` and `justify`/`align` matches expectations + - In multi-line scenarios, check the effect of `wrap` and `align-content` +- Runtime load failure + - Confirm that `FRONTEND_DIR` points to the correct location and the frontend package is built + - Check for errors in the dynamic import (`{#await}` branch in `Index.svelte`) + +Section sources + +- [frontend/antd/flex/Index.svelte:48-61](file://frontend/antd/flex/Index.svelte#L48-L61) +- [backend/modelscope_studio/components/antd/flex/**init**.py:81-81](file://backend/modelscope_studio/components/antd/flex/__init__.py#L81-L81) + +## Conclusion + +The Flex layout component in ModelScope Studio is implemented as "backend params + frontend wrapper + Antd Flex container", maintaining semantic consistency with CSS Flex while providing good configurability and maintainability. Through key props such as `orientation`/`vertical`, `wrap`, `justify`, `align`, `flex`, and `gap`, it efficiently covers common scenarios including button group alignment, content area distribution, and responsive card layouts. Combined with dynamic import and prop passthrough mechanisms, it balances performance and flexibility. + +## Appendix + +- Example entry points + - Basic example: [basic.py:1-26](file://docs/components/antd/flex/demos/basic.py#L1-L26) + - Alignment example: [align.py:1-45](file://docs/components/antd/flex/demos/align.py#L1-L45) +- Documentation: [README.md:1-9](file://docs/components/antd/flex/README.md#L1-L9) diff --git a/.wiki/en/Ant Design Components/Layout Components/Grid.md b/.wiki/en/Ant Design Components/Layout Components/Grid.md new file mode 100644 index 00000000..51992779 --- /dev/null +++ b/.wiki/en/Ant Design Components/Layout Components/Grid.md @@ -0,0 +1,348 @@ +# Grid + + +**Files referenced in this document** +- [frontend/antd/grid/row/Index.svelte](file://frontend/antd/grid/row/Index.svelte) +- [frontend/antd/grid/row/row.tsx](file://frontend/antd/grid/row/row.tsx) +- [frontend/antd/grid/col/Index.svelte](file://frontend/antd/grid/col/Index.svelte) +- [frontend/antd/grid/col/col.tsx](file://frontend/antd/grid/col/col.tsx) +- [frontend/antd/grid/context.ts](file://frontend/antd/grid/context.ts) +- [backend/modelscope_studio/components/antd/grid/row/__init__.py](file://backend/modelscope_studio/components/antd/grid/row/__init__.py) +- [backend/modelscope_studio/components/antd/grid/col/__init__.py](file://backend/modelscope_studio/components/antd/grid/col/__init__.py) +- [docs/components/antd/grid/README.md](file://docs/components/antd/grid/README.md) +- [docs/components/antd/grid/demos/basic.py](file://docs/components/antd/grid/demos/basic.py) +- [docs/components/antd/grid/demos/playground.py](file://docs/components/antd/grid/demos/playground.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document provides a systematic description of the Grid component, covering its design principles, the 24-column grid system, and responsive breakpoint configuration. It explains how to use Row and Col in depth (including grid offset, ordering, nesting rules, and alignment), provides application ideas for common scenarios such as dashboard layouts, product display pages, and form layouts, and includes responsive behavior descriptions and performance optimization recommendations. + +## Project Structure + +The Grid component is built through collaboration between a frontend Svelte wrapper layer and a backend Python component layer: the frontend handles rendering and context passing, while the backend handles parameter passthrough and lifecycle management. The docs side provides examples and explanations. + +```mermaid +graph TB +subgraph "Backend Components" +PY_ROW["Python Row component
backend/modelscope_studio/components/antd/grid/row/__init__.py"] +PY_COL["Python Col component
backend/modelscope_studio/components/antd/grid/col/__init__.py"] +end +subgraph "Frontend Wrapper" +IDX_ROW["Row wrapper entry
frontend/antd/grid/row/Index.svelte"] +ROW_IMPL["Row implementation
frontend/antd/grid/row/row.tsx"] +IDX_COL["Col wrapper entry
frontend/antd/grid/col/Index.svelte"] +COL_IMPL["Col implementation
frontend/antd/grid/col/col.tsx"] +CTX["Grid context
frontend/antd/grid/context.ts"] +end +PY_ROW --> IDX_ROW --> ROW_IMPL +PY_COL --> IDX_COL --> COL_IMPL +ROW_IMPL --> CTX +COL_IMPL --> CTX +``` + +**Diagram sources** + +- [frontend/antd/grid/row/Index.svelte:1-61](file://frontend/antd/grid/row/Index.svelte#L1-L61) +- [frontend/antd/grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [frontend/antd/grid/col/Index.svelte:1-77](file://frontend/antd/grid/col/Index.svelte#L1-L77) +- [frontend/antd/grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [backend/modelscope_studio/components/antd/grid/row/**init**.py:1-94](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L1-L94) +- [backend/modelscope_studio/components/antd/grid/col/**init**.py:1-114](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L1-L114) + +**Section sources** + +- [frontend/antd/grid/row/Index.svelte:1-61](file://frontend/antd/grid/row/Index.svelte#L1-L61) +- [frontend/antd/grid/col/Index.svelte:1-77](file://frontend/antd/grid/col/Index.svelte#L1-L77) +- [frontend/antd/grid/row/row.tsx:1-34](file://frontend/antd/grid/row/row.tsx#L1-L34) +- [frontend/antd/grid/col/col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [backend/modelscope_studio/components/antd/grid/row/**init**.py:1-94](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L1-L94) +- [backend/modelscope_studio/components/antd/grid/col/**init**.py:1-114](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L1-L114) + +## Core Components + +- Row component + - Supports alignment, gutter, wrapping, and other props for holding multiple columns and managing layout direction and distribution. + - Key props: `align`, `justify`, `gutter`, `wrap`, etc. +- Col component + - Supports span, offset, ordering, left/right pushing, and responsive breakpoints for specific content blocks. + - Key props: `span`, `offset`, `order`, `pull`, `push`, `xs`/`sm`/`md`/`lg`/`xl`/`xxl`, etc. + +All of the above props are explicitly declared with default values in the backend component, making them directly usable from the Python layer. + +**Section sources** + +- [backend/modelscope_studio/components/antd/grid/row/**init**.py:30-76](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L30-L76) +- [backend/modelscope_studio/components/antd/grid/col/**init**.py:30-95](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L30-L95) + +## Architecture Overview + +The runtime flow of Grid is as follows: the backend Python component receives params and renders the frontend wrapper; the frontend wrapper then calls the Ant Design Row/Col implementation and collects Col children via context, ultimately assembling the standard grid layout. + +```mermaid +sequenceDiagram +participant PyRow as "Backend Row component" +participant IdxRow as "Row wrapper entry" +participant RowImpl as "Row implementation" +participant Ctx as "Grid context" +participant PyCol as "Backend Col component" +participant IdxCol as "Col wrapper entry" +participant ColImpl as "Col implementation" +PyRow->>IdxRow : Render row wrapper +IdxRow->>RowImpl : Pass row params +PyCol->>IdxCol : Render col wrapper +IdxCol->>ColImpl : Pass col params +ColImpl->>Ctx : Register col item +RowImpl->>Ctx : Consume col items and render +RowImpl-->>IdxRow : Output Row container +IdxRow-->>PyRow : Return render result +``` + +**Diagram sources** + +- [frontend/antd/grid/row/Index.svelte:10-44](file://frontend/antd/grid/row/Index.svelte#L10-L44) +- [frontend/antd/grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [frontend/antd/grid/col/Index.svelte:10-47](file://frontend/antd/grid/col/Index.svelte#L10-L47) +- [frontend/antd/grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) +- [frontend/antd/grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) + +## Detailed Component Analysis + +### Row Component Analysis + +- Design notes + - Based on Ant Design Row, supports horizontal alignment (`justify`), vertical alignment (`align`), gutter, and auto-wrapping (`wrap`). + - Collects Col children via context and renders them uniformly, avoiding hard-coded child elements in Row. +- Usage recommendations + - In complex layouts, set `gutter` first to ensure consistency across breakpoints. + - Use `wrap` appropriately to avoid horizontal scrolling from long lists. +- Key props + - `align`: top/middle/bottom/stretch + - `justify`: start/end/center/space-between/space-around/space-evenly + - `gutter`: number or object (with breakpoints) or array [horizontal, vertical] + - `wrap`: boolean + +```mermaid +classDiagram +class Row { ++align ++justify ++gutter ++wrap ++render() +} +class Context { ++register(item) ++collect() +} +Row --> Context : "consume col items" +``` + +**Diagram sources** + +- [frontend/antd/grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [frontend/antd/grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) + +**Section sources** + +- [frontend/antd/grid/row/Index.svelte:12-42](file://frontend/antd/grid/row/Index.svelte#L12-L42) +- [frontend/antd/grid/row/row.tsx:7-31](file://frontend/antd/grid/row/row.tsx#L7-L31) +- [backend/modelscope_studio/components/antd/grid/row/**init**.py:30-76](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L30-L76) + +### Col Component Analysis + +- Design notes + - Based on Ant Design Col, supports `span`, `offset`, `order`, `pull`, `push`, and other basic capabilities. + - Supports responsive breakpoints xs/sm/md/lg/xl/xxl; each can specify a span value or a full attribute object. + - Registers itself via context for Row to dispatch uniformly. +- Usage recommendations + - Plan each row so total span does not exceed 24; overflowing columns will wrap automatically. + - Use `offset`/`push`/`pull` for visual offset and reordering, but be mindful of accessibility and semantics. + - On mobile, prioritize `xs`; use larger breakpoints on desktop for consistent device experience. +- Key props + - `span`: number of grid cells occupied (0 means not displayed) + - `offset`/`push`/`pull`: offset/left-shift/right-shift + - `order`: ordering + - `xs`/`sm`/`md`/`lg`/`xl`/`xxl`: breakpoint-level configuration + +```mermaid +classDiagram +class Col { ++span ++offset ++order ++pull ++push ++xs/sm/md/lg/xl/xxl ++render() +} +class Context { ++register(item) ++collect() +} +Col --> Context : "register to context" +``` + +**Diagram sources** + +- [frontend/antd/grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) +- [frontend/antd/grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) +- [backend/modelscope_studio/components/antd/grid/col/**init**.py:30-95](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L30-L95) + +**Section sources** + +- [frontend/antd/grid/col/Index.svelte:23-47](file://frontend/antd/grid/col/Index.svelte#L23-L47) +- [frontend/antd/grid/col/col.tsx:7-11](file://frontend/antd/grid/col/col.tsx#L7-L11) +- [backend/modelscope_studio/components/antd/grid/col/**init**.py:30-95](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L30-L95) + +### Responsive Breakpoints and Behavior + +- Breakpoint definitions + - xs: screen width less than 576px, also the default breakpoint + - sm: ≥ 576px + - md: ≥ 768px + - lg: ≥ 992px + - xl: ≥ 1200px + - xxl: ≥ 1600px +- Configuration methods + - Can pass an integer span directly, or pass an object to configure span and other props (such as offset, order) per breakpoint. +- Behavioral notes + - When the total span of all columns in a row exceeds 24, the overflowing columns will wrap to the next line. + - `gutter` supports breakpoint-level configuration, enabling different spacing at different screen sizes. + +**Section sources** + +- [backend/modelscope_studio/components/antd/grid/col/**init**.py:58-72](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L58-L72) +- [backend/modelscope_studio/components/antd/grid/row/**init**.py:54-60](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L54-L60) + +### Nesting Rules and Alignment + +- Nesting rules + - Only place Col inside Row; Col can continue to nest Row to form nested grids. + - Avoid excessively deep nesting to prevent styling and maintainability issues. +- Alignment + - Row provides horizontal (`justify`) and vertical (`align`) alignment. Combined with `gutter`, stable layouts are achieved. + - Vertical alignment supports `stretch`, which allows column heights to adapt to the container height. + +**Section sources** + +- [backend/modelscope_studio/components/antd/grid/row/**init**.py:34-40](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L34-L40) +- [backend/modelscope_studio/components/antd/grid/row/**init**.py:56-59](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L56-L59) + +### Practical Application Cases + +- Dashboard layout + - Use Row's `gutter` and `wrap` to control card spacing and wrapping. Col's `span` and responsive breakpoints adapt to multiple screen sizes. + - Reduce columns on narrow screens and increase on wide screens to maintain information density and readability. +- Product display page + - Hero image area uses a single full-width column; product list uses equal-width columns; sidebar uses a fixed span, main content adapts. + - Use xs/sm/md/lg/xl/xxl to configure different column counts and spacing for each breakpoint. +- Form layout + - Small form fields use smaller spans; composite fields use larger spans. On xs, merge into a single column to improve mobile usability. + - Use `offset` for fine-tuning, but avoid excessive offset that affects reading order. + +(The above are general layout strategy descriptions; see examples for specific implementations.) + +**Section sources** + +- [docs/components/antd/grid/README.md:1-9](file://docs/components/antd/grid/README.md#L1-L9) +- [docs/components/antd/grid/demos/basic.py:7-24](file://docs/components/antd/grid/demos/basic.py#L7-L24) +- [docs/components/antd/grid/demos/playground.py:17-90](file://docs/components/antd/grid/demos/playground.py#L17-L90) + +## Dependency Analysis + +- Component coupling + - Col registers itself via context; Row collects and renders from context, reducing direct coupling. + - Frontend wrapper components are only responsible for prop passthrough and rendering; logic is concentrated in the Row/Col implementations and context. +- External dependencies + - Depends on Ant Design's Row/Col components, reusing their mature grid system. + - Uses the Svelte Preprocess React toolchain for bridging and slot handling. + +```mermaid +graph LR +PY_ROW["Backend Row component"] --> IDX_ROW["Row wrapper entry"] +IDX_ROW --> ROW_IMPL["Row implementation"] +PY_COL["Backend Col component"] --> IDX_COL["Col wrapper entry"] +IDX_COL --> COL_IMPL["Col implementation"] +ROW_IMPL --> CTX["Grid context"] +COL_IMPL --> CTX +ROW_IMPL --> ANTDESIGN["Ant Design Row/Col"] +COL_IMPL --> ANTDESIGN +``` + +**Diagram sources** + +- [frontend/antd/grid/row/Index.svelte:10-18](file://frontend/antd/grid/row/Index.svelte#L10-L18) +- [frontend/antd/grid/col/Index.svelte:10-21](file://frontend/antd/grid/col/Index.svelte#L10-L21) +- [frontend/antd/grid/row/row.tsx:3-5](file://frontend/antd/grid/row/row.tsx#L3-L5) +- [frontend/antd/grid/col/col.tsx:3-5](file://frontend/antd/grid/col/col.tsx#L3-L5) +- [frontend/antd/grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) + +**Section sources** + +- [frontend/antd/grid/row/Index.svelte:10-44](file://frontend/antd/grid/row/Index.svelte#L10-L44) +- [frontend/antd/grid/col/Index.svelte:10-47](file://frontend/antd/grid/col/Index.svelte#L10-L47) +- [frontend/antd/grid/row/row.tsx:3-5](file://frontend/antd/grid/row/row.tsx#L3-L5) +- [frontend/antd/grid/col/col.tsx:3-5](file://frontend/antd/grid/col/col.tsx#L3-L5) +- [frontend/antd/grid/context.ts:3-4](file://frontend/antd/grid/context.ts#L3-L4) + +## Performance Considerations + +- Reduce unnecessary re-renders + - Split sub-components appropriately to avoid frequent full-row updates. Statically define Col responsive breakpoint configurations as much as possible to reduce dynamic computation. +- Limit nesting depth + - Deeper nesting increases style computation and layout costs. It is recommended not to exceed three levels of nesting. +- Use gutter wisely + - Many small gaps may trigger frequent reflows. Set `gutter` on the Row level rather than on individual Cols. +- Choose appropriate breakpoints + - Enable responsive configuration only at necessary breakpoints to avoid rendering overhead from too many conditional branches. +- Use span and wrap + - Reasonable span allocation and wrapping reduce complex computation and extra DOM structures. + +(This section contains general optimization recommendations and does not involve specific file analysis.) + +## Troubleshooting Guide + +- Col not showing or misaligned + - Check whether the total span per row exceeds 24; overflowing columns will wrap. + - Check for conflicts in xs/sm/md/lg/xl/xxl breakpoint configurations. +- Offset/ordering not working + - Confirm that Col's `offset`/`push`/`pull`/`order` are taking effect at the correct breakpoint. + - Ensure Row's `justify`/`align` is not overriding the expected visual result. +- Responsive not working + - Confirm that breakpoint param types are objects containing the correct attributes (e.g., span, offset). + - Confirm that the parent Row's `gutter`/`justify`/`align` is not conflicting with the breakpoint configuration. +- Performance issues + - Check for deep nesting and excessive dynamic computation; simplify the layout structure if needed. + - Avoid setting the same spacing and styles on each Col repeatedly; configure at the Row level instead. + +**Section sources** + +- [backend/modelscope_studio/components/antd/grid/col/**init**.py:58-72](file://backend/modelscope_studio/components/antd/grid/col/__init__.py#L58-L72) +- [backend/modelscope_studio/components/antd/grid/row/**init**.py:54-60](file://backend/modelscope_studio/components/antd/grid/row/__init__.py#L54-L60) + +## Conclusion + +The Grid component, through collaboration between backend params and frontend wrappers, provides grid capabilities consistent with Ant Design, while enhancing responsive breakpoints and context-based collection mechanisms. Using Row/Col's alignment, gutter, nesting, and breakpoint configuration appropriately enables stable, maintainable layout solutions to be built quickly across multiple scenarios. + +## Appendix + +- Example entry points + - Basic example: [docs/components/antd/grid/demos/basic.py:7-24](file://docs/components/antd/grid/demos/basic.py#L7-L24) + - Playground example: [docs/components/antd/grid/demos/playground.py:17-90](file://docs/components/antd/grid/demos/playground.py#L17-L90) +- Documentation: [docs/components/antd/grid/README.md:1-9](file://docs/components/antd/grid/README.md#L1-L9) diff --git a/.wiki/en/Ant Design Components/Layout Components/Layout Components.md b/.wiki/en/Ant Design Components/Layout Components/Layout Components.md new file mode 100644 index 00000000..ee16aecc --- /dev/null +++ b/.wiki/en/Ant Design Components/Layout Components/Layout Components.md @@ -0,0 +1,385 @@ +# Layout Components + + +**Files referenced in this document** +- [divider.tsx](file://frontend/antd/divider/divider.tsx) +- [flex.tsx](file://frontend/antd/flex/flex.tsx) +- [layout.base.tsx](file://frontend/antd/layout/layout.base.tsx) +- [space.tsx](file://frontend/antd/space/space.tsx) +- [splitter.tsx](file://frontend/antd/splitter/splitter.tsx) +- [context.ts](file://frontend/antd/grid/context.ts) +- [col.tsx](file://frontend/antd/grid/col/col.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Responsive Behavior](#performance-and-responsive-behavior) +8. [Mobile and Screen Adaptation](#mobile-and-screen-adaptation) +9. [Troubleshooting](#troubleshooting) +10. [Conclusion](#conclusion) +11. [Appendix: Complex Page Layout Examples and Best Practices](#appendix-complex-page-layout-examples-and-best-practices) + +## Introduction + +This chapter is intended for developers using Ant Design layout components. It systematically covers the implementation and usage of Divider, Flex, Grid, Layout, Space, Splitter, and Masonry components in this repository. The documentation focuses on the layout algorithm concepts, responsive behavior, nesting rules, and composition patterns of each component, along with recommendations for mobile adaptation and screen size compatibility. + +## Project Structure + +These layout components reside in the `antd` submodule of the frontend directory. They adopt a unified "Svelte wrapping React components" strategy (bridging Ant Design React components to Svelte via `sveltify`), and in some cases introduce context and utility functions to support more complex layout capabilities (such as grid column collection and splitter panel item rendering). + +```mermaid +graph TB +subgraph "Antd Layout Components" +D["Divider"] +F["Flex"] +L["Layout.Base"] +S["Space"] +SP["Splitter"] +G["Grid.Context"] +GC["Grid.Col"] +end +D --> |"uses Ant Design"| D +F --> |"uses Ant Design"| F +L --> |"uses Ant Design"| L +S --> |"uses Ant Design"| S +SP --> |"uses Ant Design"| SP +GC --> |"consumes context"| G +``` + +Diagram sources + +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) +- [flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +Section sources + +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) +- [flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +## Core Components + +- **Divider**: A lightweight wrapper around Ant Design's Divider. Renders an empty divider when no children are present, or a divider with content when children are provided. +- **Flex**: A simple wrapper around Ant Design's Flex that passes through all props and children directly. +- **Layout.Base**: Dynamically selects between Header, Footer, Content, or Layout based on the `component` prop, and injects CSS class names to distinguish layout regions. +- **Space**: Extends Ant Design's Space with slot rendering and `split` slot support. Internally uses `useTargets` to map children to a target collection. +- **Splitter**: Extends Ant Design's Splitter with context-based default panel collection, passing each panel's element and props through to `Panel`. +- **Grid**: Collects columns (Col) via context and injects them into Row/Col rendering logic. The Col component registers itself into the context via `ItemHandler`. +- **Masonry**: Based on Ant Design's Masonry component, supports responsive column count configuration and automatic item height adjustment. Ideal for image walls, card streams, and other unequal-height layout scenarios. Refer to [Masonry](file://.qoder/repowiki/en/content/Ant%20Design%20Components/Layout%20Components/Masonry.md) for details. + +Section sources + +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) +- [flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +## Architecture Overview + +The diagram below shows the dependency and collaboration relationships among the layout components: Space and Splitter resolve child nodes and establish target mappings before rendering; Layout.Base dynamically selects the specific layout sub-component; Grid collects Col instances via context and participates in grid layout rendering. + +```mermaid +graph LR +A["Space"] --> B["ReactSlot Rendering"] +C["Splitter"] --> D["Panel List Rendering"] +E["Layout.Base"] --> F["Header/Footer/Content/Layout"] +G["Grid.Col"] --> H["Grid.Context Collection"] +H --> I["Row/Col Rendering"] +``` + +Diagram sources + +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +## Component Details + +### Divider + +- Implementation notes + - Wraps Ant Design's Divider using `sveltify`. + - Renders a divider with children when children are present; otherwise renders an empty divider. +- Nesting rules + - Used as a separator; can be placed inside any container without affecting the parent's layout mode. +- Responsive behavior + - Determined by Ant Design; no breakpoint control by default. +- Typical usage + - Insert dividers between list items, form sections, or cards to enhance visual hierarchy. + +Section sources + +- [divider.tsx:1-15](file://frontend/antd/divider/divider.tsx#L1-L15) + +### Flex + +- Implementation notes + - Wraps Ant Design's Flex using `sveltify`, passing all props and children through directly. +- Layout algorithm + - Follows the Flexbox specification, supporting main axis, cross axis, wrapping, alignment, and other common properties. +- Nesting rules + - Flex can nest other Flex, Grid, Space, and layout components to form composite layouts. +- Responsive behavior + - Flex properties can change at breakpoints to achieve adaptive layouts using Ant Design's breakpoint configuration. +- Typical usage + - Header navigation, card groups, button groups, and other scenarios requiring flexible alignment and distribution. + +Section sources + +- [flex.tsx:1-11](file://frontend/antd/flex/flex.tsx#L1-L11) + +### Layout.Base + +- Implementation notes + - Dynamically selects between rendering Header, Footer, Content, or Layout based on the `component` prop. + - Injects CSS class names for non-layout sub-components to facilitate styling and debugging. +- Layout algorithm + - Implements page frame layout using Ant Design's Layout family of components. +- Nesting rules + - Header/Footer/Content must be direct children of Layout; Sider and other sub-components can be nested inside. +- Responsive behavior + - Achieves a responsive sidebar by combining Sider collapse/expand behavior with breakpoint strategies. +- Typical usage + - Overall page framework: top navigation + side menu + main content + footer. + +```mermaid +flowchart TD +Start(["Enter Layout.Base"]) --> CheckComp{"component type"} +CheckComp --> |header| RenderHeader["Render Header"] +CheckComp --> |footer| RenderFooter["Render Footer"] +CheckComp --> |content| RenderContent["Render Content"] +CheckComp --> |layout| RenderLayout["Render Layout"] +RenderHeader --> End(["Done"]) +RenderFooter --> End +RenderContent --> End +RenderLayout --> End +``` + +Diagram sources + +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +Section sources + +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +### Space + +- Implementation notes + - Uses Ant Design's Space and extends it with slot rendering and `split` slot support. + - Internally maps children to a target collection via `useTargets`, then renders them through `ReactSlot`. +- Layout algorithm + - Calculates spacing between elements based on direction and size, supporting wrapping and compact composition modes. +- Nesting rules + - Can nest any component; the `split` slot is used to render separators. +- Responsive behavior + - Spacing values can change at breakpoints to optimize spacing for different screen sizes. +- Typical usage + - Navigation button groups, action button groups, compact arrangement between form items. + +```mermaid +sequenceDiagram +participant U as "Caller" +participant S as "Space" +participant T as "useTargets" +participant R as "ReactSlot" +U->>S : Pass children and slots +S->>T : Parse children into targets +S->>R : Render targets +S->>R : Render split slot (if present) +R-->>U : Output layout with spacing +``` + +Diagram sources + +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) + +Section sources + +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) + +### Splitter + +- Implementation notes + - Uses Ant Design's Splitter and collects default panel list via context. + - Passes each panel's element and props through to Panel for flexible multi-panel layout. +- Layout algorithm + - Split layout based on drag or fixed proportions, supporting horizontal and vertical directions. +- Nesting rules + - Sub-panels register via context; each panel independently renders its own content. +- Responsive behavior + - Can adjust initial proportions and minimum sizes at breakpoints to ensure mobile usability. +- Typical usage + - Code editor + preview area, left/right content comparison, multi-view side-by-side display. + +```mermaid +sequenceDiagram +participant U as "Caller" +participant P as "Splitter" +participant Ctx as "Items Context" +participant Panel as "Panel" +U->>P : Provide panel slots +P->>Ctx : Get default panel list +loop Iterate panels +P->>Panel : Pass props and render +Panel-->>P : Return panel content +end +P-->>U : Output split panel layout +``` + +Diagram sources + +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) + +Section sources + +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) + +### Grid (Col and Context) + +- Implementation notes + - Col registers itself into a context named `antd-grid-cols` via `ItemHandler`. + - The context provides `withItemsContextProvider` and `useItems` for collecting and consuming column definitions. +- Layout algorithm + - Based on a 24-column grid system. Col props such as `span`, `offset`, `order`, and `gutter` determine column width and order. +- Nesting rules + - Col must be placed within a Row/Col context; responsive behavior can be configured via breakpoints. +- Responsive behavior + - Supports breakpoints: xs/sm/md/lg/xl. Different `span`/`offset` values can be set per breakpoint. +- Typical usage + - Form grids, card grids, image walls, etc. + +```mermaid +flowchart TD +A["Col component"] --> B["Register to context
key: antd-grid-cols"] +B --> C["Row/Col reads context during render"] +C --> D["Calculate layout by span/offset/order"] +D --> E["Output grid column"] +``` + +Diagram sources + +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +Section sources + +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +## Dependency Analysis + +- Inter-component coupling + - Space and Splitter directly depend on ReactSlot and context for slot and child item rendering. + - Layout.Base depends on Ant Design's Layout family components and dynamically selects sub-component types. + - Grid uses context to collect and consume Col instances, reducing coupling between Row and Col. +- External dependencies + - All components depend on their corresponding Ant Design components; layout algorithms and styles are provided by Ant Design. +- Potential circular dependencies + - No direct circular dependencies found; context is only used for data passing and does not reverse-depend on components. + +```mermaid +graph TB +Space["Space"] --> ReactSlot["ReactSlot"] +Splitter["Splitter"] --> ItemsCtx["Items Context"] +LayoutBase["Layout.Base"] --> ADLayout["Ant Design Layout"] +GridCol["Grid.Col"] --> GridCtx["Grid Context"] +``` + +Diagram sources + +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +Section sources + +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +## Performance and Responsive Behavior + +- Performance characteristics + - Components use lightweight wrappers to avoid additional state management overhead. Space's `useTargets` performs mapping only once during initialization. + - Layout.Base uses `useMemo` to cache component types, reducing unnecessary re-renders. +- Responsive behavior + - The responsiveness of Flex, Space, Grid, and Splitter is primarily driven by Ant Design's breakpoints and props. Layout parameters for different screen sizes can be configured individually in the breakpoint configuration. + - It is recommended to define breakpoint thresholds and column counts clearly during the design phase to avoid frequent reflows. + +## Mobile and Screen Adaptation + +- General strategies + - Use breakpoint configuration (e.g., xs/sm/md/lg/xl) to adjust column widths, spacing, and layout direction for small screens. + - Use compact mode and appropriate spacing in Space to avoid horizontal scrolling on mobile. + - Set minimum panel sizes and initial proportions in Splitter to ensure touch usability. +- Layout containers + - On small screens, prefer vertical layouts (Flex direction column). Hide secondary areas or use a drawer-style sidebar if necessary. +- Grid system + - Configure `offset` and `order` appropriately to maintain readability and clickability on small screens. + +## Troubleshooting + +- Children not rendering correctly + - Space hides children internally and renders targets via ReactSlot. Verify that slots are being used correctly. +- Splitter panels are empty + - Splitter relies on the default panel list provided by context. If panels are empty, nothing is rendered. Check slot naming and context registration. +- Grid columns not taking effect + - Confirm that Col is registered within a Row/Col context. Check breakpoint configuration and whether `span`/`offset` values are reasonable. +- Layout container type error + - Layout.Base only supports four types: header/footer/content/layout. Passing any other value will fall back to Layout. + +Section sources + +- [space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [col.tsx:1-14](file://frontend/antd/grid/col/col.tsx#L1-L14) + +## Conclusion + +The layout components in this repository are designed around a "lightweight wrapper + context" core philosophy. They reuse Ant Design's mature layout algorithms and styling system, while providing extensibility through slot rendering, dynamic component selection, and context collection. Through breakpoint configuration and appropriate nesting rules, high-quality page layouts that work well on both desktop and mobile can be built. + +## Appendix: Complex Page Layout Examples and Best Practices + +- Example 1: Dashboard page + - Use Layout.Base to build a header + sidebar + main body. Use Flex and Space inside the main body to organize cards and action areas. Use Divider at the bottom for separation. + - Breakpoint strategy: On small screens, collapse the action area into cards or use a drawer. +- Example 2: Content editing page + - Use Splitter to split the left directory tree from the right editor. Use Grid for form layout inside the editor. Use Space for action buttons at the bottom. + - Breakpoint strategy: On small screens, hide the directory tree and display the editor at full width. +- Example 3: Comparison display page + - Use Splitter to place two content blocks side by side. Inside each block, use Flex and Space for title, description, and action alignment. + - Breakpoint strategy: On small screens, switch to vertical stacking to preserve readability. + +Best practices + +- Prefer Flex and Space for simple layouts; introduce Splitter only for complex scenarios. +- Unify breakpoint configuration in the grid system to avoid multiple breakpoint strategies on the same page. +- Inject semantic class names into layout containers to facilitate style overrides and debugging. +- On mobile, prioritize touch interaction and adequate tap target sizes by increasing spacing and font size appropriately. diff --git a/.wiki/en/Ant Design Components/Layout Components/Layout.md b/.wiki/en/Ant Design Components/Layout Components/Layout.md new file mode 100644 index 00000000..94a9fd9b --- /dev/null +++ b/.wiki/en/Ant Design Components/Layout Components/Layout.md @@ -0,0 +1,295 @@ +# Layout + + +**Files referenced in this document** +- [frontend/antd/layout/Index.svelte](file://frontend/antd/layout/Index.svelte) +- [frontend/antd/layout/Base.svelte](file://frontend/antd/layout/Base.svelte) +- [frontend/antd/layout/layout.base.tsx](file://frontend/antd/layout/layout.base.tsx) +- [frontend/antd/layout/content/Index.svelte](file://frontend/antd/layout/content/Index.svelte) +- [frontend/antd/layout/footer/Index.svelte](file://frontend/antd/layout/footer/Index.svelte) +- [frontend/antd/layout/header/Index.svelte](file://frontend/antd/layout/header/Index.svelte) +- [frontend/antd/layout/sider/Index.svelte](file://frontend/antd/layout/sider/Index.svelte) +- [frontend/antd/layout/sider/layout.sider.tsx](file://frontend/antd/layout/sider/layout.sider.tsx) +- [docs/components/antd/layout/README.md](file://docs/components/antd/layout/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document provides a systematic introduction to the overall architecture and usage of the Layout component, covering the combination and nesting rules of layout regions including Header, Sider, Content, and Footer. It explains responsive behavior and fixed positioning strategies, provides ideas for classic page templates such as sidebar layouts, top navigation layouts, and hybrid layouts, and describes integration with the grid system and adaptive behavior at different screen sizes. It also provides practical recommendations for style customization, theme switching, and animation effects. + +## Project Structure + +The Layout component adopts a "unified base + regional sub-components" layered design: + +- Base layer: `Index.svelte` serves as the entry point. `Base.svelte` handles prop processing and rendering. `layout.base.tsx` wraps the specific Ant Design components (Header/Footer/Content/Layout). +- Region layer: header, footer, content, and sider each specify a `component` type via their own `Index.svelte`, reusing the `Base.svelte` rendering logic. +- Special region: sider provides its own `layout.sider.tsx` to support a `trigger` slot for the collapse trigger. + +```mermaid +graph TB +subgraph "Layout Component Layer" +L["Index.svelte
Unified entry"] +HB["Base.svelte
Common base"] +C["content/Index.svelte"] +F["footer/Index.svelte"] +H["header/Index.svelte"] +S["sider/Index.svelte"] +end +subgraph "Underlying Implementation Layer" +LB["layout.base.tsx
Ant Design component wrapper"] +LS["layout.sider.tsx
Sider implementation with trigger slot"] +end +L --> HB +C --> HB +F --> HB +H --> HB +S --> HB +HB --> LB +S --> LS +``` + +Diagram sources + +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/sider/Index.svelte:1-62](file://frontend/antd/layout/sider/Index.svelte#L1-L62) +- [frontend/antd/layout/sider/layout.sider.tsx:1-26](file://frontend/antd/layout/sider/layout.sider.tsx#L1-L26) + +Section sources + +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/content/Index.svelte:1-15](file://frontend/antd/layout/content/Index.svelte#L1-L15) +- [frontend/antd/layout/footer/Index.svelte:1-15](file://frontend/antd/layout/footer/Index.svelte#L1-L15) +- [frontend/antd/layout/header/Index.svelte:1-15](file://frontend/antd/layout/header/Index.svelte#L1-L15) +- [frontend/antd/layout/sider/Index.svelte:1-62](file://frontend/antd/layout/sider/Index.svelte#L1-L62) +- [frontend/antd/layout/sider/layout.sider.tsx:1-26](file://frontend/antd/layout/sider/layout.sider.tsx#L1-L26) + +## Core Components + +- Layout (overall container) + - Entry: `Index.svelte` passes props to `Base.svelte` and specifies `component` as `layout`. + - Base: `Base.svelte` reuses common prop handling logic; `layout.base.tsx` ultimately decides to render Ant Design's Layout container. +- Header (top area) + - Entry: `header/Index.svelte` specifies `component` as `header`, reusing `Base.svelte` to render Ant Design's Header. +- Footer (bottom area) + - Entry: `footer/Index.svelte` specifies `component` as `footer`, reusing `Base.svelte` to render Ant Design's Footer. +- Content (content area) + - Entry: `content/Index.svelte` specifies `component` as `content`, reusing `Base.svelte` to render Ant Design's Content. +- Sider (sidebar) + - Entry: `sider/Index.svelte` asynchronously loads `layout.sider.tsx` to implement Ant Design's Sider with `trigger` slot support. + +Section sources + +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/header/Index.svelte:1-15](file://frontend/antd/layout/header/Index.svelte#L1-L15) +- [frontend/antd/layout/footer/Index.svelte:1-15](file://frontend/antd/layout/footer/Index.svelte#L1-L15) +- [frontend/antd/layout/content/Index.svelte:1-15](file://frontend/antd/layout/content/Index.svelte#L1-L15) +- [frontend/antd/layout/sider/Index.svelte:1-62](file://frontend/antd/layout/sider/Index.svelte#L1-L62) +- [frontend/antd/layout/sider/layout.sider.tsx:1-26](file://frontend/antd/layout/sider/layout.sider.tsx#L1-L26) + +## Architecture Overview + +The diagram below shows the render chain from Svelte to Ant Design, as well as the Sider trigger slot mechanism: + +```mermaid +sequenceDiagram +participant U as "User code" +participant L as "Layout/Index.svelte" +participant B as "Base.svelte" +participant LB as "layout.base.tsx" +participant AD as "Ant Design Layout" +U->>L : Pass props such as children +L->>B : Pass through props and set component="layout" +B->>LB : Compute and select component type +LB->>AD : Render Ant Design Layout +AD-->>U : Layout container render complete +``` + +Diagram sources + +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +Section sources + +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +## Detailed Component Analysis + +### Layout Nesting and Region Composition + +- Nesting rules + - Layout is the root container and can directly contain Header, Sider, Content, and Footer. + - Sider is usually placed on the left side of Layout, Content on the right, Header at the top, and Footer at the bottom. + - More fine-grained layouts or grid systems can be further nested inside Content. +- Responsive and fixed positioning + - Implement mobile responsiveness by combining Sider's collapse props with breakpoint configuration. + - When Header/Footer has a fixed height, ensure Content height calculation is not interfered with to avoid scroll conflicts. +- Trigger and interaction + - Sider supports a custom `trigger` slot for implementing a collapse button with icon switching. + +```mermaid +flowchart TD +Start(["Start"]) --> Root["Layout root container"] +Root --> Hdr["Header top area"] +Root --> Sider["Sider sidebar"] +Root --> Cnt["Content main area"] +Root --> Ftr["Footer bottom area"] +Sider --> Trigger["trigger slot (optional)"] +Cnt --> Inner["Inner nested grids/cards/lists etc."] +Hdr --> End(["End"]) +Ftr --> End +``` + +Diagram sources + +- [frontend/antd/layout/header/Index.svelte:1-15](file://frontend/antd/layout/header/Index.svelte#L1-L15) +- [frontend/antd/layout/sider/Index.svelte:1-62](file://frontend/antd/layout/sider/Index.svelte#L1-L62) +- [frontend/antd/layout/content/Index.svelte:1-15](file://frontend/antd/layout/content/Index.svelte#L1-L15) +- [frontend/antd/layout/footer/Index.svelte:1-15](file://frontend/antd/layout/footer/Index.svelte#L1-L15) + +Section sources + +- [frontend/antd/layout/header/Index.svelte:1-15](file://frontend/antd/layout/header/Index.svelte#L1-L15) +- [frontend/antd/layout/sider/Index.svelte:1-62](file://frontend/antd/layout/sider/Index.svelte#L1-L62) +- [frontend/antd/layout/content/Index.svelte:1-15](file://frontend/antd/layout/content/Index.svelte#L1-L15) +- [frontend/antd/layout/footer/Index.svelte:1-15](file://frontend/antd/layout/footer/Index.svelte#L1-L15) + +### Sider Component and Trigger Slot + +- Trigger mechanism + - If a `trigger` slot is provided, that slot content takes priority. If no slot is provided and `trigger` is the default value, the default trigger is rendered. Otherwise, the rendered state is determined by the passed `trigger` value. +- Collapse state management + - Use Sider's `collapsed` state together with trigger behavior to implement click-toggle expand/collapse. + +```mermaid +flowchart TD +A["Enter Sider render"] --> B{"trigger slot provided?"} +B -- Yes --> C["Render slot content as trigger"] +B -- No --> D{"trigger is default value?"} +D -- Yes --> E["Render default trigger"] +D -- No --> F{"trigger is null/undefined?"} +F -- Yes --> G["Do not render trigger"] +F -- No --> H["Render passed trigger content"] +C --> I["Done"] +E --> I +G --> I +H --> I +``` + +Diagram sources + +- [frontend/antd/layout/sider/layout.sider.tsx:1-26](file://frontend/antd/layout/sider/layout.sider.tsx#L1-L26) + +Section sources + +- [frontend/antd/layout/sider/layout.sider.tsx:1-26](file://frontend/antd/layout/sider/layout.sider.tsx#L1-L26) + +### Classic Page Layout Templates + +- Sidebar layout + - Use Layout + Header + Sider + Content + Footer. Sider has a fixed width and is collapsible on mobile. +- Top navigation layout + - Use Layout + Header (top navigation only) + Content. Sider can be omitted or hidden. +- Hybrid layout + - Nest a grid system inside Content to implement multi-column content with a side information panel. + +Section sources + +- [docs/components/antd/layout/README.md:1-8](file://docs/components/antd/layout/README.md#L1-L8) + +### Integration with the Grid System + +- Use Row/Col in Content for column division, combined with responsive breakpoints for adaptive layouts. +- Note: When Header/Footer has a fixed height, Content height calculation must account for the remaining visible area to avoid overflow or scroll anomalies. + +## Dependency Analysis + +- Component coupling + - All region components depend on `Base.svelte`'s prop handling and rendering process, reducing duplicate code and improving consistency. + - Sider independently implements `layout.sider.tsx` to avoid coupling with the common Base process, enhancing extensibility. +- External dependencies + - Ant Design's Layout, Header, Footer, Content, and Sider components as render targets. + - Svelte Slot and React Slot bridging for slot passing and cloning. + +```mermaid +graph LR +Base["Base.svelte"] --> Wrap["layout.base.tsx"] +Wrap --> ADL["Ant Design Layout"] +Wrap --> ADH["Ant Design Header"] +Wrap --> ADF["Ant Design Footer"] +Wrap --> ADC["Ant Design Content"] +SBase["sider/Index.svelte"] --> SWrap["layout.sider.tsx"] +SWrap --> ADS["Ant Design Sider"] +``` + +Diagram sources + +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/sider/Index.svelte:1-62](file://frontend/antd/layout/sider/Index.svelte#L1-L62) +- [frontend/antd/layout/sider/layout.sider.tsx:1-26](file://frontend/antd/layout/sider/layout.sider.tsx#L1-L26) + +Section sources + +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/sider/Index.svelte:1-62](file://frontend/antd/layout/sider/Index.svelte#L1-L62) +- [frontend/antd/layout/sider/layout.sider.tsx:1-26](file://frontend/antd/layout/sider/layout.sider.tsx#L1-L26) + +## Performance Considerations + +- Async loading + - Sider is asynchronously loaded via `importComponent`, reducing initial bundle size and first-screen blocking. +- Prop passthrough and derivation + - `Base.svelte` handles and derives props in a unified manner, avoiding unnecessary re-renders. +- Class names + - Class names are conditionally concatenated, avoiding excessive runtime string concatenation overhead. + +Section sources + +- [frontend/antd/layout/sider/Index.svelte:1-62](file://frontend/antd/layout/sider/Index.svelte#L1-L62) +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) + +## Troubleshooting Guide + +- No content rendered + - Check if the `visible` prop has been set to `false`. Confirm the visibility check logic in `Base.svelte`. +- Sider trigger not showing + - Confirm whether a `trigger` slot has been provided. Check if the `trigger` value is `null`/`undefined` or the default value. +- Style anomalies + - Confirm that class names are correctly concatenated. Check if external styles are causing layout misalignment. + +Section sources + +- [frontend/antd/layout/Base.svelte:1-71](file://frontend/antd/layout/Base.svelte#L1-L71) +- [frontend/antd/layout/sider/layout.sider.tsx:1-26](file://frontend/antd/layout/sider/layout.sider.tsx#L1-L26) + +## Conclusion + +The Layout component achieves complete encapsulation of Ant Design's layout system through a unified base and regionalized decomposition. With the Sider trigger slot and async loading mechanism, it ensures both flexibility and performance. Combined with the grid system and responsive breakpoints, a variety of classic page layout templates can be quickly assembled, while style and theme customization meets the needs of complex business scenarios. + +## Appendix + +- Example entry reference: [docs/components/antd/layout/README.md:1-8](file://docs/components/antd/layout/README.md#L1-L8) diff --git a/.wiki/en/Ant Design Components/Layout Components/Masonry.md b/.wiki/en/Ant Design Components/Layout Components/Masonry.md new file mode 100644 index 00000000..8b818970 --- /dev/null +++ b/.wiki/en/Ant Design Components/Layout Components/Masonry.md @@ -0,0 +1,464 @@ +# Masonry + + +**Files referenced in this document** +- [frontend/antd/masonry/masonry.tsx](file://frontend/antd/masonry/masonry.tsx) +- [frontend/antd/masonry/context.ts](file://frontend/antd/masonry/context.ts) +- [frontend/antd/masonry/Index.svelte](file://frontend/antd/masonry/Index.svelte) +- [frontend/antd/masonry/package.json](file://frontend/antd/masonry/package.json) +- [backend/modelscope_studio/components/antd/masonry/__init__.py](file://backend/modelscope_studio/components/antd/masonry/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [docs/components/antd/masonry/README.md](file://docs/components/antd/masonry/README.md) +- [docs/components/antd/masonry/README-zh_CN.md](file://docs/components/antd/masonry/README-zh_CN.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +Masonry is an important layout component in ModelScope Studio, implemented based on Ant Design's Masonry component. This component is specifically designed to display content of varying heights, such as images and cards, and automatically creates a waterfall/masonry effect that distributes content evenly across multiple columns. + +The masonry layout is particularly well-suited for the following scenarios: + +- Displaying images or cards with irregular heights +- Distributing content evenly between columns +- Layout requirements that need responsive column count adjustment + +## Project Structure + +ModelScope Studio adopts a frontend-backend separated architecture. The Masonry component is organized as follows: + +```mermaid +graph TB +subgraph "Frontend Layer" +A[frontend/antd/masonry/] --> A1[masonry.tsx] +A --> A2[Index.svelte] +A --> A3[context.ts] +A --> A4[package.json] +subgraph "utils/" +B[frontend/utils/] --> B1[createItemsContext.tsx] +B --> B2[renderItems.tsx] +B --> B3[renderParamsSlot.tsx] +end +end +subgraph "Backend Layer" +C[backend/modelscope_studio/] --> C1[components/antd/masonry/] +C --> C2[components/antd/components.py] +C1 --> C3[__init__.py] +end +subgraph "Docs Layer" +D[docs/components/antd/masonry/] --> D1[README.md] +D --> D2[README-zh_CN.md] +end +A1 --> B1 +A1 --> B2 +A1 --> B3 +C3 --> A2 +``` + +**Diagram sources** + +- [frontend/antd/masonry/masonry.tsx:1-52](file://frontend/antd/masonry/masonry.tsx#L1-L52) +- [frontend/antd/masonry/Index.svelte:1-64](file://frontend/antd/masonry/Index.svelte#L1-L64) +- [backend/modelscope_studio/components/antd/masonry/**init**.py:1-83](file://backend/modelscope_studio/components/antd/masonry/__init__.py#L1-L83) + +**Section sources** + +- [frontend/antd/masonry/masonry.tsx:1-52](file://frontend/antd/masonry/masonry.tsx#L1-L52) +- [frontend/antd/masonry/Index.svelte:1-64](file://frontend/antd/masonry/Index.svelte#L1-L64) +- [backend/modelscope_studio/components/antd/masonry/**init**.py:1-83](file://backend/modelscope_studio/components/antd/masonry/__init__.py#L1-L83) + +## Core Components + +### Frontend Core Components + +The core implementation of the Masonry component resides in `frontend/antd/masonry/masonry.tsx`. It uses React and Ant Design's Masonry component and integrates with ModelScope Studio's component system. + +Main features include: + +- **React wrapper**: uses `sveltify` to wrap Svelte components as React components +- **Context management**: integrates `createItemsContext` for data sharing between components +- **Slot rendering**: supports custom slot rendering +- **Dynamic content**: supports dynamic content updates and re-rendering + +### Backend Integration Component + +The backend component is located at `backend/modelscope_studio/components/antd/masonry/__init__.py` and provides a Python interface bridging to the frontend component. + +Key props and methods: + +- **EVENTS**: defines the `layout_change` event listener +- **SLOTS**: supports `items` and `itemRender` slots +- **PROPS**: provides configuration options such as `columns`, `gutter`, and `fresh` + +**Section sources** + +- [frontend/antd/masonry/masonry.tsx:10-49](file://frontend/antd/masonry/masonry.tsx#L10-L49) +- [backend/modelscope_studio/components/antd/masonry/**init**.py:10-65](file://backend/modelscope_studio/components/antd/masonry/__init__.py#L10-L65) + +## Architecture Overview + +The overall architecture of the Masonry component uses a layered design to ensure good maintainability and extensibility: + +```mermaid +graph TD +subgraph "UI Layer" +UI[Masonry Component] +end +subgraph "Frontend Logic Layer" +FC[Function Component] +CTX[Context Provider] +SL[Slot Handling] +end +subgraph "Utility Layer" +CIC[createItemsContext] +RI[renderItems] +RPS[renderParamsSlot] +end +subgraph "Ant Design Layer" +AD[Antd Masonry] +end +subgraph "Backend Integration Layer" +BC[Backend Component] +PC[Python Interface] +end +UI --> FC +FC --> CTX +FC --> SL +FC --> AD +CTX --> CIC +SL --> RI +SL --> RPS +BC --> PC +BC --> UI +``` + +**Diagram sources** + +- [frontend/antd/masonry/masonry.tsx:1-52](file://frontend/antd/masonry/masonry.tsx#L1-L52) +- [frontend/utils/createItemsContext.tsx:97-184](file://frontend/utils/createItemsContext.tsx#L97-L184) +- [frontend/utils/renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +## Detailed Component Analysis + +### Masonry Component Implementation + +The core implementation of the Masonry component includes the following key parts: + +#### Component Wrapping and Prop Handling + +The component uses the `sveltify` function to wrap Svelte components as React components, supporting prop passing and event handling: + +```mermaid +sequenceDiagram +participant User as User +participant Masonry as Masonry Component +participant Context as Context Provider +participant Utils as Utility Functions +User->>Masonry : Pass props and children +Masonry->>Context : withItemsContextProvider wrapping +Context->>Utils : useItems to get data +Utils->>Utils : renderItems processes slots +Utils->>Masonry : Return processed data +Masonry->>Masonry : useMemo optimizes rendering +Masonry->>User : Render final result +``` + +**Diagram sources** + +- [frontend/antd/masonry/masonry.tsx:16-48](file://frontend/antd/masonry/masonry.tsx#L16-L48) +- [frontend/antd/masonry/context.ts:3-4](file://frontend/antd/masonry/context.ts#L3-L4) + +#### Data Flow Handling Mechanism + +The component manages data flow via `createItemsContext`: + +```mermaid +flowchart TD +Start([Component initialization]) --> GetItems[Get useItems context] +GetItems --> CheckSlots{Check slot type} +CheckSlots --> |has items| UseItems[Use items prop] +CheckSlots --> |no items| UseSlots[Use slot data] +UseSlots --> ResolveSlot[Resolve slot data] +ResolveSlot --> RenderItems[Call renderItems] +UseItems --> RenderItems +RenderItems --> MemoOptimize[useMemo optimization] +MemoOptimize --> FinalRender[Final render] +FinalRender --> End([Done]) +``` + +**Diagram sources** + +- [frontend/antd/masonry/masonry.tsx:18-43](file://frontend/antd/masonry/masonry.tsx#L18-L43) +- [frontend/utils/renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +**Section sources** + +- [frontend/antd/masonry/masonry.tsx:1-52](file://frontend/antd/masonry/masonry.tsx#L1-L52) +- [frontend/antd/masonry/context.ts:1-7](file://frontend/antd/masonry/context.ts#L1-L7) + +### Context Management System + +`createItemsContext` provides comprehensive context management: + +#### Context Provider Pattern + +```mermaid +classDiagram +class ItemsContextProvider { ++allowedSlots : string[] ++items : ItemsContextValue ++setItem(slotKey, index, value) ++onChange(items) +} +class ItemsContextValue { ++items : Record~string, Item[]~ ++setItem : Function ++initial : boolean +} +class ItemHandler { ++itemIndex : number ++itemSlotKey : string ++itemElement : HTMLElement ++itemProps(props, items) ++itemChildren(items) ++slots : Record~string, Slot~ +} +ItemsContextProvider --> ItemsContextValue : "provides" +ItemHandler --> ItemsContextProvider : "uses" +``` + +**Diagram sources** + +- [frontend/utils/createItemsContext.tsx:108-170](file://frontend/utils/createItemsContext.tsx#L108-L170) +- [frontend/utils/createItemsContext.tsx:190-261](file://frontend/utils/createItemsContext.tsx#L190-L261) + +#### Data Processing Flow + +The component's data processing follows this flow: + +1. **Data collection**: collects all child elements from slots +2. **Data transformation**: converts HTML elements into internal data structures +3. **Context passing**: passes data through the React Context in the component tree +4. **State management**: manages component state using `useState` and `useEffect` + +**Section sources** + +- [frontend/utils/createItemsContext.tsx:97-274](file://frontend/utils/createItemsContext.tsx#L97-L274) + +### Slot Rendering System + +The Masonry component supports a flexible slot rendering mechanism: + +#### Slot Handling Functions + +```mermaid +flowchart LR +Slots[Slot object] --> CheckSlot{Check slot exists} +CheckSlot --> |exists| RenderSlot[renderSlot rendering] +CheckSlot --> |not exists| Fallback[Fallback handling] +RenderSlot --> ParamsSlot{Parameterized slot} +ParamsSlot --> |has params| RenderParams[renderParamsSlot] +ParamsSlot --> |no params| DirectRender[Direct rendering] +RenderParams --> Clone[Clone element] +DirectRender --> Clone +Clone --> Result[Return React node] +Fallback --> Result +``` + +**Diagram sources** + +- [frontend/utils/renderParamsSlot.tsx:5-49](file://frontend/utils/renderParamsSlot.tsx#L5-L49) +- [frontend/utils/renderItems.tsx:72-94](file://frontend/utils/renderItems.tsx#L72-L94) + +**Section sources** + +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) + +## Dependency Analysis + +### Component Dependency Diagram + +```mermaid +graph TB +subgraph "Masonry Component Dependencies" +A[masonry.tsx] --> B[createItemsContext.tsx] +A --> C[renderItems.tsx] +A --> D[renderParamsSlot.tsx] +A --> E[context.ts] +end +subgraph "Context Dependencies" +B --> F[React Hooks] +B --> G[useMemoizedEqualValue] +B --> H[useMemoizedFn] +end +subgraph "Utility Function Dependencies" +C --> I[ReactSlot] +C --> J[ContextPropsProvider] +D --> K[renderSlot] +end +subgraph "Backend Integration" +L[__init__.py] --> M[AntdMasonry] +L --> N[AntdMasonryItem] +end +A -.-> O[Antd Masonry] +L -.-> P[Gradio Events] +``` + +**Diagram sources** + +- [frontend/antd/masonry/masonry.tsx:1-6](file://frontend/antd/masonry/masonry.tsx#L1-L6) +- [frontend/utils/createItemsContext.tsx:1-18](file://frontend/utils/createItemsContext.tsx#L1-L18) +- [backend/modelscope_studio/components/antd/masonry/**init**.py:1-8](file://backend/modelscope_studio/components/antd/masonry/__init__.py#L1-L8) + +### Key Dependency Descriptions + +1. **Ant Design Masonry**: core layout component providing masonry layout functionality +2. **React Hooks**: used for state management and performance optimization +3. **Gradio integration**: supports Python backend event handling +4. **Svelte Preprocess**: implements the transformation from Svelte to React + +**Section sources** + +- [frontend/antd/masonry/masonry.tsx:1-6](file://frontend/antd/masonry/masonry.tsx#L1-L6) +- [backend/modelscope_studio/components/antd/masonry/**init**.py:23-27](file://backend/modelscope_studio/components/antd/masonry/__init__.py#L23-L27) + +## Performance Considerations + +### Rendering Optimization Strategies + +The Masonry component employs multiple performance optimization techniques: + +#### useMemo Optimization + +The component uses `useMemo` to cache computation results, avoiding unnecessary re-renders: + +```typescript +const memoizedItems = useMemo(() => { + return items || renderItems(resolvedSlotItems); +}, [items, resolvedSlotItems]); +``` + +#### Event Handler Optimization + +Uses `useFunction` and `useMemoizedFn` to optimize event handler performance: + +```typescript +const itemRenderFunction = useFunction(props.itemRender); +``` + +#### Conditional Rendering + +Reduces DOM operations through conditional rendering: + +```html +
{children}
+``` + +### Memory Management + +The component implements intelligent memory management: + +1. **Reference caching**: uses `useRef` to cache expensive computation results +2. **State synchronization**: synchronizes state changes via `useEffect` +3. **Cleanup mechanism**: cleans up event listeners when the component unmounts + +## Troubleshooting Guide + +### Common Issues and Solutions + +#### 1. Component shows no content + +**Symptom**: Masonry component renders blank + +**Possible causes**: + +- Slot data not set correctly +- `items` prop not provided +- React component not wrapped correctly + +**Solutions**: + +1. Check if slots are passed correctly +2. Confirm that the `items` prop contains valid data +3. Verify that the component wrapping is correct + +#### 2. Layout is disordered + +**Symptom**: Masonry layout displays abnormally + +**Possible causes**: + +- Column count configuration is incorrect +- Gutter settings are improper +- Content height calculation error + +**Solutions**: + +1. Check the `columns` configuration +2. Adjust the `gutter` setting +3. Ensure content has correct height information + +#### 3. Performance issues + +**Symptom**: Component renders slowly or stutters + +**Possible causes**: + +- Large amounts of data causing rendering pressure +- Unnecessary re-renders +- Event handler performance issues + +**Solutions**: + +1. Use virtual scrolling to handle large datasets +2. Optimize `useMemo` dependencies +3. Reduce the complexity of event handlers + +**Section sources** + +- [frontend/antd/masonry/masonry.tsx:36-43](file://frontend/antd/masonry/masonry.tsx#L36-L43) +- [frontend/utils/createItemsContext.tsx:124-153](file://frontend/utils/createItemsContext.tsx#L124-L153) + +## Conclusion + +The Masonry layout component is a powerful and well-designed layout solution in ModelScope Studio. The component demonstrates excellent architectural design through the following characteristics: + +### Key Advantages + +1. **Modular design**: clear module division for easy maintenance and extension +2. **Performance optimization**: implements multiple performance optimization techniques to ensure a smooth user experience +3. **Flexibility**: supports various configuration options and custom rendering functionality +4. **Type safety**: complete TypeScript type definitions for a good development experience + +### Technical Highlights + +- **Context management pattern**: implements powerful data flow management via `createItemsContext` +- **Slot rendering system**: supports complex slot rendering and parameterized rendering +- **React integration**: seamlessly integrated into the React ecosystem +- **Backend compatibility**: provides a Python backend interface supporting Gradio event handling + +### Application Scenarios + +The Masonry component is particularly well-suited for: + +- Image gallery display +- Card content layouts +- Dynamic content containers +- Responsive grid layouts + +The component provides powerful layout capabilities for ModelScope Studio and is an important piece of infrastructure for building modern web applications. diff --git a/.wiki/en/Ant Design Components/Layout Components/Space.md b/.wiki/en/Ant Design Components/Layout Components/Space.md new file mode 100644 index 00000000..b8fa4abe --- /dev/null +++ b/.wiki/en/Ant Design Components/Layout Components/Space.md @@ -0,0 +1,268 @@ +# Space + + +**Files Referenced in This Document** +- [frontend/antd/space/space.tsx](file://frontend/antd/space/space.tsx) +- [frontend/antd/space/Index.svelte](file://frontend/antd/space/Index.svelte) +- [frontend/antd/space/compact/space.compact.tsx](file://frontend/antd/space/compact/space.compact.tsx) +- [frontend/antd/space/compact/Index.svelte](file://frontend/antd/space/compact/Index.svelte) +- [backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js](file://backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js) +- [backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js](file://backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js) +- [docs/components/antd/space/README.md](file://docs/components/antd/space/README.md) +- [docs/components/antd/space/README-zh_CN.md](file://docs/components/antd/space/README-zh_CN.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The Space component automatically inserts uniform spacing between multiple child elements, supporting direction control, spacing size configuration, and collaboration with separator slots. This repository provides two variants: + +- Standard Space: A wrapper around Ant Design's Space component, responsible for automatic spacing distribution and direction control. +- Compact Space (Space.Compact): A wrapper around Ant Design's Space.Compact, emphasizing tighter layouts and compact spacing strategies. + +Both variants bridge Svelte child nodes to React Space/Space.Compact children via the Svelte–React bridging mechanism, ensuring stable rendering in the Gradio ecosystem. + +## Project Structure + +The Space component consists of a frontend Svelte layer and a backend template layer: + +- Frontend Svelte layer: Handles property pass-through, style concatenation, visibility control, and child node rendering. +- Backend template layer: Generates the final React wrapper, handling slot ordering, ReactSlot rendering, and Portal bridging. + +```mermaid +graph TB +subgraph "Frontend Svelte Layer" +IDX["Index.svelte
Standard Space Entry"] +COMPACT_IDX["compact/Index.svelte
Compact Space Entry"] +SPACE_TSX["space.tsx
Standard Space React Wrapper"] +COMPACT_TSX["compact/space.compact.tsx
Compact Space React Wrapper"] +end +subgraph "Backend Template Layer" +RT_SPACE["space-BWI0-XH7.js
Standard Space Template"] +RT_COMPACT["space.compact-C2LVtCsM.js
Compact Space Template"] +end +IDX --> SPACE_TSX --> RT_SPACE +COMPACT_IDX --> COMPACT_TSX --> RT_COMPACT +``` + +**Diagram Sources** + +- [frontend/antd/space/Index.svelte:1-61](file://frontend/antd/space/Index.svelte#L1-L61) +- [frontend/antd/space/space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js:651-679](file://backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js#L651-L679) +- [frontend/antd/space/compact/Index.svelte:1-60](file://frontend/antd/space/compact/Index.svelte#L1-L60) +- [frontend/antd/space/compact/space.compact.tsx:1-24](file://frontend/antd/space/compact/space.compact.tsx#L1-L24) +- [backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js:651-674](file://backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js#L651-L674) + +**Section Sources** + +- [frontend/antd/space/Index.svelte:1-61](file://frontend/antd/space/Index.svelte#L1-L61) +- [frontend/antd/space/compact/Index.svelte:1-60](file://frontend/antd/space/compact/Index.svelte#L1-L60) +- [docs/components/antd/space/README.md:1-8](file://docs/components/antd/space/README.md#L1-L8) +- [docs/components/antd/space/README-zh_CN.md:1-8](file://docs/components/antd/space/README-zh_CN.md#L1-L8) + +## Core Components + +- Standard Space: Responsible for automatically collecting child nodes, injecting separator slots, rendering children in order, and supporting direction, size, and alignment configuration. +- Compact Space (Space.Compact): In compact mode, reduces default spacing and emphasizes tight arrangement of adjacent elements, suitable for dense layouts such as toolbars and button groups. + +Both variants dynamically load the corresponding React wrapper via Svelte's `importComponent`, and pass slots and additional props to the underlying React component. + +**Section Sources** + +- [frontend/antd/space/space.tsx:7-26](file://frontend/antd/space/space.tsx#L7-L26) +- [frontend/antd/space/compact/space.compact.tsx:7-21](file://frontend/antd/space/compact/space.compact.tsx#L7-L21) +- [frontend/antd/space/Index.svelte:10-60](file://frontend/antd/space/Index.svelte#L10-L60) +- [frontend/antd/space/compact/Index.svelte:10-60](file://frontend/antd/space/compact/Index.svelte#L10-L60) + +## Architecture Overview + +The Space call chain runs from Svelte to React and back to the DOM, involving slot resolution, child node ordering, and Portal bridging. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Component (Index.svelte)" +participant Loader as "importComponent" +participant ReactWrap as "React Wrapper (space.tsx or space.compact.tsx)" +participant BackendRT as "Backend Template (space-BWI0-XH7.js / space.compact-C2LVtCsM.js)" +participant Antd as "Ant Design Space/Space.Compact" +Svelte->>Loader : Load corresponding React wrapper +Loader-->>Svelte : Return React component +Svelte->>ReactWrap : Pass props and slots +ReactWrap->>BackendRT : Convert children to ReactSlot +BackendRT->>Antd : Render Space/Space.Compact and inject child nodes +Antd-->>Svelte : Output final DOM structure +``` + +**Diagram Sources** + +- [frontend/antd/space/Index.svelte:10-60](file://frontend/antd/space/Index.svelte#L10-L60) +- [frontend/antd/space/space.tsx:7-26](file://frontend/antd/space/space.tsx#L7-L26) +- [backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js:651-679](file://backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js#L651-L679) +- [frontend/antd/space/compact/Index.svelte:10-60](file://frontend/antd/space/compact/Index.svelte#L10-L60) +- [frontend/antd/space/compact/space.compact.tsx:7-21](file://frontend/antd/space/compact/space.compact.tsx#L7-L21) +- [backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js:651-674](file://backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js#L651-L674) + +## Detailed Component Analysis + +### Standard Space Component + +- Automatic child node collection: Parses children via utility functions, converting them to ReactSlots with controllable ordering and cloning strategy. +- Separator slot: Supports injecting a separator via `slots.split`; falls back to `props.split` if not provided. +- Property pass-through: All props except internal ones are passed through to Ant Design Space, maintaining API compatibility with the native component. + +```mermaid +flowchart TD +Start(["Enter Space Render"]) --> Collect["Collect children and resolve to targets"] +Collect --> SplitCheck{"Is split slot provided?"} +SplitCheck --> |Yes| UseSlot["Use ReactSlot for slots.split"] +SplitCheck --> |No| UseProp["Use props.split"] +UseSlot --> Render["Iterate targets and render each ReactSlot"] +UseProp --> Render +Render --> End(["Render Complete"]) +``` + +**Diagram Sources** + +- [frontend/antd/space/space.tsx:8-25](file://frontend/antd/space/space.tsx#L8-L25) +- [backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js:656-673](file://backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js#L656-L673) + +**Section Sources** + +- [frontend/antd/space/space.tsx:7-26](file://frontend/antd/space/space.tsx#L7-L26) +- [backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js:651-679](file://backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js#L651-L679) + +### Compact Space Component + +- Compact mode: Uses Ant Design's Space.Compact to reduce default spacing, suitable for button groups, toolbars, and other densely packed layouts. +- Child node handling: Similar to the standard Space — hides original children first, then renders each one as a ReactSlot, ensuring consistent slot ordering and cloning strategy. + +```mermaid +flowchart TD +StartC(["Enter Space.Compact Render"]) --> Targets["Resolve children into target node array"] +Targets --> RenderC["Render each ReactSlot and inject into Compact container"] +RenderC --> EndC(["Render Complete"]) +``` + +**Diagram Sources** + +- [frontend/antd/space/compact/space.compact.tsx:8-20](file://frontend/antd/space/compact/space.compact.tsx#L8-L20) +- [backend/modelspace_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js:651-669](file://backend/modelspace_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js#L651-L669) + +**Section Sources** + +- [frontend/antd/space/compact/space.compact.tsx:7-21](file://frontend/antd/space/compact/space.compact.tsx#L7-L21) +- [backend/modelspace_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js:651-674](file://backend/modelspace_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js#L651-L674) + +### Svelte-to-React Bridging Mechanism + +- Slot ordering: Performs stable sorting of child nodes by `slotIndex` and `subSlotIndex`, ensuring consistent render order. +- Portal bridging: Clones Svelte slot content and mounts it into the React environment while preserving event listeners and styles. +- Visibility and styles: The Svelte layer concatenates `className` and inline styles, which are ultimately injected into the React component. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte (Index.svelte)" +participant SlotSort as "Slot Ordering" +participant Bridge as "Portal Bridging" +participant React as "React Wrapper" +participant DOM as "Antd Space/Space.Compact" +Svelte->>SlotSort : Retrieve and sort slots +SlotSort-->>Bridge : Return ordered portalTargets +Bridge->>React : Generate ReactSlots and clone nodes +React->>DOM : Render final DOM +``` + +**Diagram Sources** + +- [frontend/antd/space/Index.svelte:44-60](file://frontend/antd/space/Index.svelte#L44-L60) +- [backend/modelspace_studio/components/antd/space/templates/component/space-BWI0-XH7.js:642-650](file://backend/modelspace_studio/components/antd/space/templates/component/space-BWI0-XH7.js#L642-L650) +- [frontend/antd/space/compact/Index.svelte:43-60](file://frontend/antd/space/compact/Index.svelte#L43-L60) +- [backend/modelspace_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js:642-650](file://backend/modelspace_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js#L642-L650) + +**Section Sources** + +- [frontend/antd/space/Index.svelte:10-60](file://frontend/antd/space/Index.svelte#L10-L60) +- [frontend/antd/space/compact/Index.svelte:10-60](file://frontend/antd/space/compact/Index.svelte#L10-L60) +- [backend/modelspace_studio/components/antd/space/templates/component/space-BWI0-XH7.js:642-650](file://backend/modelspace_studio/components/antd/space/templates/component/space-BWI0-XH7.js#L642-L650) +- [backend/modelspace_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js:642-650](file://backend/modelspace_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js#L642-L650) + +## Dependency Analysis + +- Component coupling: Space and Space.Compact share the same bridging logic in the frontend layer, differing only in the underlying Ant Design component used. +- External dependencies: Depends on Ant Design's Space/Space.Compact; slot and ReactSlot support is provided by `@svelte-preprocess-react`. +- Backend template: The template layer converts Svelte's slot ordering and Portal bridging logic into executable React code. + +```mermaid +graph LR +Svelte_Index["Index.svelte"] --> React_Space["space.tsx"] +Svelte_Compact["compact/Index.svelte"] --> React_Compact["compact/space.compact.tsx"] +React_Space --> RT_Space["space-BWI0-XH7.js"] +React_Compact --> RT_Compact["space.compact-C2LVtCsM.js"] +RT_Space --> Antd["Ant Design Space"] +RT_Compact --> AntdCompact["Ant Design Space.Compact"] +``` + +**Diagram Sources** + +- [frontend/antd/space/Index.svelte:10-60](file://frontend/antd/space/Index.svelte#L10-L60) +- [frontend/antd/space/space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [backend/modelspace_studio/components/antd/space/templates/component/space-BWI0-XH7.js:651-679](file://backend/modelspace_studio/components/antd/space/templates/component/space-BWI0-XH7.js#L651-L679) +- [frontend/antd/space/compact/Index.svelte:10-60](file://frontend/antd/space/compact/Index.svelte#L10-L60) +- [frontend/antd/space/compact/space.compact.tsx:1-24](file://frontend/antd/space/compact/space.compact.tsx#L1-L24) +- [backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js:651-674](file://backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js#L651-L674) + +**Section Sources** + +- [frontend/antd/space/space.tsx:1-29](file://frontend/antd/space/space.tsx#L1-L29) +- [frontend/antd/space/compact/space.compact.tsx:1-24](file://frontend/antd/space/compact/space.compact.tsx#L1-L24) +- [backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js:651-679](file://backend/modelscope_studio/components/antd/space/templates/component/space-BWI0-XH7.js#L651-L679) +- [backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js:651-674](file://backend/modelscope_studio/components/antd/space/compact/templates/component/space.compact-C2LVtCsM.js#L651-L674) + +## Performance Considerations + +- Child node cloning and Portal: Cloning and Portal mounting avoid direct DOM manipulation, but be aware of rendering costs when there are many child nodes. +- Slot ordering stability: Index-based sorting remains stable even with large datasets, but it is recommended to minimize unnecessary slot changes to reduce reflow overhead. +- SSR and Hugging Face Space: In certain deployment environments, SSR must be disabled to avoid custom component compatibility issues, which affects initial render time. Optimize resource loading at build time. + +[This section contains general performance advice and does not directly analyze specific files] + +## Troubleshooting Guide + +- Child nodes not rendering correctly: Check whether the Svelte layer is properly passing `slots` and `children`; verify that `slotIndex` and `subSlotIndex` are set correctly. +- Separator not taking effect: Confirm whether the `split` slot is correctly passed, or whether `props.split` is provided as expected. +- SSR compatibility issues: When encountering UI anomalies in Hugging Face Space, try adding `ssr_mode=False` to `demo.launch`. + +**Section Sources** + +- [frontend/antd/space/space.tsx:15-17](file://frontend/antd/space/space.tsx#L15-L17) +- [docs/components/antd/space/README.md:1-8](file://docs/components/antd/space/README.md#L1-L8) +- [docs/components/antd/space/README-zh_CN.md:1-8](file://docs/components/antd/space/README-zh_CN.md#L1-L8) + +## Conclusion + +The Space component achieves seamless integration of Ant Design Space/Space.Compact in the Gradio ecosystem through Svelte–React bridging. Standard Space is suitable for general layouts, while Space.Compact is better suited for scenarios requiring tight element arrangement. With slot ordering and Portal bridging, the component maintains good maintainability and consistency even in complex layouts. + +[This section contains summary content and does not directly analyze specific files] + +## Appendix + +- Usage examples: See the example tabs in the documentation directory for basic usage demonstrations. +- Documentation entry: Documentation for both Standard Space and Compact Space is located under `docs/components/antd/space`. + +**Section Sources** + +- [docs/components/antd/space/README.md:5-8](file://docs/components/antd/space/README.md#L5-L8) +- [docs/components/antd/space/README-zh_CN.md:5-8](file://docs/components/antd/space/README-zh_CN.md#L5-L8) diff --git a/.wiki/en/Ant Design Components/Layout Components/Splitter.md b/.wiki/en/Ant Design Components/Layout Components/Splitter.md new file mode 100644 index 00000000..2ca8ba7d --- /dev/null +++ b/.wiki/en/Ant Design Components/Layout Components/Splitter.md @@ -0,0 +1,387 @@ +# Splitter + + +**Files Referenced in This Document** +- [frontend/antd/splitter/Index.svelte](file://frontend/antd/splitter/Index.svelte) +- [frontend/antd/splitter/splitter.tsx](file://frontend/antd/splitter/splitter.tsx) +- [frontend/antd/splitter/panel/Index.svelte](file://frontend/antd/splitter/panel/Index.svelte) +- [frontend/antd/splitter/panel/splitter.panel.tsx](file://frontend/antd/splitter/panel/splitter.panel.tsx) +- [frontend/antd/splitter/context.ts](file://frontend/antd/splitter/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [backend/modelscope_studio/components/antd/splitter/panel/__init__.py](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py) +- [docs/components/antd/splitter/README.md](file://docs/components/antd/splitter/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +Splitter is a panel-splitting component based on Ant Design that divides the interface into multiple resizable areas via drag handles. It supports both horizontal and vertical orientations and uses the Panel sub-component for declarative panel organization. The component is widely applicable to scenarios such as code editors (left-right layout), image comparison (left-right or top-bottom), and multi-view side-by-side displays. + +This document provides a systematic explanation of the component's architecture design, data flow, drag-and-resize controls, responsive behavior, interaction experience, styling, and accessibility, along with typical usage examples and best practice recommendations. + +## Project Structure + +Splitter adopts a Svelte + React Slot bridging approach on the frontend, while the backend encapsulates properties and rendering logic via Python components. Key files are distributed as follows: + +- Frontend entry and bridging: `frontend/antd/splitter/Index.svelte` +- Splitter container implementation: `frontend/antd/splitter/splitter.tsx` +- Panel sub-component bridging: `frontend/antd/splitter/panel/Index.svelte` +- Panel sub-component implementation: `frontend/antd/splitter/panel/splitter.panel.tsx` +- Context and item management: `frontend/antd/splitter/context.ts`, `frontend/utils/createItemsContext.tsx` +- Backend Panel component wrapper: `backend/modelscope_studio/components/antd/splitter/panel/__init__.py` +- Documentation and examples entry: `docs/components/antd/splitter/README.md` + +```mermaid +graph TB +subgraph "Frontend (Svelte)" +A["Index.svelte
Entry Bridging"] +B["splitter.tsx
Splitter Container"] +C["panel/Index.svelte
Panel Bridging"] +D["panel/splitter.panel.tsx
Panel Implementation"] +E["context.ts
Items Context"] +F["createItemsContext.tsx
Generic Item Context Utility"] +end +subgraph "Backend (Python)" +G["panel/__init__.py
AntdSplitterPanel Wrapper"] +end +A --> B +A --> C +C --> D +B --> E +D --> E +E --> F +G --> C +``` + +Diagram Sources + +- [frontend/antd/splitter/Index.svelte:1-71](file://frontend/antd/splitter/Index.svelte#L1-L71) +- [frontend/antd/splitter/splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [frontend/antd/splitter/panel/Index.svelte:1-77](file://frontend/antd/splitter/panel/Index.svelte#L1-L77) +- [frontend/antd/splitter/panel/splitter.panel.tsx:1-14](file://frontend/antd/splitter/panel/splitter.panel.tsx#L1-L14) +- [frontend/antd/splitter/context.ts:1-7](file://frontend/antd/splitter/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [backend/modelscope_studio/components/antd/splitter/panel/**init**.py:1-85](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L1-L85) + +Section Sources + +- [frontend/antd/splitter/Index.svelte:1-71](file://frontend/antd/splitter/Index.svelte#L1-L71) +- [frontend/antd/splitter/splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [frontend/antd/splitter/panel/Index.svelte:1-77](file://frontend/antd/splitter/panel/Index.svelte#L1-L77) +- [frontend/antd/splitter/panel/splitter.panel.tsx:1-14](file://frontend/antd/splitter/panel/splitter.panel.tsx#L1-L14) +- [frontend/antd/splitter/context.ts:1-7](file://frontend/antd/splitter/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [backend/modelscope_studio/components/antd/splitter/panel/**init**.py:1-85](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L1-L85) +- [docs/components/antd/splitter/README.md:1-8](file://docs/components/antd/splitter/README.md#L1-L8) + +## Core Components + +- Splitter Container: Receives the collection of child panels, renders the Ant Design split container, and maps each Panel to an Antd Panel child item. +- Panel Sub-component: Serves as the placeholder and rendering unit for each panel, collecting panel properties and slot content via the Items context and injecting them into Splitter. +- Items Context: Provides "item collection" capability, allowing Panel to inject its own properties and DOM content into Splitter during rendering. +- Backend Wrapper: Python-layer `AntdSplitterPanel` declares and passes properties such as default size, min/max size, collapsibility, and resizability. + +Section Sources + +- [frontend/antd/splitter/splitter.tsx:7-35](file://frontend/antd/splitter/splitter.tsx#L7-L35) +- [frontend/antd/splitter/panel/splitter.panel.tsx:7-11](file://frontend/antd/splitter/panel/splitter.panel.tsx#L7-L11) +- [frontend/antd/splitter/context.ts:3-4](file://frontend/antd/splitter/context.ts#L3-L4) +- [frontend/utils/createItemsContext.tsx:97-184](file://frontend/utils/createItemsContext.tsx#L97-L184) +- [backend/modelscope_studio/components/antd/splitter/panel/**init**.py:8-68](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L8-L68) + +## Architecture Overview + +The Splitter runtime flow is as follows: + +- The Svelte entry bridging component loads the Splitter and Panel components; +- Panel writes its own properties and slot content to the Items context via ItemHandler; +- Splitter is wrapped with `withItemsContextProvider` and reads the collected panel list from the context; +- Finally, Ant Design's Splitter and Panel are rendered. + +```mermaid +sequenceDiagram +participant U as "User" +participant S as "Splitter.Index.svelte" +participant P as "Panel.Index.svelte" +participant IH as "ItemHandler (splt.panel.tsx)" +participant CTX as "ItemsContext (context.ts)" +participant RCTX as "createItemsContext.tsx" +participant C as "Antd Splitter" +U->>S : Render Splitter +S->>RCTX : Initialize Items context +U->>P : Render Panel +P->>IH : Create ItemHandler +IH->>CTX : setItem(..., index, item) +CTX-->>S : Context change callback +S->>C : Render Antd Splitter +C-->>U : Draggable split panels +``` + +Diagram Sources + +- [frontend/antd/splitter/Index.svelte:10-52](file://frontend/antd/splitter/Index.svelte#L10-L52) +- [frontend/antd/splitter/panel/Index.svelte:10-69](file://frontend/antd/splitter/panel/Index.svelte#L10-L69) +- [frontend/antd/splitter/panel/splitter.panel.tsx:7-11](file://frontend/antd/splitter/panel/splitter.panel.tsx#L7-L11) +- [frontend/antd/splitter/context.ts:3-4](file://frontend/antd/splitter/context.ts#L3-L4) +- [frontend/utils/createItemsContext.tsx:108-170](file://frontend/utils/createItemsContext.tsx#L108-L170) +- [frontend/antd/splitter/splitter.tsx:7-35](file://frontend/antd/splitter/splitter.tsx#L7-L35) + +## Detailed Component Analysis + +### Splitter Container Component + +- Responsibility boundary: Maps collected panel items to Ant Design Panel elements and renders the split container. +- Key points: + - Wrapped with `withItemsContextProvider` to ensure it can read `items` injected by Panels. + - Renders slot content to the corresponding Panel via ReactSlot. + - When no panels are present, nothing is rendered, avoiding layout issues caused by empty containers. + +```mermaid +flowchart TD +Start(["Enter Splitter"]) --> Read["Read context items"] +Read --> HasPanels{"Are there panels?"} +HasPanels -- No --> Exit["Return empty"] +HasPanels -- Yes --> Render["Iterate panels and render Antd Panel"] +Render --> Done(["Complete"]) +``` + +Diagram Sources + +- [frontend/antd/splitter/splitter.tsx:8-35](file://frontend/antd/splitter/splitter.tsx#L8-L35) + +Section Sources + +- [frontend/antd/splitter/splitter.tsx:7-35](file://frontend/antd/splitter/splitter.tsx#L7-L35) + +### Panel Sub-component + +- Responsibility boundary: Serves as the placeholder and rendering unit for a single panel, responsible for injecting its own properties and slot content into the Items context. +- Key points: + - Writes `itemIndex`, `itemSlotKey`, `itemElement`, and other information to the context via `ItemHandler`. + - Supports `visible` for display control; supports additional property pass-through and style class binding. + - Slot content is collected via the Svelte slot mechanism and rendered in Splitter as ReactSlot. + +```mermaid +classDiagram +class PanelBridge { ++props : all pass-through properties ++visible : visibility flag ++_internal.index : panel index ++elem_id/ elem_classes/ elem_style : styles and identifiers ++slots : slot content +} +class ItemHandler { ++itemIndex : number ++itemSlotKey : string ++itemElement : HTMLElement ++setItem(...) +} +PanelBridge --> ItemHandler : "Inject item" +``` + +Diagram Sources + +- [frontend/antd/splitter/panel/Index.svelte:25-69](file://frontend/antd/splitter/panel/Index.svelte#L25-L69) +- [frontend/antd/splitter/panel/splitter.panel.tsx:7-11](file://frontend/antd/splitter/panel/splitter.panel.tsx#L7-L11) +- [frontend/antd/splitter/context.ts:3-4](file://frontend/antd/splitter/context.ts#L3-L4) + +Section Sources + +- [frontend/antd/splitter/panel/Index.svelte:14-69](file://frontend/antd/splitter/panel/Index.svelte#L14-L69) +- [frontend/antd/splitter/panel/splitter.panel.tsx:7-11](file://frontend/antd/splitter/panel/splitter.panel.tsx#L7-L11) +- [frontend/antd/splitter/context.ts:3-4](file://frontend/antd/splitter/context.ts#L3-L4) + +### Items Context and Item Collection Mechanism + +- Purpose: Establishes an "item collection" channel in the component tree, enabling Panel to write its own properties and DOM content into Splitter. +- Key points: + - `withItemsContextProvider`: Provides an `ItemsContextProvider` for the component tree, maintaining an `items` map and a `setItem` method. + - `useItems`: Reads the `items` list within Splitter. + - `ItemHandler`: Writes items during Panel rendering, supporting `itemProps`, `itemChildren`, and other extended capabilities. + +```mermaid +sequenceDiagram +participant P as "Panel" +participant IH as "ItemHandler" +participant CTX as "ItemsContext" +participant SP as "Splitter" +P->>IH : Call ItemHandler +IH->>CTX : setItem(slotKey, index, item) +CTX-->>SP : Trigger onChange callback +SP->>SP : Update internal items and re-render +``` + +Diagram Sources + +- [frontend/utils/createItemsContext.tsx:108-170](file://frontend/utils/createItemsContext.tsx#L108-L170) +- [frontend/utils/createItemsContext.tsx:186-261](file://frontend/utils/createItemsContext.tsx#L186-L261) +- [frontend/antd/splitter/splitter.tsx:8-11](file://frontend/antd/splitter/splitter.tsx#L8-L11) + +Section Sources + +- [frontend/utils/createItemsContext.tsx:97-184](file://frontend/utils/createItemsContext.tsx#L97-L184) +- [frontend/utils/createItemsContext.tsx:186-261](file://frontend/utils/createItemsContext.tsx#L186-L261) +- [frontend/antd/splitter/context.ts:3-4](file://frontend/antd/splitter/context.ts#L3-L4) + +### Backend Wrapper and Property Passing + +- `AntdSplitterPanel` provides the following key properties (from the Python wrapper): + - `default_size`: Default panel size + - `min` / `max`: Minimum/maximum size + - `size`: Current size + - `collapsible`: Whether the panel is collapsible + - `resizable`: Whether the panel is resizable + - `elem_id` / `elem_classes` / `elem_style`: Styles and identifiers +- These properties are passed through the Svelte bridging layer to frontend components, ultimately affecting the behavior and appearance of Ant Design Splitter. + +Section Sources + +- [backend/modelscope_studio/components/antd/splitter/panel/**init**.py:8-68](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L8-L68) + +## Dependency Analysis + +- Component coupling: + - Splitter depends on the Items context to obtain the panel collection. + - Panel depends on the Items context via ItemHandler to write its own item. + - The frontend bridging layer (Index.svelte) is responsible for passing properties and slots to React components. +- External dependencies: + - Ant Design's Splitter/Panel interface. + - Svelte Preprocess React toolchain (`sveltify`, `ReactSlot`, `processProps`, etc.). +- Potential circular dependencies: + - Decoupled through context and callbacks to avoid circular references caused by direct mutual referencing. + +```mermaid +graph LR +IDX["Index.svelte"] --> SPLIT["splitter.tsx"] +IDX --> PANEL_IDX["panel/Index.svelte"] +PANEL_IDX --> PANEL_IMPL["panel/splitter.panel.tsx"] +SPLIT --> CTX["context.ts"] +PANEL_IMPL --> CTX +CTX --> UTILS["createItemsContext.tsx"] +``` + +Diagram Sources + +- [frontend/antd/splitter/Index.svelte:10-52](file://frontend/antd/splitter/Index.svelte#L10-L52) +- [frontend/antd/splitter/splitter.tsx:5-6](file://frontend/antd/splitter/splitter.tsx#L5-L6) +- [frontend/antd/splitter/panel/Index.svelte:10-11](file://frontend/antd/splitter/panel/Index.svelte#L10-L11) +- [frontend/antd/splitter/panel/splitter.panel.tsx:5-5](file://frontend/antd/splitter/panel/splitter.panel.tsx#L5-L5) +- [frontend/antd/splitter/context.ts:3-4](file://frontend/antd/splitter/context.ts#L3-L4) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +Section Sources + +- [frontend/antd/splitter/Index.svelte:1-71](file://frontend/antd/splitter/Index.svelte#L1-L71) +- [frontend/antd/splitter/splitter.tsx:1-38](file://frontend/antd/splitter/splitter.tsx#L1-L38) +- [frontend/antd/splitter/panel/Index.svelte:1-77](file://frontend/antd/splitter/panel/Index.svelte#L1-L77) +- [frontend/antd/splitter/panel/splitter.panel.tsx:1-14](file://frontend/antd/splitter/panel/splitter.panel.tsx#L1-L14) +- [frontend/antd/splitter/context.ts:1-7](file://frontend/antd/splitter/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +## Performance Considerations + +- Rendering strategy + - Splitter only renders the container when panels are present, avoiding the overhead of empty renders. + - `useMemoizedEqualValue` and `useMemoizedFn` reduce context update frequency and repeated renders. +- Events and state + - `setItem` and `onChange` are triggered only when values change, reducing unnecessary re-renders. +- Recommendations + - For scenarios with many panels or frequent size adjustments, limit the number of panels and update frequency. + - Set reasonable min/max sizes to avoid reflow jitter caused by extreme sizes. + +Section Sources + +- [frontend/antd/splitter/splitter.tsx:15-31](file://frontend/antd/splitter/splitter.tsx#L15-L31) +- [frontend/utils/createItemsContext.tsx:113-153](file://frontend/utils/createItemsContext.tsx#L113-L153) +- [frontend/utils/createItemsContext.tsx:234-254](file://frontend/utils/createItemsContext.tsx#L234-L254) + +## Troubleshooting Guide + +- Panel not displaying + - Check whether Panel's `visible` is true; confirm that the bridging layer has correctly passed `visible`. + - Confirm whether Panel has successfully written to the Items context (check `setItem` calls and indices). +- Drag not working + - Confirm that `resizable` and resizable direction settings are correct; check Ant Design version and whether styles are complete. +- Size anomalies + - Check whether `min`/`max` and `default_size` settings are reasonable; avoid setting them to 0 or negative values. +- Slot content not rendering + - Confirm that Panel's slot bindings are consistent with ReactSlot usage; avoid premature slot destruction. + +Section Sources + +- [frontend/antd/splitter/panel/Index.svelte:52-69](file://frontend/antd/splitter/panel/Index.svelte#L52-L69) +- [frontend/antd/splitter/splitter.tsx:14-31](file://frontend/antd/splitter/splitter.tsx#L14-L31) +- [backend/modelscope_studio/components/antd/splitter/panel/**init**.py:62-66](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L62-L66) + +## Conclusion + +Splitter achieves flexible panel organization and rendering through the Items context and Svelte/React bridging. Its core strengths are: + +- User-facing declarative API (Panel sub-component) +- Deep integration with Ant Design (drag, direction, size control) +- Extensible item collection mechanism (supports dynamic add/remove/update) + +In practice, it is recommended to set reasonable size constraints and interaction behaviors based on business scenarios, with attention to performance and maintainability. + +## Appendix + +### Configuration and Property Reference + +- Splitter Container + - Direction: Controlled by Ant Design's direction property (horizontal/vertical) + - Drag: Provided by Ant Design's drag capability + - Events: `resizeStart`/`resizeEnd` (mapped via bridging layer) +- Panel Sub-component + - `default_size` / `size`: Default/current size + - `min` / `max`: Minimum/maximum size + - `collapsible` / `resizable`: Collapsible/resizable + - `elem_id` / `elem_classes` / `elem_style`: Styles and identifiers + - `visible`: Visibility flag + +Section Sources + +- [frontend/antd/splitter/Index.svelte:25-52](file://frontend/antd/splitter/Index.svelte#L25-L52) +- [frontend/antd/splitter/splitter.tsx:16-30](file://frontend/antd/splitter/splitter.tsx#L16-L30) +- [backend/modelscope_studio/components/antd/splitter/panel/**init**.py:61-66](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L61-L66) + +### Application Scenario Examples + +- Code editor: File tree/outline on the left, code editing area on the right, with left-right drag to adjust width. +- Image comparison: Two images arranged left-right or top-bottom, with drag to adjust the ratio. +- Multi-view display: Three-column layout (left/center/right), center as main view, sides as tool/preview panels. + +Section Sources + +- [docs/components/antd/splitter/README.md:1-8](file://docs/components/antd/splitter/README.md#L1-L8) + +### Responsive Behavior and Interaction Experience + +- Responsive behavior: Adapts panel ratios based on container width/height; it is recommended to enable collapsibility on small-screen devices. +- Interaction experience: Provides visual feedback during dragging; set reasonable minimum sizes to avoid accidental triggers. + +Section Sources + +- [backend/modelscope_studio/components/antd/splitter/panel/**init**.py:14-16](file://backend/modelscope_studio/components/antd/splitter/panel/__init__.py#L14-L16) + +### Style Customization and Accessibility + +- Style customization: Inject custom styles via `elem_classes` and `elem_style`; note compatibility with Ant Design default styles. +- Animation effects: Combine CSS transitions or third-party animation libraries for smooth size switching. +- Accessibility: Provide accessible labels and keyboard operation hints for drag handles; ensure collapsible states have clear ARIA attributes. + +Section Sources + +- [frontend/antd/splitter/panel/Index.svelte:54-55](file://frontend/antd/splitter/panel/Index.svelte#L54-L55) +- [frontend/antd/splitter/splitter.tsx:16-30](file://frontend/antd/splitter/splitter.tsx#L16-L30) diff --git a/.wiki/en/Ant Design Components/Navigation Components/Anchor.md b/.wiki/en/Ant Design Components/Navigation Components/Anchor.md new file mode 100644 index 00000000..0ccd423e --- /dev/null +++ b/.wiki/en/Ant Design Components/Navigation Components/Anchor.md @@ -0,0 +1,302 @@ +# Anchor + + +**Files Referenced in This Document** +- [frontend/antd/anchor/Index.svelte](file://frontend/antd/anchor/Index.svelte) +- [frontend/antd/anchor/anchor.tsx](file://frontend/antd/anchor/anchor.tsx) +- [frontend/antd/anchor/context.ts](file://frontend/antd/anchor/context.ts) +- [frontend/antd/anchor/item/Index.svelte](file://frontend/antd/anchor/item/Index.svelte) +- [frontend/antd/anchor/item/anchor.item.tsx](file://frontend/antd/anchor/item/anchor.item.tsx) +- [backend/modelscope_studio/components/antd/anchor/__init__.py](file://backend/modelscope_studio/components/antd/anchor/__init__.py) +- [backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js](file://backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js) +- [docs/components/antd/anchor/README.md](file://docs/components/antd/anchor/README.md) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The Anchor component provides clickable navigation links within a single page, supporting scroll-based positioning to corresponding headings or sections, and can be combined with fixed mode (Affix) to remain visible while the page scrolls. This component is a wrapper around Ant Design's Anchor component and provides the following capabilities: + +- Scroll positioning: Smooth or direct scrolling to target positions of anchor items +- Link generation: Supports dynamically generating anchor items via an `items` list or slots +- Active state management: Automatically highlights anchor items currently in the viewport +- Nested structure: Anchor items support nesting to form hierarchical navigation +- Events and extensions: Supports `change`, `click`, and `affix_change` event bindings, as well as Affix fixed mode + +## Project Structure + +The Anchor component consists of a frontend Svelte wrapper layer and a backend Gradio component layer, along with an anchor item sub-component to support nesting and slot rendering. + +```mermaid +graph TB +subgraph "Frontend" +A_Index["frontend/antd/anchor/Index.svelte"] +A_Component["frontend/antd/anchor/anchor.tsx"] +A_Context["frontend/antd/anchor/context.ts"] +A_Item_Index["frontend/antd/anchor/item/Index.svelte"] +A_Item_Component["frontend/antd/anchor/item/anchor.item.tsx"] +end +subgraph "Backend" +B_Anchor["backend/modelscope_studio/components/antd/anchor/__init__.py"] +B_Item_Template["backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js"] +end +subgraph "Documentation" +D_Readme["docs/components/antd/anchor/README.md"] +end +A_Index --> A_Component +A_Component --> A_Context +A_Item_Index --> A_Item_Component +A_Component --> B_Anchor +A_Item_Component --> B_Item_Template +D_Readme --> B_Anchor +``` + +Diagram Sources + +- [frontend/antd/anchor/Index.svelte:1-66](file://frontend/antd/anchor/Index.svelte#L1-L66) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) +- [frontend/antd/anchor/item/Index.svelte:1-75](file://frontend/antd/anchor/item/Index.svelte#L1-L75) +- [frontend/antd/anchor/item/anchor.item.tsx:1-22](file://frontend/antd/anchor/item/anchor.item.tsx#L1-L22) +- [backend/modelscope_studio/components/antd/anchor/**init**.py:1-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L1-L117) +- [backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js:1-450](file://backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js#L1-L450) +- [docs/components/antd/anchor/README.md:1-8](file://docs/components/antd/anchor/README.md#L1-L8) + +Section Sources + +- [frontend/antd/anchor/Index.svelte:1-66](file://frontend/antd/anchor/Index.svelte#L1-L66) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) +- [frontend/antd/anchor/item/Index.svelte:1-75](file://frontend/antd/anchor/item/Index.svelte#L1-L75) +- [frontend/antd/anchor/item/anchor.item.tsx:1-22](file://frontend/antd/anchor/item/anchor.item.tsx#L1-L22) +- [backend/modelscope_studio/components/antd/anchor/**init**.py:1-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L1-L117) +- [backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js:1-450](file://backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js#L1-L450) +- [docs/components/antd/anchor/README.md:1-8](file://docs/components/antd/anchor/README.md#L1-L8) + +## Core Components + +- Top-level Anchor component (AntdAnchor) + - Receives an `items` list or slot children, converting them to the items structure required by Ant Design Anchor + - Supports `affix`, `bounds`, `offsetTop`, `direction`, `replace`, `rootClassName`, and other properties + - Provides `change`, `click`, and `affix_change` event binding entry points +- Anchor item component (AntdAnchorItem) + - Acts as the container for anchor items, supporting default slot content rendering + - Collaborates with the parent anchor component via the context system to achieve nesting and hierarchical display + +Section Sources + +- [backend/modelscope_studio/components/antd/anchor/**init**.py:11-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L11-L117) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) +- [frontend/antd/anchor/item/Index.svelte:1-75](file://frontend/antd/anchor/item/Index.svelte#L1-L75) +- [frontend/antd/anchor/item/anchor.item.tsx:1-22](file://frontend/antd/anchor/item/anchor.item.tsx#L1-L22) + +## Architecture Overview + +The following diagram shows the call chain from the backend Gradio component to the frontend Svelte/React wrapper layer and on to Ant Design Anchor, as well as the event and slot passing process. + +```mermaid +sequenceDiagram +participant Backend as "Backend Component
AntdAnchor" +participant FrontIndex as "Frontend Wrapper
Index.svelte" +participant AnchorTSX as "Frontend Implementation
anchor.tsx" +participant Context as "Context
context.ts" +participant Antd as "Ant Design Anchor" +Backend->>FrontIndex : Render wrapper component and pass props +FrontIndex->>AnchorTSX : Pass restProps, additionalProps, slots +AnchorTSX->>Context : Use Items context to resolve slots items/default +AnchorTSX->>Antd : Render Anchor and inject items, getContainer, getCurrentAnchor +Antd-->>AnchorTSX : Trigger change/click/affix_change event callbacks +AnchorTSX-->>FrontIndex : Pass events to backend +``` + +Diagram Sources + +- [frontend/antd/anchor/Index.svelte:1-66](file://frontend/antd/anchor/Index.svelte#L1-L66) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) +- [backend/modelscope_studio/components/antd/anchor/**init**.py:11-33](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L11-L33) + +## Detailed Component Analysis + +### Top-level Anchor Component (AntdAnchor) + +- Feature highlights + - Receives an `items` list or slot children; internally converts slots to items via utility functions + - Supports `getContainer` and `getCurrentAnchor` for custom container and current anchor determination logic + - Provides Affix fixed mode, `bounds` boundary distance, `offsetTop` top offset, `direction`, `replace` history replacement, and other configurations + - Events: `change` (anchor changed), `click` (clicked), `affix_change` (fixed state changed) +- Data flow + - Slots `items/default` → context resolution → Ant Design Anchor items + - `getContainer`/`getCurrentAnchor` are passed to Ant Design Anchor after being wrapped with `useFunction` +- Applicable scenarios + - Document tables of contents, long-list navigation, help centers, product introduction pages, and other scenarios requiring quick jumping + +```mermaid +flowchart TD +Start(["Start"]) --> Resolve["Resolve slots items/default"] +Resolve --> HasItems{"Are items params provided?"} +HasItems --> |Yes| UseParam["Use passed-in items"] +HasItems --> |No| RenderItems["Render items via utility functions"] +UseParam --> BuildProps["Build Anchor properties"] +RenderItems --> BuildProps +BuildProps --> Inject["Inject getContainer / getCurrentAnchor"] +Inject --> Render["Render Ant Design Anchor"] +Render --> End(["End"]) +``` + +Diagram Sources + +- [frontend/antd/anchor/anchor.tsx:13-42](file://frontend/antd/anchor/anchor.tsx#L13-L42) + +Section Sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [backend/modelscope_studio/components/antd/anchor/**init**.py:38-98](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L38-L98) + +### Anchor Item Component (AntdAnchorItem) + +- Feature highlights + - Acts as the container for anchor items, supporting default slot content rendering + - Maps slot content to AntdAnchor item children via `ItemHandler` + - Supports `href_target` property mapped to `target` attribute, for controlling link opening behavior +- Nested structure + - Cooperates with the parent via `createItemsContext` to support multi-level nested anchor items +- Applicable scenarios + - Grouping and hierarchically displaying sections in complex documents + +```mermaid +classDiagram +class AnchorItem { ++Allowed slot : "default" ++Property : "href_target" -> "target" ++Function : "Map slot content to item children" +} +class Context { ++useItems() ++withItemsContextProvider() ++ItemHandler +} +AnchorItem --> Context : "Use context" +``` + +Diagram Sources + +- [frontend/antd/anchor/item/anchor.item.tsx:1-22](file://frontend/antd/anchor/item/anchor.item.tsx#L1-L22) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) + +Section Sources + +- [frontend/antd/anchor/item/Index.svelte:1-75](file://frontend/antd/anchor/item/Index.svelte#L1-L75) +- [frontend/antd/anchor/item/anchor.item.tsx:1-22](file://frontend/antd/anchor/item/anchor.item.tsx#L1-L22) +- [backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js:437-449](file://backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js#L437-L449) + +### Events and Lifecycle + +- `change`: Triggered when the currently active anchor changes +- `click`: Triggered when an anchor link is clicked +- `affix_change`: Triggered when the Affix fixed mode state changes +- Lifecycle: The component updates the layout marker when it exits scope, ensuring correct render ordering + +Section Sources + +- [backend/modelscope_studio/components/antd/anchor/**init**.py:20-33](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L20-L33) +- [backend/modelscope_studio/utils/dev/component.py:24-26](file://backend/modelscope_studio/utils/dev/component.py#L24-L26) + +## Dependency Analysis + +- The frontend wrapper layer depends on Ant Design Anchor, bridged via `sveltify` and `withItemsContextProvider` +- The slot system implements parent-child component communication via `createItemsContext`, supporting both `items` and `default` slots +- The backend component inherits from `ModelScopeLayoutComponent`, providing unified layout and event binding capabilities + +```mermaid +graph LR +AnchorTSX["anchor.tsx"] --> Antd["Ant Design Anchor"] +AnchorTSX --> Context["context.ts"] +AnchorItemTSX["anchor.item.tsx"] --> Context +AnchorTSX --> Backend["AntdAnchor(__init__.py)"] +AnchorItemTSX --> BackendItem["anchor.item Template"] +``` + +Diagram Sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) +- [frontend/antd/anchor/item/anchor.item.tsx:1-22](file://frontend/antd/anchor/item/anchor.item.tsx#L1-L22) +- [backend/modelscope_studio/components/antd/anchor/**init**.py:1-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L1-L117) +- [backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js:1-450](file://backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js#L1-L450) + +Section Sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) +- [frontend/antd/anchor/item/anchor.item.tsx:1-22](file://frontend/antd/anchor/item/anchor.item.tsx#L1-L22) +- [backend/modelscope_studio/components/antd/anchor/**init**.py:1-117](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L1-L117) +- [backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js:1-450](file://backend/modelscope_studio/components/antd/anchor/item/templates/component/anchor.item-DRmYMecq.js#L1-L450) + +## Performance Considerations + +- items rendering optimization + - Use `useMemo` to cache items computation results, avoiding unnecessary re-renders + - Prefer passing the `items` parameter rather than relying on slots to reduce slot resolution costs +- Function wrapping + - Wrap `getContainer`/`getCurrentAnchor` with `useFunction` to ensure callbacks are stable and reusable +- Scroll monitoring + - Set `bounds` and `offsetTop` reasonably to avoid frequent `change` event triggers + - For large documents, consider using `replace` to replace history records, reducing memory usage +- Fixed mode (Affix) + - Affix mode keeps the component visible during scrolling; pay attention to container selection and z-index relationships to avoid occlusion + +## Troubleshooting Guide + +- Anchor not working + - Check whether `getContainer` points to the correct scroll container; if not set, the viewport may not be calculated correctly + - Confirm the target element exists and has the corresponding anchor identifier +- Active state not updating + - Check whether `bounds` and `offsetTop` settings are reasonable; too small a boundary may cause delayed switching + - Confirm the `getCurrentAnchor` return value matches the `key` or `href` in `items` +- Link opening behavior abnormal + - `href_target` maps to `target`; confirm whether it needs to open in a new window or the current window +- Events not triggering + - Confirm event bindings are enabled (`bind_change_event`, `bind_click_event`, `bind_affix_change_event`) + - Check whether state changes in Affix mode behave as expected + +Section Sources + +- [frontend/antd/anchor/anchor.tsx:13-42](file://frontend/antd/anchor/anchor.tsx#L13-L42) +- [backend/modelscope_studio/components/antd/anchor/**init**.py:20-33](file://backend/modelscope_studio/components/antd/anchor/__init__.py#L20-L33) + +## Conclusion + +The Anchor component provides flexible anchor navigation capabilities through frontend-backend collaboration. Its core strengths are: + +- Dual-channel anchor item generation via `items` and slots, meeting different scenario needs +- Deep integration with Ant Design Anchor, with comprehensive scroll positioning and active state management +- A complete event system that facilitates extended interactions and analytics tracking +- Support for nested structure and fixed mode, suitable for complex documents and long-page navigation + +## Appendix + +- Usage examples and documentation + - Refer to basic examples in the documentation for fundamental usage and parameter descriptions +- Common issues + - If the page has multiple scroll containers, explicitly specify `getContainer` + - For large documents, consider enabling `replace` to optimize history management + - To customize highlight strategy, use `getCurrentAnchor` for customization + +Section Sources + +- [docs/components/antd/anchor/README.md:1-8](file://docs/components/antd/anchor/README.md#L1-L8) diff --git a/.wiki/en/Ant Design Components/Navigation Components/Breadcrumb.md b/.wiki/en/Ant Design Components/Navigation Components/Breadcrumb.md new file mode 100644 index 00000000..36ceca66 --- /dev/null +++ b/.wiki/en/Ant Design Components/Navigation Components/Breadcrumb.md @@ -0,0 +1,393 @@ +# Breadcrumb + + +**Files Referenced in This Document** +- [frontend/antd/breadcrumb/breadcrumb.tsx](file://frontend/antd/breadcrumb/breadcrumb.tsx) +- [frontend/antd/breadcrumb/context.ts](file://frontend/antd/breadcrumb/context.ts) +- [frontend/antd/breadcrumb/Index.svelte](file://frontend/antd/breadcrumb/Index.svelte) +- [backend/modelscope_studio/components/antd/breadcrumb/__init__.py](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py) +- [backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) +- [docs/components/antd/breadcrumb/README.md](file://docs/components/antd/breadcrumb/README.md) +- [docs/components/antd/breadcrumb/README-zh_CN.md](file://docs/components/antd/breadcrumb/README-zh_CN.md) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +The Breadcrumb component displays the current location within a hierarchical structure and allows users to return to previous states. The breadcrumb component in this repository is based on Ant Design's Breadcrumb implementation, wrapped via React and bridged to the Svelte frontend, while also providing a Python backend component to support layout and event binding in the Gradio ecosystem. The component supports: + +- Navigation path display and click-to-navigate +- Custom separators and rendering of each breadcrumb item +- Advanced interactions such as dropdown menus and overflow indicators +- Dynamic path generation and permission control when integrating with routing systems +- Multi-language and theme style customization + +## Project Structure + +The Breadcrumb component consists of a frontend React wrapper layer, a Svelte bridging layer, a backend Gradio component layer, and a runtime template, organized as follows: + +```mermaid +graph TB +subgraph "Frontend" +SvelteIndex["frontend/antd/breadcrumb/Index.svelte"] +ReactWrapper["frontend/antd/breadcrumb/breadcrumb.tsx"] +ItemsCtx["frontend/antd/breadcrumb/context.ts"] +end +subgraph "Backend" +PyComp["backend/modelscope_studio/components/antd/breadcrumb/__init__.py"] +PyItem["backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py"] +DevBase["backend/modelscope_studio/utils/dev/component.py"] +ResolveDir["backend/modelscope_studio/utils/dev/resolve_frontend_dir.py"] +end +subgraph "Runtime Template" +RuntimeJS["backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js"] +end +SvelteIndex --> ReactWrapper +ReactWrapper --> ItemsCtx +PyComp --> ResolveDir +PyComp --> RuntimeJS +PyItem --> ResolveDir +PyItem --> RuntimeJS +DevBase --> PyComp +DevBase --> PyItem +``` + +Diagram Sources + +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:1-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L1-L73) +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:1-114](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L1-L114) +- [backend/modelscope_studio/utils/dev/component.py:1-169](file://backend/modelscope_studio/utils/dev/component.py#L1-L169) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:1-17](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L1-L17) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:1-766](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L1-L766) + +Section Sources + +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:1-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L1-L73) +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:1-114](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L1-L114) +- [backend/modelscope_studio/utils/dev/component.py:1-169](file://backend/modelscope_studio/utils/dev/component.py#L1-L169) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:1-17](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L1-L17) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:1-766](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L1-L766) + +## Core Components + +- Frontend React wrapper: Connects Ant Design's Breadcrumb with the Slots rendering system, supporting custom separators, item renderer functions, and dropdown icons. +- Svelte bridging: Converts backend-provided properties and slots into frontend-consumable props, and imports React components as needed. +- Backend components: Provides `AntdBreadcrumb` and `AntdBreadcrumbItem`, supporting event bindings, slots, and frontend directory resolution. +- Runtime template: Contains the actual React component implementation and slot handling logic. + +Section Sources + +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:1-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L1-L73) +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:1-114](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L1-L114) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:1-766](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L1-L766) + +## Architecture Overview + +The Breadcrumb component call chain from backend to frontend is as follows: + +```mermaid +sequenceDiagram +participant Py as "Python Backend Component
AntdBreadcrumb/AntdBreadcrumbItem" +participant Svelte as "Svelte Bridging
Index.svelte" +participant React as "React Wrapper
breadcrumb.tsx" +participant AD as "Ant Design Breadcrumb" +Py->>Svelte : Resolve frontend directory and pass properties/slots +Svelte->>React : Convert props and inject slots +React->>AD : Render Breadcrumb, apply custom separator/item renderer/dropdown icon +AD-->>React : Render result +React-->>Svelte : Return DOM +Svelte-->>Py : Render complete +``` + +Diagram Sources + +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:1-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L1-L73) +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:1-114](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L1-L114) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:1-766](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L1-L766) + +## Detailed Component Analysis + +### Frontend React Wrapper (breadcrumb.tsx) + +- Key points + - Uses `sveltify` to bridge the Svelte component to React. + - Provides breadcrumb item context via `withItemsContextProvider`. + - Supports slots: `separator`, `itemRender`, `dropdownIcon`; prefers slots, falls back to props. + - Uses `renderItems` to convert slot items into the `ItemType` list required by Ant Design. + - Uses `renderParamsSlot` to render the parameterized `itemRender` slot. +- Key flow + - Reads `items/default` from context. + - Computes the final items list (items takes priority over slots). + - Renders Ant Design Breadcrumb with injected custom separator and item renderer. + +```mermaid +flowchart TD +Start(["Enter React Wrapper"]) --> ReadCtx["Read context items/default"] +ReadCtx --> DecideItems{"Are items params provided?"} +DecideItems --> |Yes| UseParam["Use passed-in items"] +DecideItems --> |No| UseSlot["Use items/default slot"] +UseParam --> RenderItems["renderItems converts to AntD Item type"] +UseSlot --> RenderItems +RenderItems --> ApplySlots{"Do slots exist?"} +ApplySlots --> |separator| SepSlot["Use separator slot"] +ApplySlots --> |itemRender| ItemRenderSlot["Use itemRender slot"] +ApplySlots --> |dropdownIcon| DropSlot["Use dropdownIcon slot"] +ApplySlots --> |none| UseProps["Use original prop values"] +SepSlot --> RenderAD["Render AntD Breadcrumb"] +ItemRenderSlot --> RenderAD +DropSlot --> RenderAD +UseProps --> RenderAD +RenderAD --> End(["Complete"]) +``` + +Diagram Sources + +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:727-761](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L727-L761) + +Section Sources + +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:727-761](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L727-L761) + +### Svelte Bridging (Index.svelte) + +- Key points + - Retrieves backend-provided props and additional properties. + - Maps event names to camelCase as required by Ant Design. + - Renders `children` as child nodes of the React component. + - Asynchronously loads the React-wrapped Breadcrumb via `importComponent`. +- Key flow + - `processProps` normalizes properties and handles event aliases. + - `getSlots` retrieves the set of slots. + - Renders Breadcrumb and passes in slots and children. + +```mermaid +sequenceDiagram +participant Svelte as "Index.svelte" +participant Loader as "importComponent" +participant Wrapper as "breadcrumb.tsx" +Svelte->>Loader : Load React wrapper component +Loader-->>Svelte : Return component reference +Svelte->>Wrapper : Pass props/slots/children +Wrapper-->>Svelte : Return render result +``` + +Diagram Sources + +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) + +Section Sources + +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) + +### Backend Components (AntdBreadcrumb / AntdBreadcrumbItem) + +- AntdBreadcrumb + - Supported slots: `separator`, `itemRender`, `items`, `dropdownIcon`. + - Points to the frontend breadcrumb directory via `resolve_frontend_dir`. + - Inherits `ModelScopeLayoutComponent` with general layout component capabilities. +- AntdBreadcrumbItem + - Supported slots: `title`, `menu.*`, `dropdownProps.*`, `dropdownProps.menu.*`. + - Supports events: `click`, `menu_*`, `dropdownProps_*`, etc., for interacting with routes or menus. + - Points to the frontend breadcrumb/item sub-component directory via `resolve_frontend_dir`. + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++skip_api : bool ++SLOTS : list ++__init__(...) +} +class AntdBreadcrumb { ++SLOTS : list ++FRONTEND_DIR : str ++__init__(...) +} +class AntdBreadcrumbItem { ++SLOTS : list ++EVENTS : list ++FRONTEND_DIR : str ++__init__(...) +} +ModelScopeLayoutComponent <|-- AntdBreadcrumb +ModelScopeLayoutComponent <|-- AntdBreadcrumbItem +``` + +Diagram Sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:1-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L1-L73) +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:1-114](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L1-L114) + +Section Sources + +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:1-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L1-L73) +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:1-114](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L1-L114) +- [backend/modelscope_studio/utils/dev/component.py:1-169](file://backend/modelscope_studio/utils/dev/component.py#L1-L169) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:1-17](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L1-L17) + +### Runtime Template (breadcrumb-C7MaDQtV.js) + +- Key points + - Provides `createItemsContext` context for sharing breadcrumb items in the React layer. + - Provides runtime implementations of `renderItems` and `renderParamsSlot`, supporting slot cloning and parameterized rendering. + - Converts Svelte slots into React-consumable structures, supporting nested slots and menu items. +- Key flow + - Reads `items/default` from context. + - Uses utility functions `ve/oe/Mt` to convert slots into props required by AntD. + - Renders AntD Breadcrumb with custom separator and item renderer applied. + +```mermaid +flowchart TD +LoadCtx["Read context items/default"] --> MergeItems["Merge items/default"] +MergeItems --> Convert["ve/oe/Mt convert slots to React structure"] +Convert --> RenderAD["Render AntD Breadcrumb"] +RenderAD --> Done(["Complete"]) +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:727-761](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L727-L761) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:649-726](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L649-L726) + +Section Sources + +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:1-766](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L1-L766) + +## Dependency Analysis + +- Frontend dependencies + - React wrapper depends on Ant Design Breadcrumb types and rendering utilities. + - Svelte bridging depends on `@svelte-preprocess-react` component import and slot system. +- Backend dependencies + - `AntdBreadcrumb`/`AntdBreadcrumbItem` depend on `resolve_frontend_dir` for frontend directory resolution. + - Inherits `ModelScopeLayoutComponent`, reusing general layout component capabilities. +- Runtime dependencies + - The template file provides slot and context handling logic, ensuring consistent rendering behavior between frontend and backend. + +```mermaid +graph LR +PyComp["AntdBreadcrumb"] --> Resolve["resolve_frontend_dir"] +PyItem["AntdBreadcrumbItem"] --> Resolve +PyComp --> Runtime["Runtime Template breadcrumb-C7MaDQtV.js"] +PyItem --> Runtime +Svelte["Index.svelte"] --> ReactWrap["breadcrumb.tsx"] +ReactWrap --> AD["Ant Design Breadcrumb"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:56-56](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L56-L56) +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:97-97](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L97-L97) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-16](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L16) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:1-766](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L1-L766) +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) + +Section Sources + +- [backend/modelscope_studio/components/antd/breadcrumb/**init**.py:1-73](file://backend/modelscope_studio/components/antd/breadcrumb/__init__.py#L1-L73) +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:1-114](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L1-L114) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:1-17](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L1-L17) +- [frontend/antd/breadcrumb/Index.svelte:1-78](file://frontend/antd/breadcrumb/Index.svelte#L1-L78) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:1-766](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L1-L766) + +## Performance Considerations + +- Slot cloning strategy + - Slot rendering defaults to a cloning strategy to avoid duplicate rendering overhead, but can be controlled via `forceClone`. +- Computation caching + - Uses `useMemo` to cache the final items list, reducing unnecessary re-renders. +- Event mapping + - CamelCase event name mapping is performed uniformly in the Svelte layer, reducing runtime conversion costs. +- Template optimization + - The runtime template provides stable slot conversion and context merging logic, reducing branching logic and object copying. + +Section Sources + +- [frontend/antd/breadcrumb/breadcrumb.tsx:44-51](file://frontend/antd/breadcrumb/breadcrumb.tsx#L44-L51) +- [frontend/antd/breadcrumb/Index.svelte:27-58](file://frontend/antd/breadcrumb/Index.svelte#L27-L58) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:190-206](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L190-L206) + +## Troubleshooting Guide + +- Slots not taking effect + - Confirm slot names are correct (e.g., `separator`, `itemRender`), and that they are declared as supported in the React wrapper layer. + - Check whether slot elements exist in children and have not been hidden or removed. +- Events not triggering + - Confirm event names are registered in the backend component (e.g., `click`, `menu_*`, `dropdownProps_*`). + - Check whether the Svelte layer correctly maps to camelCase names required by AntD. +- Routing integration issues + - If using dropdown menus or overflow indicators, confirm that menu item `href`/`path` matches the route. + - For permission control, it is recommended to dynamically decide whether to render an item or disable clicks in `itemRender` based on user permissions. +- Style anomalies + - Use `elem_classes`/`elem_style` or `classNames`/`styles` to apply styles; ensure compatibility with AntD themes. + - To override default styles, use CSS Modules or theme variables for customization. + +Section Sources + +- [backend/modelscope_studio/components/antd/breadcrumb/item/**init**.py:15-46](file://backend/modelscope_studio/components/antd/breadcrumb/item/__init__.py#L15-L46) +- [frontend/antd/breadcrumb/Index.svelte:51-57](file://frontend/antd/breadcrumb/Index.svelte#L51-L57) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:370-391](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L370-L391) + +## Conclusion + +The Breadcrumb component achieves flexible path display and user guidance through a collaborative frontend-backend design. Its core strengths are: + +- Slot-based extensibility: Supports custom separators, item renderers, and dropdown icons. +- Event-driven: Built-in rich event listeners, making it easy to integrate with routing systems. +- Theme adaptability: Easily adapts to different themes via style properties and runtime context. +- Performance-friendly: Reduces rendering costs via caching and cloning strategies. + +## Appendix: Usage Examples and Best Practices + +- Basic usage + - Refer to documentation examples to quickly build breadcrumb paths. +- Dynamic path generation + - Use the `items` parameter or slot `items` to dynamically build a path array, generating titles and links combined with route parameters. +- Permission control + - In `itemRender`, decide whether to render an item or disable clicks based on user roles. +- Multi-language support + - Pass title and separator text via slots, or switch language-specific content in `itemRender`. +- Style customization + - Use `elem_classes`/`elem_style` or `classNames`/`styles` for custom styles; override default styles via theme variables as needed. +- Performance optimization + - Use `forceClone` and `useMemo` judiciously to avoid unnecessary cloning and re-renders. + - Enable dropdown menus and overflow indicators for long lists to reduce the number of rendered nodes. + +Section Sources + +- [docs/components/antd/breadcrumb/README.md:1-8](file://docs/components/antd/breadcrumb/README.md#L1-L8) +- [docs/components/antd/breadcrumb/README-zh_CN.md:1-8](file://docs/components/antd/breadcrumb/README-zh_CN.md#L1-L8) +- [frontend/antd/breadcrumb/breadcrumb.tsx:44-51](file://frontend/antd/breadcrumb/breadcrumb.tsx#L44-L51) +- [backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js:727-761](file://backend/modelscope_studio/components/antd/breadcrumb/templates/component/breadcrumb-C7MaDQtV.js#L727-L761) diff --git a/.wiki/en/Ant Design Components/Navigation Components/Dropdown.md b/.wiki/en/Ant Design Components/Navigation Components/Dropdown.md new file mode 100644 index 00000000..fc819847 --- /dev/null +++ b/.wiki/en/Ant Design Components/Navigation Components/Dropdown.md @@ -0,0 +1,325 @@ +# Dropdown + + +**Files Referenced in This Document** +- [frontend/antd/dropdown/dropdown.tsx](file://frontend/antd/dropdown/dropdown.tsx) +- [frontend/antd/dropdown/button/Index.svelte](file://frontend/antd/dropdown/button/Index.svelte) +- [backend/modelscope_studio/components/antd/dropdown/__init__.py](file://backend/modelscope_studio/components/antd/dropdown/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [docs/components/antd/dropdown/README.md](file://docs/components/antd/dropdown/README.md) +- [docs/components/antd/dropdown/demos/basic.py](file://docs/components/antd/dropdown/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically introduces the implementation and usage of the Dropdown component in the ModelScope Studio frontend, covering the following topics: + +- Trigger mechanisms and popup containers +- Menu item configuration and rendering +- Popup positioning and placement strategies +- Interaction behaviors and event handling +- Keyboard navigation and accessibility support +- Integration with forms, icon buttons, and text links +- Advanced usage: multi-level menus, dynamic menus, remote loading +- Performance optimization recommendations and common issues + +## Project Structure + +The Dropdown component consists of backend Python components and a frontend Svelte/React wrapper layer, bridged through the Gradio ecosystem. + +```mermaid +graph TB +subgraph "Backend" +PY_API["AntdDropdown
Python Component"] +BTN_PY["AntdDropdown.Button
Python Component"] +end +subgraph "Frontend" +WRAP["Dropdown Wrapper
dropdown.tsx"] +BTN_SVLT["Dropdown.Button Frontend Wrapper
button/Index.svelte"] +ANTD["Antd Dropdown Component"] +MENU_CTX["Menu Context Provider"] +end +PY_API --> WRAP +BTN_PY --> BTN_SVLT +WRAP --> ANTD +WRAP --> MENU_CTX +BTN_SVLT --> ANTD +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:11-38](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L11-L38) +- [frontend/antd/dropdown/dropdown.tsx:15-108](file://frontend/antd/dropdown/dropdown.tsx#L15-L108) +- [frontend/antd/dropdown/button/Index.svelte:10-70](file://frontend/antd/dropdown/button/Index.svelte#L10-L70) + +Section Sources + +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:11-38](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L11-L38) +- [frontend/antd/dropdown/dropdown.tsx:15-108](file://frontend/antd/dropdown/dropdown.tsx#L15-L108) +- [frontend/antd/dropdown/button/Index.svelte:10-70](file://frontend/antd/dropdown/button/Index.svelte#L10-L70) + +## Core Components + +- Backend Python components: `AntdDropdown` and `AntdDropdown.Button` +- Frontend wrapper layer: Dropdown (React wrapper + Antd Dropdown), Dropdown.Button (Svelte wrapper) +- Menu context: Injects "menu items" into the dropdown via the Menu Context Provider + +Key features + +- Supports injecting menu items, expand icons, overflow indicators, and custom popup rendering via slots +- Supports `getPopupContainer` for custom popup containers +- Supports `open_change`, `menu_*` series of event bindings +- Provides inline style pass-through (`innerStyle`) and container style (`overlayStyle`) + +Section Sources + +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:34-38](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L34-L38) +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:40-100](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L40-L100) +- [frontend/antd/dropdown/dropdown.tsx:15-25](file://frontend/antd/dropdown/dropdown.tsx#L15-L25) +- [frontend/antd/dropdown/dropdown.tsx:44-92](file://frontend/antd/dropdown/dropdown.tsx#L44-L92) + +## Architecture Overview + +The Dropdown call chain is as follows: + +```mermaid +sequenceDiagram +participant User as "User" +participant Py as "AntdDropdown (Python)" +participant Wrap as "Dropdown Wrapper (React)" +participant MenuCtx as "Menu Context Provider" +participant Antd as "Antd Dropdown" +participant Popup as "Popup Layer" +User->>Py : Render dropdown +Py->>Wrap : Pass properties and slots +Wrap->>MenuCtx : Read menu items +Wrap->>Antd : Render Antd Dropdown +Antd->>Popup : Display based on trigger condition +User->>Popup : Click/hover/keyboard interaction +Popup-->>Antd : Trigger callback +Antd-->>Wrap : Pass event back +Wrap-->>Py : Trigger open_change / menu_* events +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:16-32](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L16-L32) +- [frontend/antd/dropdown/dropdown.tsx:26-107](file://frontend/antd/dropdown/dropdown.tsx#L26-L107) + +## Detailed Component Analysis + +### Component 1: Dropdown + +- Role: Combines Ant Design's Dropdown with the internal menu context, supporting slot-based menu item injection and custom rendering +- Key points + - Menu item source: Uses `props.menu.items` first; otherwise renders "menu.items" from menu context + - Expand icon and overflow indicator: Can inject ReactSlot via slots or fall back to native properties + - Popup container: Supports `getPopupContainer` for custom containers + - Custom rendering: `dropdownRender` and `popupRender` can be injected via slots or passed as functions + - Inline styles: `innerStyle` is passed through to the content container + +```mermaid +flowchart TD +Start(["Enter Dropdown Wrapper"]) --> ReadCtx["Read items from menu context"] +ReadCtx --> MergeItems{"Are props.menu.items provided?"} +MergeItems --> |Yes| UseProps["Use props.menu.items"] +MergeItems --> |No| RenderItems["Render menu context items"] +UseProps --> Slots["Handle slots: expandIcon / overflowedIndicator / dropdownRender / popupRender"] +RenderItems --> Slots +Slots --> Container["getPopupContainer positioning"] +Container --> Mount["Mount to Antd Dropdown and render"] +Mount --> End(["Complete"]) +``` + +Diagram Sources + +- [frontend/antd/dropdown/dropdown.tsx:26-107](file://frontend/antd/dropdown/dropdown.tsx#L26-L107) + +Section Sources + +- [frontend/antd/dropdown/dropdown.tsx:15-108](file://frontend/antd/dropdown/dropdown.tsx#L15-L108) + +### Component 2: Dropdown.Button + +- Role: Wraps Antd Dropdown.Button in a Svelte manner, supporting slots and event mapping +- Key points + - Dynamically imports the React version of Dropdown.Button via `importComponent` + - Property mapping: `open_change` → `openChange`, `menu_open_change` → `menu_OpenChange` + - Visibility control: Controls rendering via `visible` + - Styles and IDs: Supports `elem_style`, `elem_id`, `elem_classes` pass-through + +```mermaid +sequenceDiagram +participant User as "User" +participant BtnPy as "AntdDropdown.Button (Python)" +participant BtnSvlt as "Dropdown.Button (Svelte)" +participant BtnReact as "Dropdown.Button (React)" +participant Antd as "Antd Dropdown.Button" +User->>BtnPy : Render Dropdown.Button +BtnPy->>BtnSvlt : Pass properties and slots +BtnSvlt->>BtnReact : Dynamic import and render +BtnReact->>Antd : Render Antd Dropdown.Button +User->>Antd : Click/interact +Antd-->>BtnReact : Callback event +BtnReact-->>BtnSvlt : Event pass-through +BtnSvlt-->>BtnPy : Event pass-through +``` + +Diagram Sources + +- [frontend/antd/dropdown/button/Index.svelte:10-70](file://frontend/antd/dropdown/button/Index.svelte#L10-L70) +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:8-8](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L8-L8) + +Section Sources + +- [frontend/antd/dropdown/button/Index.svelte:10-70](file://frontend/antd/dropdown/button/Index.svelte#L10-L70) +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:15-15](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L15-L15) + +### Event Handling and Keyboard Navigation + +- Event bindings + - `open_change`: Dropdown panel visibility state change + - `menu_click` / `menu_select` / `menu_deselect` / `menu_open_change`: Menu item click, selection, deselection, menu panel visibility change +- Keyboard navigation + - Uses Antd Dropdown's default keyboard behavior (up/down to move, Enter/Space to select, Esc to close) +- Accessibility support + - Preserves native semantic tags and accessibility attributes (provided by Antd Dropdown) + - Recommendation: Set `aria-controls`, `aria-expanded`, and other attributes on trigger elements to enhance accessibility + +Section Sources + +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:16-32](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L16-L32) + +### Popup Positioning and Container + +- Positioning strategy + - `placement`: Supports `topLeft`/`top`/`topRight`/`bottomLeft`/`bottom`/`bottomRight` + - `auto_adjust_overflow`: Automatically adjusts overflow +- Container selection + - `get_popup_container`: Custom popup container, commonly used for fixing to specific areas or inside scroll containers + +Section Sources + +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:56-59](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L56-L59) +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:52-52](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L52-L52) + +### Integration with Forms, Icon Buttons, and Text Links + +- Form components + - When embedding input-type components in menu items, be aware of form linkage and validation timing +- Icon buttons + - Combine `antd.Icon` with `antd.Button` (type="text" or "primary"/"default") +- Text links + - Use `antd.Button` (type="link") as menu item labels, supporting `href` and new window opening + +Section Sources + +- [docs/components/antd/dropdown/demos/basic.py:6-31](file://docs/components/antd/dropdown/demos/basic.py#L6-L31) +- [docs/components/antd/dropdown/demos/basic.py:37-47](file://docs/components/antd/dropdown/demos/basic.py#L37-L47) + +### Advanced Usage + +- Multi-level menus + - Nest sub-menu items within menu items to achieve two-level or multi-level dropdown menus +- Dynamic menus + - Inject "menu.items" via slots and update dynamically based on state at runtime +- Remote loading + - Add loading and error states in `dropdownRender`/`popupRender`, update menu items after async requests + +Section Sources + +- [frontend/antd/dropdown/dropdown.tsx:20-24](file://frontend/antd/dropdown/dropdown.tsx#L20-L24) +- [frontend/antd/dropdown/dropdown.tsx:71-92](file://frontend/antd/dropdown/dropdown.tsx#L71-L92) + +## Dependency Analysis + +- Python layer + - `AntdDropdown` exports the Button sub-component and declares supported slots and events + - Component is registered in `components.py` for unified export +- Frontend layer + - Dropdown wrapper depends on Antd Dropdown, Menu Context Provider, and slot rendering utilities + - Dropdown.Button wraps the React component via Svelte + +```mermaid +graph LR +PY["AntdDropdown (Python)"] --> WRAP["Dropdown (React)"] +WRAP --> ANTD["Antd Dropdown"] +WRAP --> CTX["Menu Context Provider"] +BTN_PY["AntdDropdown.Button (Python)"] --> BTN_SVLT["Dropdown.Button (Svelte)"] +BTN_SVLT --> BTN_REACT["Dropdown.Button (React)"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:39-40](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L39-L40) +- [backend/modelscope_studio/components/antd/components.py:39-40](file://backend/modelscope_studio/components/antd/components.py#L39-L40) +- [frontend/antd/dropdown/dropdown.tsx:10-13](file://frontend/antd/dropdown/dropdown.tsx#L10-L13) +- [frontend/antd/dropdown/button/Index.svelte:10-12](file://frontend/antd/dropdown/button/Index.svelte#L10-L12) + +Section Sources + +- [backend/modelscope_studio/components/antd/components.py:39-40](file://backend/modelscope_studio/components/antd/components.py#L39-L40) +- [frontend/antd/dropdown/dropdown.tsx:10-13](file://frontend/antd/dropdown/dropdown.tsx#L10-L13) + +## Performance Considerations + +- Menu item rendering + - Use `useMemo` to cache the menu item list, avoiding unnecessary re-renders +- Slot rendering + - Render slots only when needed, reducing unused nodes +- Popup container + - Set `getPopupContainer` reasonably to avoid frequent popup layer reflows +- Event binding + - Bind `open_change` and `menu_*` events only when necessary, avoiding excessive listeners + +Section Sources + +- [frontend/antd/dropdown/dropdown.tsx:49-57](file://frontend/antd/dropdown/dropdown.tsx#L49-L57) +- [frontend/antd/dropdown/dropdown.tsx:37-39](file://frontend/antd/dropdown/dropdown.tsx#L37-L39) + +## Troubleshooting Guide + +- Unable to display menu items + - Check whether "menu.items" is injected via slots, or whether `props.menu.items` is correctly passed +- Popup layer position abnormal + - Check whether `getPopupContainer` returns the correct container element + - Adjust `placement` and `auto_adjust_overflow` +- Events not triggering + - Confirm the corresponding events (`open_change`, `menu_*`) are enabled and correctly bound in the Python layer +- Styles not taking effect + - `innerStyle` only applies to the content container; `overlayStyle` should be passed via backend properties + +Section Sources + +- [frontend/antd/dropdown/dropdown.tsx:44-92](file://frontend/antd/dropdown/dropdown.tsx#L44-L92) +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:52-59](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L52-L59) +- [backend/modelscope_studio/components/antd/dropdown/**init**.py:16-32](file://backend/modelscope_studio/components/antd/dropdown/__init__.py#L16-L32) + +## Conclusion + +The Dropdown component implements flexible menu item injection, popup layer customization, and event binding through a "Python component + frontend wrapper + menu context" design. Combined with Antd Dropdown's mature capabilities, it can handle scenarios ranging from basic dropdowns to complex multi-level menus, dynamic and remote loading. In real projects, it is recommended to focus on performance and accessibility, using slots and events reasonably to ensure a good user experience. + +## Appendix + +- Example references + - Basic examples: Contains normal dropdown and dropdown button, as well as embedded buttons and links in menu items +- Documentation entry + - Component documentation home and example entry + +Section Sources + +- [docs/components/antd/dropdown/README.md:1-8](file://docs/components/antd/dropdown/README.md#L1-L8) +- [docs/components/antd/dropdown/demos/basic.py:33-47](file://docs/components/antd/dropdown/demos/basic.py#L33-L47) diff --git a/.wiki/en/Ant Design Components/Navigation Components/Menu.md b/.wiki/en/Ant Design Components/Navigation Components/Menu.md new file mode 100644 index 00000000..ab49acb3 --- /dev/null +++ b/.wiki/en/Ant Design Components/Navigation Components/Menu.md @@ -0,0 +1,344 @@ +# Menu + + +**Files Referenced in This Document** +- [menu.tsx](file://frontend/antd/menu/menu.tsx) +- [menu.item.tsx](file://frontend/antd/menu/item/menu.item.tsx) +- [Index.svelte](file://frontend/antd/menu/item/Index.svelte) +- [context.ts](file://frontend/antd/menu/context.ts) +- [menu.less](file://frontend/antd/menu/menu.less) +- [createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [README.md](file://docs/components/antd/menu/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically introduces the design and implementation of the navigation Menu component, covering layout modes, menu item configuration, state management, interaction behaviors, icons and disabled states, sub-menu nesting, horizontal/vertical layout switching, collapse/expand mechanisms, responsive adaptation, integration with routing systems (dynamic menus, permission control, breadcrumb linkage), accordion and multi-select modes, searchable menus, and other advanced capabilities, along with usage examples, style customization, and performance optimization recommendations. + +## Project Structure + +The Menu component consists of three parts: "container component + menu item component + context and rendering utilities". It uses Ant Design's Menu component as the underlying implementation, bridged to React via Svelte preprocessing, combined with an in-house "item context" system for flexible menu item collection and rendering. + +```mermaid +graph TB +subgraph "frontend/antd/menu" +M["menu.tsx
Menu Container"] +MI["menu.item.tsx
Menu Item Wrapper"] +IDX["Index.svelte
Menu Item Entry"] +CTX["context.ts
Item Context Export"] +LESS["menu.less
Styles and Transitions"] +end +subgraph "Utility Layer" +CIC["createItemsContext.tsx
Item Context Factory"] +RIT["renderItems.tsx
Item Renderer"] +end +subgraph "External Dependencies" +AD["Ant Design Menu
Underlying UI"] +end +IDX --> MI +MI --> CTX +CTX --> CIC +M --> RIT +M --> AD +M --> LESS +``` + +Diagram Sources + +- [menu.tsx:14-93](file://frontend/antd/menu/menu.tsx#L14-L93) +- [menu.item.tsx:9-33](file://frontend/antd/menu/item/menu.item.tsx#L9-L33) +- [Index.svelte:13-83](file://frontend/antd/menu/item/Index.svelte#L13-L83) +- [context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) +- [createItemsContext.tsx:97-273](file://frontend/utils/createItemsContext.tsx#L97-L273) +- [renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +Section Sources + +- [menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [menu.item.tsx:1-36](file://frontend/antd/menu/item/menu.item.tsx#L1-L36) +- [Index.svelte:1-84](file://frontend/antd/menu/item/Index.svelte#L1-L84) +- [context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) +- [menu.less:1-45](file://frontend/antd/menu/menu.less#L1-L45) +- [createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) + +## Core Components + +- Menu Container (Menu) + - Purpose: Wraps Ant Design Menu, unifying event pass-through, slot rendering, custom rendering of icons and overflow indicators, and item context injection. + - Key points: Supports slot extensions (e.g., `expandIcon`, `overflowedIndicator`, `popupRender`); supports `items` or slots as data sources; internally uses `renderItems` to convert the "item context" into the `ItemType` array required by Antd. +- Menu Item (MenuItem) + - Purpose: Wraps menu items from the "item context" as Antd MenuItem/SubMenu, auto-detects type (regular item/sub-menu), and injects style class names. +- Item Context (createItemsContext) + - Purpose: Provides "item collection + child item collection" context, supporting multiple slots, index positioning, property and child item transformation, change callbacks, etc. +- Renderer (renderItems) + - Purpose: Renders the "item context" tree structure into the props structure required by Antd, supporting slot injection, cloning, parameterized slots, etc. + +Section Sources + +- [menu.tsx:14-93](file://frontend/antd/menu/menu.tsx#L14-L93) +- [menu.item.tsx:9-33](file://frontend/antd/menu/item/menu.item.tsx#L9-L33) +- [createItemsContext.tsx:97-273](file://frontend/utils/createItemsContext.tsx#L97-L273) +- [renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +## Architecture Overview + +The Menu component uses a layered design of "container + item wrapper + context", bridged to React via Svelte preprocessing, then React calls Antd Menu. The item context is responsible for collecting menu items and their slots at runtime, and the renderer ultimately outputs a data structure recognizable by Antd. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Menu as "Menu Container" +participant Ctx as "Item Context" +participant Render as "renderItems" +participant Antd as "Antd Menu" +Dev->>Menu : Pass items or slots +Menu->>Ctx : withItemsContextProvider injection +Ctx-->>Menu : useItems provides items +Menu->>Render : renderItems(resolvedSlotItems, { clone }) +Render-->>Menu : Return Antd Item list +Menu->>Antd : Render and bind events +Antd-->>Dev : Trigger openChange/onSelect/onDeselect +``` + +Diagram Sources + +- [menu.tsx:18-54](file://frontend/antd/menu/menu.tsx#L18-L54) +- [createItemsContext.tsx:171-184](file://frontend/utils/createItemsContext.tsx#L171-L184) +- [renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +## Detailed Component Analysis + +### Menu Container (Menu) + +- Data source selection + - Supports directly passing `items` (Antd Item type array) or collecting via slots (default/items slots). + - If slots exist, items from slots are preferred; otherwise falls back to the default slot. +- Slot extensions + - `expandIcon`: Custom expand icon, supports parameterized rendering. + - `overflowedIndicator`: Overflow indicator (e.g., "More" button). + - `popupRender`: Custom rendering for dropdown popup layers. +- Event pass-through + - `onOpenChange`, `onSelect`, `onDeselect` are passed through as-is to Antd Menu. +- Performance optimization + - Uses `useMemo` to cache items computation results, avoiding duplicate rendering. + - Only recomputes when `items` or `resolvedSlotItems` changes. + +Section Sources + +- [menu.tsx:14-93](file://frontend/antd/menu/menu.tsx#L14-L93) + +### Menu Item (MenuItem) + +- Type detection + - When default slot children exist, auto-detects as sub-menu (SubMenu); otherwise as a regular menu item (MenuItem). +- Style class names + - Automatically injects `ms-gr-antd-menu-item` or `ms-gr-antd-menu-item-{type}` for theme and style customization. +- Slot handling + - Injects the `icon` slot into Antd's `icon` field via cloning, ensuring consistent spacing between icon and text. + +Section Sources + +- [menu.item.tsx:9-33](file://frontend/antd/menu/item/menu.item.tsx#L9-L33) + +### Item Context (createItemsContext) + +- Multi-slot support + - Allows defining multiple slots (e.g., `default`, `items`) and writing by index via `setItem`. +- Child item collection + - `ItemHandler` internally wraps `ItemsContextProvider` again, forming a "parent collection + child collection" tree structure. +- Property and child item transformation + - `itemProps` and `itemChildren` support transforming props and children of the current item for dynamic generation. +- Change notification + - The `onChange` callback returns the complete items under the current slot, making it easy for upper layers to listen for changes. + +Section Sources + +- [createItemsContext.tsx:97-273](file://frontend/utils/createItemsContext.tsx#L97-L273) + +### Renderer (renderItems) + +- Slot injection + - Injects slot elements recorded in the item context into corresponding fields (supports nested paths), with support for `withParams` parameterized slots. +- Cloning and force cloning + - `clone` controls whether to clone nodes; `forceClone` is enabled by default with `withParams` to ensure correct parameter passing. +- Child item recursion + - Recursively renders the `children` field to form a complete menu tree. +- Key generation + - Generates stable keys for each item to avoid React diff anomalies. + +Section Sources + +- [renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +### Styles and Responsive (menu.less) + +- Icon and text spacing + - When an icon is present, automatically sets `margin-inline-start` for adjacent text and adds transition animations. +- Collapsed mode + - In the `inline-collapsed` state, text is hidden and only icons are shown to improve space utilization. +- Animations and transitions + - Controls transition duration and easing via CSS variables, ensuring visual consistency. + +Section Sources + +- [menu.less:1-45](file://frontend/antd/menu/menu.less#L1-L45) + +### Svelte Entry (Index.svelte) + +- Property and slot handling + - Retrieves component properties and additional properties via `getProps`/`processProps`, supports `visible` for visibility control. + - Injects the `icon` slot into Antd's `icon` field via cloning. +- Theme and styles + - Supports `elem_id`, `elem_classes`, `elem_style` injection for theme and style customization. +- Conditional rendering + - Renders `children` only when `visible` is true. + +Section Sources + +- [Index.svelte:1-84](file://frontend/antd/menu/item/Index.svelte#L1-L84) + +## Dependency Analysis + +- Component coupling + - Menu depends on `createItemsContext` and `renderItems`; MenuItem depends on `ItemHandler` and context; Svelte entry handles property and slot preprocessing. +- External dependencies + - Ant Design Menu as the underlying UI; `ReactSlot` for slot rendering; `classnames` for class name concatenation. +- Circular dependencies + - Avoided through "exported factory + context injection"; Menu and MenuItem are decoupled via context. + +```mermaid +graph LR +Menu["menu.tsx"] --> Ctx["context.ts"] +Ctx --> CIC["createItemsContext.tsx"] +Menu --> RIT["renderItems.tsx"] +Menu --> AD["Antd Menu"] +MenuItem["menu.item.tsx"] --> Ctx +IDX["Index.svelte"] --> MenuItem +Menu --> LESS["menu.less"] +``` + +Diagram Sources + +- [menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) +- [createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [menu.item.tsx:1-36](file://frontend/antd/menu/item/menu.item.tsx#L1-L36) +- [Index.svelte:1-84](file://frontend/antd/menu/item/Index.svelte#L1-L84) +- [menu.less:1-45](file://frontend/antd/menu/menu.less#L1-L45) + +Section Sources + +- [menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [menu.item.tsx:1-36](file://frontend/antd/menu/item/menu.item.tsx#L1-L36) +- [Index.svelte:1-84](file://frontend/antd/menu/item/Index.svelte#L1-L84) +- [context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) +- [createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [menu.less:1-45](file://frontend/antd/menu/menu.less#L1-L45) + +## Performance Considerations + +- Render caching + - Menu uses `useMemo` for items computation, avoiding unnecessary re-renders. +- Event function memoization + - `createItemsContext` internally uses `useMemoizedFn`, reducing side effects caused by callback function rebuilds. +- Slot cloning strategy + - Default slot element cloning avoids state confusion caused by DOM reuse; forced cloning in `withParams` scenarios. +- Recursive rendering optimization + - `renderItems` only filters and maps valid items, avoiding empty items participating in rendering. + +Section Sources + +- [menu.tsx:46-54](file://frontend/antd/menu/menu.tsx#L46-L54) +- [createItemsContext.tsx:203-254](file://frontend/utils/createItemsContext.tsx#L203-L254) +- [renderItems.tsx:19-22](file://frontend/utils/renderItems.tsx#L19-L22) + +## Troubleshooting Guide + +- Slots not taking effect + - Check whether slot names are declared in `allowedSlots`; confirm slot elements are correctly injected into `ItemHandler`'s slots. +- Icons not showing or text not appearing + - Confirm the icon slot has been injected into the `icon` field via the Svelte entry; check behavior when the menu is in collapsed mode. +- Events not triggering + - Confirm Menu correctly passes through `onOpenChange`/`onSelect`/`onDeselect`; check Antd version compatibility. +- Sub-menus not expanding + - Check whether sub-item `children` are correctly recursed via `renderItems`; confirm the `itemChildren` callback returns the correct child item list. +- Style anomalies + - Check whether `menu.less` is imported; confirm theme variables (e.g., `--ms-gr-ant-menu-icon-margin-inline-end`) are set correctly. + +Section Sources + +- [menu.tsx:35-88](file://frontend/antd/menu/menu.tsx#L35-L88) +- [menu.item.tsx:16-30](file://frontend/antd/menu/item/menu.item.tsx#L16-L30) +- [Index.svelte:69-78](file://frontend/antd/menu/item/Index.svelte#L69-L78) +- [menu.less:1-45](file://frontend/antd/menu/menu.less#L1-L45) + +## Conclusion + +This Menu component enhances and extends Ant Design Menu through a "container + item wrapper + context" architecture, featuring a flexible slot system, powerful sub-menu and icon support, and good performance and maintainability. Combined with routing systems and permission control, complex navigation scenarios can be quickly built. + +## Appendix + +### Usage Examples (Path Guide) + +- Basic examples + - Refer to documentation example tabs: `` + - Example file location: `docs/components/antd/menu/README.md` +- Dynamic menus and permission control + - Dynamically pass menu items via the `items` property; filter items based on user permissions in `onChange`. +- Breadcrumb linkage + - Update the breadcrumb data source in `onSelect`; generate titles and paths combined with route parameters. +- Accordion and multi-select + - Control expand state and selected items using `onOpenChange`/`onSelect`; Antd Menu natively supports accordion and multi-select modes. +- Searchable menus + - Implement a search input externally, filter `items` and pass them to Menu; or inject a search component in a slot. + +Section Sources + +- [README.md:1-8](file://docs/components/antd/menu/README.md#L1-L8) + +### Style Customization Guide + +- Custom icon and text spacing + - Modify the `--ms-gr-ant-menu-icon-margin-inline-end` variable to adjust icon-text spacing. +- Collapsed mode text hiding + - Control text visibility and transitions in collapsed mode via rules in `menu.less`. +- Theme class names + - Use `ms-gr-antd-menu-item-*` class names for themed style overrides. + +Section Sources + +- [menu.less:1-45](file://frontend/antd/menu/menu.less#L1-L45) + +### Advanced Feature Implementation Key Points + +- Sub-menu nesting + - Return the sub-item array via the `itemChildren` callback in `ItemHandler`; `renderItems` will recursively render them. +- Icon setup + - Inject the `icon` slot into Antd's `icon` field in the Svelte entry. +- Disabled state + - Control disabled via Antd MenuItem's `disabled` property; set dynamically in the item context. +- Responsive adaptation + - Antd Menu itself supports responsiveness; combine CSS variables and layout containers for the best experience. + +Section Sources + +- [menu.item.tsx:16-30](file://frontend/antd/menu/item/menu.item.tsx#L16-L30) +- [Index.svelte:69-78](file://frontend/antd/menu/item/Index.svelte#L69-L78) +- [renderItems.tsx:99-112](file://frontend/utils/renderItems.tsx#L99-L112) diff --git a/.wiki/en/Ant Design Components/Navigation Components/Navigation Components.md b/.wiki/en/Ant Design Components/Navigation Components/Navigation Components.md new file mode 100644 index 00000000..8bfa696d --- /dev/null +++ b/.wiki/en/Ant Design Components/Navigation Components/Navigation Components.md @@ -0,0 +1,542 @@ +# Navigation Components + + +**Files Referenced in This Document** +- [frontend/antd/anchor/anchor.tsx](file://frontend/antd/anchor/anchor.tsx) +- [frontend/antd/anchor/context.ts](file://frontend/antd/anchor/context.ts) +- [frontend/antd/breadcrumb/breadcrumb.tsx](file://frontend/antd/breadcrumb/breadcrumb.tsx) +- [frontend/antd/breadcrumb/context.ts](file://frontend/antd/breadcrumb/context.ts) +- [frontend/antd/dropdown/dropdown.tsx](file://frontend/antd/dropdown/dropdown.tsx) +- [frontend/antd/menu/menu.tsx](file://frontend/antd/menu/menu.tsx) +- [frontend/antd/menu/context.ts](file://frontend/antd/menu/context.ts) +- [frontend/antd/pagination/pagination.tsx](file://frontend/antd/pagination/pagination.tsx) +- [frontend/antd/steps/steps.tsx](file://frontend/antd/steps/steps.tsx) +- [frontend/antd/steps/context.ts](file://frontend/antd/steps/context.ts) +- [frontend/antd/layout/layout.base.tsx](file://frontend/antd/layout/layout.base.tsx) +- [frontend/antd/layout/Index.svelte](file://frontend/antd/layout/Index.svelte) +- [frontend/antd/layout/package.json](file://frontend/antd/layout/package.json) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/utils/omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically organizes and explains the implementation and usage of Ant Design navigation-related components in this repository, covering the following components: Anchor, Breadcrumb, Dropdown, Menu, Pagination, and Steps. The document focuses on: + +- Component state management and event handling mechanisms +- Integration approaches and best practices with routing systems +- Implementation of permission control in navigation +- Navigation pattern design guide: top navigation, sidebar navigation, hybrid navigation +- Implementation methods for multi-level navigation and performance optimization suggestions +- Interaction design and user experience optimization key points + +## Project Structure + +Navigation-related components are primarily located in the `antd` sub-module of the frontend directory, organized using a common pattern of "on-demand rendering + context injection", working with utility functions for slot rendering and property adaptation. + +```mermaid +graph TB +subgraph "Navigation Components" +A["Anchor
Anchor Links"] +B["Breadcrumb
Breadcrumb Trail"] +C["Dropdown
Dropdown Menu"] +D["Menu
Navigation Menu"] +E["Pagination
Pagination"] +F["Steps
Steps Bar"] +end +subgraph "Utility Tools" +U1["createItemsContext.tsx
Context Factory"] +U2["renderItems.tsx
Slot Item Renderer"] +U3["renderParamsSlot.tsx
Parameterized Slot"] +U4["useFunction.ts
Function Wrapper"] +U5["omitUndefinedProps.ts
Property Filter"] +end +subgraph "Layout" +L1["layout.base.tsx
Base Layout Container"] +L2["layout/Index.svelte
Layout Entry"] +L3["layout/package.json
Export Configuration"] +end +A --> U1 +B --> U1 +D --> U1 +F --> U1 +C --> D +A --> U2 +B --> U2 +D --> U2 +F --> U2 +A --> U3 +B --> U3 +D --> U3 +F --> U3 +C --> U4 +D --> U5 +L1 --> L2 +L3 --> L2 +``` + +Diagram Sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/package.json:1-15](file://frontend/antd/layout/package.json#L1-L15) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/utils/omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + +Section Sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/package.json:1-15](file://frontend/antd/layout/package.json#L1-L15) + +## Core Components + +This section provides an overall capability and behavioral description of each navigation component for quick orientation. + +- Anchor + - Responsible for in-page positioning and highlighting, supporting container selectors and current anchor callbacks + - Injects items via context, supporting slot-based child item rendering +- Breadcrumb + - Displays the current page path, supporting custom separators, item renderers, and dropdown icons + - Supports replacing default rendering logic via slots +- Dropdown + - Based on Ant Design Dropdown, supports nested menu items, popup layer rendering, and overflow indicators + - Shares items rendering strategy with the menu context +- Menu + - Supports expand icons, overflow indicators, and popup rendering + - Provides open/select/deselect event pass-through +- Pagination + - Supports total count rendering, quick jumper, and custom page number rendering + - Event callbacks are uniformly handled by function wrappers +- Steps + - Supports custom progress dot rendering + - Injects items via context, supporting slot-based child items + +Section Sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) + +## Architecture Overview + +Navigation components universally adopt a unified architecture of "Svelte wrapper + React component + slot rendering + context injection". Key characteristics are: + +- Use `sveltify` to bridge React components as Svelte components +- Inject items context via `withItemsContextProvider` to uniformly handle combinations of children and slots +- Use `renderItems` and `renderParamsSlot` to render slot items and parameterized slots +- Use `useFunction` to wrap callbacks, ensuring stable execution in the Svelte environment +- Use `omitUndefinedProps` to filter undefined properties, avoiding passing invalid values to underlying components + +```mermaid +sequenceDiagram +participant S as "Svelte Component" +participant P as "withItemsContextProvider" +participant R as "renderItems/renderParamsSlot" +participant A as "Antd Component" +participant U as "useFunction/omitUndefinedProps" +S->>P : Pass props and slots +P->>R : Resolve items and slots +R-->>P : Return normalized items/rendered nodes +P->>U : Wrap callbacks / filter properties +U-->>P : Return safe props +P->>A : Render Antd component +A-->>S : Trigger event callbacks +``` + +Diagram Sources + +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/utils/omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + +## Detailed Component Analysis + +### Anchor Analysis + +- Data flow and state + - Injects items via context, supporting combinations of children and slots + - Uses `useMemo` to cache items computation results, avoiding redundant renders +- Events and callbacks + - `getContainer` and `getCurrentAnchor` are wrapped with `useFunction` for stable invocation in Svelte +- Slots and rendering + - Uses explicit items first; otherwise resolves from `default` or `items` slot in context +- Performance and usability + - Recomputes items only when necessary, reducing rendering overhead + - Hides the children container to avoid duplicate rendering + +```mermaid +flowchart TD +Start(["Enter Anchor Render"]) --> Resolve["Resolve context items"] +Resolve --> HasExplicit{"Are explicit items provided?"} +HasExplicit --> |Yes| UseExplicit["Use explicit items"] +HasExplicit --> |No| UseSlot["Use items/default slot"] +UseSlot --> Memo["useMemo caches items"] +UseExplicit --> Memo +Memo --> Render["Render Antd Anchor"] +Render --> End(["Complete"]) +``` + +Diagram Sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) + +Section Sources + +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/anchor/context.ts:1-7](file://frontend/antd/anchor/context.ts#L1-L7) + +### Breadcrumb Analysis + +- Data flow and state + - Merges items and slots, supporting custom separators and item renderers + - `dropdownIcon` and `separator` can be replaced via slots +- Slots and rendering + - `itemRender`, `dropdown_icon`, and `separator` are rendered via `renderParamsSlot` and ReactSlot +- Callbacks and events + - Maintains interface compatibility with Antd Breadcrumb, with no additional wrapping + +```mermaid +sequenceDiagram +participant S as "Svelte Breadcrumb" +participant Ctx as "Context Resolution" +participant Slot as "Slot Rendering" +participant A as "Antd Breadcrumb" +S->>Ctx : Get items/default +Ctx-->>S : Return items +S->>Slot : Render separator/itemRender/dropdownIcon +Slot-->>S : Return nodes +S->>A : Pass items and rendered slots +A-->>S : Trigger click/navigation +``` + +Diagram Sources + +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) + +Section Sources + +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/breadcrumb/context.ts:1-7](file://frontend/antd/breadcrumb/context.ts#L1-L7) + +### Dropdown Analysis + +- Data flow and state + - Internal menu items are injected via menu context, supporting `expandIcon` and overflow indicator slots + - `dropdownRender` and `popupRender` support parameterized slots +- Events and callbacks + - `getPopupContainer` is wrapped with `useFunction` +- Relationship with Menu + - Shares menu context and reuses the items rendering strategy + +```mermaid +classDiagram +class Dropdown { ++props ++slots ++menu.items ++dropdownRender() ++popupRender() ++getPopupContainer() +} +class MenuContext { ++items ++expandIcon ++overflowedIndicator +} +Dropdown --> MenuContext : "Shared context" +``` + +Diagram Sources + +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) + +Section Sources + +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) + +### Menu Analysis + +- Data flow and state + - Injects items via context, supporting `expandIcon`, overflow indicator, and popup render slot + - open/select/deselect events are passed through +- Property handling + - Uses `omitUndefinedProps` to filter undefined properties, avoiding passing invalid values to underlying components +- Slots and rendering + - `expandIcon`, `overflowedIndicator`, `popup_render` are rendered via `renderParamsSlot` and ReactSlot + +```mermaid +flowchart TD +Enter(["Enter Menu Render"]) --> Ctx["Resolve context items/default"] +Ctx --> Items["renderItems normalization"] +Items --> Props["omitUndefinedProps filter properties"] +Props --> Slots["Slots: expandIcon/overflowedIndicator/popup_render"] +Slots --> Antd["Render Antd Menu"] +Antd --> Events["Pass through open/select/deselect"] +Events --> Exit(["Complete"]) +``` + +Diagram Sources + +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) +- [frontend/utils/omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + +Section Sources + +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/menu/context.ts:1-7](file://frontend/antd/menu/context.ts#L1-L7) + +### Pagination Analysis + +- Data flow and state + - Supports slot-based configuration for `showTotal`, `itemRender`, and `showQuickJumper.goButton` + - `onChange` callback is wrapped with `useFunction` +- Slots and rendering + - `itemRender` and `goButton` are rendered via `renderParamsSlot` and ReactSlot + +```mermaid +sequenceDiagram +participant S as "Svelte Pagination" +participant Slot as "Slot Rendering" +participant A as "Antd Pagination" +S->>Slot : Render itemRender/goButton +Slot-->>S : Return nodes +S->>A : Pass configuration and wrapped callbacks +A-->>S : onChange(page, pageSize) +``` + +Diagram Sources + +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) + +Section Sources + +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) + +### Steps Analysis + +- Data flow and state + - Injects items via context, supporting `progressDot` slotting + - Wraps `progressDot` callback via `useFunction` +- Slots and rendering + - `progressDot` is rendered via `renderParamsSlot` + +```mermaid +flowchart TD +Start(["Enter Steps Render"]) --> Ctx["Resolve items/default"] +Ctx --> Normalize["renderItems normalization"] +Normalize --> Slot["Render progressDot"] +Slot --> Antd["Render Antd Steps"] +Antd --> End(["Complete"]) +``` + +Diagram Sources + +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/steps/context.ts:1-7](file://frontend/antd/steps/context.ts#L1-L7) + +Section Sources + +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/steps/context.ts:1-7](file://frontend/antd/steps/context.ts#L1-L7) + +### Layout and Navigation Patterns + +- Base layout container + - The Base component dynamically selects Layout, Header, Footer, or Content based on the `component` parameter + - Class names differentiate style scopes +- Layout entry and exports + - `Index.svelte` serves as the entry point; `layout/package.json` provides Gradio export configuration + +```mermaid +graph LR +Base["layout.base.tsx
Base Component"] --> |component| L["Layout"] +Base --> H["Header"] +Base --> F["Footer"] +Base --> C["Content"] +Index["layout/Index.svelte"] --> Base +Package["layout/package.json"] --> Index +``` + +Diagram Sources + +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/package.json:1-15](file://frontend/antd/layout/package.json#L1-L15) + +Section Sources + +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/antd/layout/Index.svelte:1-18](file://frontend/antd/layout/Index.svelte#L1-L18) +- [frontend/antd/layout/package.json:1-15](file://frontend/antd/layout/package.json#L1-L15) + +## Dependency Analysis + +- Inter-component coupling + - Dropdown and Menu share menu context, forming a weakly-coupled reuse relationship + - Anchor, Breadcrumb, Steps, and Menu all depend on the `createItemsContext` factory and `renderItems` +- External dependencies + - Ant Design React component library + - Svelte Preprocess React (`sveltify`, `ReactSlot`) + - Utility functions (`useFunction`, `renderItems`, `renderParamsSlot`, `omitUndefinedProps`) + +```mermaid +graph TB +subgraph "Components" +M["Menu"] +D["Dropdown"] +A["Anchor"] +B["Breadcrumb"] +S["Steps"] +P["Pagination"] +end +subgraph "Utilities" +Ctx["createItemsContext"] +RI["renderItems"] +RS["renderParamsSlot"] +UF["useFunction"] +OU["omitUndefinedProps"] +end +M --> Ctx +D --> Ctx +A --> Ctx +B --> Ctx +S --> Ctx +M --> RI +D --> RI +A --> RI +B --> RI +S --> RI +M --> RS +D --> RS +A --> RS +B --> RS +S --> RS +M --> OU +D --> UF +A --> UF +B --> UF +S --> UF +P --> UF +``` + +Diagram Sources + +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/utils/omitUndefinedProps.ts](file://frontend/utils/omitUndefinedProps.ts) + +Section Sources + +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) + +## Performance Considerations + +- Rendering optimization + - Many components use `useMemo` to cache items computation results, avoiding unnecessary re-renders + - Using `renderItems` and `renderParamsSlot` for unified slot rendering reduces branching logic +- Callbacks and properties + - Using `useFunction` to wrap callbacks ensures stable execution within the Svelte lifecycle + - Using `omitUndefinedProps` to filter undefined properties reduces the processing burden on underlying components +- Complexity and extensibility + - The `createItemsContext` factory provides a consistent items injection strategy for multiple components, improving extensibility + - Slot-based design gives components stronger customizability while keeping default behavior stable + +## Troubleshooting Guide + +- Slots not taking effect + - Check whether slot key names match the component conventions (e.g., `menu.items`, `itemRender`, `progressDot`) + - Confirm slot nodes have been correctly passed to the component (ReactSlot and renderParamsSlot) +- items not displaying + - Confirm context is correctly injected (`withItemsContextProvider`) + - Check whether the combination of children and slots is being correctly resolved +- Callbacks not triggering + - Confirm callbacks are wrapped with `useFunction` + - Check the event pass-through chain (`onOpenChange`/`onSelect`/`onDeselect`, etc.) +- Layout anomalies + - Check the `component` parameter and class name mapping of `layout.base` + - Confirm style scopes have not been overridden by external styles + +Section Sources + +- [frontend/antd/menu/menu.tsx:1-96](file://frontend/antd/menu/menu.tsx#L1-L96) +- [frontend/antd/dropdown/dropdown.tsx:1-111](file://frontend/antd/dropdown/dropdown.tsx#L1-L111) +- [frontend/antd/anchor/anchor.tsx:1-46](file://frontend/antd/anchor/anchor.tsx#L1-L46) +- [frontend/antd/breadcrumb/breadcrumb.tsx:1-67](file://frontend/antd/breadcrumb/breadcrumb.tsx#L1-L67) +- [frontend/antd/steps/steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [frontend/antd/pagination/pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +## Conclusion + +The navigation components in this repository use a unified context and slot rendering strategy as their core, achieving a high-cohesion, low-coupling component system. Through collaboration among tools like `useMemo`, `useFunction`, and `renderItems`, they ensure both performance and powerful customizability. Combined with layout components, they can flexibly construct multiple navigation patterns such as top navigation, sidebar navigation, and hybrid navigation, with good extensibility for routing integration and permission control. + +## Appendix + +- Navigation Pattern Design Guide (conceptual recommendations) + - Top navigation: Suitable for scenarios with clear entry points and shallow hierarchy; pair with Breadcrumb for improved path awareness + - Sidebar navigation: Suitable for content-rich admin systems requiring quick switching; pair with Anchor for fast positioning + - Hybrid navigation: Top main navigation + sidebar secondary navigation, balancing global and local operations +- Routing Integration and Permission Control (conceptual recommendations) + - Routing integration: Inject route metadata into the `items` of Menu/Breadcrumb/Steps to achieve navigation-route linkage + - Permission control: Filter `items` before rendering to show only nodes the user has permission to access +- Multi-level Navigation Implementation and Performance Considerations (conceptual recommendations) + - Use virtual scrolling and lazy loading to reduce large list rendering pressure + - Enable folding and caching for deep-level menus to avoid frequent re-renders + - Preserve necessary navigation state during route transitions to improve user experience diff --git a/.wiki/en/Ant Design Components/Navigation Components/Pagination.md b/.wiki/en/Ant Design Components/Navigation Components/Pagination.md new file mode 100644 index 00000000..662cae68 --- /dev/null +++ b/.wiki/en/Ant Design Components/Navigation Components/Pagination.md @@ -0,0 +1,340 @@ +# Pagination + + +**Files Referenced in This Document** +- [pagination.tsx](file://frontend/antd/pagination/pagination.tsx) +- [Index.svelte](file://frontend/antd/pagination/Index.svelte) +- [__init__.py](file://backend/modelscope_studio/components/antd/pagination/__init__.py) +- [basic.py](file://docs/components/antd/pagination/demos/basic.py) +- [data_changes.py](file://docs/components/antd/pagination/demos/data_changes.py) +- [README.md](file://docs/components/antd/pagination/README.md) +- [app.py](file://docs/components/antd/pagination/app.py) +- [table/__init__.py](file://backend/modelscope_studio/components/antd/table/__init__.py) +- [list/__init__.py](file://backend/modelscope_studio/components/antd/list/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically introduces the implementation and usage of the Pagination component in the ModelScope Studio frontend and backend, covering the following topics: + +- Data pagination mechanism: How to calculate page ranges and boundaries based on total item count and page size +- Page navigation logic: Clicking page numbers, quick jumper, previous/next page, first/last page +- Total count display: Displaying current range and total via the "show total" callback or property +- Configuration details: Page size settings, default page number, page size selector, quick jumper, simple mode, size, disabled state, single-page hiding, etc. +- Integration with data tables and list views: How to link pagination with tables/lists for data loading, state synchronization, and error handling +- Internationalization support, style customization, responsive adaptation +- Advanced usage: large data pagination, virtual scrolling, server-side pagination +- Complete examples and performance optimization recommendations + +## Project Structure + +The Pagination component consists of three parts: + +- Frontend Svelte wrapper layer: Handles property pass-through, slot rendering, and visibility control +- Frontend React encapsulation layer: Connects to Ant Design's Pagination and supports slots and function-based rendering +- Backend Gradio component: Defines events, slots, property mappings, and render entry points + +```mermaid +graph TB +subgraph "Backend" +PY_INIT["Python Initialization
__init__.py"] +end +subgraph "Frontend" +IDX["Svelte Wrapper Layer
Index.svelte"] +REACT["React Encapsulation Layer
pagination.tsx"] +ANTDP["Ant Design Pagination"] +end +PY_INIT --> IDX --> REACT --> ANTDP +``` + +Diagram Sources + +- [Index.svelte:1-68](file://frontend/antd/pagination/Index.svelte#L1-L68) +- [pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) +- [**init**.py:1-107](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L1-L107) + +Section Sources + +- [Index.svelte:1-68](file://frontend/antd/pagination/Index.svelte#L1-L68) +- [pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) +- [**init**.py:1-107](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L1-L107) + +## Core Components + +- Backend component class: Defines events, slots, property mappings, and render directory +- Frontend wrapper layer: Uniformly handles properties, class names, styles, visibility, and slots +- React encapsulation layer: Connects to Ant Design's Pagination, supporting custom rendering and slot injection + +Key points + +- Events: `change`, `showSizeChange` +- Slots: `showQuickJumper.goButton`, `itemRender` +- Property mapping: e.g., `show_size_change` → `showSizeChange` + +Section Sources + +- [**init**.py:14-25](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L14-L25) +- [Index.svelte:22-48](file://frontend/antd/pagination/Index.svelte#L22-L48) +- [pagination.tsx:8-52](file://frontend/antd/pagination/pagination.tsx#L8-L52) + +## Architecture Overview + +The Pagination component call chain is as follows: + +```mermaid +sequenceDiagram +participant User as "User" +participant Backend as "Backend Component Class
AntdPagination" +participant FrontIndex as "Frontend Wrapper Layer
Index.svelte" +participant ReactLayer as "React Encapsulation Layer
pagination.tsx" +participant Antd as "Ant Design Pagination" +User->>Backend : Render request +Backend->>FrontIndex : Pass properties and slots +FrontIndex->>ReactLayer : Pass through properties and slots +ReactLayer->>Antd : Render component and bind events +User->>Antd : Trigger pagination/page size change +Antd-->>ReactLayer : onChange(page, pageSize) +ReactLayer-->>FrontIndex : Callback triggered +FrontIndex-->>Backend : Event callback e.g. change +``` + +Diagram Sources + +- [**init**.py:14-21](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L14-L21) +- [Index.svelte:54-66](file://frontend/antd/pagination/Index.svelte#L54-L66) +- [pagination.tsx:36-38](file://frontend/antd/pagination/pagination.tsx#L36-L38) + +## Detailed Component Analysis + +### Configuration Options and Behavior + +- Basic parameters + - Total items: `total` + - Default page number: `default_current` + - Current page: `current` + - Items per page: `default_page_size` / `page_size` + - Page size options: `page_size_options` + - Disabled: `disabled` + - Hide on single page: `hide_on_single_page` + - Size: `size` (small/default) + - Alignment: `align` (start/center/end) + - Simple mode: `simple` + - Show title: `show_title` + - Show fewer items: `show_less_items` + - Responsive: `responsive` + - Custom rendering: `item_render` + - Show total: `show_total` + - Quick jumper: `show_quick_jumper` (with optional `goButton` slot) + - Show page size selector: `show_size_changer` +- Slots + - `showQuickJumper.goButton`: Quick jump button + - `itemRender`: Custom page number item rendering + +Section Sources + +- [**init**.py:26-88](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L26-L88) +- [Index.svelte:46-47](file://frontend/antd/pagination/Index.svelte#L46-L47) +- [pagination.tsx:12-47](file://frontend/antd/pagination/pagination.tsx#L12-L47) + +### Events and State Synchronization + +- `change`: Triggered when page number or page size changes, returns (page, pageSize) +- `showSizeChange`: Triggered when page size changes +- Gradio state linkage: Write page number and page size to `gr.State` via event callbacks to drive data loading + +Section Sources + +- [**init**.py:14-21](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L14-L21) +- [data_changes.py:6-11](file://docs/components/antd/pagination/demos/data_changes.py#L6-L11) + +### Data Pagination Mechanism and Page Navigation Logic + +- Calculation rules + - Total pages: `Math.ceil(total / pageSize)` + - Current page range: 1 to total pages + - Boundary handling: `current` falls back to a valid value when out of range +- Navigation flow + - Click page number: Triggers `change` + - Previous/next/first/last page: Handled internally by Ant Design and triggers `change` + - Quick jump: When `show_quick_jumper` is enabled and a `goButton` slot is provided, the slot button executes the jump +- Custom rendering + - Use `itemRender` to customize page button content + - Use `show_total` to display range/total on the left side of pagination + +```mermaid +flowchart TD +Start(["Start"]) --> Init["Receive total and pageSize"] +Init --> CalcPages["Calculate total pages"] +CalcPages --> ValidateCurrent["Validate current is in valid range"] +ValidateCurrent --> Render["Render page buttons"] +Render --> Jump["User clicks page/jump button"] +Jump --> ChangeEvent["Trigger change(page, pageSize)"] +ChangeEvent --> UpdateState["Update state e.g. gr.State"] +UpdateState --> LoadData["Load data based on new page number"] +LoadData --> End(["End"]) +``` + +Diagram Sources + +- [pagination.tsx:36-38](file://frontend/antd/pagination/pagination.tsx#L36-L38) +- [data_changes.py:6-11](file://docs/components/antd/pagination/demos/data_changes.py#L6-L11) + +### Integration with Data Tables and List Views + +- Table integration + - Enable `pagination` in the table component and bind the pagination `change` event with the table data loading logic + - Use `show_size_changer` to dynamically switch items per page, linked with table column width and row height +- List integration + - List components support a `pagination` parameter that can directly accept a pagination instance + - List's load-more (`load_more`) and pagination can be used separately or in combination +- State synchronization + - Write pagination state to `gr.State` as input for subsequent data requests + - Table/list `loading` state and pagination `disabled` state can be linked to avoid concurrent requests + +Section Sources + +- [table/**init**.py:114-133](file://backend/modelscope_studio/components/antd/table/__init__.py#L114-L133) +- [list/**init**.py:59-82](file://backend/modelscope_studio/components/antd/list/__init__.py#L59-L82) +- [data_changes.py:24-28](file://docs/components/antd/pagination/demos/data_changes.py#L24-L28) + +### Internationalization, Style Customization, and Responsive Adaptation + +- Internationalization + - Provide locale via `ConfigProvider`; pagination text follows global configuration +- Style customization + - Supports `elem_id`, `elem_classes`, `elem_style`, and `additional_props` + - Theme-level customization via `root_class_name` and `class_names`/`styles` +- Responsive + - When `responsive` is enabled, the component automatically adjusts layout and font size on small-screen devices + +Section Sources + +- [README.md:1-14](file://docs/components/antd/pagination/README.md#L1-L14) +- [Index.svelte:56-58](file://frontend/antd/pagination/Index.svelte#L56-L58) +- [**init**.py:49-50](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L49-L50) + +### Advanced Usage: Large Data Pagination, Virtual Scrolling, Server-side Pagination + +- Large data pagination + - Use a large `total` combined with a smaller `page_size` and reasonable `page_size_options` + - Load data on demand via the `change` event to avoid rendering all data at once +- Virtual scrolling + - Table components support a `virtual` parameter that can significantly improve rendering performance for large datasets +- Server-side pagination + - Pagination only handles UI interaction; actual data is provided by backend APIs, with the frontend making requests in `change` and updating tables/lists + - Combine `loading` state and disabled state to prevent duplicate requests + +Section Sources + +- [table/**init**.py:129-130](file://backend/modelscope_studio/components/antd/table/__init__.py#L129-L130) +- [data_changes.py:6-11](file://docs/components/antd/pagination/demos/data_changes.py#L6-L11) + +### Examples and Best Practices + +- Basic example + - Demonstrates `total`, quick jumper, page size selector, and total count display +- Data change example + - Write page number and page size to `gr.State` via `change` event, and show a notification on button click +- Best practices + - Decouple pagination state from data requests using event-driven approach + - Disable pagination during data loading to avoid concurrency + - Set `page_size_options` reasonably to balance loading speed and user experience + +Section Sources + +- [basic.py:7-11](file://docs/components/antd/pagination/demos/basic.py#L7-L11) +- [data_changes.py:6-11](file://docs/components/antd/pagination/demos/data_changes.py#L6-L11) + +## Dependency Analysis + +- Component coupling + - Backend component class and frontend wrapper layer are loosely coupled, communicating via properties and slots as contracts + - React encapsulation layer's dependency on Ant Design is explicit, making it easy to upgrade and replace +- Events and slots + - Events: `change`, `showSizeChange` + - Slots: `showQuickJumper.goButton`, `itemRender` +- External dependencies + - Ant Design Pagination + - Gradio event system and state management + +```mermaid +graph LR +PY["Backend Component Class
__init__.py"] --> IDX["Frontend Wrapper Layer
Index.svelte"] +IDX --> REACT["React Encapsulation Layer
pagination.tsx"] +REACT --> ANTDP["Ant Design Pagination"] +PY --> |"Events/Slots"| PY +``` + +Diagram Sources + +- [**init**.py:14-25](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L14-L25) +- [Index.svelte:54-66](file://frontend/antd/pagination/Index.svelte#L54-L66) +- [pagination.tsx:28-48](file://frontend/antd/pagination/pagination.tsx#L28-L48) + +Section Sources + +- [**init**.py:14-25](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L14-L25) +- [Index.svelte:54-66](file://frontend/antd/pagination/Index.svelte#L54-L66) +- [pagination.tsx:28-48](file://frontend/antd/pagination/pagination.tsx#L28-L48) + +## Performance Considerations + +- Rendering optimization + - Use virtual scrolling (tables) to reduce DOM count + - Control `page_size` to avoid excessive single-page rendering pressure +- Request optimization + - Only make data requests on `change` to avoid frequent refreshes + - Disable pagination during requests to prevent duplicate requests +- Styles and resources + - Use `elem_classes` and style caching reasonably to reduce repaints + - Avoid heavy computations in `itemRender` + +## Troubleshooting Guide + +- Issue: Pagination not triggering `change` + - Check whether the `change` event is correctly bound + - Confirm `total` and `page_size` settings are reasonable +- Issue: Page size switching not working + - Check whether `show_size_changer` is enabled + - Confirm `show_size_change` property mapping is correct +- Issue: Quick jump button not displaying + - Check whether the `showQuickJumper.goButton` slot is provided +- Issue: Styles not taking effect + - Check usage of `elem_id`, `elem_classes`, `elem_style`, and `root_class_name` +- Issue: Internationalization text anomalies + - Confirm `ConfigProvider` is correctly configured with the locale + +Section Sources + +- [Index.svelte:46-47](file://frontend/antd/pagination/Index.svelte#L46-L47) +- [pagination.tsx:39-47](file://frontend/antd/pagination/pagination.tsx#L39-L47) +- [README.md:1-14](file://docs/components/antd/pagination/README.md#L1-L14) + +## Conclusion + +The Pagination component achieves a flexible pagination experience through clear frontend-backend separation and event/slot contracts. Combined with table and list components, high-performance, extensible data browsing interfaces can be easily built. For large dataset scenarios, combining virtual scrolling and server-side pagination strategies is recommended to ensure smooth interactions and efficient resource usage. + +## Appendix + +- Example entry + - Documentation app entry: [app.py:1-7](file://docs/components/antd/pagination/app.py#L1-L7) +- Example scripts + - Basic example: [basic.py:1-15](file://docs/components/antd/pagination/demos/basic.py#L1-L15) + - Data change example: [data_changes.py:1-36](file://docs/components/antd/pagination/demos/data_changes.py#L1-L36) +- Component source code + - Backend component class: [**init**.py:1-107](file://backend/modelscope_studio/components/antd/pagination/__init__.py#L1-L107) + - Frontend wrapper layer: [Index.svelte:1-68](file://frontend/antd/pagination/Index.svelte#L1-L68) + - React encapsulation layer: [pagination.tsx:1-55](file://frontend/antd/pagination/pagination.tsx#L1-L55) diff --git a/.wiki/en/Ant Design Components/Navigation Components/Steps.md b/.wiki/en/Ant Design Components/Navigation Components/Steps.md new file mode 100644 index 00000000..093c2db9 --- /dev/null +++ b/.wiki/en/Ant Design Components/Navigation Components/Steps.md @@ -0,0 +1,425 @@ +# Steps + + +**Files Referenced in This Document** +- [steps.tsx](file://frontend/antd/steps/steps.tsx) +- [steps.item.tsx](file://frontend/antd/steps/item/steps.item.tsx) +- [Index.svelte](file://frontend/antd/steps/item/Index.svelte) +- [context.ts](file://frontend/antd/steps/context.ts) +- [package.json](file://frontend/antd/steps/package.json) +- [gradio.config.js](file://frontend/antd/steps/gradio.config.js) +- [__init__.py](file://backend/modelscope_studio/components/antd/steps/__init__.py) +- [README.md](file://docs/components/antd/steps/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The Steps component guides users through multiple stages in sequence within a task flow, serving as a typical process indicator component. This component is based on Ant Design's Steps implementation, provided in a form directly usable from the Python backend via Gradio/Svelte frontend bridging. It supports multiple layout modes (horizontal/vertical), size specifications (default/small), state management (wait/process/finish/error), and custom progress dot rendering (progressDot slot). The component also provides integration capabilities for form wizards, business processes, user registration, and other scenarios, with support for style customization and responsive adaptation. + +## Project Structure + +The Steps component consists of frontend Svelte components and backend ModelScope component wrappers, with frontend-backend interaction following Gradio component conventions. Key files are distributed as follows: + +- Frontend: `steps.tsx` (main component), `steps.item.tsx` (step item wrapper), `Index.svelte` (step item entry), `context.ts` (step item context), `package.json` (export config), `gradio.config.js` (build config) +- Backend: `__init__.py` (Python wrapper, exposing properties and events) +- Documentation: `README.md` (component description and example placeholders) + +```mermaid +graph TB +subgraph "Frontend" +F_steps_tsx["steps.tsx
Main Component"] +F_item_index["Index.svelte
Step Item Entry"] +F_item_impl["steps.item.tsx
Step Item Implementation"] +F_context["context.ts
Step Item Context"] +F_pkg["package.json
Export Config"] +F_cfg["gradio.config.js
Build Config"] +end +subgraph "Backend" +B_init["__init__.py
Python Wrapper"] +end +subgraph "Documentation" +D_readme["README.md
Component Description"] +end +F_steps_tsx --> F_context +F_steps_tsx --> F_item_impl +F_item_index --> F_item_impl +F_steps_tsx --> B_init +F_pkg --> F_steps_tsx +F_cfg --> F_steps_tsx +D_readme --> B_init +``` + +**Diagram Sources** + +- [steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [steps.item.tsx:1-14](file://frontend/antd/steps/item/steps.item.tsx#L1-L14) +- [Index.svelte:1-65](file://frontend/antd/steps/item/Index.svelte#L1-L65) +- [context.ts:1-7](file://frontend/antd/steps/context.ts#L1-L7) +- [package.json:1-15](file://frontend/antd/steps/package.json#L1-L15) +- [gradio.config.js:1-4](file://frontend/antd/steps/gradio.config.js#L1-L4) +- [**init**.py:1-95](file://backend/modelscope_studio/components/antd/steps/__init__.py#L1-L95) +- [README.md:1-8](file://docs/components/antd/steps/README.md#L1-L8) + +**Section Sources** + +- [steps.tsx:1-52](file://frontend/antd/steps/steps.tsx#L1-L52) +- [steps.item.tsx:1-14](file://frontend/antd/steps/item/steps.item.tsx#L1-L14) +- [Index.svelte:1-65](file://frontend/antd/steps/item/Index.svelte#L1-L65) +- [context.ts:1-7](file://frontend/antd/steps/context.ts#L1-L7) +- [package.json:1-15](file://frontend/antd/steps/package.json#L1-L15) +- [gradio.config.js:1-4](file://frontend/antd/steps/gradio.config.js#L1-L4) +- [**init**.py:1-95](file://backend/modelscope_studio/components/antd/steps/__init__.py#L1-L95) +- [README.md:1-8](file://docs/components/antd/steps/README.md#L1-L8) + +## Core Components + +- Main Component Steps (frontend): Responsible for receiving props, parsing slots (e.g., `progressDot`), merging items data sources (explicit items or slot items/default), and passing the final data to Ant Design's Steps. +- Step Item StepsItem (frontend): Serves as the React wrapper for step items, injecting step items into the Steps container through the ItemHandler context. +- Step Item Entry Index.svelte: Renders StepsItem in Svelte and handles properties such as visibility, class names, IDs, inline styles, and slots. +- Context: Provides `createItemsContext` capabilities to establish a stable parent-child relationship and data channel between Steps and StepsItem. +- Backend wrapper AntdSteps: Provides rich properties (`current`, `direction`, `size`, `status`, `type`, `responsive`, etc.) and declares supported slots (`progressDot`, `items`). + +**Section Sources** + +- [steps.tsx:10-49](file://frontend/antd/steps/steps.tsx#L10-L49) +- [steps.item.tsx:7-11](file://frontend/antd/steps/item/steps.item.tsx#L7-L11) +- [Index.svelte:16-64](file://frontend/antd/steps/item/Index.svelte#L16-L64) +- [context.ts:3-4](file://frontend/antd/steps/context.ts#L3-L4) +- [**init**.py:11-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L11-L77) + +## Architecture Overview + +The runtime control flow of the Steps component: the frontend Steps component reads the step item collection from context and resolves `items` or the default slot; if a `progressDot` slot exists, it renders via parameterized slot; otherwise falls back to function or boolean value form. Ant Design's Steps receives the final items and progress dot configuration, renders the UI, and triggers the `change` event (monitored by the backend). + +```mermaid +sequenceDiagram +participant Py as "Backend Component
AntdSteps" +participant FE as "Frontend Component
Steps" +participant Ctx as "Context
withItemsContextProvider" +participant AD as "Ant Design Steps" +Py->>FE : Render component and pass props +FE->>Ctx : Request current step item collection +Ctx-->>FE : Return items/default +FE->>FE : Resolve items or default slot +FE->>FE : Handle progressDot slot/function +FE->>AD : Pass items and progress dot configuration +AD-->>FE : Render UI +FE-->>Py : Trigger change event monitored by backend +``` + +**Diagram Sources** + +- [steps.tsx:16-44](file://frontend/antd/steps/steps.tsx#L16-L44) +- [context.ts:3-4](file://frontend/antd/steps/context.ts#L3-L4) +- [**init**.py:16-20](file://backend/modelscope_studio/components/antd/steps/__init__.py#L16-L20) + +**Section Sources** + +- [steps.tsx:16-44](file://frontend/antd/steps/steps.tsx#L16-L44) +- [context.ts:3-4](file://frontend/antd/steps/context.ts#L3-L4) +- [**init**.py:16-20](file://backend/modelscope_studio/components/antd/steps/__init__.py#L16-L20) + +## Detailed Component Analysis + +### Steps Main Component (Steps) + +- Functional responsibilities + - Receives all available props for Ant Design Steps and extends children support. + - Reads step item collection from context; prefers explicit items, then uses default slot items/default. + - Progress dot configuration supports two forms: slot `progressDot` (parameterized rendering) or function/boolean value. + - Uses `useMemo` to stabilize items, avoiding unnecessary re-renders. +- Key behaviors + - Hides children (`display: none`) to avoid duplicate rendering; actual content is injected via slots. + - `progressDot` priority: uses slot rendering if a slot exists; otherwise uses function or native boolean/string configuration. +- Typical usage + - Directly pass a steps array in `items`, or inject step items via slots. + - Use the `progressDot` slot to customize the rendering logic of each step indicator. + +```mermaid +flowchart TD +Start(["Enter Steps Render"]) --> ReadCtx["Read items/default from context"] +ReadCtx --> HasExplicit{"Are explicit items provided?"} +HasExplicit --> |Yes| UseExplicit["Use explicit items"] +HasExplicit --> |No| UseDefault["Use default slot items/default"] +UseExplicit --> ResolveItems["Resolve step item list"] +UseDefault --> ResolveItems +ResolveItems --> HasProgressDotSlot{"Does progressDot slot exist?"} +HasProgressDotSlot --> |Yes| RenderSlot["Parameterized slot rendering"] +HasProgressDotSlot --> |No| UseFuncOrProp["Use function/boolean/string configuration"] +RenderSlot --> RenderAD["Render Ant Design Steps"] +UseFuncOrProp --> RenderAD +RenderAD --> End(["Complete"]) +``` + +**Diagram Sources** + +- [steps.tsx:18-44](file://frontend/antd/steps/steps.tsx#L18-L44) + +**Section Sources** + +- [steps.tsx:10-49](file://frontend/antd/steps/steps.tsx#L10-L49) + +### Step Item (StepsItem) + +- Functional responsibilities + - Serves as the React wrapper for step items, combining step item properties with context, handed to `ItemHandler`. + - Bridges TypeScript/React components to the Svelte ecosystem via `sveltify`. +- Integration key points + - Works with Steps context to ensure step items are correctly injected into the container. + - Supports additional property pass-through and internal index (`itemIndex`) passing. + +```mermaid +classDiagram +class StepsItem { ++props : step item properties ++Renders to ItemHandler +} +class ItemHandler { ++Inject step item ++Maintain context +} +StepsItem --> ItemHandler : "Wrap and inject" +``` + +**Diagram Sources** + +- [steps.item.tsx:7-11](file://frontend/antd/steps/item/steps.item.tsx#L7-L11) +- [context.ts:3-4](file://frontend/antd/steps/context.ts#L3-L4) + +**Section Sources** + +- [steps.item.tsx:7-11](file://frontend/antd/steps/item/steps.item.tsx#L7-L11) +- [context.ts:3-4](file://frontend/antd/steps/context.ts#L3-L4) + +### Step Item Entry (Index.svelte) + +- Functional responsibilities + - Dynamically imports StepsItem in Svelte and renders it. + - Handles visibility, class names, IDs, inline styles, slots, and other properties. + - Injects child nodes into StepsItem via `{@render children()}`. +- Design key points + - Uses `getProps`/`processProps` to retrieve and filter internal properties that don't need pass-through. + - Gets the slot key via `getSlotKey` and passes it to StepsItem for slot identification. + +```mermaid +flowchart TD +SStart(["Index.svelte Render Start"]) --> ImportItem["Dynamic import StepsItem"] +ImportItem --> GetProps["Extract component and additional properties"] +GetProps --> CheckVisible{"Visibility check"} +CheckVisible --> |Hidden| Skip["Skip rendering"] +CheckVisible --> |Visible| RenderItem["Render StepsItem with properties/slots"] +RenderItem --> SEnd(["End"]) +Skip --> SEnd +``` + +**Diagram Sources** + +- [Index.svelte:16-64](file://frontend/antd/steps/item/Index.svelte#L16-L64) + +**Section Sources** + +- [Index.svelte:1-65](file://frontend/antd/steps/item/Index.svelte#L1-L65) + +### Backend Wrapper (AntdSteps) + +- Property overview (selected) + - Current step `current`, direction `direction` (horizontal/vertical), initial value `initial`, label position `label_placement`, title position `title_placement`, percentage `percent`, progress dot `progress_dot`, responsive `responsive`, size `size` (small/default), status `status` (wait/process/finish/error), type `type` (default/navigation/inline), root class name `root_class_name`, class names `class_names`, styles `styles`, slots `items`/`progressDot`, etc. +- Events + - `change`: Listens for step change events (bound by the backend). +- Others + - `FRONTEND_DIR` points to the frontend steps component directory. + - `skip_api` is `True`, indicating the component does not participate in the standard API flow. + +```mermaid +classDiagram +class AntdSteps { ++current : number ++direction : "horizontal|vertical" ++initial : number ++label_placement : "horizontal|vertical" ++title_placement : "horizontal|vertical"|None ++percent : number|None ++progress_dot : bool|string ++responsive : bool ++size : "small|default"|None ++status : "wait|process|finish|error" ++type : "default|navigation|inline" ++items : list|None ++root_class_name : str|None ++class_names : dict|str|None ++styles : dict|str|None ++EVENTS : ["change"] ++SLOTS : ["progressDot","items"] +} +``` + +**Diagram Sources** + +- [**init**.py:25-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L25-L77) + +**Section Sources** + +- [**init**.py:11-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L11-L77) + +## Dependency Analysis + +- Frontend dependencies + - Uses Ant Design's Steps as the underlying UI component. + - Bridges React components to Svelte via `sveltify`. + - Provides step item context via `createItemsContext`. + - Renders step items and slots using `renderItems`/`renderParamsSlot`. +- Backend dependencies + - Interacts with Gradio via `ModelScopeLayoutComponent`. + - Specifies the frontend component directory via `resolve_frontend_dir`. +- Exports and build + - `package.json` specifies Gradio and default export paths. + - `gradio.config.js` performs build configuration based on global `defineConfig`. + +```mermaid +graph LR +Pkg["package.json"] --> StepsTSX["steps.tsx"] +Cfg["gradio.config.js"] --> StepsTSX +StepsTSX --> AD["Ant Design Steps"] +StepsTSX --> Ctx["createItemsContext"] +StepsTSX --> Utils["renderItems / renderParamsSlot"] +StepsTSX --> Py["AntdSteps(__init__.py)"] +``` + +**Diagram Sources** + +- [package.json:4-12](file://frontend/antd/steps/package.json#L4-L12) +- [gradio.config.js:1-4](file://frontend/antd/steps/gradio.config.js#L1-L4) +- [steps.tsx:1-8](file://frontend/antd/steps/steps.tsx#L1-L8) +- [**init**.py:77-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L77-L77) + +**Section Sources** + +- [package.json:1-15](file://frontend/antd/steps/package.json#L1-L15) +- [gradio.config.js:1-4](file://frontend/antd/steps/gradio.config.js#L1-L4) +- [steps.tsx:1-8](file://frontend/antd/steps/steps.tsx#L1-L8) +- [**init**.py:77-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L77-L77) + +## Performance Considerations + +- Data stabilization: Uses `useMemo` to stabilize items, reducing unnecessary re-renders. +- Slot rendering: The `progressDot` slot uses parameterized rendering to avoid repeatedly creating complex structures in each render. +- Visibility control: The step item entry checks `visible` to hide invisible items, reducing DOM overhead. +- Event binding: Binds the `change` event only when needed, avoiding unnecessary callback triggers. + +[This section contains general performance advice and does not require specific file references] + +## Troubleshooting Guide + +- Issue: Step items not displaying + - Check whether Steps has correctly injected `items` or slot `items/default`. + - Confirm the step item's `visible` property is true. +- Issue: Progress dots not rendering as expected + - If using the `progressDot` slot, confirm the slot key matches the component conventions. + - If using function/boolean value, confirm the passed configuration matches Ant Design's expectations. +- Issue: Styles or class names not taking effect + - Check whether `root_class_name`, `class_names`, `styles` are correctly passed. + - Confirm CSS scope and override rules. +- Issue: Responsive layout anomalies + - Check whether the combination of `responsive` and `direction` is as expected. + - Confirm parent container width and breakpoint settings. + +**Section Sources** + +- [steps.tsx:20-44](file://frontend/antd/steps/steps.tsx#L20-L44) +- [Index.svelte:49-64](file://frontend/antd/steps/item/Index.svelte#L49-L64) +- [**init**.py:25-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L25-L77) + +## Conclusion + +The Steps component achieves complete wrapping and extension of Ant Design Steps through a clear frontend-backend layered design. It supports multiple layouts, multiple states, customizable progress dots, and responsive adaptation, suitable for form wizards, business processes, user registration, and other scenarios. Through context and slot mechanisms, the component has good composability and maintainability. + +[This section contains summary content and does not require specific file references] + +## Appendix + +### Step Item (Item) Configuration Options + +- Basic properties + - Title: Text for the step item title. + - Description: Description text for the step item. + - Icon: Icon element for the step item. +- State and behavior + - Status: `wait`, `process`, `finish`, `error`, indicating the current state of the step. + - Visibility: `visible` controls whether the step item is rendered. + - Internal index: `itemIndex` identifies the step item's position in the list. +- Slots and styles + - Slots: Support injecting custom content via slots. + - Class names and IDs: `elem_classes`, `elem_id` for styling and positioning. + - Inline styles: `elem_style` for local style overrides. + +**Section Sources** + +- [Index.svelte:16-64](file://frontend/antd/steps/item/Index.svelte#L16-L64) +- [steps.item.tsx:7-11](file://frontend/antd/steps/item/steps.item.tsx#L7-L11) + +### Layout Modes and Application Scenarios + +- Horizontal steps bar (horizontal) + - Suitable for linear processes such as form wizards and payment flows. +- Vertical steps bar (vertical) + - Suitable for long processes or scenarios emphasizing chronological order. +- Small steps bar (small) + - Suitable for space-constrained or simplified interfaces. + +**Section Sources** + +- [**init**.py:30-39](file://backend/modelscope_studio/components/antd/steps/__init__.py#L30-L39) + +### Integration with Form Wizards, Business Processes, and User Registration + +- Form wizards + - Use `current` and `status` to control the current step and state; synchronize backend state via `change` events. +- Business processes + - Use `direction` and `responsive` for process visualization; use `progress_dot` to customize process nodes. +- User registration + - Use `size` and `type` to switch between different styles; use `items` and slots to organize registration steps. + +**Section Sources** + +- [**init**.py:25-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L25-L77) +- [steps.tsx:16-44](file://frontend/antd/steps/steps.tsx#L16-L44) + +### Style Customization and Responsive Adaptation + +- Style customization + - Use `root_class_name`, `class_names`, `styles` for overall and local style control. + - Granularly control step item appearance via `elem_classes`, `elem_id`, `elem_style`. +- Responsive adaptation + - Use the combination of `responsive` and `direction` to adapt for mobile and desktop layouts. + +**Section Sources** + +- [**init**.py:40-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L40-L77) +- [Index.svelte:52-58](file://frontend/antd/steps/item/Index.svelte#L52-L58) + +### Usage Examples and Best Practices + +- Example references + - The documentation provides basic example placeholders; combine with `AntdSteps` properties and slots for demonstrations. +- Best practices + - Clearly define step states and navigation logic to avoid state confusion. + - Use the `progress_dot` slot judiciously to maintain visual consistency. + - Break down steps for complex processes to improve user experience. + +**Section Sources** + +- [README.md:1-8](file://docs/components/antd/steps/README.md#L1-L8) +- [**init**.py:25-77](file://backend/modelscope_studio/components/antd/steps/__init__.py#L25-L77) diff --git a/.wiki/en/Ant Design Components/Other Components.md b/.wiki/en/Ant Design Components/Other Components.md new file mode 100644 index 00000000..1e73e57f --- /dev/null +++ b/.wiki/en/Ant Design Components/Other Components.md @@ -0,0 +1,325 @@ +# Other Components + + +**Files referenced in this document** +- [frontend/antd/affix/affix.tsx](file://frontend/antd/affix/affix.tsx) +- [frontend/antd/affix/Index.svelte](file://frontend/antd/affix/Index.svelte) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/config-provider/locales.ts](file://frontend/antd/config-provider/locales.ts) +- [frontend/antd/config-provider/Index.svelte](file://frontend/antd/config-provider/Index.svelte) +- [frontend/antd/float-button/float-button.tsx](file://frontend/antd/float-button/float-button.tsx) +- [frontend/antd/layout/layout.base.tsx](file://frontend/antd/layout/layout.base.tsx) +- [frontend/antd/float-button/group/float-button.group.less](file://frontend/antd/float-button/group/float-button.group.less) +- [frontend/antd/menu/menu.less](file://frontend/antd/menu/menu.less) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This chapter focuses on the "Other Components" scenario of Ant Design Studio, covering two types of auxiliary components: Affix and ConfigProvider. We will systematically explain positioning mechanisms, scroll monitoring and boundary handling, as well as theme customization, language switching, and component default configuration, combining real implementations from the repository to provide actionable application scenarios, performance optimization and memory management suggestions, and best practices for component collaboration. + +## Project Structure + +- Frontend uses Svelte + React hybrid encapsulation mode: Svelte layer handles property/slot pass-through and conditional rendering, React layer handles specific UI behaviors (such as Affix, ConfigProvider, etc.). +- Utility layer provides common capabilities, such as converting external functions into function wrappers that can be safely used in React. +- Style layer ensures theme and prefix isolation through CSS-in-JS StyleProvider, avoiding global pollution. + +```mermaid +graph TB +subgraph "Svelte Layer" +A_Index["Affix/Index.svelte"] +C_Index["ConfigProvider/Index.svelte"] +end +subgraph "React Layer" +A_Impl["affix.tsx
Wraps Ant Design Affix"] +C_Impl["config-provider.tsx
Wraps Ant Design ConfigProvider"] +FBT["float-button.tsx
Float Button"] +LBase["layout.base.tsx
Layout Base"] +end +subgraph "Utilities and Resources" +UF["useFunction.ts
Function Wrapper"] +LOC["locales.ts
Multi-language Mapping and On-demand Loading"] +FBGroupLess["float-button.group.less
Group Styles"] +MenuLess["menu.less
Menu Styles"] +end +A_Index --> A_Impl +C_Index --> C_Impl +A_Impl --> UF +C_Impl --> UF +C_Impl --> LOC +FBT --> UF +LBase --> |"Layout Composition"| A_Impl +LBase --> |"Layout Composition"| C_Impl +FBGroupLess --> FBT +MenuLess --> C_Impl +``` + +Diagram Source + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [frontend/antd/float-button/group/float-button.group.less:1-31](file://frontend/antd/float-button/group/float-button.group.less#L1-L31) +- [frontend/antd/menu/menu.less:1-45](file://frontend/antd/menu/menu.less#L1-L45) + +Section Source + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [frontend/antd/float-button/group/float-button.group.less:1-31](file://frontend/antd/float-button/group/float-button.group.less#L1-L31) +- [frontend/antd/menu/menu.less:1-45](file://frontend/antd/menu/menu.less#L1-L45) + +## Core Components + +- Affix + - Positioning Mechanism: Calculates element fixed state based on target container scroll position; supports custom target containers (such as page or a scroll area). + - Boundary Handling: Controls fixed/unbind timing through threshold to avoid elements being incorrectly fixed or prematurely unbound. + - Scroll Monitoring: Converts externally passed container selectors into React-usable callbacks through function wrappers. +- ConfigProvider + - Theme Customization: Supports light/dark mode and compact algorithm switch, dynamically combining algorithm lists to achieve theme switching. + - Language Switching: According to browser or specified language, asynchronously loads Antd language pack and dayjs language pack on demand. + - Component Default Configuration: Uniformly encapsulates global behaviors like getPopupContainer, getTargetContainer, renderEmpty, etc. + - Style Isolation: Injects high-priority styles through CSS-in-JS StyleProvider to avoid style conflicts. + +Section Source + +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) + +## Architecture Overview + +The diagram below shows the interaction relationship between Svelte and React layers, as well as ConfigProvider's extension points in theme and language aspects. + +```mermaid +sequenceDiagram +participant S as "Svelte Layer" +participant R as "React Layer" +participant U as "Utility Layer" +participant L as "Language Resources" +S->>R : Pass-through properties/slots +R->>U : useFunction wraps container selector/callback +R->>L : On-demand load language pack and dayjs language +L-->>R : Return language pack object +R-->>S : Render result with theme and language +``` + +Diagram Source + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) + +## Detailed Component Analysis + +### Affix Component + +- Design Points + - Svelte layer handles conditional rendering and property pass-through, supports visible for display control. + - React layer converts externally passed container selectors into React-executable functions through useFunction, ensuring stable and reliable scroll monitoring. + - Supports slots and child node rendering for carrying complex content in fixed state. +- Key Flow + - Property Processing: Maps get_target to target, handled internally by the Affix component. + - Rendering: Only renders when visible is true, reducing unnecessary DOM overhead. +- Usage Suggestions + - For non-window scroll containers, be sure to explicitly pass the target function to point to the correct container. + - Set thresholds reasonably to avoid jitter caused by frequent switching between fixed/unbound states. + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant S as "Affix/Index.svelte" +participant R as "affix.tsx" +participant A as "Antd Affix" +UI->>S : Pass visible/get_target/properties +S->>R : Pass-through properties and slots +R->>R : useFunction wraps target +R->>A : Render Affix and pass target +A-->>UI : Fixed/unbound state update +``` + +Diagram Source + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) + +Section Source + +- [frontend/antd/affix/Index.svelte:1-72](file://frontend/antd/affix/Index.svelte#L1-L72) +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) + +### ConfigProvider Component + +- Design Points + - Theme: Dynamically combines algorithms through themeMode and theme.algorithm, supporting dark and compact modes. + - Language: Automatically maps to available language sets based on locale, asynchronously loads Antd language pack and dayjs language pack on demand. + - Container: Uniformly provides function wrappers for getPopupContainer and getTargetContainer, ensuring popups and overlays render to the correct container. + - Slots: Supports slot parameters like renderEmpty, implemented through renderParamsSlot for flexible extension. + - Styles: Injects high-priority styles through StyleProvider to avoid style conflicts. +- Key Flow + - Language Initialization: Parses browser language or passed locale into standard format and loads corresponding language pack. + - Theme Initialization: Generates algorithm array based on themeMode and user configuration, passes to Ant Design. + - Container Callback: Uses useFunction to wrap callbacks, ensuring stable operation within React lifecycle. + - Slot Rendering: Wraps slot content as ReactSlot or renderParamsSlot, maintaining type safety. + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant S as "ConfigProvider/Index.svelte" +participant R as "config-provider.tsx" +participant U as "useFunction.ts" +participant LOC as "locales.ts" +participant SP as "StyleProvider" +UI->>S : Pass theme_mode/locale/theme etc. +S->>R : Pass-through properties and slots +R->>U : useFunction wraps getPopupContainer/getTargetContainer/renderEmpty +R->>LOC : Parse locale and on-demand load language pack +LOC-->>R : Return language pack object +R->>SP : Inject high-priority styles +SP-->>UI : Render subtree with theme and language +``` + +Diagram Source + +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) + +Section Source + +- [frontend/antd/config-provider/Index.svelte:1-72](file://frontend/antd/config-provider/Index.svelte#L1-L72) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) + +### FloatButton and Layout.Base + +- FloatButton + - Supports slots like icon/description/tooltip/badge, implemented through ReactSlot for flexible rendering. + - tooltip supports object configuration and callback wrapping, ensuring popup container and callback stability. +- Layout.Base + - Dynamically selects Header/Footer/Content/Layout through component type selector, unifies class name prefix for easy style control. + +Section Source + +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +## Dependency Analysis + +- Component Coupling + - Both Affix and ConfigProvider depend on useFunction for function wrapping, reducing cross-layer call risks. + - ConfigProvider depends on language mapping and on-demand loading capabilities provided by locales.ts. +- External Dependencies + - Ant Design component library and dayjs language packs. + - CSS-in-JS StyleProvider for style isolation and priority control. +- Potential Circular Dependencies + - No direct circular dependencies in current implementation; if business side re-introduces ConfigProvider/Affix in slots, carefully control rendering levels. + +```mermaid +graph LR +A["affix.tsx"] --> UF["useFunction.ts"] +C["config-provider.tsx"] --> UF +C --> LOC["locales.ts"] +C --> SP["StyleProvider"] +F["float-button.tsx"] --> UF +L["layout.base.tsx"] --> |"Composition"| A +L --> |"Composition"| C +``` + +Diagram Source + +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) + +Section Source + +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [frontend/antd/float-button/float-button.tsx:1-75](file://frontend/antd/float-button/float-button.tsx#L1-L75) +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) + +## Performance Considerations + +- Scroll Monitoring and Repaint + - Affix's target should point to minimized scroll containers as much as possible to avoid pressure on full-page scrolling. + - Set thresholds and fixed heights reasonably to reduce reflow and repaint caused by frequent switching. +- Language Pack On-demand Loading + - ConfigProvider only triggers language pack loading when locale changes, avoiding repeated requests. + - dayjs language pack and Antd language pack are loaded asynchronously, note network and caching strategies. +- Function Wrapping and Stability + - Use useFunction to wrap callbacks to avoid new functions being generated on each render causing unnecessary child component updates. +- Style Injection + - StyleProvider high-priority injection reduces style override costs; avoid frequent theme switching in hot paths. + +## Troubleshooting Guide + +- Affix not working + - Check whether the target function is correctly passed, or whether updates are not triggered when container scrolls. + - Confirm visible condition is satisfied and container has scrollbar. +- Language switching ineffective + - Check whether locale has a mapping in locales.ts; confirm asynchronous loading succeeded. + - Ensure dayjs.locale switching succeeded. +- Theme switching abnormal + - Check whether themeMode and theme.algorithm combination is as expected. + - Note algorithm array concatenation order and null value filtering. +- Slot rendering issues + - Confirm slot key and renderParamsSlot mapping consistency. + - ReactSlot's clone parameter should be enabled as needed to avoid duplicate mounting. + +Section Source + +- [frontend/antd/affix/affix.tsx:1-14](file://frontend/antd/affix/affix.tsx#L1-L14) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/config-provider/locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) + +## Conclusion + +- Affix and ConfigProvider, as auxiliary components, undertake the key responsibilities of "positioning and scrolling" and "theme and language" in Ant Design Studio. +- Through layered encapsulation of Svelte and React, both usability and powerful extensibility are guaranteed. +- In actual projects, it is recommended to prioritize using ConfigProvider for global unified configuration at the application root, then use Affix locally on pages that need fixed layouts or toolbars. + +## Appendix + +- Best Practices for Component Collaboration + - Place ConfigProvider at the application root to centrally manage theme and language; use Affix locally on pages that need fixed elements. + - Use Layout.Base to unify layout structure, combined with FloatButton to improve interaction efficiency. + - For complex slot scenarios, prefer using ReactSlot and renderParamsSlot to ensure type safety and controllable rendering. +- Styles and Themes + - Avoid style conflicts through StyleProvider and prefix class names (like ms-gr-ant). + - Menu and float button style files can be used as references, adjust border-radius, spacing, and transition effects as needed. diff --git a/.wiki/en/Ant Design X Components/Ant Design X Components.md b/.wiki/en/Ant Design X Components/Ant Design X Components.md new file mode 100644 index 00000000..207c9fdb --- /dev/null +++ b/.wiki/en/Ant Design X Components/Ant Design X Components.md @@ -0,0 +1,626 @@ +# Ant Design X Components + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/antdx/file_card/__init__.py](file://backend/modelscope_studio/components/antdx/file_card/__init__.py) +- [backend/modelscope_studio/components/antdx/file_card/list/__init__.py](file://backend/modelscope_studio/components/antdx/file_card/list/__init__.py) +- [backend/modelscope_studio/components/antdx/file_card/list/item/__init__.py](file://backend/modelscope_studio/components/antdx/file_card/list/item/__init__.py) +- [backend/modelscope_studio/components/antdx/mermaid/__init__.py](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py) +- [backend/modelscope_studio/components/antdx/folder/directory_icon/__init__.py](file://backend/modelscope_studio/components/antdx/folder/directory_icon/__init__.py) +- [backend/modelscope_studio/components/antdx/folder/tree_node/__init__.py](file://backend/modelscope_studio/components/antdx/folder/tree_node/__init__.py) +- [frontend/antdx/file-card/file-card.tsx](file://frontend/antdx/file-card/file-card.tsx) +- [frontend/antdx/file-card/base.tsx](file://frontend/antdx/file-card/base.tsx) +- [frontend/antdx/mermaid/mermaid.tsx](file://frontend/antdx/mermaid/mermaid.tsx) +- [frontend/antdx/folder/folder.tsx](file://frontend/antdx/folder/folder.tsx) +- [frontend/antdx/thought-chain/thought-chain.tsx](file://frontend/antdx/thought-chain/thought-chain.tsx) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [frontend/antdx/conversations/conversations.tsx](file://frontend/antdx/conversations/conversations.tsx) +- [frontend/antdx/welcome/welcome.tsx](file://frontend/antdx/welcome/welcome.tsx) +- [frontend/antdx/prompts/prompts.tsx](file://frontend/antdx/prompts/prompts.tsx) +- [frontend/antdx/attachments/attachments.tsx](file://frontend/antdx/attachments/attachments.tsx) +- [frontend/antdx/sender/sender.tsx](file://frontend/antdx/sender/sender.tsx) +- [frontend/antdx/suggestion/suggestion.tsx](file://frontend/antdx/suggestion/suggestion.tsx) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/think/think.tsx](file://frontend/antdx/think/think.tsx) +- [frontend/antdx/notification/notification.tsx](file://frontend/antdx/notification/notification.tsx) +- [frontend/antdx/sources/sources.tsx](file://frontend/antdx/sources/sources.tsx) + + +## Update Summary + +**Changes Made** + +- Added file card component system (FileCard, FileCardList, FileCardListItem) +- Added Mermaid diagram component +- Added folder component (Folder) and its subcomponents (DirectoryIcon, TreeNode) +- Added thought chain component (ThoughtChain) and its subcomponents +- Updated component export structure to sync with Ant Design X version +- Enhanced component collaboration capabilities, supporting richer slot-based rendering + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Usability Recommendations](#performance-and-usability-recommendations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the Ant Design X component library for ModelScope Studio, designed for machine learning and AI application scenarios. It systematically covers general components (such as bubbles, conversation lists), wake components (welcome pages, prompts), expression components (attachments, sender, suggestions), confirmation components (thought chain), feedback components (actions), and newly added advanced components like file cards, Mermaid diagrams, and folders. It provides end-to-end examples and best practices to help developers build consistent, scalable, and user-friendly interfaces for conversational AI, multimodal input, knowledge retrieval augmentation, and chart visualization scenarios. + +## Project Structure + +The Ant Design X component library exports through Python packages on the backend and encapsulates @ant-design/x capabilities using Svelte/React bidirectional bridging on the frontend, exposing composable components uniformly. The overall structure is as follows: + +```mermaid +graph TB +subgraph "Backend Export Layer" +A["backend/modelscope_studio/components/antdx/__init__.py"] +B["backend/modelscope_studio/components/antdx/components.py"] +end +subgraph "Frontend Wrapper Layer" +C["frontend/antdx/bubble/bubble.tsx"] +D["frontend/antdx/conversations/conversations.tsx"] +E["frontend/antdx/welcome/welcome.tsx"] +F["frontend/antdx/prompts/prompts.tsx"] +G["frontend/antdx/attachments/attachments.tsx"] +H["frontend/antdx/sender/sender.tsx"] +I["frontend/antdx/suggestion/suggestion.tsx"] +J["frontend/antdx/actions/actions.tsx"] +K["frontend/antdx/think/think.tsx"] +L["frontend/antdx/notification/notification.tsx"] +M["frontend/antdx/sources/sources.tsx"] +N["frontend/antdx/file-card/file-card.tsx"] +O["frontend/antdx/mermaid/mermaid.tsx"] +P["frontend/antdx/folder/folder.tsx"] +Q["frontend/antdx/thought-chain/thought-chain.tsx"] +end +A --> C +A --> D +A --> E +A --> F +A --> G +A --> H +A --> I +A --> J +A --> K +A --> L +A --> M +A --> N +A --> O +A --> P +A --> Q +B --> C +B --> D +B --> E +B --> F +B --> G +B --> H +B --> I +B --> J +B --> K +B --> L +B --> M +B --> N +B --> O +B --> P +B --> Q +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [frontend/antdx/folder/folder.tsx:1-124](file://frontend/antdx/folder/folder.tsx#L1-L124) +- [frontend/antdx/thought-chain/thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) + +**Section Source** + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Core Components + +This section provides a categorized functional overview of key AI scenario components, including newly added advanced components, for quick identification and combined use. + +- General Components + - Bubble: Used to display message content, avatars, additional information, and footers, supporting slot-based rendering and editable configurations. + - Conversations: Used to display and manage historical conversations, supporting menus, grouping, and expand controls. +- Wake Components + - Welcome: Used as a guide page after application startup or reset, supporting titles, descriptions, icons, and additional areas. + - Prompts: Used to display a set of clickable prompt templates, helping users quickly start conversations. +- Expression Components + - Attachments: Used to upload and manage files, supporting placeholders, previews, image properties, and upload hooks. + - Sender: Used for text input and paste file upload, supporting skill hints, prefix/suffix, and submit interception. + - Suggestion: Used for autocomplete/suggestion panels in input context, supporting trigger strategies and slot-based item rendering. +- Confirmation Components + - Think: Used to display loading state, icons, and titles during reasoning, enhancing perceptibility. + - ThoughtChain: Used to display multi-step reasoning processes, supporting sub-item components and slot-based rendering. +- Feedback Components + - Actions: Used to provide action entries (such as copy, download, feedback) on the right side of content area, supporting dropdown menus and popup rendering. +- Advanced Components + - FileCard: Used to display file information, supporting multiple types, previews, masks, and loading states. + - Mermaid Diagram: Used to render Mermaid flowcharts, sequence diagrams, etc., supporting theme switching and custom actions. + - Folder: Used for file system browsing, supporting directory icon mapping, file content services, and preview rendering. +- Tool Components + - XProvider: Global configuration and context provider, extending antd's ConfigProvider, providing theme, language, popup container, and other global capabilities for @ant-design/x components. + - CodeHighlighter: Code highlighting display component, supporting theme customization, header slots, and syntax highlighting style overrides. + - Mermaid: Flowchart/mind map component, integrating highlighting and action item rendering, supporting light/dark theme switching and custom actions. + - Notification: Browser notification wrapper, providing permission requests, open/close, visibility control, and callbacks. +- Data Components + - FileCard: Used to display a single file card, supporting image placeholder, preview configuration, mask, and loading indicator slot customization. + - Folder: Used to display folder tree structure, supporting treeData, directoryIcons, empty state rendering, directory title, preview rendering slots. + - Sources: Used to display data source list, supporting items and title slots. + - Think: Used to display "thinking" records and status, supporting loading, icon, title slots for different visual feedback in different states. + +**Section Source** + +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [frontend/antdx/conversations/conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [frontend/antdx/welcome/welcome.tsx:1-44](file://frontend/antdx/welcome/welcome.tsx#L1-L44) +- [frontend/antdx/prompts/prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [frontend/antdx/attachments/attachments.tsx:1-413](file://frontend/antdx/attachments/attachments.tsx#L1-L413) +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) +- [frontend/antdx/suggestion/suggestion.tsx:1-165](file://frontend/antdx/suggestion/suggestion.tsx#L1-L165) +- [frontend/antdx/think/think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) +- [frontend/antdx/thought-chain/thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [frontend/antdx/folder/folder.tsx:1-124](file://frontend/antdx/folder/folder.tsx#L1-L124) + +## Architecture Overview + +The diagram below shows how frontend components bridge to @ant-design/x and achieve flexible rendering and event handling through slots and function wrapping, including the architecture of newly added components. + +```mermaid +graph TB +subgraph "Frontend Wrapper" +U["sveltify wrapper
slot rendering/function wrapping"] +V["@ant-design/x native components"] +W["Utilities and context
renderItems / renderParamsSlot / useFunction"] +X["File service and resource resolution
getFetchableUrl / resolveFileSrc"] +Y["Theme and styles
themeMode / highlightProps"] +end +U --> V +U --> W +U --> X +U --> Y +``` + +**Diagram Source** + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [frontend/antdx/folder/folder.tsx:1-124](file://frontend/antdx/folder/folder.tsx#L1-L124) +- [frontend/antdx/thought-chain/thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) + +## Component Details + +### General Components + +#### Bubble + +- Key Capabilities + - Supports slot-based rendering for avatars, titles, content, footers, and extra areas. + - Supports editable configuration (including "OK/Cancel" text slots). + - Supports loading state and content rendering function wrapping. +- Usage Recommendations + - Use as a message carrier in conversation flows, combined with Sender input and Attachments. + - For long content, enable editable and content rendering functions to improve interaction efficiency. +- Key Paths + - [frontend/antdx/bubble/bubble.tsx:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) + +**Section Source** + +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) + +#### Conversations + +- Key Capabilities + - Supports slot-based configuration for menu items, overflow indicators, and expand icons. + - Supports functional configuration for grouping and collapse behavior. + - Internally reuses menu context for unified event propagation and DOM blocking. +- Usage Recommendations + - Combine with Sender/Attachments to form a closed loop of "input-generate-review". + - Implement "delete, rename, export" operations through menu items. +- Key Paths + - [frontend/antdx/conversations/conversations.tsx:59-175](file://frontend/antdx/conversations/conversations.tsx#L59-L175) + +**Section Source** + +- [frontend/antdx/conversations/conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) + +### Wake Components + +#### Welcome + +- Key Capabilities + - Supports slot-based title, description, icon, and additional areas. + - Icon supports passing file data and automatically resolves to accessible URL. +- Usage Recommendations + - Use as the first screen guide after application initialization or conversation reset. +- Key Paths + - [frontend/antdx/welcome/welcome.tsx:8-41](file://frontend/antdx/welcome/welcome.tsx#L8-L41) + +**Section Source** + +- [frontend/antdx/welcome/welcome.tsx:1-44](file://frontend/antdx/welcome/welcome.tsx#L1-L44) + +#### Prompts + +- Key Capabilities + - Supports title slot and item collection slot-based rendering. + - Provides item collection through context, simplifying external parameter passing. +- Usage Recommendations + - Place above welcome page or input box to help users quickly select intent templates. +- Key Paths + - [frontend/antdx/prompts/prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) + +**Section Source** + +- [frontend/antdx/prompts/prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) + +### Expression Components + +#### Attachments + +- Key Capabilities + - Supports placeholders, previews, image properties, upload hooks, and maximum count limits. + - Supports custom beforeUpload, customRequest, isImageUrl, previewFile, and other functions. + - Slot-based extension for "extra icons, download/remove/preview icons, placeholder content". +- Usage Recommendations + - Combine with Sender's paste upload for drag/paste-to-upload functionality. + - Note the interaction between maxCount and upload status to avoid concurrency conflicts. +- Key Paths + - [frontend/antdx/attachments/attachments.tsx:36-410](file://frontend/antdx/attachments/attachments.tsx#L36-L410) + +**Section Source** + +- [frontend/antdx/attachments/attachments.tsx:1-413](file://frontend/antdx/attachments/attachments.tsx#L1-L413) + +#### Sender + +- Key Capabilities + - Supports prefix/suffix/header/footer slots; supports "skill hint" configuration. + - Supports paste file upload callback, uniformly outputting file path array. + - Through value change hooks and submit interception, avoids mistaken submission when suggestion panel is open. +- Usage Recommendations + - Collaborate with Suggestion to ensure submission only after suggestion panel closes. + - Connect with backend streaming output via onValueChange. +- Key Paths + - [frontend/antdx/sender/sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) + +**Section Source** + +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) + +#### Suggestion + +- Key Capabilities + - Supports items slot and children slot-based rendering. + - Passes keyboard events and trigger logic through context, supporting custom shouldTrigger. + - Supports getPopupContainer functional configuration. +- Usage Recommendations + - Combine with Sender/Textarea to implement @mentions, /commands, keyword completion. + - Control open state and shouldTrigger to avoid triggering during IME composition. +- Key Paths + - [frontend/antdx/suggestion/suggestion.tsx:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) + +**Section Source** + +- [frontend/antdx/suggestion/suggestion.tsx:1-165](file://frontend/antdx/suggestion/suggestion.tsx#L1-L165) + +### Confirmation Components + +#### Think + +- Key Capabilities + - Displays loading state, icon, and title during reasoning, enhancing perceptibility. + - Supports slot-based override of default rendering. +- Usage Recommendations + - Insert before streaming output to clearly inform users that the model is thinking. +- Key Paths + - [frontend/antdx/think/think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +**Section Source** + +- [frontend/antdx/think/think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +#### ThoughtChain + +- Key Capabilities + - Supports multi-step reasoning process display, with built-in default and sub-item rendering logic. + - Provides item collection through context, supporting slot-based and default item fallback. + - Reuses common rendering utilities to maintain consistency with other components. +- Usage Recommendations + - Display step-by-step thinking process in complex reasoning scenarios. + - Combine with Bubble component to form a complete reasoning display chain. +- Key Paths + - [frontend/antdx/thought-chain/thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) + +**Section Source** + +- [frontend/antdx/thought-chain/thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) + +### Feedback Components + +#### Actions + +- Key Capabilities + - Supports dropdown menus, popup rendering, and menu item slot-based configuration. + - Reuses menu context for unified event propagation. +- Usage Recommendations + - Provide "copy, download, feedback" operations on the right side of Bubble or content card. +- Key Paths + - [frontend/antdx/actions/actions.tsx:17-120](file://frontend/antdx/actions/actions.tsx#L17-L120) + +**Section Source** + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) + +### Advanced Components + +#### FileCard + +- Key Capabilities + - Supports multiple file types (image, file, audio, video) display. + - Supports slot-based configuration for icons, descriptions, masks, loading states. + - Built-in image preview functionality, supporting custom preview container and toolbar. + - Automatically resolves file sources, supporting local files and remote URLs. +- Usage Recommendations + - Display file information after upload completion. + - Combine with file list component to form a complete file management interface. +- Key Paths + - [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) + - [frontend/antdx/file-card/base.tsx:15-41](file://frontend/antdx/file-card/base.tsx#L15-L41) + +**Section Source** + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) + +#### Mermaid Diagram + +- Key Capabilities + - Supports Mermaid syntax diagram rendering, including flowcharts, sequence diagrams, etc. + - Built-in syntax highlighting, supporting light/dark theme switching. + - Supports custom action buttons and header slots. + - Reuses action component context for consistent interaction experience. +- Usage Recommendations + - Use in document generation or process display scenarios. + - Combine with thought chain component to display complex algorithm flows. +- Key Paths + - [frontend/antdx/mermaid/mermaid.tsx:33-82](file://frontend/antdx/mermaid/mermaid.tsx#L33-L82) + +**Section Source** + +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) + +#### Folder + +- Key Capabilities + - Supports file system browsing and directory structure display. + - Supports custom directory icon mapping and node rendering. + - Built-in file content service, supporting dynamic loading of file content. + - Supports empty state rendering, preview rendering, and title slot-based configuration. +- Usage Recommendations + - Use in knowledge base or project file management scenarios. + - Combine with file card component to provide complete file browsing experience. +- Key Paths + - [frontend/antdx/folder/folder.tsx:16-121](file://frontend/antdx/folder/folder.tsx#L16-L121) + +**Section Source** + +- [frontend/antdx/folder/folder.tsx:1-124](file://frontend/antdx/folder/folder.tsx#L1-L124) + +### Other Utility Components + +#### Notification + +- Key Capabilities + - Lightweight notification based on browser notification permission, supporting visibility control and permission callbacks. +- Usage Recommendations + - Push desktop notifications when background tasks complete or important events occur. +- Key Paths + - [frontend/antdx/notification/notification.tsx:6-50](file://frontend/antdx/notification/notification.tsx#L6-L50) + +**Section Source** + +- [frontend/antdx/notification/notification.tsx:1-51](file://frontend/antdx/notification/notification.tsx#L1-L51) + +#### Sources + +- Key Capabilities + - Supports title slot and item collection slot-based rendering. +- Usage Recommendations + - Display reference sources at the end of answers to enhance credibility. +- Key Paths + - [frontend/antdx/sources/sources.tsx:9-41](file://frontend/antdx/sources/sources.tsx#L9-L41) + +**Section Source** + +- [frontend/antdx/sources/sources.tsx:1-42](file://frontend/antdx/sources/sources.tsx#L1-L42) + +## Dependency Analysis + +- Backend Export Layer + - Unifies Ant Design X component exports through **init**.py and components.py, including newly added file cards, Mermaid, folders, and other components. +- Frontend Wrapper Layer + - All components use sveltify wrapping, uniformly handling slots, function wrapping, and event propagation. + - Extensively uses renderItems, renderParamsSlot, useFunction, and other utilities to ensure rendering consistency and flexibility. + - Most components reuse menu and item collection contexts to reduce duplicate configuration costs. + - Newly added components introduce file service resolution and theme switching mechanisms. + +```mermaid +graph LR +P["Python Export
__init__.py / components.py
New Component Exports"] --> Q["Svelte/React Wrapper
sveltify + New Components"] +Q --> R["Utilities and Rendering
renderItems / renderParamsSlot / useFunction"] +Q --> S["Context Providers
menu/items/context + New Contexts"] +Q --> T["@ant-design/x Native Components"] +Q --> U["File Service
getFetchableUrl / resolveFileSrc"] +Q --> V["Theme System
themeMode / highlightProps"] +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [frontend/antdx/folder/folder.tsx:1-124](file://frontend/antdx/folder/folder.tsx#L1-L124) + +**Section Source** + +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Performance and Usability Recommendations + +- Rendering Optimization + - Use useMemo to wrap complex calculation results (such as menu items, suggestion items, tree data, file lists) to reduce unnecessary re-rendering. + - Reasonably split slot rendering to avoid repeated slot mounting when parent level changes frequently. + - Use virtual scrolling for large file lists to improve rendering performance. +- Events and State + - Intercept submission during suggestion panel open to avoid mistaken triggering. + - Disable interaction or show progress during upload to prevent duplicate uploads. + - File card component supports lazy loading to avoid rendering too many images at once. +- Accessibility + - Provide alternative text for icons and buttons to ensure screen reader friendliness. + - Provide keyboard accessibility and focus management for notifications and prompts. + - Mermaid diagrams provide accessibility labels for screen reader narration. +- Data Consistency + - Uniformly update file list after successful upload to avoid state drift. + - In streaming output scenarios, maintain clear transitions between "thinking state - content state - action state". + - File service uses caching mechanism to avoid repeated loading of the same file. +- Theme Adaptation + - Mermaid component automatically adapts to theme mode to ensure diagram readability. + - File card supports dark mode to enhance visual experience. + +## Troubleshooting Guide + +- Slots Not Working + - Check if slots object and corresponding key names are passed correctly. + - Confirm if slot rendering function is correctly wrapped as executable function. +- Upload Failed or Stuck + - Verify beforeUpload/customRequest/isImageUrl function return values and exception handling. + - Check maxCount and current file list length to avoid exceeding limits. +- Suggestion Panel Not Appearing + - Confirm shouldTrigger trigger conditions and input focus state. + - Check open state and whether getPopupContainer container exists. +- Notification Not Showing + - Confirm browser notification permission is granted, request permission flow if necessary. +- Menu Event Abnormal + - Check if onClick is correctly stopped from bubbling to avoid affecting outer interactions. +- File Card Display Abnormal + - Check if file source resolution is correct, confirm getFetchableUrl function works properly. + - Confirm file type and icon mapping match. +- Mermaid Diagram Rendering Failed + - Check if Mermaid syntax is correct, confirm chart type support. + - Confirm theme mode configuration is correct. +- Folder Component Not Responding + - Check if file content service is correctly implemented, confirm async loading function works properly. + - Confirm directory icon mapping and node data format are correct. + +**Section Source** + +- [frontend/antdx/attachments/attachments.tsx:275-354](file://frontend/antdx/attachments/attachments.tsx#L275-L354) +- [frontend/antdx/sender/sender.tsx:126-130](file://frontend/antdx/sender/sender.tsx#L126-L130) +- [frontend/antdx/suggestion/suggestion.tsx:135-140](file://frontend/antdx/suggestion/suggestion.tsx#L135-L140) +- [frontend/antdx/notification/notification.tsx:20-46](file://frontend/antdx/notification/notification.tsx#L20-L46) +- [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) +- [frontend/antdx/mermaid/mermaid.tsx:33-82](file://frontend/antdx/mermaid/mermaid.tsx#L33-L82) +- [frontend/antdx/folder/folder.tsx:16-121](file://frontend/antdx/folder/folder.tsx#L16-L121) + +## Conclusion + +The Ant Design X component library provides a complete closed loop from "input-generate-feedback-confirm-display" for AI applications in ModelScope Studio. Through unified slot-based and function wrapping mechanisms, components maintain strong consistency with @ant-design/x while enhancing customizability and maintainability in multimodal, conversational, and chart visualization scenarios. The newly added file cards, Mermaid diagrams, folders, and other components further enrich the display capabilities of AI applications. It is recommended to follow the interaction rhythm of "template first, then generate; think first, then display; confirm first, then submit" in actual projects, and continuously optimize performance and accessibility combining with best practices. + +## Appendix + +### Component Collaboration and Integration Example (Conceptual Flow) + +The following is an end-to-end flow diagram of a typical "Q&A + attachments + charts + file management" scenario to help understand the collaboration between newly added components. + +```mermaid +sequenceDiagram +participant U as "User" +participant W as "Welcome" +participant P as "Prompts" +participant S as "Sender" +participant A as "Attachments" +participant B as "Bubble" +participant T as "Think" +participant TC as "ThoughtChain" +participant X as "Actions" +participant So as "Sources" +participant FC as "FileCard" +participant M as "Mermaid Diagram" +U->>W : Open application +W-->>U : Display welcome page +U->>P : Click prompt +P-->>S : Fill input content +U->>A : Upload attachment +A-->>FC : Render file card +U->>S : Submit question +S-->>T : Show thinking state +T-->>TC : Display reasoning process +TC-->>B : Display generated content +B-->>X : Provide actions on right side +B-->>So : Display reference sources +U->>B : View diagram +B-->>M : Render Mermaid diagram +``` + +**Diagram Source** + +- [frontend/antdx/welcome/welcome.tsx:8-41](file://frontend/antdx/welcome/welcome.tsx#L8-L41) +- [frontend/antdx/prompts/prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) +- [frontend/antdx/sender/sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) +- [frontend/antdx/attachments/attachments.tsx:36-410](file://frontend/antdx/attachments/attachments.tsx#L36-L410) +- [frontend/antdx/bubble/bubble.tsx:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) +- [frontend/antdx/think/think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) +- [frontend/antdx/thought-chain/thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) +- [frontend/antdx/actions/actions.tsx:17-120](file://frontend/antdx/actions/actions.tsx#L17-L120) +- [frontend/antdx/sources/sources.tsx:9-41](file://frontend/antdx/sources/sources.tsx#L9-L41) +- [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) +- [frontend/antdx/mermaid/mermaid.tsx:33-82](file://frontend/antdx/mermaid/mermaid.tsx#L33-L82) + +### New Component Feature Comparison Table + +| Component Category | Component Name | Main Function | Applicable Scenarios | +| ----------------------- | --------------- | ------------------------------------------------------- | ---------------------------------------------------------- | +| General Components | Bubble | Message content display, avatar, additional information | Conversation interface, message display | +| General Components | Conversations | Historical conversation management, menu operations | Conversation management, history records | +| Wake Components | Welcome | Application guide, initialization interface | First visit, reset interface | +| Wake Components | Prompts | Template prompts, quick start | Guide users, improve efficiency | +| Expression Components | Attachments | File upload management, preview | Multimodal input, file processing | +| Expression Components | Sender | Text input, paste upload | User input, real-time interaction | +| Expression Components | Suggestion | Autocomplete, suggestion panel | Improve input efficiency, smart hints | +| Confirmation Components | Think | Reasoning process indication, loading state | Streaming output, status feedback | +| Confirmation Components | ThoughtChain | Multi-step reasoning display | Complex algorithms, process display | +| Feedback Components | Actions | Action entries, menu rendering | Content operations, quick functions | +| Advanced Components | FileCard | File information display, preview | File management, content display | +| Advanced Components | Mermaid Diagram | Flowchart, sequence diagram rendering | Document generation, algorithm display | +| Advanced Components | Folder | File system browsing, content service | Knowledge base, project management | +| Tool Components | XProvider | Global configuration, theme/language provider | Application root node, global configuration | +| Tool Components | CodeHighlighter | Code highlighting, theme customization | Code display, document generation | +| Data Components | Sources | Data source list display, title slot | Reference source display, knowledge retrieval augmentation | +| Data Components | Think | Thinking state display, slot-based | AI thinking process visualization | + +**Section Source** + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [frontend/antdx/folder/folder.tsx:1-124](file://frontend/antdx/folder/folder.tsx#L1-L124) +- [frontend/antdx/thought-chain/thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) diff --git a/.wiki/en/Ant Design X Components/Components Overview.md b/.wiki/en/Ant Design X Components/Components Overview.md new file mode 100644 index 00000000..989c5f00 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Components Overview.md @@ -0,0 +1,368 @@ +# Components Overview + + +**Files referenced in this document** +- [README-zh_CN.md](file://README-zh_CN.md) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) +- [backend/modelscope_studio/components/__init__.py](file://backend/modelscope_studio/components/__init__.py) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/pro/__init__.py](file://backend/modelscope_studio/components/pro/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/components/pro/components.py](file://backend/modelscope_studio/components/pro/components.py) +- [frontend/antd/package.json](file://frontend/antd/package.json) +- [frontend/antdx/package.json](file://frontend/antdx/package.json) +- [frontend/base/package.json](file://frontend/base/package.json) +- [frontend/pro/package.json](file://frontend/pro/package.json) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [frontend/pro/chatbot/chatbot.tsx](file://frontend/pro/chatbot/chatbot.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +Ant Design X component library is an enhanced UI component system designed for machine learning and large model application scenarios, built on Gradio. It provides more flexible layout capabilities, richer interaction patterns, and specialized components for AI scenarios such as conversations, visualization, and multimodal input. Its core goal is to significantly improve the user experience and development efficiency of AI applications while maintaining ease of use. + +- Design Philosophy + - Centered on "composable, extensible, customizable", covering full-stack capabilities from basic controls to professional scenario components. + - Deeply optimized for AI application interaction paradigms (such as conversation bubbles, thought chains, prompt engineering, file cards, mind maps, etc.). + - Seamlessly integrates with Ant Design and Ant Design X ecosystems, reusing mature design languages and interaction specifications. + +- Value Proposition + - Improves professionalism and consistency of AI application interfaces, reducing costs from prototype to production. + - Directly addresses typical business pain points through specialized components (such as chat bubbles, thought chains, code highlighting, Mermaid diagrams, etc.). + - Compatible with Gradio ecosystem, can be used independently or mixed with traditional components. + +**Section Source** + +- [README-zh_CN.md:17-32](file://README-zh_CN.md#L17-L32) + +## Project Structure + +The project adopts a multi-package organization with frontend-backend separation. The backend Python packages handle component export and ecosystem bridging, while the frontend uses Svelte/React hybrid approach to wrap Ant Design/Ant Design X components and adapts them to Gradio-usable components through the unified sveltify tool. + +```mermaid +graph TB +subgraph "Backend Python Packages" +A_init["components/__init__.py"] +A_antd["antd/__init__.py"] +A_antdx["antdx/__init__.py"] +A_pro["pro/__init__.py"] +A_base["base/__init__.py"] +end +subgraph "Frontend NPM Packages" +F_antd["@modelscope-studio/antd
version: 2.0.0"] +F_antdx["@modelscope-studio/antdx
version: 2.0.0"] +F_pro["@modelscope-studio/pro
version: 2.0.0"] +F_base["@modelscope-studio/base
version: 2.0.0"] +end +A_init --> A_antd +A_init --> A_antdx +A_init --> A_pro +A_init --> A_base +A_antd --> F_antd +A_antdx --> F_antdx +A_pro --> F_pro +A_base --> F_base +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) +- [frontend/pro/package.json:1-6](file://frontend/pro/package.json#L1-L6) +- [frontend/base/package.json:1-6](file://frontend/base/package.json#L1-L6) + +**Section Source** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) +- [frontend/pro/package.json:1-6](file://frontend/pro/package.json#L1-L6) +- [frontend/base/package.json:1-6](file://frontend/base/package.json#L1-L6) + +## Core Components + +- Base Layer (Base) + - Provides basic capabilities such as common containers, text, slots, loops, filtering, etc., supporting complex layouts and conditional rendering. + - Typical components: Application, AutoLoading, Div, Each, Filter, Fragment, Markdown, Slot, Span, Text. + +- Ant Design (Antd) + - Covers the complete Ant Design component family, including buttons, forms, layouts, navigation, feedback, display, editors, etc. + - Supports nested sub-components (such as Button.Group, Form.Item, Tree.TreeNode, etc.) for building complex forms and tree structures. + +- Ant Design X (AntdX) + - Advanced components specifically designed for AI scenarios, such as conversation bubbles, thought chains, prompts, file cards, Mermaid diagrams, etc. + - Emphasizes content editability, renderability, and interactivity, suitable for dynamic content presentation and editing in LLM applications. + +- Pro (Pro) + - Integrated component collection for professional scenarios, such as Chatbot, Monaco Editor, Multimodal Input, Web Sandbox. + - Integrates multiple sub-components with contexts to provide out-of-the-box AI application scaffolds. + +**Section Source** + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) + +## Architecture Overview + +The overall architecture consists of three parts: "backend component export + frontend adaptation layer + ecosystem integration". The backend aggregates and exports sub-modules through Python packages; the frontend wraps native components using Svelte/React hybrid approach and bridges React components to Svelte/Gradio environment through sveltify; meanwhile providing utility functions and contexts for advanced capabilities like slots, render functions, and event callbacks. + +```mermaid +graph TB +subgraph "Backend" +Py_API["Python Export API
components/__init__.py"] +Py_antd["Antd Component Export"] +Py_antdx["AntdX Component Export"] +Py_pro["Pro Component Export"] +Py_base["Base Component Export"] +end +subgraph "Frontend" +FE_antd["antd/button.tsx
sveltify adaptation"] +FE_antdx["antdx/bubble/bubble.tsx
slots/render functions"] +FE_pro["pro/chatbot/chatbot.tsx
context+state management"] +end +subgraph "Ecosystem" +AD["Ant Design"] +ADX["Ant Design X"] +GR["Gradio"] +end +Py_API --> Py_antd +Py_API --> Py_antdx +Py_API --> Py_pro +Py_API --> Py_base +Py_antd --> FE_antd +Py_antdx --> FE_antdx +Py_pro --> FE_pro +FE_antd --> AD +FE_antdx --> ADX +FE_pro --> ADX +FE_antd --> GR +FE_antdx --> GR +FE_pro --> GR +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/components.py:1-144](file://backend/modelscope_studio/components/antd/components.py#L1-L144) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [frontend/pro/chatbot/chatbot.tsx:1-475](file://frontend/pro/chatbot/chatbot.tsx#L1-L475) + +## Detailed Component Analysis + +### Antd Button Component (Basic Control) + +- Design Points + - Uses sveltify to adapt Ant Design's Button to Svelte/Gradio component. + - Supports slots (such as icon, loading.icon) and value binding, automatically handling priority between children and controlled value. + - Compatible handling of loading's delay configuration to ensure combination with slots. + +```mermaid +flowchart TD +Start(["Enter Button Rendering"]) --> ParseSlots["Parse Slots and Props"] +ParseSlots --> HasIcon{"Has icon slot?"} +HasIcon --> |Yes| RenderIcon["Use ReactSlot to render icon slot"] +HasIcon --> |No| UsePropIcon["Use prop icon"] +RenderIcon --> HasLoadingIcon{"Has loading.icon slot?"} +UsePropIcon --> HasLoadingIcon +HasLoadingIcon --> |Yes| RenderLoadingIcon["Use ReactSlot to render loading.icon slot
and preserve delay config"] +HasLoadingIcon --> |No| UsePropLoading["Use prop loading"] +RenderLoadingIcon --> RenderButton["Render Ant Design Button"] +UsePropLoading --> RenderButton +RenderButton --> End(["Complete"]) +``` + +**Diagram Source** + +- [frontend/antd/button/button.tsx:8-36](file://frontend/antd/button/button.tsx#L8-L36) + +**Section Source** + +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) + +### AntdX Bubble Component (AI Scenario) + +- Design Points + - Based on Ant Design X's Bubble, provides multi-slots for avatar, content, footer, extra area, loading render, content render, etc. + - Supports editable okText/cancelText slots and boolean switches, typing, header/footer/avatar/extra functional configurations. + - Converts slots to executable functions through useFunction and renderParamsSlot, enhancing programmability. + +```mermaid +sequenceDiagram +participant C as "Caller" +participant B as "Bubble Component" +participant R as "ReactSlot/renderParamsSlot" +participant F as "useFunction" +C->>B : Pass props and slots +B->>F : Parse header/footer/avatar/extra/typing/editable +F-->>B : Return executable function or default value +B->>R : If content/header/footer/avatar/loadingRender/contentRender slots exist +R-->>B : Render slot content +B-->>C : Render final Bubble +``` + +**Diagram Source** + +- [frontend/antdx/bubble/bubble.tsx:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) + +**Section Source** + +- [frontend/antdx/bubble/bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) + +### Pro Chatbot Component (Conversation Scenario) + +- Design Points + - Based on Ant Design X's Bubble.List, combines custom context and hooks to implement scrolling, editing, copying, liking, retrying, welcome message, etc. + - Maps different roles (user, assistant, internal welcome) to corresponding bubble styles and behaviors through useRole. + - Built-in Markdown rendering, theme mode, root path passing, and other configurations to meet multimodal content display needs. + +```mermaid +sequenceDiagram +participant U as "User" +participant CB as "Chatbot" +participant BL as "Bubble.List" +participant CTX as "Role Context" +participant H as "hooks(scroll/edit)" +U->>CB : Input message/operation +CB->>CTX : Parse message role and configuration +CTX-->>CB : Return corresponding bubble configuration +CB->>H : Trigger scroll/edit state update +H-->>CB : Update state +CB->>BL : Render message list +BL-->>U : Display conversation bubbles +``` + +**Diagram Source** + +- [frontend/pro/chatbot/chatbot.tsx:76-472](file://frontend/pro/chatbot/chatbot.tsx#L76-L472) + +**Section Source** + +- [frontend/pro/chatbot/chatbot.tsx:1-475](file://frontend/pro/chatbot/chatbot.tsx#L1-L475) + +## Dependency Analysis + +- Version and Namespace + - All frontend packages use unified version number (2.0.0), namespace is @modelscope-studio, convenient for publishing and management. +- Component Export and Grouping + - Backend exports by functional domains: antd, antdx, pro, base, corresponding to Ant Design component family, AI specialized components, professional scenario components, and basic capabilities. +- Frontend-Backend Mapping + - Each backend export module corresponds to a frontend package, forming stable mapping relationships, ensuring component names and ecosystem consistency. + +```mermaid +graph LR +Py_antd["Backend antd Export"] --> FE_antd["Frontend @modelscope-studio/antd"] +Py_antdx["Backend antdx Export"] --> FE_antdx["Frontend @modelscope-studio/antdx"] +Py_pro["Backend pro Export"] --> FE_pro["Frontend @modelscope-studio/pro"] +Py_base["Backend base Export"] --> FE_base["Frontend @modelscope-studio/base"] +``` + +**Diagram Source** + +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [frontend/antd/package.json:1-6](file://frontend/antd/package.json#L1-L6) +- [frontend/antdx/package.json:1-6](file://frontend/antdx/package.json#L1-L6) +- [frontend/pro/package.json:1-6](file://frontend/pro/package.json#L1-L6) +- [frontend/base/package.json:1-6](file://frontend/base/package.json#L1-L6) + +**Section Source** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) + +## Performance Considerations + +- Rendering and Slots + - Avoid unnecessary re-rendering through combination of slots and render functions; only perform parameterized rendering when slots exist. +- State and Computation + - Use useMemo and useMemoizedFn to cache configurations and callbacks, reducing invalid re-renders and object creation. +- Scrolling and Interaction + - Use local state and throttling strategies for high-frequency interactions like scrolling, editing, liking, ensuring smooth experience. + +[This section is general guidance, no specific file references required] + +## Troubleshooting Guide + +- Page Not Displaying Correctly (Hugging Face Space) + - Add ssr_mode=False parameter in demo.launch() to avoid display issues caused by server-side rendering. +- Component Import Failed + - Confirm modelscope_studio is installed and correctly import modelscope_studio.components.\* namespace. +- Version Mismatch + - Check if backend and frontend package versions are consistent to avoid runtime errors due to version differences. + +**Section Source** + +- [README-zh_CN.md:32-32](file://README-zh_CN.md#L32-L32) +- [README-zh_CN.md:38-42](file://README-zh_CN.md#L38-L42) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) + +## Conclusion + +Ant Design X component library systematically improves the interface expressiveness and interaction efficiency of machine learning and large model applications through a three-layer architecture of "basic controls + AI specialized components + professional scenario components". With Gradio as the entry point, Ant Design/Ant Design X as the foundation, and frontend adaptation layer as the bridge, it forms a stable, scalable, and maintainable component system. Developers can use this library to quickly build high-quality AI application interfaces and gain consistent and professional user experience in conversation, visualization, multimodal input, and other scenarios. + +[This section is summary content, no specific file references required] + +## Appendix + +### Quick Start + +- Installation + - Use pip to install modelscope_studio. +- Example + - Import Application, ConfigProvider, AutoLoading from modelscope_studio in Blocks, and use antd components for layout and interaction. + +**Section Source** + +- [README-zh_CN.md:38-57](file://README-zh_CN.md#L38-L57) + +### Component Classification and Usage Scenarios + +- Base Layer (Base) + - Scenarios: General layout, conditional rendering, text and slot management. + - Typical: Application, AutoLoading, Markdown, Slot, Text, Span, Div, Each, Filter, Fragment. +- Ant Design (Antd) + - Scenarios: Forms, navigation, feedback, display, layout, and other general UI. + - Typical: Button, Form, Layout, Menu, Modal, Table, Tabs, Tree, Upload, etc. +- Ant Design X (AntdX) + - Scenarios: Conversation bubbles, thought chains, prompts, file cards, Mermaid diagrams, and other AI-specific interactions. + - Typical: Bubble, Conversations, Sender, ThoughtChain, Prompts, Attachments, Mermaid, Notification, Welcome, XProvider. +- Pro (Pro) + - Scenarios: Integrated AI application scaffolds, such as chatbots, code editors, multimodal input, Web sandbox. + - Typical: Chatbot, MonacoEditor, MultimodalInput, WebSandbox. + +**Section Source** + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) diff --git a/.wiki/en/Ant Design X Components/Confirmation Components/Confirmation Components.md b/.wiki/en/Ant Design X Components/Confirmation Components/Confirmation Components.md new file mode 100644 index 00000000..46576d36 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Confirmation Components/Confirmation Components.md @@ -0,0 +1,408 @@ +# Confirmation Components + + +**Files Referenced in This Document** +- [AntdXThoughtChain/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py) +- [AntdXThoughtChainItem/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py) +- [AntdXThoughtChainThoughtChainItem/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py) +- [thought-chain.tsx](file://frontend/antdx/thought-chain/thought-chain.tsx) +- [context.ts](file://frontend/antdx/thought-chain/context.ts) +- [basic.py](file://docs/components/antdx/thought_chain/demos/basic.py) +- [item_status.py](file://docs/components/antdx/thought_chain/demos/item_status.py) +- [nested_use.py](file://docs/components/antdx/thought_chain/demos/nested_use.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document provides systematic technical documentation for the Ant Design X Confirmation Components (ThoughtChain), covering the following aspects: + +- Thought chain construction and state management: How to configure states, collapsible behavior, and nested structures through node item configuration +- Visual presentation: How to combine node content, icons, titles, descriptions, extra action areas, and footers +- Configuration options and events: Supported properties, slots, and event callbacks +- Style and class name customization: How to control appearance via prefix class names, style objects, and root class names +- Usage examples: From basic usage to state switching, nested usage, and user interaction +- Value statement: The significance of this component in improving AI transparency and trustworthiness + +## Project Structure + +The Ant Design X ThoughtChain component is composed of a backend Python component and a frontend React/Svelte wrapper layer, with documentation examples located in the docs directory. + +```mermaid +graph TB +subgraph "Backend Components" +A["AntdXThoughtChain
Thought Chain Container"] +B["AntdXThoughtChainItem
Node Item (Simplified)"] +C["AntdXThoughtChainThoughtChainItem
Node Item (Full)"] +end +subgraph "Frontend Wrapper Layer" +D["thought-chain.tsx
React Wrapper + Slot Resolution"] +E["context.ts
items Context"] +end +subgraph "Documentation Examples" +F["basic.py
Basic Usage"] +G["item_status.py
State Switching Demo"] +H["nested_use.py
Nested Usage"] +end +A --> D +B --> D +C --> D +D --> E +F --> A +G --> A +H --> A +``` + +**Diagram Sources** + +- [AntdXThoughtChain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [AntdXThoughtChainItem/**init**.py:8-78](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L8-L78) +- [AntdXThoughtChainThoughtChainItem/**init**.py:8-81](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L8-L81) +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [context.ts:1-7](file://frontend/antdx/thought-chain/context.ts#L1-L7) +- [basic.py:24-77](file://docs/components/antdx/thought_chain/demos/basic.py#L24-L77) +- [item_status.py:36-71](file://docs/components/antdx/thought_chain/demos/item_status.py#L36-L71) +- [nested_use.py:6-68](file://docs/components/antdx/thought_chain/demos/nested_use.py#L6-L68) + +**Section Sources** + +- [AntdXThoughtChain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) + +## Core Components + +- Container Component: AntdXThoughtChain + - Responsibility: Acts as the root container of the thought chain, responsible for receiving node lists, expanded keys, line styles, prefix class names, and other configurations; notifies expanded state changes via event binding + - Key Capabilities: Supports items slot; expand event; configurable default expanded keys and current expanded keys +- Node Item Component (Simplified): AntdXThoughtChainItem + - Responsibility: Carries the basic information and appearance of a single node, supporting title, description, icon, status, variant, and blink effect + - Key Capabilities: Supports description, icon, title slots; status enum (pending/success/error/abort) +- Node Item Component (Full): AntdXThoughtChainThoughtChainItem + - Responsibility: Carries richer node content, supporting content, description, footer, icon, title slots, as well as key, collapsible, status, and other properties + - Key Capabilities: Supports collapse/expand, state switching, and extra action areas + +**Section Sources** + +- [AntdXThoughtChain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) +- [AntdXThoughtChainItem/**init**.py:8-78](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L8-L78) +- [AntdXThoughtChainThoughtChainItem/**init**.py:8-81](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L8-L81) + +## Architecture Overview + +The frontend wrapper layer maps backend components to React components, uniformly resolves slots, and passes them to @ant-design/x's ThoughtChain implementation, while collecting items slot content via the context mechanism. + +```mermaid +sequenceDiagram +participant Py as "Python Backend Component" +participant Wrap as "React Wrapper thought-chain.tsx" +participant Ctx as "items Context context.ts" +participant X as "@ant-design/x ThoughtChain" +Py->>Wrap : Render ThoughtChain container +Wrap->>Ctx : Read items/default slots +Ctx-->>Wrap : Return items list +Wrap->>X : Pass props and resolved items +X-->>Wrap : Render node tree +Wrap-->>Py : Output final UI +``` + +**Diagram Sources** + +- [thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) +- [context.ts:1-7](file://frontend/antdx/thought-chain/context.ts#L1-L7) + +## Detailed Component Analysis + +### Container Component: AntdXThoughtChain + +- Main Responsibilities + - Receives items list and expanded key configuration, determining the initial expanded state + - Supports the expand event to monitor expanded key changes + - Provides the items slot for declarative node organization +- Key Properties + - expanded_keys / default_expanded_keys: Current expanded keys and default expanded keys + - items: Array of node data + - line: Line style (boolean or line type enum) + - prefix_cls: Prefix class name + - styles / class_names / root_class_name: Style and class name customization +- Events + - expand: Triggered when expanded keys change +- Lifecycle + - preprocess/postprocess/example\_\* all return empty values, indicating this component does not participate in data serialization + +```mermaid +classDiagram +class AntdXThoughtChain { ++expanded_keys ++default_expanded_keys ++items ++line ++prefix_cls ++styles ++class_names ++root_class_name ++EVENTS ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +``` + +**Diagram Sources** + +- [AntdXThoughtChain/**init**.py:30-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L30-L86) + +**Section Sources** + +- [AntdXThoughtChain/**init**.py:12-86](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L86) + +### Node Item Component (Simplified): AntdXThoughtChainItem + +- Main Responsibilities + - Represents a single thought node's title, description, icon, and status + - Supports multiple appearance variants and blink effects +- Key Properties + - description / icon / title: Node basic information + - status: Node status (pending/success/error/abort) + - variant: Appearance variant (solid/outlined/text) + - blink: Whether to blink + - Slots: description, icon, title +- Lifecycle + - Same as the container component; does not participate in data serialization + +```mermaid +classDiagram +class AntdXThoughtChainItem { ++description ++icon ++title ++status ++variant ++blink ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +``` + +**Diagram Sources** + +- [AntdXThoughtChainItem/**init**.py:18-78](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L18-L78) + +**Section Sources** + +- [AntdXThoughtChainItem/**init**.py:8-78](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L8-L78) + +### Node Item Component (Full): AntdXThoughtChainThoughtChainItem + +- Main Responsibilities + - Carries richer node content, supporting content, footer, extra, and other slots + - Supports key, collapsible, status, and other properties for complex interactions and state management +- Key Properties + - content / description / footer / icon / title: Content and decoration + - key: Node unique identifier + - collapsible: Whether it is collapsible + - status: Node status + - Slots: content, description, footer, icon, title +- Lifecycle + - Same as the container component; does not participate in data serialization + +```mermaid +classDiagram +class AntdXThoughtChainThoughtChainItem { ++content ++description ++extra ++footer ++icon ++title ++status ++key ++collapsible ++blink ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +``` + +**Diagram Sources** + +- [AntdXThoughtChainThoughtChainItem/**init**.py:18-81](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L18-L81) + +**Section Sources** + +- [AntdXThoughtChainThoughtChainItem/**init**.py:8-81](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L8-L81) + +### Frontend Wrapper and Slot Resolution + +- thought-chain.tsx + - Wraps @ant-design/x's ThoughtChain via sveltify + - Uses withItemsContextProvider and useItems to resolve items/default slots + - Converts slot content into props.items via renderItems +- context.ts + - Provides items context, supporting slot collection in nested scenarios + +```mermaid +flowchart TD +Start(["Render Entry"]) --> ReadSlots["Read items/default slots"] +ReadSlots --> Resolve["Call renderItems to resolve nodes"] +Resolve --> RenderX["Render @ant-design/x ThoughtChain"] +RenderX --> End(["Complete"]) +``` + +**Diagram Sources** + +- [thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) +- [context.ts:1-7](file://frontend/antdx/thought-chain/context.ts#L1-L7) + +**Section Sources** + +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [context.ts:1-7](file://frontend/antdx/thought-chain/context.ts#L1-L7) + +### Usage Examples and Scenarios + +#### Basic Usage and Collapsible Behavior + +- Key Points + - Create a ThoughtChain container under XProvider + - Use a Switch to control the collapsible property, dynamically toggling node collapsibility + - Inject extra/content/footer via Slot for rich node content +- Applicable Scenarios + - Display the execution flow and current status of multi-step tasks + - Provide node-level action buttons and supplementary information + +**Section Sources** + +- [basic.py:24-77](file://docs/components/antdx/thought_chain/demos/basic.py#L24-L77) + +#### Node State Switching (Success/Error/In Progress) + +- Key Points + - Use Each to dynamically generate node lists + - Step-by-step update node status and icons via button clicks to simulate real runtime status + - Supports visual feedback for pending/error/success three states +- Applicable Scenarios + - Display stage-by-stage results during AI inference + - Increase user confidence in execution progress and results + +**Section Sources** + +- [item_status.py:36-71](file://docs/components/antdx/thought_chain/demos/item_status.py#L36-L71) + +#### Nested Usage (Sub-Thought Chains) + +- Key Points + - Nest another ThoughtChain inside the node content of a parent ThoughtChain + - Child nodes also support slots like extra/content/footer +- Applicable Scenarios + - Complex tasks broken down into multiple sub-tasks, refined layer by layer + - Display hierarchical decision or reasoning chains + +**Section Sources** + +- [nested_use.py:6-68](file://docs/components/antdx/thought_chain/demos/nested_use.py#L6-L68) + +## Dependency Analysis + +- Component Coupling + - Both the container and node items inherit from ModelScopeLayoutComponent, sharing a unified lifecycle and property system + - The frontend wrapper layer is only responsible for slot resolution and property forwarding, without introducing business logic +- External Dependencies + - @ant-design/x's ThoughtChain provides actual rendering capabilities + - Gradio event system is used for expand event binding +- Potential Risks + - Slot names and order must strictly match; otherwise rendering may fail + - When the items list is empty, ensure fallback to the default slot + +```mermaid +graph LR +Py["Python Component"] --> Wrap["React Wrapper Layer"] +Wrap --> X["@ant-design/x ThoughtChain"] +Wrap --> Ctx["items Context"] +Py --> Gradio["Gradio Event System"] +``` + +**Diagram Sources** + +- [AntdXThoughtChain/**init**.py:20-25](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L20-L25) +- [thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) + +**Section Sources** + +- [AntdXThoughtChain/**init**.py:20-25](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L20-L25) +- [thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) + +## Performance Considerations + +- Render Optimization + - Uses useMemo to cache items computation results, avoiding unnecessary re-renders + - Reduces DOM count via lazy slot loading and conditional rendering +- Data Flow + - The items list should maintain stable references; use the key field to improve diff efficiency +- Interaction Experience + - For scenarios with many nodes, prioritize collapsible and step-by-step loading strategies + +## Troubleshooting Guide + +- Symptom: Nodes not showing or showing as empty + - Check whether items are correctly passed or the default slot is populated + - Confirm slot name casing matches the documentation +- Symptom: expand event not working + - Confirm event binding is enabled (bind_expand_event) + - Check whether the container is in an interactive state +- Symptom: Nested ThoughtChain not working + - Ensure the child ThoughtChain is correctly nested in the content slot of the parent node + - Check whether the child ThoughtChain's slots are correctly declared + +## Conclusion + +The Ant Design X ThoughtChain component, through its layered design of "container + node items" combined with frontend slot resolution and @ant-design/x's rendering capabilities, achieves structured recording and visual presentation of the AI thinking process. Its state-driven node appearance, flexible slot extension, and collapsible interaction can effectively improve users' understanding and trust in complex reasoning processes. With documentation examples, developers can quickly build various application scenarios from basic flows to nested sub-chains. + +## Appendix + +### API Quick Reference + +- Container Component AntdXThoughtChain + - Properties: expanded_keys, default_expanded_keys, items, line, prefix_cls, styles, class_names, root_class_name + - Events: expand + - Slots: items +- Node Item Component (Simplified) AntdXThoughtChainItem + - Properties: description, icon, title, status, variant, blink + - Slots: description, icon, title +- Node Item Component (Full) AntdXThoughtChainThoughtChainItem + - Properties: content, description, extra, footer, icon, title, status, key, collapsible, blink + - Slots: content, description, footer, icon, title + +### Usage Recommendations + +- Transparency and Trustworthiness + - Provide clear status and icon hints to help users understand the execution result of each step + - Offer additional explanations and actionable entry points for key decision nodes to enhance user control +- Accessibility + - Provide readable alternative text for icons and statuses + - Ensure keyboard accessibility and screen reader friendliness diff --git a/.wiki/en/Ant Design X Components/Confirmation Components/ThoughtChain Component.md b/.wiki/en/Ant Design X Components/Confirmation Components/ThoughtChain Component.md new file mode 100644 index 00000000..079ace1b --- /dev/null +++ b/.wiki/en/Ant Design X Components/Confirmation Components/ThoughtChain Component.md @@ -0,0 +1,380 @@ +# ThoughtChain Component + + +**Files Referenced in This Document** +- [backend module exports](file://backend/modelscope_studio/components/antdx/__init__.py) +- [ThoughtChain main component definition](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py) +- [ThoughtChain item component definition](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py) +- [ThoughtChain advanced item component definition](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py) +- [Frontend ThoughtChain implementation](file://frontend/antdx/thought-chain/thought-chain.tsx) +- [Frontend ThoughtChain item implementation](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx) +- [Frontend ThoughtChain advanced item implementation](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx) +- [Frontend ThoughtChain context utility](file://frontend/antdx/thought-chain/context.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +The ThoughtChain component is a powerful visualization tool provided by ModelScope Studio, specifically designed to record and display the AI's thinking process. This component clearly presents complex reasoning paths through a tree structure, helping users understand the logical flow of AI decision-making. + +The core value of this component lies in: + +- **Enhanced Transparency**: Enables users to see the complete thinking process of AI +- **Improved Explainability**: Improves the understandability of AI behavior through step-by-step visual presentation +- **Debugging Support**: Enables developers and users to track and analyze AI decision paths +- **User Experience Optimization**: Provides intuitive visual feedback to enhance human-machine interaction + +## Project Structure + +ModelScope Studio adopts a layered architecture design; the ThoughtChain component is located in the antdx component library and is deeply integrated with the Gradio ecosystem. + +```mermaid +graph TB +subgraph "Backend Python Layer" +A[Antdx Component Exports] --> B[ThoughtChain Main Component] +A --> C[ThoughtChain Item Component] +A --> D[ThoughtChain Advanced Item Component] +end +subgraph "Frontend React Layer" +E[ThoughtChain Frontend Implementation] +F[ThoughtChain Item Frontend Implementation] +G[ThoughtChain Advanced Item Frontend Implementation] +H[Context Utility] +end +subgraph "Third-party Libraries" +I[@ant-design/x] +J[Gradio Ecosystem] +end +B --> E +C --> F +D --> G +E --> I +F --> I +G --> I +H --> E +H --> G +E --> J +F --> J +G --> J +``` + +**Diagram Sources** + +- [backend module exports:35-41](file://backend/modelscope_studio/components/antdx/__init__.py#L35-L41) +- [ThoughtChain main component definition:12-18](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L18) +- [ThoughtChain item component definition:8-11](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L8-L11) +- [ThoughtChain advanced item component definition:8-11](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L8-L11) + +**Section Sources** + +- [backend module exports:35-41](file://backend/modelscope_studio/components/antdx/__init__.py#L35-L41) +- [ThoughtChain main component definition:12-18](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L12-L18) + +## Core Components + +### ThoughtChain Main Component + +The main component is responsible for overall layout and state management, supporting multiple configuration options: + +**Core Configuration Options:** + +- `expanded_keys`: List of node key values to expand by default +- `default_expanded_keys`: Initial default expanded node key values +- `items`: Array of thinking step data +- `line`: Connector line style (solid, dashed, dotted) +- `prefix_cls`: Custom prefix class name +- `styles`: Inline style object or string +- `class_names`: Class name mapping object + +**Event Handling:** + +- `expand`: Callback function for when expand/collapse key values change + +### ThoughtChainItem Sub-item Component + +Used to represent a single thinking step, supporting rich customization options: + +**Core Properties:** + +- `description`: Step description text +- `icon`: Custom icon name +- `title`: Step title +- `status`: Status value (pending, success, error, abort) +- `variant`: Appearance variant (solid, outlined, text) +- `blink`: Whether to enable blink effect + +**Slot Support:** + +- `description`: Custom description content +- `icon`: Custom icon content +- `title`: Custom title content + +### ThoughtChainThoughtChainItem Advanced Sub-item Component + +Provides more complex functionality, supporting nested structures: + +**Extended Properties:** + +- `content`: Main content text +- `extra`: Extra information +- `footer`: Footer content +- `collapsible`: Whether it is collapsible +- `key`: Unique key identifier + +**Advanced Slots:** + +- `content`: Main content area +- `description`: Description content +- `footer`: Footer content +- `icon`: Icon content +- `title`: Title content + +**Section Sources** + +- [ThoughtChain main component definition:30-67](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L30-L67) +- [ThoughtChain item component definition:18-58](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L18-L58) +- [ThoughtChain advanced item component definition:18-59](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L18-L59) + +## Architecture Overview + +The ThoughtChain component adopts a frontend-backend separation architecture design, achieving seamless integration through the Gradio ecosystem. + +```mermaid +sequenceDiagram +participant User as User Interface +participant Backend as Backend Component +participant Frontend as Frontend Implementation +participant AntDX as Ant Design X +participant Context as Context Management +User->>Backend : Create ThoughtChain component +Backend->>Frontend : Resolve frontend directory +Frontend->>Context : Initialize context +Context->>AntDX : Load core components +User->>Backend : Set configuration parameters +Backend->>Frontend : Pass component properties +Frontend->>AntDX : Render thought chain +AntDX->>User : Display visualization result +Note over User,AntDX : Supports dynamic updates and interaction +``` + +**Diagram Sources** + +- [ThoughtChain main component definition:68-68](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L68-L68) +- [Frontend ThoughtChain implementation:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) +- [Frontend ThoughtChain context utility:1-4](file://frontend/antdx/thought-chain/context.ts#L1-L4) + +## Detailed Component Analysis + +### Data Flow Processing + +```mermaid +flowchart TD +Start([Component Initialization]) --> ParseProps["Parse component properties"] +ParseProps --> InitContext["Initialize context"] +InitContext --> LoadItems["Load thinking step data"] +LoadItems --> RenderChain["Render thought chain"] +RenderChain --> HandleEvents["Handle user interactions"] +HandleEvents --> UpdateState["Update component state"] +UpdateState --> ReRender["Re-render"] +ReRender --> End([Complete]) +LoadItems --> CheckSlots{"Check slot content"} +CheckSlots --> |Has Slots| ProcessSlots["Process slot content"] +CheckSlots --> |No Slots| UseProps["Use property values"] +ProcessSlots --> RenderChain +UseProps --> RenderChain +``` + +**Diagram Sources** + +- [Frontend ThoughtChain implementation:14-35](file://frontend/antdx/thought-chain/thought-chain.tsx#L14-L35) +- [Frontend ThoughtChain item implementation:12-27](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L12-L27) + +### State Management System + +The component supports four core states, each with specific visual representations: + +```mermaid +stateDiagram-v2 +[*] --> NotStarted +NotStarted --> InProgress : Start execution +InProgress --> Completed : Execution successful +InProgress --> Failed : Execution error +InProgress --> Aborted : User interrupt +Completed --> [*] +Failed --> [*] +Aborted --> [*] +note right of NotStarted : Display waiting state +note right of InProgress : Display loading animation +note right of Completed : Display success icon +note right of Failed : Display error state +note right of Aborted : Display abort prompt +``` + +**Diagram Sources** + +- [ThoughtChain item component definition:24-25](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L24-L25) +- [ThoughtChain advanced item component definition:29-30](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L29-L30) + +### Slot System Architecture + +```mermaid +classDiagram +class ThoughtChainItem { ++description : string ++icon : string ++title : string ++status : Status ++variant : Variant ++blink : boolean ++slots : Description|Icon|Title +} +class ThoughtChainThoughtChainItem { ++content : string ++extra : string ++footer : string ++collapsible : boolean ++key : string ++slots : Content|Description|Footer|Icon|Title +} +class SlotProcessor { ++processDescription() : ReactNode ++processIcon() : ReactNode ++processTitle() : ReactNode ++renderSlots() : JSX.Element +} +ThoughtChainItem --> SlotProcessor : uses +ThoughtChainThoughtChainItem --> SlotProcessor : uses +SlotProcessor --> ReactSlot : processes slots +``` + +**Diagram Sources** + +- [ThoughtChain item component definition:15-16](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py#L15-L16) +- [ThoughtChain advanced item component definition:15-16](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py#L15-L16) +- [Frontend ThoughtChain item implementation:18-26](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L18-L26) + +**Section Sources** + +- [Frontend ThoughtChain implementation:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) +- [Frontend ThoughtChain item implementation:9-30](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L9-L30) +- [Frontend ThoughtChain advanced item implementation:7-11](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L7-L11) + +## Dependency Analysis + +### Component Dependency Diagram + +```mermaid +graph TB +subgraph "Core Dependencies" +A[@ant-design/x] --> B[ThoughtChain Core] +A --> C[ThoughtChain.Item] +A --> D[ThoughtChain.ThoughtChainItem] +end +subgraph "Utility Dependencies" +E[@svelte-preprocess-react] --> F[sveltify Conversion] +E --> G[ReactSlot Processing] +H[@utils/renderItems] --> I[Item Rendering] +J[@utils/createItemsContext] --> K[Context Management] +end +subgraph "Gradio Integration" +L[Gradio Event System] --> M[EventListener] +N[Gradio Component System] --> O[ModelScopeLayoutComponent] +end +B --> E +C --> E +D --> E +B --> L +C --> N +D --> N +E --> H +E --> J +``` + +**Diagram Sources** + +- [Frontend ThoughtChain implementation:1-7](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L7) +- [Frontend ThoughtChain item implementation:1-7](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L1-L7) +- [Frontend ThoughtChain advanced item implementation:1-3](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L1-L3) +- [ThoughtChain main component definition:5-8](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L5-L8) + +### Version Compatibility + +The component design follows these compatibility principles: + +- Supports the latest version features of Gradio +- Compatible with TypeScript 4.0+ type system +- Adapts to React 17+ and Svelte 3+ ecosystems +- Backward compatible with Ant Design X 0.x versions + +**Section Sources** + +- [ThoughtChain main component definition:1-8](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L1-L8) +- [Frontend ThoughtChain implementation:1-7](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L7) + +## Performance Considerations + +### Rendering Optimization Strategies + +1. **Lazy Loading Mechanism**: Use `sveltify` for on-demand loading +2. **Memory Management**: Use `useMemo` appropriately to cache computation results +3. **Event Handling**: Optimize event binding via `EventListener` +4. **Slot Rendering**: Delay rendering slot content to reduce initial load + +### Best Practice Recommendations + +- **Data Preprocessing**: Format data before passing it to the component +- **State Minimization**: Avoid frequent state updates that trigger unnecessary re-renders +- **Resource Management**: Clean up unused component instances in a timely manner +- **Error Boundaries**: Use Gradio's error boundary mechanism to handle exceptions + +## Troubleshooting Guide + +### Common Issues and Solutions + +**Issue 1: Component Not Displaying** + +- Check the `visible` property setting +- Confirm the `render` property is `true` +- Verify the CSS styles of the parent container + +**Issue 2: Status Display Anomalies** + +- Confirm the status value is within the allowed range +- Check whether the `blink` property is correctly configured +- Verify the correctness of style class names + +**Issue 3: Slot Content Not Taking Effect** + +- Confirm the slot name is spelled correctly +- Check the type matching of slot content +- Verify the rendering timing of the slot + +**Section Sources** + +- [ThoughtChain main component definition:74-85](file://backend/modelscope_studio/components/antdx/thought_chain/__init__.py#L74-L85) +- [Frontend ThoughtChain item implementation:12-27](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L12-L27) + +## Conclusion + +The ThoughtChain component provides powerful visualization capabilities for displaying the AI thinking process in AI applications. Through its carefully designed architecture and rich configuration options, this component not only improves AI transparency and trustworthiness but also provides users with an intuitive interactive experience. + +**Summary of Core Advantages:** + +- **Complete Thought Process Visualization**: Multi-level presentation from simple to complex +- **Flexible Configuration Options**: Meets usage needs in different scenarios +- **Good Performance**: Optimized rendering mechanism ensures a smooth experience +- **Comprehensive Error Handling**: Robust exception handling mechanism ensures stability +- **Excellent Extensibility**: Modular architecture facilitates feature extension and customization + +This component is particularly suitable for application scenarios that need to display AI decision-making processes, such as intelligent customer service, data analysis, and content creation, and can significantly improve user understanding and trust in AI behavior. diff --git a/.wiki/en/Ant Design X Components/Confirmation Components/ThoughtChainItem Component.md b/.wiki/en/Ant Design X Components/Confirmation Components/ThoughtChainItem Component.md new file mode 100644 index 00000000..793a9e4a --- /dev/null +++ b/.wiki/en/Ant Design X Components/Confirmation Components/ThoughtChainItem Component.md @@ -0,0 +1,410 @@ +# ThoughtChainItem Component + + +**Files Referenced in This Document** +- [thought-chain.tsx](file://frontend/antdx/thought-chain/thought-chain.tsx) +- [thought-chain.thought-chain-item.tsx](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx) +- [thought-chain.item.tsx](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx) +- [context.ts](file://frontend/antdx/thought-chain/context.ts) +- [createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [thought-chain.Index.svelte](file://frontend/antdx/thought-chain/Index.svelte) +- [thought-chain.thought-chain-item.Index.svelte](file://frontend/antdx/thought-chain/thought-chain-item/Index.svelte) +- [thought-chain.item.Index.svelte](file://frontend/antdx/thought-chain/item/Index.svelte) +- [thought_chain_item/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/thought_chain_item/__init__.py) +- [thought_chain/__init__.py](file://backend/modelscope_studio/components/antdx/thought_chain/item/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +ThoughtChainItem is the core sub-component of the ThoughtChain component system in ModelScope Studio, used to represent and manage individual thinking steps in complex thought flows. This component provides complete state management, event handling, and visual presentation capabilities, supporting the visualization of multiple states (pending, in progress, completed, failed, etc.). + +This component is based on Ant Design X's ThoughtChain implementation and achieves flexible inter-component communication and state synchronization through a custom Items Context system. The component supports a slot mechanism, allowing developers to customize content areas such as titles, descriptions, and icons. + +## Project Structure + +The ThoughtChainItem component system adopts a layered architecture design, consisting of three parts: frontend React components, Svelte wrappers, and backend Python components: + +```mermaid +graph TB +subgraph "Frontend Architecture" +A[ThoughtChain Main Container] --> B[ThoughtChainItem Sub-item] +B --> C[React Component Layer] +C --> D[Svelte Wrapper Layer] +end +subgraph "Backend Architecture" +E[Python Component Layer] --> F[Frontend Directory Mapping] +F --> G[Static Resource Generation] +end +subgraph "State Management" +H[Items Context] --> I[ItemHandler] +I --> J[State Synchronization] +end +A --> H +B --> I +``` + +**Diagram Sources** + +- [thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) +- [thought-chain.thought-chain-item.tsx:7-11](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L7-L11) +- [context.ts:1-6](file://frontend/antdx/thought-chain/context.ts#L1-L6) + +**Section Sources** + +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [thought-chain.thought-chain-item.tsx:1-14](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L1-L14) +- [thought-chain.item.tsx:1-33](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L1-L33) + +## Core Components + +### ThoughtChain Main Container + +The ThoughtChain component is the root container of the entire thought chain system, responsible for coordinating the rendering and state management of all sub-items: + +```mermaid +classDiagram +class ThoughtChain { ++items : Array ++children : ReactNode ++useMemo() items ++withItemsContextProvider() wrapper ++renderItems() processor +} +class ItemsContext { ++items : Object ++setItem() method ++initial : boolean ++onChange() callback +} +class ItemHandler { ++itemIndex : number ++itemSlotKey : string ++itemProps : function ++itemChildren : function ++slots : Object ++children : ReactNode +} +ThoughtChain --> ItemsContext : "uses" +ItemsContext --> ItemHandler : "provides" +ItemHandler --> ThoughtChain : "updates" +``` + +**Diagram Sources** + +- [thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) +- [context.ts:3-4](file://frontend/antdx/thought-chain/context.ts#L3-L4) +- [createItemsContext.tsx:102-170](file://frontend/utils/createItemsContext.tsx#L102-L170) + +### ThoughtChainItem Sub-item Component + +ThoughtChainItem provides two implementation approaches: direct React implementation and ItemHandler-based wrapper implementation. + +**Section Sources** + +- [thought-chain.thought-chain-item.tsx:7-11](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L7-L11) +- [thought-chain.item.tsx:9-27](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L9-L27) + +## Architecture Overview + +ThoughtChainItem adopts a layered architecture design, ensuring loose coupling and high cohesion between components: + +```mermaid +sequenceDiagram +participant App as Application +participant Chain as ThoughtChain +participant Handler as ItemHandler +participant Item as ThoughtChainItem +participant XChain as Ant Design X +App->>Chain : Render thought chain +Chain->>Handler : Create item handler +Handler->>Item : Process sub-item data +Item->>XChain : Render actual component +XChain-->>Item : Return render result +Item-->>Handler : Update state +Handler-->>Chain : Synchronize state +Chain-->>App : Render complete +``` + +**Diagram Sources** + +- [thought-chain.tsx:14-34](file://frontend/antdx/thought-chain/thought-chain.tsx#L14-L34) +- [createItemsContext.tsx:190-261](file://frontend/utils/createItemsContext.tsx#L190-L261) + +### State Management System + +The component's state management is based on React Context and the custom Items Context system: + +```mermaid +flowchart TD +A[User Action] --> B[State Change] +B --> C[ItemHandler Processing] +C --> D[Update Items Context] +D --> E[Trigger Re-render] +E --> F[Ant Design X Renders] +F --> G[Visual Feedback] +H[Async Operation] --> I[State Switch] +I --> J[Loading Indicator] +J --> K[Completion State] +L[Error Handling] --> M[Error State] +M --> N[Retry Mechanism] +``` + +**Diagram Sources** + +- [createItemsContext.tsx:124-153](file://frontend/utils/createItemsContext.tsx#L124-L153) +- [createItemsContext.tsx:234-237](file://frontend/utils/createItemsContext.tsx#L234-L237) + +**Section Sources** + +- [createItemsContext.tsx:97-274](file://frontend/utils/createItemsContext.tsx#L97-L274) + +## Detailed Component Analysis + +### ThoughtChainItem Property Configuration + +The component supports rich property configuration to meet different usage scenarios: + +| Property Name | Type | Required | Description | +| ------------- | ------------------------------------------ | -------- | -------------------------------------- | +| title | ReactNode \| string | No | Thought item title content | +| description | ReactNode \| string | No | Thought item description content | +| icon | ReactNode | No | Custom icon component | +| status | 'wait' \| 'process' \| 'finish' \| 'error' | No | Current status | +| key | string \| number | No | Unique key identifier | +| itemIndex | number | Yes | Index position in the parent container | +| itemSlotKey | string | No | Slot key value | +| itemProps | function | No | Dynamic property computation function | +| itemChildren | function | No | Child item generation function | + +### State Management Mechanism + +The component supports four core states, each with corresponding visual representations: + +```mermaid +stateDiagram-v2 +[*] --> Pending +Pending --> InProgress : Start execution +InProgress --> Completed : Execution successful +InProgress --> Failed : Execution error +Completed --> [*] +Failed --> Pending : Retry +Failed --> [*] : Abandon +``` + +**Diagram Sources** + +- [thought-chain.item.tsx:16-27](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L16-L27) + +### Event Handling Mechanism + +The component provides complete event handling capabilities: + +| Event Type | Callback | Trigger Timing | Parameters | +| ---------------- | -------- | --------------- | -------------------- | +| onClick | function | User clicks | event, itemData | +| onStatusChange | function | Status changes | oldStatus, newStatus | +| onRenderComplete | function | Render complete | itemData | +| onError | function | Error occurs | error, itemData | + +**Section Sources** + +- [thought-chain.thought-chain-item.tsx:7-11](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L7-L11) +- [thought-chain.item.tsx:9-27](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L9-L27) + +### Usage Examples + +#### Basic Usage + +```javascript +// Simple thought item configuration + + + +``` + +#### Advanced Configuration + +```javascript +// Complex configuration with dynamic properties + + } + description={} + icon={} + status={status} + itemProps={(props, items) => ({ + ...props, + onClick: () => handleItemClick(props.key), + className: getStatusClass(status), + })} + > +
Extra content
+
+
+``` + +#### Async State Management + +```javascript +// State management for async operations +const asyncOperation = async (itemId) => { + try { + // Set to in-progress state + updateItemStatus(itemId, 'process'); + + // Execute async operation + const result = await performOperation(); + + // Set to completed state + updateItemStatus(itemId, 'finish'); + return result; + } catch (error) { + // Set to failed state + updateItemStatus(itemId, 'error'); + throw error; + } +}; +``` + +**Section Sources** + +- [thought-chain.thought-chain-item.tsx:7-11](file://frontend/antdx/thought-chain/thought-chain-item/thought-chain.thought-chain-item.tsx#L7-L11) +- [thought-chain.item.tsx:16-27](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L16-L27) + +## Dependency Analysis + +The component system uses a modular design with clear responsibilities for each part: + +```mermaid +graph TB +subgraph "Core Dependencies" +A[React] --> B[Ant Design X] +B --> C[Ant Design Icons] +end +subgraph "Utility Libraries" +D[React Slot] --> E[Context Props] +F[Lodash-es] --> G[Utility Functions] +end +subgraph "Custom Implementation" +H[createItemsContext] --> I[ItemHandler] +J[renderItems] --> K[Property Handling] +end +A --> H +B --> J +C --> I +``` + +**Diagram Sources** + +- [thought-chain.tsx:1-8](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L8) +- [createItemsContext.tsx:1-18](file://frontend/utils/createItemsContext.tsx#L1-L18) + +### External Dependencies + +The component system depends on the following key external libraries: + +- **@ant-design/x**: Provides the core ThoughtChain component implementation +- **@svelte-preprocess-react**: Implements Svelte-to-React bridging +- **@utils/**: Custom utility function collection +- **classnames**: CSS class name composition tool + +**Section Sources** + +- [thought-chain.tsx:1-8](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L8) +- [thought-chain.item.tsx:1-7](file://frontend/antdx/thought-chain/item/thought-chain.item.tsx#L1-L7) + +## Performance Considerations + +### Rendering Optimization + +The component system employs multiple performance optimization strategies: + +1. **Memoization**: Use `useMemo` and `useCallback` to optimize rendering performance +2. **Conditional Rendering**: Only re-render components when necessary +3. **Batch Updates**: Reduce unnecessary re-renders through the Context system + +### Memory Management + +- **Reference Caching**: Use `useRef` to cache expensive computation results +- **Cleanup Mechanism**: Clean up timers and event listeners when the component unmounts +- **Circular Reference Protection**: Avoid circular dependencies in Context Providers + +### State Synchronization Optimization + +```mermaid +flowchart LR +A[State Change] --> B{Update Needed?} +B --> |No| C[Return Directly] +B --> |Yes| D[Compute New State] +D --> E[Update Context] +E --> F[Trigger Re-render] +F --> G[Optimized DOM Operations] +``` + +## Troubleshooting Guide + +### Common Issues and Solutions + +#### 1. Component Not Displaying or Displaying as Empty + +**Possible Causes**: + +- `itemIndex` or `itemSlotKey` not correctly set +- Slot content not correctly passed +- Context Provider not correctly configured + +**Solution**: + +```javascript +// Ensure correct index and slot configuration + + {children} + +``` + +#### 2. State Updates Not Taking Effect + +**Possible Causes**: + +- Status value not correctly passed to Ant Design X component +- Context update logic error + +**Solution**: +Check the state update logic in `ItemHandler`, ensuring the `setItem` method is called correctly. + +#### 3. Performance Issues + +**Possible Causes**: + +- Frequent state changes causing excessive re-renders +- Large number of sub-items not properly optimized + +**Solution**: +Use `useMemo` and `useCallback` to optimize expensive computations and callback functions. + +**Section Sources** + +- [createItemsContext.tsx:124-153](file://frontend/utils/createItemsContext.tsx#L124-L153) +- [createItemsContext.tsx:234-237](file://frontend/utils/createItemsContext.tsx#L234-L237) + +## Conclusion + +The ThoughtChainItem component is a fully functional, architecturally clean React component system. It achieves loose coupling between components through a carefully designed Context system, provides powerful extensibility through a flexible slot mechanism, and ensures a good user experience through a comprehensive event handling mechanism. + +This component system is particularly suited for building complex thought flow applications, effectively managing the states and interactions of multiple thinking steps, and providing users with an intuitive thought process visualization experience. Its modular architectural design also provides a solid foundation for future feature extensions and maintenance. diff --git a/.wiki/en/Ant Design X Components/Data Components/Data Components.md b/.wiki/en/Ant Design X Components/Data Components/Data Components.md new file mode 100644 index 00000000..76b89fcc --- /dev/null +++ b/.wiki/en/Ant Design X Components/Data Components/Data Components.md @@ -0,0 +1,372 @@ +# Data Components + + +**Files Referenced in This Document** +- [frontend/antdx/file-card/file-card.tsx](file://frontend/antdx/file-card/file-card.tsx) +- [frontend/antdx/file-card/base.tsx](file://frontend/antdx/file-card/base.tsx) +- [frontend/antdx/folder/folder.tsx](file://frontend/antdx/folder/folder.tsx) +- [frontend/antdx/folder/context.ts](file://frontend/antdx/folder/context.ts) +- [frontend/antdx/sources/sources.tsx](file://frontend/antdx/sources/sources.tsx) +- [frontend/antdx/sources/context.ts](file://frontend/antdx/sources/context.ts) +- [frontend/antdx/think/think.tsx](file://frontend/antdx/think/think.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document covers the data components of Ant Design X, focusing on four components: FileCard, Folder, Sources, and Think. It provides an in-depth analysis of system architecture, component responsibilities, data flow and processing logic, integration points, and error handling, along with ready-to-use examples and best practices to help developers quickly understand and correctly use these components. + +## Project Structure + +The frontend components of Ant Design X are located in the `frontend/antdx` directory. Each component typically consists of three parts: + +- Component entry file: Responsible for bridging Svelte and React ecosystems, injecting slots and functional callbacks. +- Base implementation file: Encapsulates actual component interactions with @ant-design/x, handles data parsing and default behavior. +- Context and utilities: Provides context capabilities for slot items via createItemsContext, supporting dynamic rendering and extension. + +```mermaid +graph TB +subgraph "Ant Design X Data Components" +FC["FileCard"] +F["Folder"] +S["Sources"] +T["Think"] +end +subgraph "Base Implementation" +BFC["BaseFileCard"] +CtxF["Folder Context
treeData/directoryIcons"] +CtxS["Sources Context
items/title"] +end +subgraph "External Dependencies" +ADX["@ant-design/x
Native Component Library"] +Utils["@utils/*
Utilities & Hooks"] +end +FC --> BFC +F --> CtxF +S --> CtxS +FC --> ADX +F --> ADX +S --> ADX +T --> ADX +FC --> Utils +F --> Utils +S --> Utils +T --> Utils +``` + +Diagram sources + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) +- [frontend/antdx/folder/folder.tsx:1-123](file://frontend/antdx/folder/folder.tsx#L1-L123) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) +- [frontend/antdx/sources/sources.tsx:1-42](file://frontend/antdx/sources/sources.tsx#L1-L42) +- [frontend/antdx/sources/context.ts:1-7](file://frontend/antdx/sources/context.ts#L1-L7) +- [frontend/antdx/think/think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +Section sources + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) +- [frontend/antdx/folder/folder.tsx:1-123](file://frontend/antdx/folder/folder.tsx#L1-L123) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) +- [frontend/antdx/sources/sources.tsx:1-42](file://frontend/antdx/sources/sources.tsx#L1-L42) +- [frontend/antdx/sources/context.ts:1-7](file://frontend/antdx/sources/context.ts#L1-L7) +- [frontend/antdx/think/think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +## Core Components + +- FileCard: Displays a single file card, supporting image placeholders, preview configuration, and slot-based customization of masks and loading indicators. Internally parses file resource URLs via BaseFileCard to ensure accessibility. + - **Sub-component hierarchy**: FileCard is the top-level single card component; `FileCardList` (list layer) arranges multiple file cards; `FileCardListItem` (list item layer) encapsulates the rendering logic of a single list item. The hierarchy is: FileCardList → FileCardListItem → FileCard. + - **Backend exports**: `FileCard`, `FileCardList`, and `FileCardListItem` are all exported via [backend/modelscope_studio/components/antdx/**init**.py](file://backend/modelscope_studio/components/antdx/__init__.py). +- Folder: Displays a folder tree structure, supporting treeData, directoryIcons, empty state rendering, directory title, preview title, and preview rendering slots. Provides dynamic node and icon injection via context. +- Sources: Displays a list of data sources, supporting items and title slots. Provides a default item collection via context for unified injection in parent containers. +- Think: Displays "thinking" records and status, supporting loading, icon, and title slots for different visual feedback in various states. + - **Difference between Think and ThoughtChain**: Think (`antdx.Think`) is a lightweight single-step "thinking status" display component, typically embedded in bubble streams to indicate a single "thinking" state (belongs to data components). ThoughtChain (`antdx.ThoughtChain`) is a multi-step reasoning chain component used to display a complete reasoning sequence with inner child item support (belongs to confirmation components). Their use cases differ: Think is suitable for single-state indication; ThoughtChain is suitable for multi-step reasoning display. + +Section sources + +- [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) +- [frontend/antdx/file-card/base.tsx:9-41](file://frontend/antdx/file-card/base.tsx#L9-L41) +- [frontend/antdx/folder/folder.tsx:16-120](file://frontend/antdx/folder/folder.tsx#L16-L120) +- [frontend/antdx/folder/context.ts:3-13](file://frontend/antdx/folder/context.ts#L3-L13) +- [frontend/antdx/sources/sources.tsx:9-39](file://frontend/antdx/sources/sources.tsx#L9-L39) +- [frontend/antdx/sources/context.ts:3-4](file://frontend/antdx/sources/context.ts#L3-L4) +- [frontend/antdx/think/think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +## Architecture Overview + +All four components adopt a layered design of "entry layer + base implementation/context": + +- Entry layer: Uses sveltify to bridge Svelte components to the React ecosystem, uniformly handling slots and functional callbacks, and ensuring property alignment with @ant-design/x. +- Base implementation/context: Builds on the entry layer to further encapsulate data parsing, default value handling, slot rendering, and context injection, reducing duplicate logic and improving maintainability. + +```mermaid +sequenceDiagram +participant U as "Caller" +participant FC as "FileCard Entry" +participant BFC as "BaseFileCard" +participant ADX as "@ant-design/x" +U->>FC : Pass props and slots +FC->>FC : Process slots and functional callbacks +FC->>BFC : Pass resolved props +BFC->>ADX : Render FileCard and resolve src +ADX-->>U : Display file card +``` + +Diagram sources + +- [frontend/antdx/file-card/file-card.tsx:34-124](file://frontend/antdx/file-card/file-card.tsx#L34-L124) +- [frontend/antdx/file-card/base.tsx:31-41](file://frontend/antdx/file-card/base.tsx#L31-L41) + +Section sources + +- [frontend/antdx/file-card/file-card.tsx:17-124](file://frontend/antdx/file-card/file-card.tsx#L17-L124) +- [frontend/antdx/file-card/base.tsx:9-41](file://frontend/antdx/file-card/base.tsx#L9-L41) + +## Detailed Component Analysis + +### FileCard Component Analysis + +- Responsibilities and Capabilities + - File information display: Supports file name, description, icon, placeholder image, loading indicator, etc. + - Actions and preview: Supports image preview configuration (container, mask, close icon, toolbar, custom image rendering). + - Slot-based extension: Flexibly replaces icon, description, mask, spinProps._, and imageProps._ via slots. + - Resource resolution: Converts relative paths or FileData to accessible URLs via BaseFileCard's src resolution logic. +- Key Flow + - Entry layer resolves slots and functional callbacks and constructs preview configuration. + - Passes resolved imageProps and spinProps to BaseFileCard. + - BaseFileCard uses rootUrl and apiPrefix to compute the accessible file URL. +- Usage Recommendations + - When customizing preview toolbars or masks, prefer slot injection over directly overriding complex objects. + - For large files or unstable network environments, configure placeholder images and loading indicators appropriately to improve user experience. + +```mermaid +flowchart TD +Start(["Enter FileCard"]) --> ParseSlots["Resolve slots and functional callbacks"] +ParseSlots --> BuildPreview["Build imageProps.preview configuration"] +BuildPreview --> ResolveSrc["BaseFileCard resolves src
rootUrl + apiPrefix"] +ResolveSrc --> Render["Render @ant-design/x FileCard"] +Render --> End(["Done"]) +``` + +Diagram sources + +- [frontend/antdx/file-card/file-card.tsx:34-124](file://frontend/antdx/file-card/file-card.tsx#L34-L124) +- [frontend/antdx/file-card/base.tsx:15-41](file://frontend/antdx/file-card/base.tsx#L15-L41) + +Section sources + +- [frontend/antdx/file-card/file-card.tsx:9-124](file://frontend/antdx/file-card/file-card.tsx#L9-L124) +- [frontend/antdx/file-card/base.tsx:9-41](file://frontend/antdx/file-card/base.tsx#L9-L41) + +### Folder Component Analysis + +- Responsibilities and Capabilities + - Tree structure display: Supports treeData and directory icon mapping via directoryIcons. + - Dynamic content service: Loads file content via fileContentService.onLoadFileContent. + - Slot-based extension: Supports emptyRender, previewRender, directoryTitle, and previewTitle. + - Context injection: Obtains default nodes and icon collections via useTreeNodeItems and useDirectoryIconItems. +- Key Flow + - Resolves treeData or default from context, prioritizing explicitly passed treeData. + - Converts directoryIcons into an icon dictionary keyed by file extension. + - Converts slots and functional callbacks to render functions required by @ant-design/x. +- Usage Recommendations + - For complex directory structures, prefer context injection of default nodes to reduce repetitive configuration. + - Preview render functions should be kept lightweight to avoid heavy computation during rendering. + +```mermaid +sequenceDiagram +participant U as "Caller" +participant F as "Folder Entry" +participant Ctx as "Folder Context" +participant ADX as "@ant-design/x Folder" +U->>F : Pass treeData/directoryIcons/slots +F->>Ctx : Read default nodes and icons +F->>F : Resolve slots and functional callbacks +F->>ADX : Render treeData and directoryIcons +ADX-->>U : Display folder tree +``` + +Diagram sources + +- [frontend/antdx/folder/folder.tsx:25-119](file://frontend/antdx/folder/folder.tsx#L25-L119) +- [frontend/antdx/folder/context.ts:3-13](file://frontend/antdx/folder/context.ts#L3-L13) + +Section sources + +- [frontend/antdx/folder/folder.tsx:16-120](file://frontend/antdx/folder/folder.tsx#L16-L120) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) + +### Sources Component Analysis + +- Responsibilities and Capabilities + - Data source list display: Supports items list and title slot. + - Context injection: Obtains default items and default via useItems, prioritizing explicitly passed items. + - Render enhancement: Uses renderItems to clone and render item collections from context into the format required by @ant-design/x. +- Key Flow + - Resolves items or default from context and merges into the final list. + - Passes title and items to @ant-design/x Sources. +- Usage Recommendations + - Inject default items centrally in a parent container for reuse across multiple locations. + - For large lists, apply pagination or lazy loading optimization upstream. + +```mermaid +sequenceDiagram +participant U as "Caller" +participant S as "Sources Entry" +participant Ctx as "Sources Context" +participant ADX as "@ant-design/x Sources" +U->>S : Pass items/slots +S->>Ctx : Read default items/default +S->>ADX : Render items and title +ADX-->>U : Display data source list +``` + +Diagram sources + +- [frontend/antdx/sources/sources.tsx:9-39](file://frontend/antdx/sources/sources.tsx#L9-L39) +- [frontend/antdx/sources/context.ts:3-4](file://frontend/antdx/sources/context.ts#L3-L4) + +Section sources + +- [frontend/antdx/sources/sources.tsx:9-39](file://frontend/antdx/sources/sources.tsx#L9-L39) +- [frontend/antdx/sources/context.ts:1-7](file://frontend/antdx/sources/context.ts#L1-L7) + +### Think Component Analysis + +- Responsibilities and Capabilities + - Thinking record and status display: Supports loading, icon, and title slots, enabling different content to be shown in various states (e.g., loading, complete, failed). + - Thin wrapper: Acts as a thin wrapper that directly forwards to the @ant-design/x Think component. +- Usage Recommendations + - In async thinking workflows, combine with the loading slot to provide friendlier user feedback. + - Use icon and title slots to differentiate thinking phases or result types. + +```mermaid +sequenceDiagram +participant U as "Caller" +participant T as "Think Entry" +participant ADX as "@ant-design/x Think" +U->>T : Pass loading/icon/title/slots +T->>ADX : Directly forward props and slots +ADX-->>U : Display thinking status +``` + +Diagram sources + +- [frontend/antdx/think/think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +Section sources + +- [frontend/antdx/think/think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +## Dependency Analysis + +- Inter-component Coupling + - FileCard and BaseFileCard: Low coupling, decoupled via props passing and resolution. + - Folder and Sources: Each depends on its own context module, independent from each other, rendered via @ant-design/x components. + - Think: No context dependency, directly bridges @ant-design/x. +- External Dependencies + - @ant-design/x: The foundational library for all component rendering. + - @utils/\*: Provides common capabilities such as slot rendering, functional callback wrapping, and context creation. + +```mermaid +graph LR +FC["FileCard"] --> BFC["BaseFileCard"] +F["Folder"] --> CtxF["Folder Context"] +S["Sources"] --> CtxS["Sources Context"] +T["Think"] +BFC --> ADX["@ant-design/x"] +F --> ADX +S --> ADX +T --> ADX +FC --> Utils["@utils/*"] +F --> Utils +S --> Utils +T --> Utils +``` + +Diagram sources + +- [frontend/antdx/file-card/file-card.tsx:1-7](file://frontend/antdx/file-card/file-card.tsx#L1-L7) +- [frontend/antdx/file-card/base.tsx:1-7](file://frontend/antdx/file-card/base.tsx#L1-L7) +- [frontend/antdx/folder/folder.tsx:1-7](file://frontend/antdx/folder/folder.tsx#L1-L7) +- [frontend/antdx/sources/sources.tsx:1-5](file://frontend/antdx/sources/sources.tsx#L1-L5) +- [frontend/antdx/think/think.tsx:1-4](file://frontend/antdx/think/think.tsx#L1-L4) + +Section sources + +- [frontend/antdx/file-card/file-card.tsx:1-7](file://frontend/antdx/file-card/file-card.tsx#L1-L7) +- [frontend/antdx/file-card/base.tsx:1-7](file://frontend/antdx/file-card/base.tsx#L1-L7) +- [frontend/antdx/folder/folder.tsx:1-7](file://frontend/antdx/folder/folder.tsx#L1-L7) +- [frontend/antdx/sources/sources.tsx:1-5](file://frontend/antdx/sources/sources.tsx#L1-L5) +- [frontend/antdx/think/think.tsx:1-4](file://frontend/antdx/think/think.tsx#L1-L4) + +## Performance Considerations + +- Slot rendering cost control + - Place heavy content in slots, but avoid repeated computation in render functions; use useMemo for caching when necessary. +- Data parsing and transfer + - FileCard's src resolution is only triggered when dependencies change, avoiding unnecessary URL computation. +- List rendering optimization + - Sources and Folder use clone and memo strategies when resolving items to reduce repeated rendering. +- Preview and images + - Configure placeholder images and loading indicators appropriately to prevent large images from blocking the initial render. + +## Troubleshooting Guide + +- Image not displaying + - Check whether src is a relative path; confirm rootUrl and apiPrefix are configured correctly. + - Reference: [frontend/antdx/file-card/base.tsx:15-29](file://frontend/antdx/file-card/base.tsx#L15-L29) +- Preview function abnormal + - Confirm that imageProps.preview slots are correctly injected and functional callbacks are properly wrapped. + - Reference: [frontend/antdx/file-card/file-card.tsx:34-124](file://frontend/antdx/file-card/file-card.tsx#L34-L124) +- Directory icons not working + - Confirm directoryIcons are mapped by file extension and injected via context. + - Reference: [frontend/antdx/folder/folder.tsx:71-87](file://frontend/antdx/folder/folder.tsx#L71-L87) +- Data source list empty + - Check whether items and default are correctly injected or explicitly overridden. + - Reference: [frontend/antdx/sources/sources.tsx:13-33](file://frontend/antdx/sources/sources.tsx#L13-L33) +- Thinking status not updating + - Confirm loading/icon/title slots are correctly injected and functional callbacks are properly wrapped. + - Reference: [frontend/antdx/think/think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +Section sources + +- [frontend/antdx/file-card/base.tsx:15-29](file://frontend/antdx/file-card/base.tsx#L15-L29) +- [frontend/antdx/file-card/file-card.tsx:34-124](file://frontend/antdx/file-card/file-card.tsx#L34-L124) +- [frontend/antdx/folder/folder.tsx:71-87](file://frontend/antdx/folder/folder.tsx#L71-L87) +- [frontend/antdx/sources/sources.tsx:13-33](file://frontend/antdx/sources/sources.tsx#L13-L33) +- [frontend/antdx/think/think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +## Conclusion + +This document systematically covers the frontend implementation and usage of Ant Design X data components, focusing on FileCard, Folder, Sources, and Think. Through slot and functional callback bridging in the entry layer, data parsing and default value handling in the base implementation, and context-driven dynamic injection mechanisms, these components maintain API semantics consistent with @ant-design/x while providing stronger extensibility and maintainability. It is recommended to follow the usage guidelines and best practices in this document in actual projects for a more stable and efficient experience. + +## Appendix + +- Usage Examples (Based on Component Responsibilities and Interfaces) + - File card display and preview + - Key steps: Prepare file data src, configure imageProps.preview slots (e.g., mask, toolbar), and optionally set placeholder image and loading indicator. + - Reference: [frontend/antdx/file-card/file-card.tsx:34-124](file://frontend/antdx/file-card/file-card.tsx#L34-L124), [frontend/antdx/file-card/base.tsx:15-41](file://frontend/antdx/file-card/base.tsx#L15-L41) + - Folder tree structure and directory management + - Key steps: Prepare treeData or inject default nodes via context; configure extension-based mapping for directoryIcons; inject emptyRender, previewRender, directoryTitle, and previewTitle as needed. + - Reference: [frontend/antdx/folder/folder.tsx:25-119](file://frontend/antdx/folder/folder.tsx#L25-L119), [frontend/antdx/folder/context.ts:3-13](file://frontend/antdx/folder/context.ts#L3-L13) + - Data source management and metadata display + - Key steps: Inject default items or default in the parent container; override items when needed; customize title via the title slot. + - Reference: [frontend/antdx/sources/sources.tsx:9-39](file://frontend/antdx/sources/sources.tsx#L9-L39), [frontend/antdx/sources/context.ts:3-4](file://frontend/antdx/sources/context.ts#L3-L4) + - Thinking record and status management + - Key steps: Inject loading/icon/title slots at different stages; switch displayed content based on status in async workflows. + - Reference: [frontend/antdx/think/think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) diff --git a/.wiki/en/Ant Design X Components/Data Components/FileCard Component.md b/.wiki/en/Ant Design X Components/Data Components/FileCard Component.md new file mode 100644 index 00000000..e84b0231 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Data Components/FileCard Component.md @@ -0,0 +1,441 @@ +# FileCard Component + + +**Files Referenced in This Document** +- [frontend/antdx/file-card/file-card.tsx](file://frontend/antdx/file-card/file-card.tsx) +- [frontend/antdx/file-card/base.tsx](file://frontend/antdx/file-card/base.tsx) +- [frontend/antdx/file-card/Index.svelte](file://frontend/antdx/file-card/Index.svelte) +- [frontend/antdx/file-card/list/file-card.list.tsx](file://frontend/antdx/file-card/list/file-card.list.tsx) +- [frontend/antdx/file-card/list/context.ts](file://frontend/antdx/file-card/list/context.ts) +- [frontend/antdx/file-card/list/item/file-card.list.item.tsx](file://frontend/antdx/file-card/list/item/file-card.list.item.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +The FileCard component is an important component in the ModelScope Studio frontend framework, extended and encapsulated based on the Ant Design X FileCard component. It provides file display, preview, and upload capabilities, supporting multiple file types and custom configuration options. + +The component consists of three core parts: + +- **Base FileCard component**: Provides core file display functionality +- **FileCard List component**: Used to display a list view of multiple file cards +- **FileCard List Item component**: The concrete implementation of a single file card in a list + +## Project Structure + +The FileCard component is located in the antdx component library of the frontend project, organized in a modular manner: + +```mermaid +graph TB +subgraph "FileCard Component Structure" +FC[FileCard Core Component] +FCL[FileCard List Component] +FCListItem[FileCard List Item Component] +Base[Base FileCard Component] +FC --> Base +FCL --> FCListItem +FCListItem --> Base +end +subgraph "Frontend Component Libraries" +Antdx[antdx Component Library] +Antd[antd Component Library] +Utils[Utility Functions] +end +FC -.-> Antdx +FCL -.-> Antdx +FCListItem -.-> Antdx +Base -.-> Antdx +Base -.-> Antd +FC -.-> Utils +FCL -.-> Utils +FCListItem -.-> Utils +``` + +**Diagram sources** + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/list/file-card.list.tsx:1-68](file://frontend/antdx/file-card/list/file-card.list.tsx#L1-L68) + +**Section sources** + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/list/file-card.list.tsx:1-68](file://frontend/antdx/file-card/list/file-card.list.tsx#L1-L68) + +## Core Components + +### Base FileCard Component (BaseFileCard) + +The BaseFileCard component is the foundation of the entire FileCard system, responsible for handling file source resolution and basic file display logic. + +**Key Features:** + +- Supports both string and FileData type file sources +- Automatically resolves accessible file URLs +- Integrates Ant Design X's FileCard component +- Provides root URL and API prefix configuration + +**Key Methods:** + +- `resolveFileSrc()`: Resolves the file source, supporting both local and remote files +- `BaseFileCard`: Main component rendering logic + +**Section sources** + +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) + +### FileCard Component + +The FileCard component is a further encapsulation of the base component, adding React Slot support and richer configuration options. + +**Main Features:** + +- Supports the React Slot system +- Enhanced image preview functionality +- Loading state indicator configuration +- Custom icon and description content + +**Core Configuration:** + +- `imageProps.placeholder`: Placeholder configuration +- `imageProps.preview`: Preview function configuration +- `spinProps`: Loading state configuration +- `slots`: Slot system support + +**Section sources** + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) + +### FileCard List Component (FileCardList) + +The FileCardList component is used to display multiple file cards, supporting bulk operations and unified configuration. + +**Key Features:** + +- Bulk file management +- Removable functionality +- Slot system integration +- Item context management + +**Section sources** + +- [frontend/antdx/file-card/list/file-card.list.tsx:1-68](file://frontend/antdx/file-card/list/file-card.list.tsx#L1-L68) + +### FileCard List Item Component (FileCardListItem) + +The concrete implementation of a single file card in a list, inheriting all functionality of the base file card. + +**Key Features:** + +- List item handling mechanism +- Slot parameter passing +- Preview configuration +- Item context integration + +**Section sources** + +- [frontend/antdx/file-card/list/item/file-card.list.item.tsx:1-83](file://frontend/antdx/file-card/list/item/file-card.list.item.tsx#L1-L83) + +## Architecture Overview + +The FileCard component adopts a layered architecture design, forming a clear hierarchy from the underlying base component to the upper-level application components: + +```mermaid +graph TD +subgraph "Application Layer" +App[Application] +Demo[Demo App] +end +subgraph "Component Layer" +SvelteIndex[Index.svelte Entry] +FileCard[FileCard Component] +FileCardList[FileCardList Component] +FileCardListItem[FileCardListItem Component] +end +subgraph "Base Layer" +BaseFileCard[BaseFileCard Component] +AntdX[Ant Design X] +Utils[Utility Functions] +end +subgraph "Data Layer" +FileData[File Data Model] +Config[Configuration Object] +Slots[Slot System] +end +App --> SvelteIndex +Demo --> SvelteIndex +SvelteIndex --> FileCard +SvelteIndex --> FileCardList +FileCardList --> FileCardListItem +FileCard --> BaseFileCard +FileCardList --> BaseFileCard +FileCardListItem --> BaseFileCard +BaseFileCard --> AntdX +FileCard --> Utils +FileCardList --> Utils +FileCardListItem --> Utils +BaseFileCard --> FileData +FileCard --> Config +FileCardList --> Config +FileCardListItem --> Config +FileCard --> Slots +FileCardList --> Slots +FileCardListItem --> Slots +``` + +**Diagram sources** + +- [frontend/antdx/file-card/Index.svelte:1-66](file://frontend/antdx/file-card/Index.svelte#L1-L66) +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/list/file-card.list.tsx:1-68](file://frontend/antdx/file-card/list/file-card.list.tsx#L1-L68) + +## Detailed Component Analysis + +### Base FileCard Component Class Diagram + +```mermaid +classDiagram +class BaseFileCardProps { ++string rootUrl ++string apiPrefix ++string|FileData src ++XFileCardProps props +} +class BaseFileCard { ++resolveFileSrc(src, rootUrl, apiPrefix) string ++render() ReactElement +} +class FileCardProps { ++BaseFileCardProps props ++React.ReactNode children ++object slots ++object imageProps ++object spinProps +} +class FileCard { ++getConfig(value) object ++render() ReactElement +} +class FileCardListProps { ++FileCardListProps props ++ItemType[] items ++React.ReactNode children ++string rootUrl ++string apiPrefix ++function removable +} +class FileCardList { ++render() ReactElement ++resolveItems() ItemType[] +} +class FileCardListItemProps { ++BaseFileCardProps props ++ItemHandlerProps props ++object slots ++object imageProps +} +class FileCardListItem { ++getConfig(value) object ++render() ReactElement +} +BaseFileCardProps <|-- FileCardProps +BaseFileCardProps <|-- FileCardListItemProps +FileCardProps <|-- FileCard +FileCardListProps <|-- FileCardList +FileCardListItemProps <|-- FileCardListItem +FileCard --> BaseFileCard +FileCardList --> FileCardListItem +FileCardListItem --> BaseFileCard +``` + +**Diagram sources** + +- [frontend/antdx/file-card/base.tsx:9-13](file://frontend/antdx/file-card/base.tsx#L9-L13) +- [frontend/antdx/file-card/file-card.tsx:17-34](file://frontend/antdx/file-card/file-card.tsx#L17-L34) +- [frontend/antdx/file-card/list/file-card.list.tsx:14-21](file://frontend/antdx/file-card/list/file-card.list.tsx#L14-L21) +- [frontend/antdx/file-card/list/item/file-card.list.item.tsx:16-31](file://frontend/antdx/file-card/list/item/file-card.list.item.tsx#L16-L31) + +### File Source Resolution Flow + +```mermaid +flowchart TD +Start([Start resolving file source]) --> CheckSrc{Check src parameter} +CheckSrc --> |Empty| ReturnEmpty[Return empty value] +CheckSrc --> |String| CheckProtocol{Check protocol} +CheckSrc --> |Object| CheckObject{Check object properties} +CheckProtocol --> |Starts with http| ReturnString[Return string directly] +CheckProtocol --> |Does not start with http| ResolveURL[Call getFetchableUrl] +CheckObject --> CheckUrl{Check url property} +CheckObject --> CheckPath{Check path property} +CheckUrl --> |Exists| ReturnUrl[Return url] +CheckUrl --> |Does not exist| ResolvePath[Call getFetchableUrl] +CheckPath --> |Exists| ResolvePath +CheckPath --> |Does not exist| ReturnUndefined[Return undefined] +ResolveURL --> ReturnResolved[Return resolved URL] +ResolvePath --> ReturnResolved +ReturnEmpty --> End([End]) +ReturnString --> End +ReturnUrl --> End +ReturnResolved --> End +ReturnUndefined --> End +``` + +**Diagram sources** + +- [frontend/antdx/file-card/base.tsx:15-29](file://frontend/antdx/file-card/base.tsx#L15-L29) + +### Slot System Workflow + +```mermaid +sequenceDiagram +participant App as Application +participant FileCard as FileCard Component +participant BaseFileCard as BaseFileCard Component +participant SlotSystem as Slot System +participant Utils as Utility Functions +App->>FileCard : Render component +FileCard->>SlotSystem : Get slot configuration +SlotSystem-->>FileCard : Return slot data +FileCard->>Utils : Process slot parameters +Utils-->>FileCard : Return processed result +FileCard->>BaseFileCard : Pass configuration +BaseFileCard->>BaseFileCard : Render file card +BaseFileCard-->>App : Output final component +``` + +**Diagram sources** + +- [frontend/antdx/file-card/file-card.tsx:34-124](file://frontend/antdx/file-card/file-card.tsx#L34-L124) +- [frontend/antdx/file-card/base.tsx:31-41](file://frontend/antdx/file-card/base.tsx#L31-L41) + +**Section sources** + +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/list/file-card.list.tsx:1-68](file://frontend/antdx/file-card/list/file-card.list.tsx#L1-L68) +- [frontend/antdx/file-card/list/item/file-card.list.item.tsx:1-83](file://frontend/antdx/file-card/list/item/file-card.list.item.tsx#L1-L83) + +## Dependency Analysis + +The dependency relationship of the FileCard component is relatively clear, primarily depending on the Ant Design X component library and internal utility functions: + +```mermaid +graph LR +subgraph "External Dependencies" +AntdX[Ant Design X] +React[React] +Svelte[Svelte] +end +subgraph "Internal Dependencies" +Utils[Utility Functions] +Hooks[React Hooks] +Context[Context System] +end +subgraph "FileCard Components" +BaseFileCard[BaseFileCard] +FileCard[FileCard] +FileCardList[FileCardList] +FileCardListItem[FileCardListItem] +end +FileCard --> BaseFileCard +FileCardList --> FileCardListItem +FileCardListItem --> BaseFileCard +BaseFileCard --> AntdX +FileCard --> Utils +FileCardList --> Utils +FileCardListItem --> Utils +FileCard --> Hooks +FileCardList --> Hooks +FileCardListItem --> Hooks +FileCard --> Context +FileCardList --> Context +FileCardListItem --> Context +BaseFileCard --> React +FileCard --> Svelte +FileCardList --> Svelte +FileCardListItem --> Svelte +``` + +**Diagram sources** + +- [frontend/antdx/file-card/file-card.tsx:1-7](file://frontend/antdx/file-card/file-card.tsx#L1-L7) +- [frontend/antdx/file-card/base.tsx:1-7](file://frontend/antdx/file-card/base.tsx#L1-L7) +- [frontend/antdx/file-card/list/file-card.list.tsx:1-8](file://frontend/antdx/file-card/list/file-card.list.tsx#L1-L8) + +**Section sources** + +- [frontend/antdx/file-card/file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [frontend/antdx/file-card/base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) +- [frontend/antdx/file-card/list/file-card.list.tsx:1-68](file://frontend/antdx/file-card/list/file-card.list.tsx#L1-L68) + +## Performance Considerations + +The FileCard component was designed with performance optimization in mind: + +### Memory Management + +- Uses `useMemo` to cache file source resolution results +- Avoids unnecessary component re-renders +- Proper use of React Slots to reduce DOM operations + +### Render Optimization + +- Conditional rendering of slot content +- Lazy loading components to avoid initial render pressure +- Optimized performance for the image preview feature + +### Data Flow Optimization + +- Unidirectional data flow design +- Avoids passing deeply nested objects +- Reasonable event handling mechanisms + +## Troubleshooting Guide + +### Common Issues and Solutions + +**File not displaying** + +- Check whether the file source URL is correct +- Confirm network connectivity and permission settings +- Verify that the file format is supported + +**Preview function abnormal** + +- Check the image preview configuration +- Confirm the slot system is working correctly +- Verify that the container element exists + +**Component rendering error** + +- Check the usage of React Slots +- Confirm that required dependencies are installed correctly +- Verify the import path of the component + +**Section sources** + +- [frontend/antdx/file-card/base.tsx:15-29](file://frontend/antdx/file-card/base.tsx#L15-L29) +- [frontend/antdx/file-card/file-card.tsx:34-124](file://frontend/antdx/file-card/file-card.tsx#L34-L124) + +## Conclusion + +The FileCard component is a fully functional and well-designed frontend component system. Through its clear layered architecture, flexible slot system, and comprehensive configuration options, it provides users with powerful file management and display capabilities. + +The main advantages of the component include: + +- **Modular design**: Clear component hierarchy structure +- **Flexible configuration**: Rich configuration options and slot system +- **Performance optimization**: Reasonable memory management and render optimization +- **Easy to extend**: Standardized interface design facilitates feature extension + +This component system provides ModelScope Studio with reliable file processing capabilities to meet the needs of various file display and management scenarios. diff --git a/.wiki/en/Ant Design X Components/Data Components/Folder Component.md b/.wiki/en/Ant Design X Components/Data Components/Folder Component.md new file mode 100644 index 00000000..453d315d --- /dev/null +++ b/.wiki/en/Ant Design X Components/Data Components/Folder Component.md @@ -0,0 +1,359 @@ +# Folder Component + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/folder/__init__.py](file://backend/modelscope_studio/components/antdx/folder/__init__.py) +- [frontend/antdx/folder/Index.svelte](file://frontend/antdx/folder/Index.svelte) +- [frontend/antdx/folder/folder.tsx](file://frontend/antdx/folder/folder.tsx) +- [frontend/antdx/folder/context.ts](file://frontend/antdx/folder/context.ts) +- [frontend/antdx/folder/package.json](file://frontend/antdx/folder/package.json) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [docs/components/antdx/folder/README-zh_CN.md](file://docs/components/antdx/folder/README-zh_CN.md) +- [docs/components/antdx/folder/README.md](file://docs/components/antdx/folder/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +The Folder component is an important file tree component in ModelScope Studio, built on top of Ant Design X's Folder component. It is primarily used to display file system structures, providing hierarchical browsing of files and folders. It supports event handling for file clicks, folder clicks, selected file changes, and expanded path changes, along with rich customization options. + +The component is implemented on the frontend using the Svelte framework, bridged to Ant Design X's native component through a React preprocessing mechanism, achieving a complete data flow and event flow from the Python backend to the React frontend. + +## Project Structure + +The location and organizational structure of the Folder component within the project: + +```mermaid +graph TB +subgraph "Backend (Python)" +A[backend/modelscope_studio/components/antdx/] --> B[folder/] +B --> C[__init__.py
AntdXFolder class] +B --> D[directory_icon/] +B --> E[tree_node/] +end +subgraph "Frontend (TypeScript/Svelte)" +F[frontend/antdx/] --> G[folder/] +G --> H[Index.svelte
Component Entry] +G --> I[folder.tsx
React Implementation] +G --> J[context.ts
Context Management] +G --> K[package.json
Package Config] +end +subgraph "Documentation" +L[docs/components/antdx/folder/] +L --> M[README-zh_CN.md] +L --> N[README.md] +end +A --> F +F --> L +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:1-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L1-L114) +- [frontend/antdx/folder/Index.svelte:1-81](file://frontend/antdx/folder/Index.svelte#L1-L81) +- [frontend/antdx/folder/folder.tsx:1-124](file://frontend/antdx/folder/folder.tsx#L1-L124) + +**Section sources** + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:1-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L1-L114) +- [frontend/antdx/folder/Index.svelte:1-81](file://frontend/antdx/folder/Index.svelte#L1-L81) +- [frontend/antdx/folder/folder.tsx:1-124](file://frontend/antdx/folder/folder.tsx#L1-L124) + +## Core Components + +### AntdXFolder Class + +AntdXFolder is the core backend component class, inheriting from ModelScopeLayoutComponent. It defines the complete component interface and behavioral specification. + +**Key Features:** + +- Supports multiple event listeners (file_click, folder_click, selected_file_change, expanded_paths_change) +- Provides rich configuration properties (tree_data, selectable, selected_file, expanded_paths, etc.) +- Supports a slot system (emptyRender, previewRender, directoryTitle, etc.) +- Integrates component lifecycle management in the Gradio ecosystem + +**Key Property Descriptions:** + +- `tree_data`: File tree data structure defining the hierarchy of files and folders +- `selectable`: Whether file selection is allowed +- `selected_file`: Currently selected file path list +- `expanded_paths`: Default expanded path list +- `directory_icons`: Custom directory icon mapping + +**Section sources** + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:12-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L12-L114) + +### Frontend Component Architecture + +The frontend component adopts a layered architecture design, implemented through bridging Svelte and React: + +```mermaid +classDiagram +class AntdXFolder { ++TreeNode ++DirectoryIcon ++EVENTS ++SLOTS ++tree_data ++selectable ++selected_file ++expanded_paths ++directory_icons ++FRONTEND_DIR ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +class FolderComponent { ++slots ++children ++previewRender ++previewTitle ++fileContentService ++treeData ++directoryIcons ++emptyRender ++directoryTitle +} +class ContextProviders { ++withTreeNodeItemsContextProvider ++withDirectoryIconItemsContextProvider ++useTreeNodeItems ++useDirectoryIconItems +} +AntdXFolder --> FolderComponent : "Frontend rendering" +FolderComponent --> ContextProviders : "Use context" +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:12-114](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L12-L114) +- [frontend/antdx/folder/folder.tsx:16-124](file://frontend/antdx/folder/folder.tsx#L16-L124) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) + +**Section sources** + +- [frontend/antdx/folder/folder.tsx:16-124](file://frontend/antdx/folder/folder.tsx#L16-L124) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) + +## Architecture Overview + +The overall architecture of the Folder component adopts a layered design, achieving a complete data flow from the Python backend to the React frontend: + +```mermaid +sequenceDiagram +participant Backend as Backend Component +participant Svelte as Svelte Layer +participant React as React Component +participant AntDX as Ant Design X +participant User as User +User->>Backend : Create Folder component +Backend->>Svelte : Render component +Svelte->>React : Load Folder component +React->>AntDX : Initialize AntdXFolder +AntDX->>User : Display file tree interface +User->>AntDX : Click file/folder +AntDX->>React : Trigger event callback +React->>Svelte : Forward event +Svelte->>Backend : Update state +Backend->>User : Return result +Note over Backend,User : Data binding and event handling +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:19-35](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L19-L35) +- [frontend/antdx/folder/Index.svelte:10-81](file://frontend/antdx/folder/Index.svelte#L10-L81) +- [frontend/antdx/folder/folder.tsx:25-121](file://frontend/antdx/folder/folder.tsx#L25-L121) + +## Detailed Component Analysis + +### Event Handling Mechanism + +The Folder component supports multiple event listeners, each with its specific functionality and trigger conditions: + +```mermaid +flowchart TD +A[User Interaction] --> B{Event Type} +B --> |file_click| C[File Click Event] +B --> |folder_click| D[Folder Click Event] +B --> |selected_file_change| E[Selected File Change] +B --> |expanded_paths_change| F[Expanded Paths Change] +B --> |file_content_service_load_file_content| G[File Content Load] +C --> H[Update bind_fileClick_event] +D --> I[Update bind_folderClick_event] +E --> J[Update bind_selectedFileChange_event] +F --> K[Update bind_expandedPathsChange_event] +G --> L[Update bind_fileContentService_loadFileContent_event] +H --> M[Execute callback function] +I --> M +J --> M +K --> M +L --> M +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:19-35](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L19-L35) + +### Slot System + +The component provides a flexible slot system, allowing developers to customize various display content: + +| Slot Name | Description | Use Case | +| -------------- | --------------------- | -------------------------------------------------- | +| emptyRender | Empty state rendering | Display custom content when the file tree is empty | +| previewRender | Preview rendering | Customize file preview content | +| directoryTitle | Directory title | Customize directory display title | +| previewTitle | Preview title | Customize preview title display | +| treeData | Tree data | Customize tree data structure | +| directoryIcons | Directory icons | Customize file type icons | + +**Section sources** + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:37-41](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L37-L41) + +### Data Flow Processing + +The component's data flow processing uses React's useMemo optimization mechanism: + +```mermaid +flowchart LR +A[Raw Data] --> B[useMemo Optimization] +B --> C[Data Transformation] +C --> D[Context Provider] +D --> E[Child Component Consumption] +F[External Input] --> G[props.treeData] +H[Internal Generation] --> I[renderItems] +G --> C +I --> C +J[Directory Icons] --> K[Object Mapping] +K --> L[extension -> ReactNode] +``` + +**Diagram sources** + +- [frontend/antdx/folder/folder.tsx:60-88](file://frontend/antdx/folder/folder.tsx#L60-L88) + +**Section sources** + +- [frontend/antdx/folder/folder.tsx:60-88](file://frontend/antdx/folder/folder.tsx#L60-L88) + +## Dependency Analysis + +The dependency relationships of the Folder component reflect a clear layered architecture: + +```mermaid +graph TB +subgraph "External Dependencies" +A[@ant-design/x] --> B[AntdXFolder] +C[classnames] --> D[Svelte Style Processing] +E[react] --> F[React Slot] +end +subgraph "Internal Dependencies" +G[createItemsContext] --> H[Context Provider] +I[renderItems] --> J[Item Rendering] +K[renderParamsSlot] --> L[Parameterized Slots] +M[useFunction] --> N[Function Wrapping] +end +subgraph "Component Hierarchy" +O[AntdXFolder] --> P[Index.svelte] +P --> Q[folder.tsx] +Q --> R[React Component] +R --> S[Ant Design X] +end +A --> R +G --> Q +I --> Q +K --> Q +M --> Q +``` + +**Diagram sources** + +- [frontend/antdx/folder/folder.tsx:1-15](file://frontend/antdx/folder/folder.tsx#L1-L15) +- [frontend/antdx/folder/Index.svelte:1-10](file://frontend/antdx/folder/Index.svelte#L1-L10) +- [frontend/antdx/folder/context.ts:1-16](file://frontend/antdx/folder/context.ts#L1-L16) + +**Section sources** + +- [frontend/antdx/folder/package.json:1-15](file://frontend/antdx/folder/package.json#L1-L15) +- [frontend/antdx/folder/folder.tsx:1-15](file://frontend/antdx/folder/folder.tsx#L1-L15) + +## Performance Considerations + +### Render Optimization + +The component adopts several performance optimization strategies: + +1. **useMemo optimization**: Memoizes treeData and directoryIcons to avoid unnecessary recomputation +2. **Conditional rendering**: Only renders children content when needed, reducing the number of DOM nodes +3. **Lazy loading**: Implements dynamic import and lazy loading of components via importComponent + +### Memory Management + +- Context providers use appropriate cleanup mechanisms +- Event handlers are wrapped with useFunction to ensure correct `this` binding +- Slot content is rendered on demand to avoid memory leaks + +## Troubleshooting Guide + +### Common Issues and Solutions + +**Issue 1: Component not displaying** + +- Check whether tree_data is correctly set +- Confirm that the FRONTEND_DIR path is correctly resolved +- Verify the component's visible property + +**Issue 2: Events not triggering** + +- Confirm that event listeners are correctly registered +- Check whether bind\_\*\_event properties are set +- Verify that the callback function signature is correct + +**Issue 3: Icons not displaying** + +- Check the directory_icons configuration +- Confirm that the extension mapping is correct +- Verify the import path of icon components + +**Section sources** + +- [backend/modelscope_studio/components/antdx/folder/**init**.py:97-101](file://backend/modelscope_studio/components/antdx/folder/__init__.py#L97-L101) + +## Conclusion + +The Folder component is a fully functional file tree component with a clear architecture. It successfully combines the powerful capabilities of Ant Design X with the ModelScope Studio ecosystem, providing users with an excellent file browsing experience. + +**Main Advantages:** + +- Complete event handling mechanism +- Flexible slot system +- Excellent performance +- Clear code structure +- Good extensibility + +**Applicable Scenarios:** + +- File management systems +- Code editors +- Asset management tools +- Document browsing applications + +This component provides ModelScope Studio with powerful file tree display capabilities and serves as an important foundational component for building complex frontend applications. diff --git a/.wiki/en/Ant Design X Components/Data Components/Sources Component.md b/.wiki/en/Ant Design X Components/Data Components/Sources Component.md new file mode 100644 index 00000000..820ea89b --- /dev/null +++ b/.wiki/en/Ant Design X Components/Data Components/Sources Component.md @@ -0,0 +1,422 @@ +# Sources Component + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/sources/__init__.py](file://backend/modelscope_studio/components/antdx/sources/__init__.py) +- [backend/modelscope_studio/components/antdx/sources/item/__init__.py](file://backend/modelscope_studio/components/antdx/sources/item/__init__.py) +- [frontend/antdx/sources/sources.tsx](file://frontend/antdx/sources/sources.tsx) +- [frontend/antdx/sources/item/sources.item.tsx](file://frontend/antdx/sources/item/sources.item.tsx) +- [frontend/antdx/sources/context.ts](file://frontend/antdx/sources/context.ts) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [docs/components/antdx/sources/README-zh_CN.md](file://docs/components/antdx/sources/README-zh_CN.md) +- [docs/components/antdx/sources/demos/basic.py](file://docs/components/antdx/sources/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +The Sources component is a core component in ModelScope Studio for displaying a list of information sources in AI chat scenarios. Built on top of Ant Design X's Sources component, it is specifically designed to display references, link sources, and other related information. + +The component supports multiple configuration options, including title settings, expanded state control, inline display mode, and provides complete event handling mechanisms including click events and expand events. + +## Project Structure + +The Sources component adopts a frontend/backend separated architecture design, mainly consisting of the following structure: + +```mermaid +graph TB +subgraph "Backend Component Layer" +Backend[AntdXSources
Main Component] +BackendItem[AntdXSourcesItem
Child Item Component] +end +subgraph "Frontend Component Layer" +Frontend[Sources
React Component] +FrontendItem[SourcesItem
React Child Item Component] +Context[Context
Context Management] +end +subgraph "Utility Layer" +Utils[ModelScopeLayoutComponent
Base Component Class] +Resolver[resolve_frontend_dir
Path Resolver] +end +Backend --> Utils +BackendItem --> Utils +Backend --> Frontend +BackendItem --> FrontendItem +Frontend --> Context +Backend --> Resolver +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/antdx/sources/**init**.py:11-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L11-L92) +- [frontend/antdx/sources/sources.tsx:1-41](file://frontend/antdx/sources/sources.tsx#L1-L41) + +**Section sources** + +- [backend/modelscope_studio/components/antdx/sources/**init**.py:1-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L1-L92) +- [backend/modelscope_studio/components/antdx/sources/item/**init**.py:1-68](file://backend/modelscope_studio/components/antdx/sources/item/__init__.py#L1-L68) + +## Core Components + +### AntdXSources Main Component + +AntdXSources is the main container of the Sources component, responsible for managing the display and interaction of the entire data source list. + +**Key Features:** + +- Supports title display and customization +- Configurable expand icon position (start/end) +- Default expanded and controlled expanded states +- Inline display mode support +- Active key management +- Popover overlay width setting + +**Key Properties:** + +- `title`: Title text displayed at the top of the component +- `items`: Array configuration of data source items +- `expand_icon_position`: Display position of the expand icon +- `default_expanded`: Default expanded state +- `expanded`: Controlled expanded state +- `inline`: Whether to enable inline display mode +- `active_key`: Currently active item key +- `popover_overlay_width`: Popover overlay width + +### AntdXSourcesItem Child Item Component + +AntdXSourcesItem represents a single data source entry, used to display specific source information. + +**Key Features:** + +- Supports customization of title, icon, and description +- Link address configuration +- Unique key identifier +- Slot system support + +**Key Properties:** + +- `key`: Unique identifier of the item +- `title`: Item title +- `description`: Item description information +- `icon`: Custom icon +- `url`: Navigation link address + +**Section sources** + +- [backend/modelscope_studio/components/antdx/sources/**init**.py:30-73](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L30-L73) +- [backend/modelscope_studio/components/antdx/sources/item/**init**.py:18-48](file://backend/modelscope_studio/components/antdx/sources/item/__init__.py#L18-L48) + +## Architecture Overview + +The Sources component adopts a layered architecture design, achieving clear separation of concerns: + +```mermaid +sequenceDiagram +participant App as Application +participant Backend as Backend Component +participant Frontend as Frontend Component +participant AntDX as Ant Design X +participant Context as Context Management +App->>Backend : Create Sources component +Backend->>Backend : Resolve frontend directory +Backend->>Frontend : Render React component +Frontend->>Context : Initialize context provider +Frontend->>AntDX : Use native Sources component +AntDX-->>Frontend : Return render result +Frontend-->>App : Output final component +Note over Backend,Frontend : Event binding and data passing +Backend->>Backend : Bind expand/click events +Backend->>Frontend : Pass event callbacks +``` + +**Diagram sources** + +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-16](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L16) +- [frontend/antdx/sources/sources.tsx:9-38](file://frontend/antdx/sources/sources.tsx#L9-L38) + +**Section sources** + +- [frontend/antdx/sources/sources.tsx:1-41](file://frontend/antdx/sources/sources.tsx#L1-L41) +- [frontend/antdx/sources/item/sources.item.tsx:1-14](file://frontend/antdx/sources/item/sources.item.tsx#L1-L14) + +## Detailed Component Analysis + +### Backend Component Implementation + +#### ModelScopeLayoutComponent Base Class + +All Sources components inherit from ModelScopeLayoutComponent, a layout component base class specifically designed for ModelScope Studio. + +**Core Functions:** + +- Provides the basic framework for Gradio components +- Handles component lifecycle management +- Supports slot system integration +- Manages internal component state + +#### AntdXSources Component Implementation + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++EVENTS : list ++SLOTS : list ++skip_api : bool ++FRONTEND_DIR : str ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdXSources { ++title : str ++items : list ++expand_icon_position : str ++default_expanded : bool ++expanded : bool ++inline : bool ++active_key : str ++popover_overlay_width : str|int|float ++Item : class ++EVENTS : list ++SLOTS : list +} +class AntdXSourcesItem { ++key : str ++description : str ++icon : str ++title : str ++url : str ++EVENTS : list ++SLOTS : list +} +ModelScopeLayoutComponent <|-- AntdXSources +ModelScopeLayoutComponent <|-- AntdXSourcesItem +AntdXSources --> AntdXSourcesItem : contains +``` + +**Diagram sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/components/antdx/sources/**init**.py:11-92](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L11-L92) +- [backend/modelscope_studio/components/antdx/sources/item/**init**.py:8-68](file://backend/modelscope_studio/components/antdx/sources/item/__init__.py#L8-L68) + +**Frontend Component Implementation** + +#### Sources React Component + +The Sources component is implemented using React, integrated with the Svelte ecosystem through the sveltify wrapper. + +**Core Features:** + +- Uses Ant Design X's native Sources component +- Supports a slot system, allowing custom title content +- Dynamically processes item lists +- Event handling mechanism + +#### SourcesItem React Child Component + +SourcesItem is the React implementation of a single data source item, processing item logic through ItemHandler. + +**Key Features:** + +- Accepts partial SourcesProps type +- Uses ItemHandler for item processing +- Supports additional item handler properties + +**Section sources** + +- [frontend/antdx/sources/sources.tsx:1-41](file://frontend/antdx/sources/sources.tsx#L1-L41) +- [frontend/antdx/sources/item/sources.item.tsx:1-14](file://frontend/antdx/sources/item/sources.item.tsx#L1-L14) + +### Event Handling Mechanism + +The Sources component supports two main events: + +```mermaid +flowchart TD +Start([Component Initialization]) --> BindEvents["Bind event listeners"] +BindEvents --> ExpandEvent["Expand event listener"] +BindEvents --> ClickEvent["Click event listener"] +ExpandEvent --> ExpandCallback["bind_expand_event callback"] +ClickEvent --> ClickCallback["bind_click_event callback"] +ExpandCallback --> UpdateInternal["Update internal state"] +ClickCallback --> UpdateInternal +UpdateInternal --> End([Event handling complete]) +``` + +**Diagram sources** + +- [backend/modelscope_studio/components/antdx/sources/**init**.py:18-25](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L18-L25) + +**Event Types:** + +- `expand`: Triggered when the user expands or collapses a data source +- `click`: Triggered when the user clicks a data source item + +**Section sources** + +- [backend/modelscope_studio/components/antdx/sources/**init**.py:18-25](file://backend/modelscope_studio/components/antdx/sources/__init__.py#L18-L25) + +### Slot System + +The Sources component supports a flexible slot system, allowing developers to customize different parts of the component: + +```mermaid +graph LR +subgraph "Slot System" +Items[items slot
Main item list] +Default[default slot
Default item content] +Title[title slot
Custom title] +end +subgraph "Render Logic" +Resolve[Resolve slot content] +Fallback[Fall back to default content] +Render[Render final result] +end +Items --> Resolve +Default --> Resolve +Title --> Resolve +Resolve --> Fallback +Fallback --> Render +``` + +**Diagram sources** + +- [frontend/antdx/sources/sources.tsx:12-36](file://frontend/antdx/sources/sources.tsx#L12-L36) + +**Supported Slots:** + +- `items`: Main data source item list +- `default`: Default item content +- `title`: Custom title content + +**Section sources** + +- [frontend/antdx/sources/sources.tsx:12-36](file://frontend/antdx/sources/sources.tsx#L12-L36) + +## Dependency Analysis + +The dependency relationship of the Sources component is relatively straightforward, primarily depending on Ant Design X and related utility libraries: + +```mermaid +graph TB +subgraph "External Dependencies" +AntDX[@ant-design/x
Ant Design X Core Components] +SveltePreprocess[@svelte-preprocess-react
Svelte-React Bridge] +Utils[@utils/*
Utility Function Library] +end +subgraph "Internal Dependencies" +Component[ModelScopeLayoutComponent
Base Component Class] +Context[createItemsContext
Context Management] +ResolveDir[resolve_frontend_dir
Path Resolution] +end +subgraph "Sources Components" +Sources[AntdXSources] +SourcesItem[AntdXSourcesItem] +end +Sources --> AntDX +Sources --> SveltePreprocess +Sources --> Utils +Sources --> Component +Sources --> Context +Sources --> ResolveDir +SourcesItem --> AntDX +SourcesItem --> SveltePreprocess +SourcesItem --> Context +``` + +**Diagram sources** + +- [frontend/antdx/sources/sources.tsx:1-5](file://frontend/antdx/sources/sources.tsx#L1-L5) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py:4-16](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py#L4-L16) + +**Main Dependency Notes:** + +- `@ant-design/x`: Provides the core Sources component implementation +- `@svelte-preprocess-react`: Implements the bridge between Svelte and React +- `@utils/*`: Provides common utility functions such as renderItems, createItemsContext, etc. + +**Section sources** + +- [frontend/antdx/sources/sources.tsx:1-5](file://frontend/antdx/sources/sources.tsx#L1-L5) +- [backend/modelscope_studio/components/antdx/components.py:30-31](file://backend/modelscope_studio/components/antdx/components.py#L30-L31) + +## Performance Considerations + +The Sources component was designed with performance optimization in mind: + +### Render Optimization + +1. **Memoization**: Uses React's useMemo to cache computation results and avoid unnecessary re-renders +2. **Conditional rendering**: Only renders component content when needed +3. **Lazy loading**: Delays content loading through an event-driven approach + +### Memory Management + +1. **Component unmounting**: Properly handles the mounting and unmounting process +2. **Event cleanup**: Cleans up event listeners when the component is destroyed +3. **State management**: Uses a minimal state update strategy + +### Data Processing Optimization + +1. **Batch updates**: Supports batch data source updates +2. **Incremental rendering**: Only updates the parts that have changed +3. **Virtualization support**: Provides virtualized rendering capability for large data source sets + +## Troubleshooting Guide + +### Common Issues and Solutions + +**Issue 1: Component not displaying** + +- Check whether the Ant Design X dependency is correctly installed +- Confirm that the frontend directory path resolution is correct +- Verify the component's visibility property setting + +**Issue 2: Events not responding** + +- Confirm that event listeners are correctly bound +- Check parameter passing in event callback functions +- Verify the component's event handling logic + +**Issue 3: Slot content not displaying** + +- Check whether the slot name is correct +- Confirm the method of passing slot content +- Verify the rendering priority of slots + +**Issue 4: Performance issues** + +- Check the number and complexity of data sources +- Optimize the rendering logic of data sources +- Consider using virtualized rendering + +**Section sources** + +- [docs/components/antdx/sources/demos/basic.py:1-46](file://docs/components/antdx/sources/demos/basic.py#L1-L46) + +## Conclusion + +The Sources component is a well-designed, fully functional component that successfully combines the powerful capabilities of Ant Design X with the ModelScope Studio ecosystem. The component has the following advantages: + +1. **Clear architecture**: Layered design with clear responsibilities +2. **Strong extensibility**: Supports rich configuration options and slot system +3. **Excellent performance**: Ensures good performance through multiple optimization techniques +4. **Easy to use**: Provides an intuitive API and complete documentation support + +This component is particularly suitable for displaying references, managing link sources, and similar scenarios in AI chat applications, providing developers with powerful data source display capabilities. Through reasonable event handling and the slot system, developers can easily customize the behavior and appearance of the component to meet various complex business requirements. diff --git a/.wiki/en/Ant Design X Components/Data Components/Think Component.md b/.wiki/en/Ant Design X Components/Data Components/Think Component.md new file mode 100644 index 00000000..01c4c113 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Data Components/Think Component.md @@ -0,0 +1,457 @@ +# Think Component + + +**Files Referenced in This Document** +- [think/__init__.py](file://backend/modelscope_studio/components/antdx/think/__init__.py) +- [components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [think.tsx](file://frontend/antdx/think/think.tsx) +- [Index.svelte](file://frontend/antdx/think/Index.svelte) +- [thought-chain.tsx](file://frontend/antdx/thought-chain/thought-chain.tsx) +- [context.ts](file://frontend/antdx/thought-chain/context.ts) +- [__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +The Think component is a core visualization component in ModelScope Studio for visualizing and tracking the thinking process of AI agents. Built on top of Ant Design X's Think component, it is specifically designed to display the reasoning process, decision chain, and intermediate thinking results of agents in conversational systems. + +The main design philosophy of this component is to provide transparent visualization of AI decision-making processes, allowing users to understand how AI agents think, analyze, and make decisions. Through detailed recording and display of the thinking process, users can better trust and optimize the behavior of AI systems. + +## Project Structure + +The Think component is located in the antdx component library within the project architecture, adopting a frontend/backend separated design pattern: + +```mermaid +graph TB +subgraph "Backend Layer" +Backend[ModelScope Studio Backend] +ThinkPy[Think Python Component] +ComponentsPy[Component Registration] +end +subgraph "Frontend Layer" +Frontend[ModelScope Studio Frontend] +ThinkTSX[Think TypeScript Component] +IndexSvelte[Think Svelte Wrapper] +ThoughtChain[ThoughtChain Component] +end +subgraph "External Dependencies" +AntDX[Ant Design X] +Gradio[Gradio Framework] +end +Backend --> ThinkPy +ThinkPy --> ComponentsPy +Frontend --> ThinkTSX +ThinkTSX --> IndexSvelte +IndexSvelte --> AntDX +ComponentsPy --> Frontend +Gradio --> Backend +``` + +**Diagram sources** + +- [think/**init**.py:1-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L1-L79) +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +**Section sources** + +- [think/**init**.py:1-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L1-L79) +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Core Components + +### Think Component Class Definition + +The Think component inherits from `ModelScopeLayoutComponent`, providing complete property configuration and event handling: + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++visible : bool ++elem_id : str ++elem_classes : list[str] ++elem_style : dict ++render : bool ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdXThink { ++additional_props : dict ++icon : str ++styles : dict ++class_names : dict ++loading : str|bool ++title : str ++root_class_name : str ++default_expanded : bool ++expanded : bool ++blink : bool ++EVENTS : list ++SLOTS : list ++FRONTEND_DIR : str ++skip_api : bool +} +class Think { ++slots : dict ++props : ThinkProps ++loading : ReactNode ++icon : ReactNode ++title : ReactNode +} +ModelScopeLayoutComponent <|-- AntdXThink +AntdXThink --> Think : "Frontend rendering" +``` + +**Diagram sources** + +- [think/**init**.py:8-79](file://backend/modelscope_studio/components/antdx/think/__init__.py#L8-L79) +- [think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +### Key Property Configuration + +The Think component supports rich configuration options, including: + +- **Basic properties**: Icon, title, style class names +- **State properties**: Loading state, expanded state, blink effect +- **Event properties**: Expand event binding +- **Slot system**: Supports three slots: loading, icon, title + +**Section sources** + +- [think/**init**.py:21-60](file://backend/modelscope_studio/components/antdx/think/__init__.py#L21-L60) +- [think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +## Architecture Overview + +The Think component adopts a layered architecture design, achieving clear separation between frontend and backend: + +```mermaid +sequenceDiagram +participant User as User Interface +participant Backend as Backend Think Component +participant Frontend as Frontend Wrapper +participant AntDX as Ant Design X +participant React as React Component +User->>Backend : Create Think component instance +Backend->>Backend : Configure component properties +Backend->>Frontend : Render frontend wrapper +Frontend->>AntDX : Load Ant Design X Think +AntDX->>React : Render React component +React->>React : Process slot content +React->>User : Display thinking process +Note over Backend,React : Complete component lifecycle management +``` + +**Diagram sources** + +- [Index.svelte:10-67](file://frontend/antdx/think/Index.svelte#L10-L67) +- [think.tsx:6-21](file://frontend/antdx/think/think.tsx#L6-L21) + +### Component Lifecycle + +```mermaid +flowchart TD +Start([Component Initialization]) --> Config[Configure properties] +Config --> Render[Render frontend wrapper] +Render --> LoadAntDX[Load Ant Design X] +LoadAntDX --> ProcessSlots[Process slot content] +ProcessSlots --> Display[Display thinking process] +Display --> EventBind[Bind event listeners] +EventBind --> Ready[Component ready] +Ready --> UserInteraction[User interaction] +UserInteraction --> UpdateState[Update state] +UpdateState --> ReRender[Re-render] +ReRender --> Ready +Ready --> Cleanup[Component destruction] +Cleanup --> End([End]) +``` + +**Diagram sources** + +- [think/**init**.py:12-16](file://backend/modelscope_studio/components/antdx/think/__init__.py#L12-L16) +- [Index.svelte:55-68](file://frontend/antdx/think/Index.svelte#L55-L68) + +## Detailed Component Analysis + +### Backend Implementation Analysis + +The backend Think component implements the complete Gradio component interface: + +#### Event System + +The component supports the expand event for handling changes in expanded state: + +```mermaid +stateDiagram-v2 +[*] --> Collapsed : Default collapsed state +Collapsed --> Expanded : Trigger expand event +Expanded --> Collapsed : User clicks to collapse +Collapsed --> Blinking : Set blink property +Blinking --> Collapsed : Blink effect ends +note right of Expanded +In the expanded state, the thinking process +can be viewed in detail +end note +note right of Blinking +The blink effect is used to attract attention, +typically indicating a new thinking process +end note +``` + +**Diagram sources** + +- [think/**init**.py:12-16](file://backend/modelscope_studio/components/antdx/think/__init__.py#L12-L16) + +#### Slot System + +The component supports three slots, allowing flexible content customization: + +| Slot Name | Type | Purpose | Default Value | +| --------- | --------- | ------------------------ | ------------- | +| loading | ReactNode | Custom loading indicator | props.loading | +| icon | ReactNode | Custom icon | props.icon | +| title | ReactNode | Custom title content | props.title | + +**Section sources** + +- [think/**init**.py:18-19](file://backend/modelscope_studio/components/antdx/think/__init__.py#L18-L19) +- [think.tsx:12-16](file://frontend/antdx/think/think.tsx#L12-L16) + +### Frontend Implementation Analysis + +The frontend uses a hybrid architecture of Svelte + React: + +#### Svelte Wrapper + +Index.svelte provides complete component wrapping functionality: + +```mermaid +classDiagram +class IndexSvelte { ++props : ComponentProps ++slots : Slots ++proceedProps : ProcessedProps ++AwaitedThink : ComponentPromise ++getProps() ++getSlots() ++processProps() +} +class ThinkWrapper { ++style : CSSProperties ++className : string ++id : string ++slots : dict ++children : ReactNode +} +IndexSvelte --> ThinkWrapper : "Render" +ThinkWrapper --> AntDThink : "Contains" +``` + +**Diagram sources** + +- [Index.svelte:12-67](file://frontend/antdx/think/Index.svelte#L12-L67) + +#### React Component Bridge + +think.tsx implements the bridge from Svelte to React: + +- Uses `sveltify` to convert React components to Svelte components +- Handles slot content through `ReactSlot` +- Directly calls Ant Design X's native Think component + +**Section sources** + +- [Index.svelte:1-69](file://frontend/antdx/think/Index.svelte#L1-L69) +- [think.tsx:1-24](file://frontend/antdx/think/think.tsx#L1-L24) + +### ThoughtChain Integration + +The Think component and the ThoughtChain component form a complete thinking process visualization system: + +```mermaid +graph LR +subgraph "Thinking Process" +Think[Think Component] +ThoughtChain[ThoughtChain Component] +end +subgraph "Data Flow" +Items[Thinking Item List] +Status[State Management] +Timeline[Timeline] +end +subgraph "UI Display" +ChainView[Chain View] +DetailView[Detail View] +TimelineView[Timeline View] +end +Think --> Items +ThoughtChain --> Items +Items --> Status +Status --> Timeline +Timeline --> ChainView +Timeline --> DetailView +Timeline --> TimelineView +``` + +**Diagram sources** + +- [thought-chain.tsx:11-40](file://frontend/antdx/thought-chain/thought-chain.tsx#L11-L40) +- [context.ts:1-7](file://frontend/antdx/thought-chain/context.ts#L1-L7) + +**Section sources** + +- [thought-chain.tsx:1-43](file://frontend/antdx/thought-chain/thought-chain.tsx#L1-L43) +- [context.ts:1-7](file://frontend/antdx/thought-chain/context.ts#L1-L7) + +## Dependency Analysis + +### Component Dependency Diagram + +```mermaid +graph TB +subgraph "Core Dependencies" +Gradio[Gradio Framework] +AntD[Ant Design X] +Svelte[Svelte Framework] +end +subgraph "Internal Dependencies" +Utils[Development Utilities] +Layout[Layout Component] +Slot[Slot System] +end +subgraph "Think Component" +ThinkPy[Python Component] +ThinkTSX[TypeScript Component] +ThinkSvelte[Svelte Wrapper] +end +Gradio --> ThinkPy +AntD --> ThinkTSX +Svelte --> ThinkSvelte +Utils --> ThinkPy +Layout --> ThinkPy +Slot --> ThinkTSX +ThinkPy --> ThinkTSX +ThinkTSX --> ThinkSvelte +``` + +**Diagram sources** + +- [components.py:34-34](file://backend/modelscope_studio/components/antdx/components.py#L34-L34) +- [**init**.py:34-34](file://backend/modelscope_studio/components/antdx/__init__.py#L34-L34) + +### Version Compatibility + +The component ensures compatibility with the following versions: + +- **Gradio**: >= 4.0.0 +- **Ant Design X**: >= 0.1.0 +- **Svelte**: >= 3.54.0 +- **React**: >= 18.0.0 + +**Section sources** + +- [components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Performance Considerations + +### Render Optimization + +1. **Lazy loading mechanism**: The frontend uses dynamic imports to reduce initial load time +2. **Conditional rendering**: Only renders the component when visible, avoiding unnecessary computation +3. **Slot optimization**: Efficiently handles slot content through ReactSlot + +### Memory Management + +- Automatically cleans up event listeners when the component is destroyed +- Proper props handling to avoid memory leaks +- Uses useMemo to optimize rendering of complex data structures + +## Troubleshooting Guide + +### Common Issues and Solutions + +#### Component Not Displaying + +**Symptom**: The Think component is created successfully but does not appear in the interface + +**Possible Causes**: + +1. The `visible` property is set to False +2. The `render` property is set to False +3. Parent container style issues + +**Solutions**: + +- Check the component's `visible` and `render` properties +- Verify the parent container's CSS styles +- Confirm the component is imported correctly + +#### Slot Content Not Working + +**Symptom**: Custom loading, icon, title slot content is not displayed + +**Possible Causes**: + +1. Incorrect slot name +2. Slot content type mismatch +3. Incorrect slot passing method + +**Solutions**: + +- Confirm the slot names are 'loading', 'icon', or 'title' +- Verify that slot content is a valid ReactNode +- Check the slot passing syntax + +#### Event Handling Abnormal + +**Symptom**: The expand event cannot be triggered normally + +**Possible Causes**: + +1. Event listener not correctly bound +2. Event callback function error +3. Component state issue + +**Solutions**: + +- Check the EVENTS array configuration +- Verify the event callback function logic +- Confirm component state synchronization + +**Section sources** + +- [think/**init**.py:12-16](file://backend/modelscope_studio/components/antdx/think/__init__.py#L12-L16) + +## Conclusion + +As a core visualization component of ModelScope Studio, the Think component successfully achieves transparent display of AI thinking processes. Through carefully designed architecture and rich configuration options, this component provides developers and users with powerful thinking process tracking capabilities. + +### Main Advantages + +1. **Complete visualization**: Provides various thinking process display methods from simple to complex +2. **Flexible configuration**: Supports rich property configuration and slot customization +3. **Good performance**: Uses modern frontend technology stack to ensure a smooth user experience +4. **Easy to integrate**: Seamlessly integrates with the Gradio ecosystem + +### Application Scenarios + +- **AI assistants**: Display the reasoning process and decision chain of agents +- **Data analysis**: Visualize data exploration and analysis thinking +- **Code generation**: Display the thinking process and logic of code generation +- **Multimodal applications**: Support thinking processes for various input types such as text and images + +This component lays a solid foundation for building trustworthy and explainable AI applications and is an indispensable important component of modern AI products. diff --git a/.wiki/en/Ant Design X Components/Expression Components/Attachments Component.md b/.wiki/en/Ant Design X Components/Expression Components/Attachments Component.md new file mode 100644 index 00000000..3a7966c7 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Expression Components/Attachments Component.md @@ -0,0 +1,731 @@ +# Attachments Component + + +**Files Referenced in This Document** +- [Index.svelte](file://frontend/antdx/attachments/Index.svelte) +- [attachments.tsx](file://frontend/antdx/attachments/attachments.tsx) +- [__init__.py](file://backend/modelscope_studio/components/antdx/attachments/__init__.py) +- [README-zh_CN.md](file://docs/components/antdx/attachments/README-zh_CN.md) +- [basic.py](file://docs/components/antdx/attachments/demos/basic.py) +- [combination.py](file://docs/components/antdx/attachments/demos/combination.py) +- [file_card.py](file://docs/components/antdx/attachments/demos/file_card.py) +- [multimodal-input.tsx](file://frontend/pro/multimodal-input/multimodal-input.tsx) +- [upload.ts](file://frontend/utils/upload.ts) +- [file-card.tsx](file://frontend/antdx/file-card/file-card.tsx) +- [base.tsx](file://frontend/antdx/file-card/base.tsx) +- [app.py](file://docs/components/antdx/attachments/app.py) +- [package.json](file://frontend/antdx/attachments/package.json) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The Attachments component is a powerful file management and upload solution provided by ModelScope Studio. Built on top of Ant Design X's Attachments component, it provides complete file upload, preview, management, and deletion capabilities. + +### Key Features + +- **Multi-format Support**: Supports uploading and previewing of multiple file types including images, documents, audio, and video +- **Drag and Drop Upload**: Provides an intuitive drag-and-drop file upload experience +- **Batch Management**: Supports simultaneous upload and management of multiple files +- **Real-time Preview**: Built-in file preview functionality with thumbnail and full-content viewing +- **Flexible Configuration**: Rich configuration options and customization capabilities +- **Responsive Design**: Adapts to various screen sizes and devices + +## Project Structure + +The Attachments component adopts a frontend-backend separation architecture, primarily consisting of the following parts: + +```mermaid +graph TB +subgraph "Frontend Layer" +A[Index.svelte
Component Entry] +B[attachments.tsx
Core Implementation] +C[file-card.tsx
File Card Component] +D[base.tsx
Base File Card] +E[multimodal-input.tsx
Multimodal Input Integration] +end +subgraph "Backend Layer" +F[__init__.py
Python Component Wrapper] +end +subgraph "Utility Layer" +G[upload.ts
File URL Handling] +H[package.json
Package Config] +end +A --> B +B --> C +C --> D +B --> G +F --> A +E --> B +``` + +**Diagram Sources** + +- [Index.svelte:1-98](file://frontend/antdx/attachments/Index.svelte#L1-L98) +- [attachments.tsx:1-413](file://frontend/antdx/attachments/attachments.tsx#L1-L413) +- [**init**.py:21-64](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L21-L64) + +**Section Sources** + +- [Index.svelte:1-98](file://frontend/antdx/attachments/Index.svelte#L1-L98) +- [attachments.tsx:1-413](file://frontend/antdx/attachments/attachments.tsx#L1-L413) +- [**init**.py:21-64](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L21-L64) + +## Core Components + +### Component Architecture + +The Attachments component uses a layered architecture design ensuring good maintainability and extensibility: + +```mermaid +classDiagram +class Attachments { ++FileData[] items ++upload(files) Promise~FileData[]~ ++onValueChange(value) void ++onChange(value) void ++disabled boolean ++maxCount number ++imageProps ImageProps ++placeholder Function|Object ++showUploadList Object|boolean ++beforeUpload Function ++customRequest Function ++previewFile Function ++isImageUrl Function ++itemRender Function ++iconRender Function ++data Object|Function ++getDropContainer Function +} +class FileCard { ++BaseFileCardProps props ++imageProps ImageProps ++description ReactNode ++icon ReactNode ++mask ReactNode ++spinProps SpinProps ++children ReactNode +} +class BaseFileCard { ++string|FileData src ++string rootUrl ++string apiPrefix ++resolveFileSrc() string +} +class UploadUtils { ++getFetchableUrl() string ++getFileUrl() string|undefined ++isUrl() boolean +} +Attachments --> FileCard : "renders" +FileCard --> BaseFileCard : "inherits" +Attachments --> UploadUtils : "uses" +``` + +**Diagram Sources** + +- [attachments.tsx:36-83](file://frontend/antdx/attachments/attachments.tsx#L36-L83) +- [file-card.tsx:17-34](file://frontend/antdx/file-card/file-card.tsx#L17-L34) +- [base.tsx:9-13](file://frontend/antdx/file-card/base.tsx#L9-L13) +- [upload.ts:12-44](file://frontend/utils/upload.ts#L12-L44) + +### Data Flow Processing + +The component internally implements a complex data flow processing mechanism: + +```mermaid +sequenceDiagram +participant U as User +participant A as Attachments Component +participant P as Preview System +participant S as Server +participant V as Validator +U->>A : Select/drag files +A->>V : Call beforeUpload validation +V-->>A : Validation result +A->>A : Update temporary file list +A->>S : Call upload function +S-->>A : Return FileData array +A->>A : Merge file list +A->>P : Render preview +P-->>U : Display file preview +U->>A : Delete file +A->>S : Send delete request +S-->>A : Confirm deletion +A->>A : Update state +``` + +**Diagram Sources** + +- [attachments.tsx:275-354](file://frontend/antdx/attachments/attachments.tsx#L275-L354) + +**Section Sources** + +- [attachments.tsx:1-413](file://frontend/antdx/attachments/attachments.tsx#L1-L413) +- [file-card.tsx:1-127](file://frontend/antdx/file-card/file-card.tsx#L1-L127) +- [base.tsx:1-44](file://frontend/antdx/file-card/base.tsx#L1-L44) + +## Architecture Overview + +### Overall Architecture Design + +The Attachments component uses a modern frontend architecture pattern combining the advantages of React and Svelte: + +```mermaid +graph TD +subgraph "User Interface Layer" +UI[User Interface] +SL[Svelte Component] +RC[React Component] +end +subgraph "Business Logic Layer" +AM[Attachment Manager] +VM[View Model] +CM[Configuration Manager] +end +subgraph "Data Access Layer" +FS[File System] +CS[Cloud Storage] +LS[Local Storage] +end +subgraph "Utility Service Layer" +PU[Preview Service] +US[Upload Service] +VS[Validation Service] +end +UI --> SL +SL --> RC +RC --> AM +AM --> VM +AM --> CM +AM --> FS +AM --> CS +AM --> LS +AM --> PU +AM --> US +AM --> VS +``` + +**Diagram Sources** + +- [Index.svelte:1-98](file://frontend/antdx/attachments/Index.svelte#L1-L98) +- [attachments.tsx:1-413](file://frontend/antdx/attachments/attachments.tsx#L1-L413) + +### Component Lifecycle + +```mermaid +stateDiagram-v2 +[*] --> Initializing +Initializing --> LoadingConfig +LoadingConfig --> RenderingUI +RenderingUI --> WaitingForInteraction +WaitingForInteraction --> FileUpload +FileUpload --> ValidatingFile +ValidatingFile --> Uploading +Uploading --> UploadComplete +UploadComplete --> RenderingPreview +RenderingPreview --> WaitingForInteraction +WaitingForInteraction --> FileDeletion +FileDeletion --> DeletionConfirm +DeletionConfirm --> UpdatingState +UpdatingState --> WaitingForInteraction +WaitingForInteraction --> ErrorHandling +ErrorHandling --> WaitingForInteraction +WaitingForInteraction --> [*] +``` + +**Diagram Sources** + +- [attachments.tsx:132-354](file://frontend/antdx/attachments/attachments.tsx#L132-L354) + +## Detailed Component Analysis + +### Core Functionality Implementation + +#### File Upload Mechanism + +The component implements a complete file upload flow supporting multiple upload strategies: + +```mermaid +flowchart TD +Start([Start Upload]) --> Validate[Validate File] +Validate --> Valid{Validation Passed?} +Valid --> |No| Error[Return Error] +Valid --> |Yes| Prepare[Prepare Upload] +Prepare --> Upload[Execute Upload] +Upload --> Progress[Update Progress] +Progress --> Complete{Upload Complete?} +Complete --> |No| Progress +Complete --> |Yes| Process[Process Response] +Process --> Success[Upload Success] +Success --> End([End]) +Error --> End +``` + +**Diagram Sources** + +- [attachments.tsx:292-354](file://frontend/antdx/attachments/attachments.tsx#L292-L354) + +#### File Preview System + +The component integrates powerful file preview functionality supporting visualization of multiple file types: + +| File Type | Preview Support | Special Features | +| --------- | ----------------------- | ---------------------------- | +| Image | ✅ Full Preview | Zoom, rotate, download | +| Document | ✅ Thumbnail Preview | Online view, download | +| PDF | ✅ Page-by-page Preview | Navigation, search | +| Audio | ✅ Player | Playback control, volume | +| Video | ✅ Player | Playback control, fullscreen | +| Archive | ✅ Thumbnail | Extract preview | + +#### Batch Management Features + +The component provides efficient batch file management capabilities: + +```mermaid +graph LR +subgraph "Batch Operations" +BA[Batch Select] +BM[Batch Delete] +BC[Batch Download] +BR[Batch Rename] +end +subgraph "State Management" +FS[File State] +SS[Selection State] +PS[Processing State] +end +BA --> SS +BM --> FS +BC --> FS +BR --> FS +SS --> PS +FS --> PS +``` + +**Diagram Sources** + +- [attachments.tsx:304-342](file://frontend/antdx/attachments/attachments.tsx#L304-L342) + +**Section Sources** + +- [attachments.tsx:275-409](file://frontend/antdx/attachments/attachments.tsx#L275-L409) + +### Configuration Options + +#### Basic Configuration + +| Option | Type | Default | Description | +| ---------------- | ----------------- | -------- | --------------------------------------- | +| `disabled` | boolean | false | Whether to disable upload functionality | +| `maxCount` | number | Infinity | Maximum number of files | +| `multiple` | boolean | true | Whether to support multi-file upload | +| `accept` | string | \* | Accepted file types | +| `showUploadList` | boolean \| object | true | Whether to show the upload list | + +#### Advanced Configuration + +| Option | Type | Default | Description | +| --------------- | -------- | ------- | --------------------------------- | +| `beforeUpload` | Function | - | Validation function before upload | +| `customRequest` | Function | - | Custom upload request | +| `previewFile` | Function | - | Custom file preview | +| `isImageUrl` | Function | - | Determine if it is an image URL | +| `itemRender` | Function | - | Custom file item rendering | +| `iconRender` | Function | - | Custom icon rendering | + +#### Preview Configuration + +| Option | Type | Default | Description | +| ---------------------------------- | --------- | ------- | ------------------------ | +| `imageProps.preview.mask` | ReactNode | - | Preview mask layer | +| `imageProps.preview.closeIcon` | ReactNode | - | Close button icon | +| `imageProps.preview.toolbarRender` | Function | - | Custom toolbar rendering | +| `imageProps.preview.imageRender` | Function | - | Custom image rendering | + +**Section Sources** + +- [attachments.tsx:36-83](file://frontend/antdx/attachments/attachments.tsx#L36-L83) + +### Event Callback Mechanism + +The component provides a rich event callback interface: + +```mermaid +sequenceDiagram +participant C as Caller +participant A as Attachments Component +participant H as Callback Handler +C->>A : Bind event listeners +A->>H : Register callback functions +Note over A,H : User interaction triggers events +A->>H : Trigger onChange event +H-->>A : Return processing result +A->>H : Trigger onRemove event +H-->>A : Return processing result +A->>H : Trigger onValueChange event +H-->>A : Return processing result +``` + +**Diagram Sources** + +- [**init**.py:27-43](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L27-L43) + +#### Event Types + +| Event Name | Trigger Timing | Parameters | Description | +| ---------- | ------------------ | ---------- | ---------------------------------------------- | +| `change` | File state changes | FileData[] | Triggered when the file list changes | +| `remove` | File deleted | FileData | Triggered when a file is deleted | +| `preview` | File preview | FileData | Triggered when a file starts previewing | +| `download` | File download | FileData | Triggered when a file starts downloading | +| `drop` | File dragged | FileData[] | Triggered when files are dragged into the area | + +**Section Sources** + +- [**init**.py:27-43](file://backend/modelscope_studio/components/antdx/attachments/__init__.py#L27-L43) + +### Error Handling Mechanism + +The component implements a comprehensive error handling system: + +```mermaid +flowchart TD +Start([Start Processing]) --> Try[Execute Operation] +Try --> Success{Operation Successful?} +Success --> |Yes| Complete[Complete Processing] +Success --> |No| Catch[Catch Error] +Catch --> Type{Error Type?} +Type --> |Network Error| Network[Handle Network Error] +Type --> |Permission Error| Auth[Handle Permission Error] +Type --> |Format Error| Format[Handle Format Error] +Type --> |Size Error| Size[Handle Size Error] +Type --> |Other Error| Other[Handle Other Error] +Network --> Retry[Retry Mechanism] +Auth --> Login[Re-login] +Format --> Fix[Fix Format] +Size --> Reduce[Reduce File Size] +Other --> Report[Report Issue] +Retry --> Try +Login --> Try +Fix --> Try +Reduce --> Try +Report --> End([End]) +Complete --> End +``` + +**Diagram Sources** + +- [attachments.tsx:350-354](file://frontend/antdx/attachments/attachments.tsx#L350-L354) + +**Section Sources** + +- [attachments.tsx:350-354](file://frontend/antdx/attachments/attachments.tsx#L350-L354) + +## Dependency Analysis + +### External Dependencies + +The component depends on several key external libraries: + +```mermaid +graph TB +subgraph "Core Dependencies" +AX[@ant-design/x
Ant Design X Component Library] +ANTD[antd
Ant Design Component Library] +GRADIO[@gradio/client
Gradio Client] +REACT[react
React Framework] +end +subgraph "Utility Libraries" +Lodash[lodash-es
Utility Functions] +Classnames[classnames
Class Name Handling] +SveltePreprocess[svelte-preprocess-react
Svelte Preprocessing] +end +subgraph "Component Dependencies" +FileCard[FileCard Component] +Utils[Utility Functions] +Hooks[React Hooks] +end +Attachments --> AX +Attachments --> ANTD +Attachments --> GRADIO +Attachments --> REACT +Attachments --> Lodash +Attachments --> Classnames +Attachments --> SveltePreprocess +Attachments --> FileCard +Attachments --> Utils +Attachments --> Hooks +``` + +**Diagram Sources** + +- [attachments.tsx:1-17](file://frontend/antdx/attachments/attachments.tsx#L1-L17) +- [package.json:1-15](file://frontend/antdx/attachments/package.json#L1-L15) + +### Internal Module Dependencies + +```mermaid +graph TD +subgraph "Frontend Modules" +A[Index.svelte] +B[attachments.tsx] +C[file-card.tsx] +D[base.tsx] +E[upload.ts] +F[multimodal-input.tsx] +end +subgraph "Backend Modules" +G[__init__.py] +end +A --> B +B --> C +C --> D +B --> E +F --> B +G --> A +``` + +**Diagram Sources** + +- [Index.svelte:1-98](file://frontend/antdx/attachments/Index.svelte#L1-L98) +- [attachments.tsx:1-413](file://frontend/antdx/attachments/attachments.tsx#L1-L413) + +**Section Sources** + +- [package.json:1-15](file://frontend/antdx/attachments/package.json#L1-L15) +- [Index.svelte:1-98](file://frontend/antdx/attachments/Index.svelte#L1-L98) + +## Performance Considerations + +### Upload Performance Optimization + +The component was designed with performance optimization in mind: + +- **Concurrent Upload Control**: Limit the number of simultaneously uploading files via `maxCount` +- **Progress Display**: Display upload progress in real time to improve user experience +- **Memory Management**: Clean up temporary file data promptly to avoid memory leaks +- **Caching Strategy**: Cache already-uploaded files to reduce redundant uploads + +### Preview Performance Optimization + +```mermaid +graph LR +subgraph "Preview Optimization Strategies" +A[Lazy Loading Preview] +B[Thumbnail Generation] +C[Virtual Scrolling] +D[Preloading Mechanism] +end +subgraph "Performance Metrics" +E[Initial Load Time] +F[Memory Usage] +G[CPU Utilization] +H[Network Bandwidth] +end +A --> E +B --> F +C --> G +D --> H +``` + +### Memory Management + +The component implements intelligent memory management: + +- **File Object Reuse**: Reuse existing file objects to avoid redundant creation +- **Garbage Collection**: Release file data that is no longer in use in a timely manner +- **State Synchronization**: Maintain consistency between local state and server state + +## Troubleshooting Guide + +### Common Issues and Solutions + +#### Upload Failure + +**Problem Description**: Error occurs during file upload + +**Possible Causes**: + +- Unstable network connection +- Unsupported file format +- File size exceeds limit +- Insufficient permissions + +**Solutions**: + +1. Check network connection status +2. Verify file format is in the `accept` list +3. Confirm file size does not exceed `maxSize` limit +4. Check user permission settings + +#### Preview Failure + +**Problem Description**: File cannot be previewed normally + +**Possible Causes**: + +- Browser compatibility issues +- File corruption +- URL parsing error + +**Solutions**: + +1. Try opening in a different browser +2. Re-upload the file +3. Check file integrity +4. Verify URL format is correct + +#### Performance Issues + +**Problem Description**: Component runs slowly or stutters + +**Possible Causes**: + +- Too many files +- Files are too large +- Insufficient memory + +**Solutions**: + +1. Reduce the number of simultaneously uploading files +2. Optimize file sizes +3. Increase system memory +4. Use `maxCount` to limit the number of files + +**Section Sources** + +- [attachments.tsx:350-354](file://frontend/antdx/attachments/attachments.tsx#L350-L354) + +### Debugging Tips + +#### Enable Debug Mode + +```javascript +// Enable detailed logging in development environment +const attachments = new Attachments({ + debug: true, + // other configs... +}); +``` + +#### Monitor Upload Progress + +```javascript +attachments.on('upload-progress', (progress) => { + console.log(`Upload progress: ${progress}%`); +}); +``` + +## Conclusion + +The Attachments component is a fully functional, high-performance file management solution. It not only provides basic file upload and preview capabilities, but also features advanced batch management, custom configuration, and error handling. + +### Key Advantages + +1. **Comprehensive Features**: Covers all core needs for file upload, preview, and management +2. **Easy to Use**: Clean API design for quick integration +3. **Highly Customizable**: Rich configuration options to meet various use cases +4. **Excellent Performance**: Optimized algorithms and architecture ensure a smooth user experience +5. **Stable and Reliable**: Comprehensive error handling and exception recovery mechanisms + +### Applicable Scenarios + +- Online document management systems +- File transfer in instant messaging applications +- Media management on content creation platforms +- File sharing on enterprise collaboration platforms +- Assignment submission systems on educational platforms + +## Appendix + +### API Reference + +#### Props + +| Property | Type | Required | Default | Description | +| ---------------- | ----------------- | -------- | -------- | -------------------------------------------------------- | +| `items` | FileData[] | Yes | [] | Current file list | +| `upload` | Function | Yes | - | Upload function, accepts RcFile[] and returns FileData[] | +| `onValueChange` | Function | No | - | Value change callback | +| `onChange` | Function | No | - | String path change callback | +| `disabled` | boolean | No | false | Whether to disable | +| `maxCount` | number | No | Infinity | Maximum number of files | +| `accept` | string | No | \* | Accepted file types | +| `multiple` | boolean | No | true | Whether multi-select is supported | +| `showUploadList` | boolean \| object | No | true | Whether to show the upload list | +| `imageProps` | ImageProps | No | - | Image preview configuration | + +#### Events + +| Event Name | Parameters | Description | +| ---------- | ---------- | --------------------- | +| `change` | FileData[] | File list changed | +| `remove` | FileData | File deleted | +| `preview` | FileData | File preview started | +| `download` | FileData | File download started | +| `drop` | FileData[] | File dragged | + +#### Slots + +| Slot Name | Parameters | Description | +| ---------------------------------- | ------------------------ | -------------------------- | +| `placeholder` | type: 'drop' \| 'inline' | Placeholder content | +| `placeholder.title` | type | Title content | +| `placeholder.description` | type | Description content | +| `placeholder.icon` | type | Icon content | +| `iconRender` | file, fileList | Custom icon rendering | +| `itemRender` | file, fileList | Custom file item rendering | +| `showUploadList.previewIcon` | file, fileList | Preview icon | +| `showUploadList.removeIcon` | file, fileList | Delete icon | +| `showUploadList.downloadIcon` | file, fileList | Download icon | +| `showUploadList.extra` | file, fileList | Extra actions | +| `imageProps.placeholder` | file, fileList | Image placeholder | +| `imageProps.preview.mask` | file, fileList | Preview mask | +| `imageProps.preview.closeIcon` | file, fileList | Close icon | +| `imageProps.preview.toolbarRender` | file, fileList | Toolbar rendering | +| `imageProps.preview.imageRender` | file, fileList | Image rendering | + +### Best Practices + +#### Performance Optimization Recommendations + +1. **Set `maxCount` Appropriately**: Set a suitable maximum file count based on the application scenario +2. **Use Lazy Loading**: For large numbers of files, consider pagination or virtual scrolling +3. **Optimize File Sizes**: Compress images and video files before upload +4. **Caching Strategy**: Establish a caching mechanism for frequently used files + +#### Security Considerations + +1. **File Type Validation**: Also perform file type checking on the server side +2. **Size Limits**: Set reasonable file size upper limits +3. **Virus Scanning**: Perform security scanning on uploaded files +4. **Permission Control**: Ensure only authorized users can access files + +#### User Experience Optimization + +1. **Progress Feedback**: Provide clear upload progress indicators +2. **Error Messages**: Friendly error messages and solutions +3. **Batch Operations**: Support batch selection and operations +4. **Responsive Design**: Adapt to various devices and screen sizes + +**Section Sources** + +- [README-zh_CN.md:1-10](file://docs/components/antdx/attachments/README-zh_CN.md#L1-L10) +- [basic.py:1-51](file://docs/components/antdx/attachments/demos/basic.py#L1-L51) +- [combination.py:1-75](file://docs/components/antdx/attachments/demos/combination.py#L1-L75) +- [file_card.py:1-72](file://docs/components/antdx/attachments/demos/file_card.py#L1-L72) diff --git a/.wiki/en/Ant Design X Components/Expression Components/Expression Components.md b/.wiki/en/Ant Design X Components/Expression Components/Expression Components.md new file mode 100644 index 00000000..b0bd77fb --- /dev/null +++ b/.wiki/en/Ant Design X Components/Expression Components/Expression Components.md @@ -0,0 +1,322 @@ +# Expression Components + + +**Files Referenced in This Document** +- [frontend/antdx/attachments/attachments.tsx](file://frontend/antdx/attachments/attachments.tsx) +- [frontend/antdx/sender/sender.tsx](file://frontend/antdx/sender/sender.tsx) +- [frontend/antdx/suggestion/suggestion.tsx](file://frontend/antdx/suggestion/suggestion.tsx) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Usability Recommendations](#performance-and-usability-recommendations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document covers the Ant Design X Expression Components, focusing on three main components: + +- Attachments: Responsible for file upload, preview, list management, and placeholder rendering +- Sender: Responsible for message input, paste-to-upload, submission, and input state synchronization +- Suggestion: Responsible for command completion, trigger strategies, context forwarding, and popup container configuration + +The documentation provides a complete explanation from system architecture, data flow, processing logic, and inter-component collaboration mechanisms to usage examples and troubleshooting recommendations, helping developers quickly understand and correctly integrate these components. + +## Project Structure + +The frontend components of Ant Design X are located under frontend/antdx and are organized in a modular fashion. The backend Python wrapper layer exports unified aliases in backend/modelscope_studio/components/antdx, making them directly accessible in the Python ecosystem. + +```mermaid +graph TB +subgraph "Backend Wrapper Layer" +PY_API["Python Export Aliases
components.py / __init__.py"] +end +subgraph "Frontend Ant Design X Components" +ATT["Attachments
File Upload and Management"] +SND["Sender
Message Input and Submission"] +SUG["Suggestion
Quick Commands and Completion"] +end +PY_API --> ATT +PY_API --> SND +PY_API --> SUG +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/components.py:7-32](file://backend/modelscope_studio/components/antdx/components.py#L7-L32) +- [backend/modelscope_studio/components/antdx/**init**.py:7-41](file://backend/modelscope_studio/components/antdx/__init__.py#L7-L41) + +Section Sources + +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) + +## Core Components + +- Attachments + - Responsibility: Encapsulates @ant-design/x Attachments, providing upload hooks, placeholder rendering, enhanced image preview, custom icons, max count control, remove callback, and value change notifications + - Key Capabilities: Pre-upload validation, concurrent upload state, file list deduplication and merging, error fallback +- Sender + - Responsibility: Encapsulates @ant-design/x Sender, providing two-way value binding, paste-file-upload, skill panel (skill) slot-based configuration, and submit events that only fire when the suggestion panel is closed + - Key Capabilities: Input change synchronization, paste file upload, slot-based header/footer/prefix/suffix, skill hints and closable configuration +- Suggestion + - Responsibility: Encapsulates @ant-design/x Suggestion, supporting dynamic items rendering, slot-based label/icon/extra areas, popup container customization, and controlled/uncontrolled open state switching + - Key Capabilities: Trigger strategy hooks, context forwarding, keyboard event interception and forwarding, popup container positioning + +Section Sources + +- [frontend/antdx/attachments/attachments.tsx:36-410](file://frontend/antdx/attachments/attachments.tsx#L36-L410) +- [frontend/antdx/sender/sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) +- [frontend/antdx/suggestion/suggestion.tsx:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) + +## Architecture Overview + +The three work together: the user types text in Sender and pastes files; Sender hands the files to the upload function to generate persistable file information, which is then passed back via callback to the upper layer. Meanwhile, Suggestion provides command completion; only when it is closed does Sender actually submit the content, preventing accidental submission. + +```mermaid +sequenceDiagram +participant U as "User" +participant S as "Sender" +participant A as "Attachments" +participant P as "Upload Function (upload)" +participant C as "Upper Application" +U->>S : "Input text/paste file" +S->>P : "Paste file upload" +P-->>S : "Return file info list" +S-->>C : "onPasteFile(urls)" +S-->>C : "onChange(value)" +S->>C : "onSubmit(...)" +Note over S,C : "Submit only fires when Suggestion is closed" +U->>A : "Drag/select file" +A->>P : "Call upload hook" +P-->>A : "Return file info" +A-->>C : "onValueChange(items)" +A-->>C : "onChange(paths)" +``` + +Diagram Sources + +- [frontend/antdx/sender/sender.tsx:135-138](file://frontend/antdx/sender/sender.tsx#L135-L138) +- [frontend/antdx/attachments/attachments.tsx:329-348](file://frontend/antdx/attachments/attachments.tsx#L329-L348) +- [frontend/antdx/suggestion/suggestion.tsx:135-140](file://frontend/antdx/suggestion/suggestion.tsx#L135-L140) + +## Component Details + +### Attachments Component + +- Key Features + - File Upload: Accepts arrays of native file objects via the upload hook, returns file info arrays; supports maxCount to control single/multi-file mode + - Preview Enhancement: imageProps.preview supports mask, closeIcon, toolbarRender, imageRender with slot-based and function-based configuration + - List Management: Automatic deduplication (based on uid/url/path), status marking (done/uploading), remove callback, and value change notifications + - Placeholder Rendering: placeholder supports slot-based and function-based title/description/icon + - Interaction Protection: Disables interactions during upload to prevent re-submission +- Data Flow and Key Paths + - Change Handling: The onChange handler distinguishes between add/remove branches; for additions, it first injects a temporary "uploading" state, then calls upload, and finally merges results and fires callbacks + - Image Preview: Highly customizable via getContainer, toolbarRender, imageRender, etc. in imageProps.preview + - Display List: Icons and extras in showUploadList support slot-based and function-based overrides +- Error Handling + - Captures upload exceptions and restores upload state to prevent UI freeze +- Complexity and Performance + - Deduplication and state merging are O(n), suitable for medium-scale file lists + - Slot-based rendering computes on demand, avoiding unnecessary re-renders + +```mermaid +flowchart TD +Start(["Enter onChange"]) --> IsRemove{"Is it a remove operation?"} +IsRemove --> |Yes| RemoveFlow["Execute onRemove callback
Update fileList and fire callback"] +IsRemove --> |No| AddFlow["Enter add flow"] +AddFlow --> BeforeUpload["beforeUpload hook (optional)"] +BeforeUpload --> BeforeUploadOk{"Returns true?"} +BeforeUploadOk --> |No| End(["End"]) +BeforeUploadOk --> |Yes| SetUploading["Set uploading state"] +SetUploading --> Filter["Filter incomplete files and truncate by maxCount"] +Filter --> TempList["Generate temporary uploading entries"] +TempList --> CallUpload["Call upload hook"] +CallUpload --> Merge["Merge returned file info into final list"] +Merge --> UpdateState["Update fileList and fire onValueChange/onChange"] +UpdateState --> End +``` + +Diagram Sources + +- [frontend/antdx/attachments/attachments.tsx:275-354](file://frontend/antdx/attachments/attachments.tsx#L275-L354) + +Section Sources + +- [frontend/antdx/attachments/attachments.tsx:36-410](file://frontend/antdx/attachments/attachments.tsx#L36-L410) + +### Sender Component + +- Key Features + - Input Binding: Two-way synchronization of value and onChange, supports external controlled mode + - Paste Upload: onPasteFile hands pasted file collections to the upload hook and passes back file path arrays + - Skill Panel: skill.title/toolTip/closable supports slot-based and function-based configuration + - Submit Control: onSubmit is only triggered when Suggestion is closed, preventing accidental submission when the suggestion panel is open + - Slot-based Layout: header/footer/prefix/suffix support ReactSlot injection +- Key Interactions + - Uses useSuggestionOpenContext to get the suggestion panel open/close state, determining whether to allow submission + - formatResult/customRender in slotConfig are wrapped as functions via createFunction +- Error Handling + - Paste upload failure does not affect the input box state, only logs are recorded +- Performance and Complexity + - Value changes and slot rendering are both lightweight, suitable for high-frequency input scenarios + +```mermaid +sequenceDiagram +participant U as "User" +participant S as "Sender" +participant Ctx as "Suggestion Open Context" +participant P as "Upload Function (upload)" +U->>S : "Paste file" +S->>P : "upload(files)" +P-->>S : "Return file info" +S-->>U : "onPasteFile(urls)" +U->>S : "Click submit/press Enter" +S->>Ctx : "Read suggestion panel state" +alt Suggestion panel is closed +S-->>U : "onSubmit(...)" +else Suggestion panel is open +S-->>U : "Ignore submission" +end +``` + +Diagram Sources + +- [frontend/antdx/sender/sender.tsx:126-130](file://frontend/antdx/sender/sender.tsx#L126-L130) +- [frontend/antdx/sender/sender.tsx:135-138](file://frontend/antdx/sender/sender.tsx#L135-L138) + +Section Sources + +- [frontend/antdx/sender/sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) + +### Suggestion Component + +- Key Features + - Dynamic items: Supports two sources — an items function or slot-based items/default; slot items take priority + - Slot-based Rendering: label/icon/extra/children support ReactSlot injection and patchSlots processing + - Trigger Strategy: The shouldTrigger hook can intercept keyboard events to implement custom trigger conditions + - Popup Container: getPopupContainer supports function-based and slot-based configuration for positioning in complex layouts + - State Control: open can be controlled (internally self-managed when undefined); onOpenChange forwards the underlying state +- Context and Events + - Passes the current active item and keyboard event handling to the child tree via SuggestionContext and SuggestionOpenContext + - In the children render function, the real children are hidden and only shown when a slot exists +- Performance and Complexity + - items rendering is computed on demand; slot-based patch only applies to necessary fields + +```mermaid +flowchart TD +Init(["Initialize items rendering"]) --> Resolve["Resolve items/default slots"] +Resolve --> ItemsFn["items function (optional)"] +ItemsFn --> Merge["Merge into final items array"] +Merge --> Render["Render each item's label/icon/extra subitems"] +Render --> Patch["patchSlots applies slot-based overrides"] +Patch --> Open["Control display based on open state"] +Open --> Trigger["shouldTrigger intercepts keyboard events"] +Trigger --> Done(["Complete"]) +``` + +Diagram Sources + +- [frontend/antdx/suggestion/suggestion.tsx:89-121](file://frontend/antdx/suggestion/suggestion.tsx#L89-L121) +- [frontend/antdx/suggestion/suggestion.tsx:135-140](file://frontend/antdx/suggestion/suggestion.tsx#L135-L140) + +Section Sources + +- [frontend/antdx/suggestion/suggestion.tsx:64-162](file://frontend/antdx/suggestion/suggestion.tsx#L64-L162) + +## Dependency Analysis + +- Backend Exports + - components.py and **init**.py uniformly export AntdXAttachments/AntdXSender/AntdXSuggestion and other components as Attachments/Sender/Suggestion for direct use on the Python side +- Frontend Encapsulation + - All three components bridge @ant-design/x native components via sveltify to React components supporting slots and function-based configuration + - Uses utility hooks such as useFunction/useValueChange/useTargets to achieve parameter functionalization and value synchronization +- Inter-component Coupling + - Sender and Suggestion are loosely coupled via context: Sender only submits when Suggestion is closed, avoiding interaction conflicts + - Attachments and Sender are decoupled via the upload callback: upload logic is provided by the upper layer; components only handle UI and state + +```mermaid +graph LR +PY["Python Export Aliases"] --> ATT["Frontend Attachments"] +PY --> SND["Frontend Sender"] +PY --> SUG["Frontend Suggestion"] +ATT --> AX["@ant-design/x Attachments"] +SND --> AX2["@ant-design/x Sender"] +SUG --> AX3["@ant-design/x Suggestion"] +SND -- "Suggestion panel state" --> CTX["Suggestion Open Context"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/components.py:7-32](file://backend/modelscope_studio/components/antdx/components.py#L7-L32) +- [backend/modelscope_studio/components/antdx/**init**.py:7-41](file://backend/modelscope_studio/components/antdx/__init__.py#L7-L41) +- [frontend/antdx/sender/sender.tsx:72-72](file://frontend/antdx/sender/sender.tsx#L72-L72) + +Section Sources + +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/antdx/**init**.py:1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) + +## Performance and Usability Recommendations + +- Attachments Upload + - Set maxCount appropriately to avoid memory pressure from uploading too many files at once + - Perform format/size validation in beforeUpload to reduce invalid requests + - Use imageProps.preview's getContainer to mount the preview overlay to the appropriate container, avoiding scroll penetration +- Sender + - Use throttle/debounce strategies for high-frequency input (can be implemented in the upper layer) to reduce onChange frequency + - In multi-slot scenarios, reuse function-based configurations as much as possible to reduce slot rendering overhead +- Suggestion + - Keep the items rendering structure stable to avoid frequent DOM reconstruction + - Only perform necessary checks in shouldTrigger to avoid blocking keyboard events +- Global + - In complex layouts, prioritize using getPopupContainer for suggestion panel positioning to ensure visibility + - Provide friendly prompts for upload failures to avoid user confusion + +## Troubleshooting Guide + +- Attachments Cannot Delete + - Check whether the remove branch in onChange is being prematurely returned + - Confirm there is a matching uid entry in validFileList +- Upload Not Responding + - Confirm the upload hook return value is Promise and does not throw errors + - Check whether maxCount is limiting the number of new additions +- Preview Not Displaying + - Confirm imageProps.preview configuration is enabled and the container returned by getContainer exists +- Submission Blocked + - Check whether Suggestion's open state is true; Sender only triggers onSubmit when it is closed +- Paste Upload Failure + - Check in the onPasteFile callback whether the path array returned by upload is empty + - Check the console for exception stacks + +Section Sources + +- [frontend/antdx/attachments/attachments.tsx:275-354](file://frontend/antdx/attachments/attachments.tsx#L275-L354) +- [frontend/antdx/sender/sender.tsx:126-138](file://frontend/antdx/sender/sender.tsx#L126-L138) +- [frontend/antdx/suggestion/suggestion.tsx:135-140](file://frontend/antdx/suggestion/suggestion.tsx#L135-L140) + +## Conclusion + +The Expression Components are designed around a closed loop of "input—upload—completion—submit", achieving high extensibility through slot-based and function-based configuration, while isolating interactions via context to avoid accidental triggers. Attachments manages the file lifecycle, Sender controls input and submission timing, and Suggestion provides intelligent completion and trigger strategies. Together, they can satisfy typical scenarios such as multimodal input, attachment handling, and command execution. + +## Appendix: Usage Examples and Best Practices + +- Multimodal Input and Attachment Handling + - In Sender, listen to onChange/onPasteFile, convert pasted files into persistent paths via the upload hook, then submit text and file paths together + - Configure beforeUpload/isImageUrl and other hooks in Attachments to improve the upload experience +- Quick Commands and User Behavior Analysis + - Use Suggestion's items and shouldTrigger to implement command completion; use getPopupContainer to ensure popup positioning + - Record user open/close behavior of the suggestion panel via onOpenChange and SuggestionOpenContext for subsequent analysis +- Component Collaboration + - When Suggestion is open, Sender should not submit; when Suggestion is closed, trigger onSubmit to avoid interfering with user input + - Implement flexible UI combinations via slots (header/footer/prefix/suffix/skill.\*) diff --git a/.wiki/en/Ant Design X Components/Expression Components/Sender Component.md b/.wiki/en/Ant Design X Components/Expression Components/Sender Component.md new file mode 100644 index 00000000..2c56e537 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Expression Components/Sender Component.md @@ -0,0 +1,315 @@ +# Sender Component + + +**Files Referenced in This Document** +- [frontend/antdx/sender/sender.tsx](file://frontend/antdx/sender/sender.tsx) +- [frontend/antdx/sender/header/sender.header.tsx](file://frontend/antdx/sender/header/sender.header.tsx) +- [frontend/antdx/sender/switch/sender.switch.tsx](file://frontend/antdx/sender/switch/sender.switch.tsx) +- [backend/modelscope_studio/components/antdx/sender/__init__.py](file://backend/modelscope_studio/components/antdx/sender/__init__.py) +- [backend/modelscope_studio/components/antdx/sender/header/__init__.py](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py) +- [backend/modelscope_studio/components/antdx/sender/switch/__init__.py](file://backend/modelscope_studio/components/antdx/sender/switch/__init__.py) +- [docs/components/antdx/sender/README.md](file://docs/components/antdx/sender/README.md) +- [docs/components/antdx/attachments/demos/combination.py](file://docs/components/antdx/attachments/demos/combination.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Configuration and Usage Examples](#appendix-configuration-and-usage-examples) + +## Introduction + +The Sender component is an input component designed for chat scenarios, providing message sending, input handling, paste-to-upload, submit type control, header panel, and switch control capabilities. On the frontend it is based on Ant Design X's Sender implementation, and it provides a Python API on the backend through a Gradio adaptation layer. It supports slot-based extensions (such as prefix/suffix, header, footer, skill panel, etc.) and event binding. + +## Project Structure + +The Sender component consists of a "frontend Svelte wrapper + backend Python component" and is accompanied by Header and Switch subcomponents; documentation and examples are located in the docs directory. + +```mermaid +graph TB +subgraph "Frontend" +F_sender["frontend/antdx/sender/sender.tsx"] +F_header["frontend/antdx/sender/header/sender.header.tsx"] +F_switch["frontend/antdx/sender/switch/sender.switch.tsx"] +end +subgraph "Backend" +B_sender["backend/.../antdx/sender/__init__.py"] +B_header["backend/.../antdx/sender/header/__init__.py"] +B_switch["backend/.../antdx/sender/switch/__init__.py"] +end +subgraph "Documentation and Examples" +D_readme["docs/components/antdx/sender/README.md"] +D_demo["docs/components/antdx/attachments/demos/combination.py"] +end +F_sender --> B_sender +F_header --> B_header +F_switch --> B_switch +D_readme --> B_sender +D_demo --> B_sender +``` + +**Diagram Sources** + +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) +- [frontend/antdx/sender/header/sender.header.tsx:1-21](file://frontend/antdx/sender/header/sender.header.tsx#L1-L21) +- [frontend/antdx/sender/switch/sender.switch.tsx:1-34](file://frontend/antdx/sender/switch/sender.switch.tsx#L1-L34) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:1-149](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L1-L149) +- [backend/modelscope_studio/components/antdx/sender/header/**init**.py:1-74](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py#L1-L74) +- [backend/modelscope_studio/components/antdx/sender/switch/**init**.py:1-81](file://backend/modelscope_studio/components/antdx/sender/switch/__init__.py#L1-L81) +- [docs/components/antdx/sender/README.md:1-10](file://docs/components/antdx/sender/README.md#L1-L10) +- [docs/components/antdx/attachments/demos/combination.py:1-75](file://docs/components/antdx/attachments/demos/combination.py#L1-L75) + +**Section Sources** + +- [frontend/antdx/sender/sender.tsx:1-174](file://frontend/antdx/sender/sender.tsx#L1-L174) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:1-149](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L1-L149) + +## Core Components + +- Sender (Main Component) + - Manages input value, intercepts submit events, handles paste file upload, renders slots, and configures skill panel (including Tooltip and closable). + - Exposes callbacks and properties such as value, onChange, onSubmit, and onPasteFile. +- Sender.Header (Header Panel) + - Supports title slot, optional expand/collapse, and closable features. +- Sender.Switch (Switch Control) + - Supports custom "checked/unchecked" text and icon slots. + +**Section Sources** + +- [frontend/antdx/sender/sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) +- [frontend/antdx/sender/header/sender.header.tsx:7-18](file://frontend/antdx/sender/header/sender.header.tsx#L7-L18) +- [frontend/antdx/sender/switch/sender.switch.tsx:7-31](file://frontend/antdx/sender/switch/sender.switch.tsx#L7-L31) + +## Architecture Overview + +Sender bridges Ant Design X's Sender in the frontend via a Svelte wrapper, and exposes it to the Gradio ecosystem via a Python component in the backend. Its data flow and event flow are as follows: + +```mermaid +sequenceDiagram +participant U as "User" +participant FE as "Frontend Sender (Svelte)" +participant ADX as "Ant Design X Sender" +participant BK as "Backend Sender (Python)" +U->>FE : Input/paste/click send +FE->>FE : useValueChange(value/onValueChange) +FE->>ADX : Render and pass props (including slots/skill config) +ADX-->>FE : onChange(value) +FE-->>BK : Change event (Gradio) +ADX-->>FE : onSubmit(args) +FE->>FE : Check if suggestion is open (block auto-submit) +FE-->>BK : submit event (Gradio) +FE->>FE : onPasteFile(files) -> upload(files) -> onPasteFile(urls) +``` + +**Diagram Sources** + +- [frontend/antdx/sender/sender.tsx:68-138](file://frontend/antdx/sender/sender.tsx#L68-L138) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:21-59](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L21-L59) + +## Detailed Component Analysis + +### Main Component: Sender (Message Sending and Input Handling) + +- Input and State + - Uses controlled value and onChange combined with useValueChange to manage externally provided value and internal changes. +- Submit Logic + - onSubmit is intercepted: if the suggestion panel is open, the external submit is not triggered to avoid accidental submission. + - External submit events are reported via the Gradio event system. +- Paste Upload + - onPasteFile receives a native File list, calls the upload callback to perform the upload, and passes the returned file path array back to onPasteFile. +- Slots and Advanced Features + - Supports suffix/header/prefix/footer slots; supports skill.title, skill.toolTip.title, skill.closable.closeIcon slots. + - Skill configuration supports Tooltip and closable behavior; Tooltip's afterOpenChange and getPopupContainer can be wrapped as functions. +- Event Mapping + - Events such as change, submit, cancel, allow_speech_recording_change, key_down/key_press, focus/blur, paste, paste_file, skill_closable_close are all mapped to Gradio events. + +```mermaid +flowchart TD +Start(["Enter Sender Render"]) --> Slots["Resolve slots and skill config"] +Slots --> Render["Render Ant Design X Sender"] +Render --> OnChange["onChange(value) -> Update local value"] +Render --> OnSubmit["onSubmit(args)"] +OnSubmit --> CheckOpen{"Is suggestion panel open?"} +CheckOpen --> |Yes| BlockSubmit["Block external submit"] +CheckOpen --> |No| FireSubmit["Fire external submit (Gradio)"] +Render --> Paste["onPasteFile(files)"] +Paste --> Upload["upload(files) -> FileData[]"] +Upload --> OnPasteFile["onPasteFile(urls) callback"] +OnChange --> End(["Complete"]) +FireSubmit --> End +BlockSubmit --> End +OnPasteFile --> End +``` + +**Diagram Sources** + +- [frontend/antdx/sender/sender.tsx:68-138](file://frontend/antdx/sender/sender.tsx#L68-L138) + +**Section Sources** + +- [frontend/antdx/sender/sender.tsx:18-171](file://frontend/antdx/sender/sender.tsx#L18-L171) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:21-66](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L21-L66) + +### Subcomponent: Sender.Header (Header Panel) + +- Key Features + - Supports the title slot; all other attributes are forwarded to Ant Design X Header. + - The open_change event is mapped through Gradio. +- Usage Scenarios + - Used with Sender to insert attachments or extend the input area. + +**Section Sources** + +- [frontend/antdx/sender/header/sender.header.tsx:7-18](file://frontend/antdx/sender/header/sender.header.tsx#L7-L18) +- [backend/modelscope_studio/components/antdx/sender/header/**init**.py:12-20](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py#L12-L20) + +### Subcomponent: Sender.Switch (Switch Control) + +- Key Features + - Supports checkedChildren, unCheckedChildren, and icon slots for custom text and icons. + - The change event is mapped through Gradio. +- Usage Scenarios + - Controls voice input mode, quick submit mode, etc. + +**Section Sources** + +- [frontend/antdx/sender/switch/sender.switch.tsx:7-31](file://frontend/antdx/sender/switch/sender.switch.tsx#L7-L31) +- [backend/modelscope_studio/components/antdx/sender/switch/**init**.py:12-19](file://backend/modelscope_studio/components/antdx/sender/switch/__init__.py#L12-L19) + +### Class Relationship Diagram (Code Level) + +```mermaid +classDiagram +class AntdXSender { ++EVENTS ++SLOTS ++__init__(...) ++FRONTEND_DIR ++api_info() ++preprocess(payload) ++postprocess(value) +} +class AntdXSenderHeader { ++EVENTS ++SLOTS ++__init__(...) ++FRONTEND_DIR +} +class AntdXSenderSwitch { ++EVENTS ++SLOTS ++__init__(...) ++FRONTEND_DIR +} +AntdXSender --> AntdXSenderHeader : "contains" +AntdXSender --> AntdXSenderSwitch : "contains" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/sender/**init**.py:14-128](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L14-L128) +- [backend/modelscope_studio/components/antdx/sender/header/**init**.py:8-56](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py#L8-L56) +- [backend/modelscope_studio/components/antdx/sender/switch/**init**.py:8-63](file://backend/modelscope_studio/components/antdx/sender/switch/__init__.py#L8-L63) + +## Dependency Analysis + +- Frontend Dependencies + - Uses @svelte-preprocess-react to bridge React components to Svelte. + - Uses @ant-design/x's Sender/Header/Switch. + - Uses @gradio/client's FileData type and Gradio events. +- Backend Dependencies + - Based on Gradio's ModelScopeDataLayoutComponent/ModelScopeLayoutComponent abstraction for unified event and slot mapping. +- Documentation and Examples + - README provides basic example entry; combination examples demonstrate collaboration with Attachments, Badge, Button, and other components. + +```mermaid +graph LR +Svelte["Svelte Wrapper (Sender)"] --> ADX["Ant Design X Sender"] +Svelte --> Hooks["@utils/* hooks"] +Svelte --> Slot["ReactSlot Slots"] +Backend["Python Sender Component"] --> Gradio["Gradio Event System"] +Backend --> Frontend["Frontend Component Mapping"] +Docs["Documentation and Examples"] --> Backend +Docs --> Frontend +``` + +**Diagram Sources** + +- [frontend/antdx/sender/sender.tsx:1-10](file://frontend/antdx/sender/sender.tsx#L1-L10) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:14-128](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L14-L128) +- [docs/components/antdx/sender/README.md:1-10](file://docs/components/antdx/sender/README.md#L1-L10) + +**Section Sources** + +- [frontend/antdx/sender/sender.tsx:1-10](file://frontend/antdx/sender/sender.tsx#L1-L10) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:14-128](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L14-L128) + +## Performance Considerations + +- Slots and Function Wrapping + - Tooltip callbacks and slots are wrapped as functions and rendered with ReactSlot to avoid unnecessary re-renders; it is recommended to cache or stabilize slot content in the upper layer. +- Submit Interception + - It is recommended to disable auto-submit when the suggestion panel is open to reduce invalid requests. +- File Upload + - onPasteFile should be processed asynchronously as much as possible to avoid blocking the UI; for large files, consider chunked or direct server-side upload strategies. + +## Troubleshooting Guide + +- Submit Unexpectedly Intercepted + - If submit is not triggered due to the suggestion panel not being closed, check the suggestion panel state or temporarily disable the interception logic. +- Paste Upload Not Working + - Confirm the upload callback correctly returns a FileData array containing a path field; the onPasteFile callback should receive a string array. +- Slot Content Not Displaying + - Confirm the slot names match those supported by the component (e.g., skill.title, skill.toolTip.title, skill.closable.closeIcon). +- Events Not Firing + - Check whether the backend EVENTS list contains the corresponding event name and whether the frontend is correctly bound. + +**Section Sources** + +- [frontend/antdx/sender/sender.tsx:126-138](file://frontend/antdx/sender/sender.tsx#L126-L138) +- [backend/modelscope_studio/components/antdx/sender/**init**.py:21-59](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L21-L59) + +## Conclusion + +The Sender component, through its integrated frontend and backend design, provides powerful input and submission capabilities for chat scenarios. Combined with Header, Switch, and the slot system, it can be flexibly extended to support multimodal input and complex interactions. In practice, pay attention to event interception, slot stability, and the robustness of the upload process. + +## Appendix: Configuration and Usage Examples + +### Configuration Overview (Backend) + +- Basic Properties + - value/default_value/placeholder/loading/disabled/read_only/auto_size/submit_type, etc. +- Slots + - suffix/header/prefix/footer/skill.title/skill.toolTip.title/skill.closable.closeIcon. +- Events + - change, submit, cancel, allow_speech_recording_change, key_down/key_press, focus/blur, paste, paste_file, skill_closable_close. +- Subcomponents + - Header, Switch (each supporting corresponding slots and events). + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/sender/**init**.py:61-127](file://backend/modelscope_studio/components/antdx/sender/__init__.py#L61-L127) +- [backend/modelscope_studio/components/antdx/sender/header/**init**.py:19-54](file://backend/modelscope_studio/components/antdx/sender/header/__init__.py#L19-L54) +- [backend/modelscope_studio/components/antdx/sender/switch/**init**.py:18-61](file://backend/modelscope_studio/components/antdx/sender/switch/__init__.py#L18-L61) + +### Chatbot Integration Example (Overview) + +- Text Messages + - Use Sender as input, listen to the submit event to get text content, and combine with backend model inference to return results. +- Multimodal Content + - Collaborate with Sender.Header/Attachments; upload images/files via paste or drag; the path list returned by onPasteFile can be used for subsequent processing. +- Special Commands + - Parse input in onChange or submit, recognize commands like "/reset" and "/help", and execute corresponding logic. + +**Section Sources** + +- [docs/components/antdx/attachments/demos/combination.py:26-71](file://docs/components/antdx/attachments/demos/combination.py#L26-L71) +- [docs/components/antdx/sender/README.md:5-10](file://docs/components/antdx/sender/README.md#L5-L10) diff --git a/.wiki/en/Ant Design X Components/Expression Components/Suggestion Component.md b/.wiki/en/Ant Design X Components/Expression Components/Suggestion Component.md new file mode 100644 index 00000000..b686630f --- /dev/null +++ b/.wiki/en/Ant Design X Components/Expression Components/Suggestion Component.md @@ -0,0 +1,338 @@ +# Suggestion Component + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/suggestion/__init__.py](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py) +- [backend/modelscope_studio/components/antdx/suggestion/item/__init__.py](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py) +- [frontend/antdx/suggestion/suggestion.tsx](file://frontend/antdx/suggestion/suggestion.tsx) +- [frontend/antdx/suggestion/item/suggestion.item.tsx](file://frontend/antdx/suggestion/item/suggestion.item.tsx) +- [frontend/antdx/suggestion/context.ts](file://frontend/antdx/suggestion/context.ts) +- [docs/components/antdx/suggestion/README.md](file://docs/components/antdx/suggestion/README.md) +- [backend/modelscope_studio/components/pro/chatbot/__init__.py](file://backend/modelscope_studio/components/pro/chatbot/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Interaction Features](#performance-and-interaction-features) +8. [Usage Examples and Best Practices](#usage-examples-and-best-practices) +9. [Troubleshooting](#troubleshooting) +10. [Conclusion](#conclusion) + +## Introduction + +The Suggestion component provides capabilities such as "quick commands", "intelligent completion", "context-aware suggestions", and "personalized recommendations" in AI assistant conversation scenarios. Based on Ant Design X's Suggestion capability and bridged via React wrapper and Gradio layout components, it implements: + +- Instruction Definition: Organized as "suggestion items" supporting multi-dimensional information such as labels, icons, and extra content. +- Trigger Conditions: Can be controlled by input keyboard events or external state to open/close the panel. +- Execution Logic: Triggers callbacks after selecting a suggestion, enabling subsequent processing on the Python side. +- Control Mode: Supports both controlled and uncontrolled modes; the open state can be set directly from the Python side. +- Dynamic Updates: The suggestion list can be dynamically generated via slots or functions and can be hot-updated at runtime. + +This component is widely used in interactive scenarios requiring "quick actions" such as chatbots, code assistants, and content creation. + +## Project Structure + +The Suggestion component is composed of a backend Python component and a frontend React implementation, unified through a context system for slot rendering and dynamic data injection. + +```mermaid +graph TB +subgraph "Backend Python" +PY_SUG["AntdXSuggestion
Component Class"] +PY_ITEM["AntdXSuggestionItem
Suggestion Item Class"] +end +subgraph "Frontend React" +FE_SUG["Suggestion
React Wrapper"] +FE_ITEM["SuggestionItem
Item Wrapper"] +CTX["context.ts
items Context"] +end +PY_SUG --> FE_SUG +PY_ITEM --> FE_ITEM +FE_SUG --> CTX +FE_ITEM --> CTX +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/suggestion/item/**init**.py:8-68](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py#L8-L68) +- [frontend/antdx/suggestion/suggestion.tsx:64-165](file://frontend/antdx/suggestion/suggestion.tsx#L64-L165) +- [frontend/antdx/suggestion/item/suggestion.item.tsx:7-22](file://frontend/antdx/suggestion/item/suggestion.item.tsx#L7-L22) +- [frontend/antdx/suggestion/context.ts:1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/suggestion/item/**init**.py:8-68](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py#L8-L68) +- [frontend/antdx/suggestion/suggestion.tsx:64-165](file://frontend/antdx/suggestion/suggestion.tsx#L64-L165) +- [frontend/antdx/suggestion/item/suggestion.item.tsx:7-22](file://frontend/antdx/suggestion/item/suggestion.item.tsx#L7-L22) +- [frontend/antdx/suggestion/context.ts:1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) + +## Core Components + +- AntdXSuggestion (Backend Component) + - Supported Events: select (item selected), open_change (panel open/close). + - Supported Slots: items, children. + - Key Properties: items (suggestion list), block (block-level display), open (controlled open/close), should_trigger (custom trigger), root style class name and inline styles, etc. + - Frontend Mapping: resolve_frontend_dir("suggestion", type="antdx"). +- AntdXSuggestionItem (Backend Suggestion Item) + - Supported Slots: label, icon, extra. + - Key Properties: value, label, extra, icon, key. + - Frontend Mapping: resolve_frontend_dir("suggestion", "item", type="antdx"). + +Both components declare skip_api=True, indicating they do not participate in the standard API flow but instead complete interactions through events and slots. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/suggestion/item/**init**.py:8-68](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py#L8-L68) + +## Architecture Overview + +Suggestion wraps Ant Design X's Suggestion component in the frontend via React, combined with a slot system and context to implement suggestion item rendering and event forwarding. In the backend, it bridges through Gradio layout components to support Python-side control and event binding. + +```mermaid +sequenceDiagram +participant U as "User" +participant FE as "Frontend Suggestion" +participant ADX as "Ant Design X Suggestion" +participant CTX as "Items Context" +participant PY as "Backend AntdXSuggestion" +U->>FE : Input text/press key +FE->>ADX : Render suggestion panel +FE->>CTX : Resolve items slots +CTX-->>FE : Return suggestion item collection +FE->>ADX : Inject items and callbacks +U->>FE : Select a suggestion item +FE->>PY : Trigger select event +PY-->>FE : Callback handled on Python side +FE-->>U : Update UI/execute action +``` + +**Diagram Sources** + +- [frontend/antdx/suggestion/suggestion.tsx:77-162](file://frontend/antdx/suggestion/suggestion.tsx#L77-L162) +- [frontend/antdx/suggestion/context.ts:1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:18-27](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L18-L27) + +## Component Details + +### Backend Component: AntdXSuggestion + +- Event Binding + - select: Triggered when a suggestion item is selected; event binding is enabled on the backend via internal flags. + - open_change: Triggered when the panel open/close state changes, facilitating controlled/uncontrolled switching. +- Slot Support + - items: Suggestion item collection, dynamically generated via slots or functions. + - children: Used to wrap host elements such as input boxes, combined with should_trigger to customize trigger logic. +- Key Property Points + - items: Can be a string, list, or function; function form supports dynamic computation. + - open: In controlled mode, the panel open/close is explicitly set from the Python side. + - should_trigger: Custom keyboard event trigger determining when to show the suggestion panel. + - Styles: Supports class_names, styles, root_class_name, etc. +- Lifecycle + - preprocess/postprocess/example_payload/example_value all return empty values, indicating this component does not participate in data serialization. + +```mermaid +classDiagram +class AntdXSuggestion { ++EVENTS ++SLOTS ++items ++block ++open ++should_trigger ++root_class_name ++class_names ++styles ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +class AntdXSuggestionItem { ++EVENTS ++SLOTS ++value ++label ++extra ++icon ++key ++skip_api +} +AntdXSuggestion --> AntdXSuggestionItem : "uses" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) +- [backend/modelscope_studio/components/antdx/suggestion/item/**init**.py:8-68](file://backend/modelscope_studio/components/antdx/suggestion/item/__init__.py#L8-L68) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-86](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L86) + +### Frontend Implementation: Suggestion (React Wrapper) + +- Slots and Context + - Uses withItemsContextProvider to provide an items context, supporting both default and items slot sets. + - Converts slot content into suggestion item structures via renderItems and patchSlots. +- Dynamic Suggestion List + - items can be a function or slot resolution result; falls back to the default slot if empty. + - Uses useMemoizedEqualValue and useMemo to optimize rendering and comparison. +- Trigger and Open/Close + - shouldTrigger: Triggers onTrigger as needed in onKeyDown to determine whether to show the panel. + - open: Supports both props.open uncontrolled mode and internal state controlled mode. +- Event Forwarding + - onOpenChange: Determines whether to update internal state based on the presence of props.open. + - children: Injects context and forwards events via SuggestionChildrenWrapper. + +```mermaid +flowchart TD +Start(["Enter Suggestion Render"]) --> ResolveItems["Resolve items slots/functions"] +ResolveItems --> ItemsEmpty{"Are items empty?"} +ItemsEmpty -- Yes --> Fallback["Fall back to default slot"] +ItemsEmpty -- No --> UseProvided["Use provided items function/array"] +Fallback --> BuildList["Build suggestion item list"] +UseProvided --> BuildList +BuildList --> PatchSlots["patchSlots renders label/icon/extra sub-slots"] +PatchSlots --> SetOpen["Set/sync open state based on props.open"] +SetOpen --> Render["Render Ant Design X Suggestion and forward events"] +Render --> End(["Complete"]) +``` + +**Diagram Sources** + +- [frontend/antdx/suggestion/suggestion.tsx:77-162](file://frontend/antdx/suggestion/suggestion.tsx#L77-L162) +- [frontend/antdx/suggestion/context.ts:1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) + +**Section Sources** + +- [frontend/antdx/suggestion/suggestion.tsx:64-165](file://frontend/antdx/suggestion/suggestion.tsx#L64-L165) +- [frontend/antdx/suggestion/context.ts:1-7](file://frontend/antdx/suggestion/context.ts#L1-L7) + +### Frontend Implementation: SuggestionItem (Item Wrapper) + +- Renders slot default as suggestion item children via ItemHandler. +- Only allows the default slot, simplifying suggestion item content organization. + +**Section Sources** + +- [frontend/antdx/suggestion/item/suggestion.item.tsx:7-22](file://frontend/antdx/suggestion/item/suggestion.item.tsx#L7-L22) + +## Dependency Analysis + +- Component Coupling + - AntdXSuggestion depends on AntdXSuggestionItem as the suggestion item container. + - Frontend Suggestion depends on Ant Design X's Suggestion component and internal utility functions (such as patchSlots, renderItems). +- Data Flow + - Slots → Context Resolution → Suggestion Item Structure → Render → Event Callback → Python Processing. +- Event Chain + - Frontend onOpenChange/select → Backend event listener → Python callback. + +```mermaid +graph LR +PY_SUG["Backend AntdXSuggestion"] --> FE_SUG["Frontend Suggestion"] +PY_ITEM["Backend AntdXSuggestionItem"] --> FE_ITEM["Frontend SuggestionItem"] +FE_SUG --> ADX["Ant Design X Suggestion"] +FE_SUG --> CTX["Items Context"] +FE_ITEM --> CTX +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-16](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L16) +- [frontend/antdx/suggestion/suggestion.tsx:64-86](file://frontend/antdx/suggestion/suggestion.tsx#L64-L86) +- [frontend/antdx/suggestion/item/suggestion.item.tsx:7-18](file://frontend/antdx/suggestion/item/suggestion.item.tsx#L7-L18) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:11-16](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L11-L16) +- [frontend/antdx/suggestion/suggestion.tsx:64-86](file://frontend/antdx/suggestion/suggestion.tsx#L64-L86) +- [frontend/antdx/suggestion/item/suggestion.item.tsx:7-18](file://frontend/antdx/suggestion/item/suggestion.item.tsx#L7-L18) + +## Performance and Interaction Features + +- Render Optimization + - Uses useMemoizedEqualValue and useMemo to cache props and items, avoiding redundant renders. + - Only rebuilds the suggestion item list when items or slots change. +- Event Throttling + - Uses requestAnimationFrame in shouldTrigger to defer keyboard event processing, reducing main thread blocking risk. +- Open/Close Control + - Uncontrolled Mode: onOpenChange internally maintains the open state. + - Controlled Mode: Determined by props.open; onOpenChange only callbacks without modifying state. +- Slot Rendering + - patchSlots converts label/icon/extra sub-slots into corresponding fields, reducing cross-component communication costs. + +**Section Sources** + +- [frontend/antdx/suggestion/suggestion.tsx:36-57](file://frontend/antdx/suggestion/suggestion.tsx#L36-L57) +- [frontend/antdx/suggestion/suggestion.tsx:94-121](file://frontend/antdx/suggestion/suggestion.tsx#L94-L121) +- [frontend/antdx/suggestion/suggestion.tsx:135-140](file://frontend/antdx/suggestion/suggestion.tsx#L135-L140) + +## Usage Examples and Best Practices + +### Basic Usage (Documentation Examples) + +- The documentation provides three examples: basic, block-level display, and Python-controlled; reference: + - [docs/components/antdx/suggestion/README.md:5-10](file://docs/components/antdx/suggestion/README.md#L5-L10) + +### AI Assistant Scenario Examples (Conceptual Description) + +- Common Commands + - Define a set of fixed command suggestion items that execute on click, suitable for "quick start" scenarios. +- Context-aware Suggestions + - Dynamically generate suggestion lists based on current input or message history to improve relevance. +- Personalized Recommendations + - Based on user preferences or usage records, prioritize high-hit-rate suggestion items. +- Python-side Control + - Control panel show/hide by setting the open property; receive selected items via the select event and execute corresponding logic on the Python side. + +### Instruction Definition and Triggering + +- Instruction Definition + - Use AntdXSuggestionItem to organize suggestion items, supporting fields like label, icon, and extra. +- Trigger Conditions + - Can customize keyboard event triggers via should_trigger; can also control panel open/close via the open property. +- Execution Logic + - After selecting a suggestion item, the select event is triggered; the Python side can handle business logic in the callback. + +### Style and Interaction Customization + +- Styles + - Customize styles via class*names, styles, root_class_name, and backend elem*\* properties. +- Interaction + - The children slot is used to host input boxes and other host components, combined with should_trigger for more flexible trigger strategies. + +**Section Sources** + +- [docs/components/antdx/suggestion/README.md:5-10](file://docs/components/antdx/suggestion/README.md#L5-L10) +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:32-67](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L32-L67) +- [frontend/antdx/suggestion/suggestion.tsx:77-86](file://frontend/antdx/suggestion/suggestion.tsx#L77-L86) + +## Troubleshooting + +- Suggestion Items Not Displaying + - Check whether items is empty; if empty, confirm the default slot is correctly populated. + - Confirm slot names match (items/default). +- Panel Cannot Open + - If using controlled open, ensure the open state is correctly set on the Python side. + - Check whether should_trigger correctly implements the trigger logic. +- Events Not Firing + - Confirm event listeners are registered (select/open_change). + - Check whether Python-side callbacks are correctly bound. + +**Section Sources** + +- [frontend/antdx/suggestion/suggestion.tsx:87-121](file://frontend/antdx/suggestion/suggestion.tsx#L87-L121) +- [backend/modelscope_studio/components/antdx/suggestion/**init**.py:18-27](file://backend/modelscope_studio/components/antdx/suggestion/__init__.py#L18-L27) + +## Conclusion + +The Suggestion component, through its "backend layout component + frontend React wrapper + slot context" architecture, achieves high-performance, extensible quick command and intelligent completion capabilities. It supports controlled/uncontrolled open/close, dynamic suggestion lists, custom triggers, and event callbacks, making it suitable for various AI assistant and creation scenarios. It is recommended to dynamically generate suggestion items based on business context in practice, and implement closed-loop interactions through Python-side events. diff --git a/.wiki/en/Ant Design X Components/Feedback Components/ActionItem Component.md b/.wiki/en/Ant Design X Components/Feedback Components/ActionItem Component.md new file mode 100644 index 00000000..9af5a0fe --- /dev/null +++ b/.wiki/en/Ant Design X Components/Feedback Components/ActionItem Component.md @@ -0,0 +1,258 @@ +# ActionItem Component + + +**Files referenced in this document** +- [frontend/antdx/actions/action-item/Index.svelte](file://frontend/antdx/actions/action-item/Index.svelte) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [backend/modelscope_studio/components/antdx/actions/__init__.py](file://backend/modelscope_studio/components/antdx/actions/__init__.py) +- [backend/modelscope_studio/components/antdx/actions/action_item/__init__.py](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py) +- [backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js](file://backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Parameter Reference](#appendix-usage-examples-and-parameter-reference) + +## Introduction + +ActionItem is the core sub-component in the Ant Design X Actions component system, used to present a single clickable or interactive operation item within an Actions container. It supports multiple forms (text, icon, custom rendering), nested sub-menus, danger state, trigger strategies (hover/click), and the ability to extend content through slots. The component provides both a frontend Svelte wrapper layer and a backend Gradio Python encapsulation layer, forming a complete "Python configuration + frontend rendering" pipeline. + +## Project Structure + +The directory and related files for ActionItem are organized as follows: + +- Frontend wrapper layer (Svelte): frontend/antdx/actions/action-item/Index.svelte +- Frontend main component (React): frontend/antdx/actions/actions.tsx (contains the main Actions component) +- Backend encapsulation layer (Gradio Python): backend/modelscope_studio/components/antdx/actions/action_item/**init**.py +- Frontend bridge and runtime (build artifact): backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js +- Backend Actions main component: backend/modelscope_studio/components/antdx/actions/**init**.py + +```mermaid +graph TB +subgraph "Backend" +PY_INIT["Python: actions/__init__.py\nDefines AntdXActions"] +PY_ITEM["Python: action_item/__init__.py\nDefines AntdXActionsActionItem"] +end +subgraph "Frontend" +SVELTE["Svelte: action-item/Index.svelte\nWraps React component"] +REACT_MAIN["React: actions.tsx\nMain Actions component"] +RUNTIME["JS Runtime: actions.action-item-*.js\nBridge and rendering logic"] +end +PY_ITEM --> SVELTE +SVELTE --> RUNTIME +PY_INIT --> REACT_MAIN +REACT_MAIN --> RUNTIME +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/actions/**init**.py:15-94](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L94) +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:10-62](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L10-L62) +- [frontend/antdx/actions/action-item/Index.svelte:14-98](file://frontend/antdx/actions/action-item/Index.svelte#L14-L98) +- [frontend/antdx/actions/actions.tsx:1-200](file://frontend/antdx/actions/actions.tsx#L1-L200) +- [backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js:419-431](file://backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js#L419-L431) + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/**init**.py:15-94](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L94) +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:10-62](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L10-L62) +- [frontend/antdx/actions/action-item/Index.svelte:14-98](file://frontend/antdx/actions/action-item/Index.svelte#L14-L98) +- [frontend/antdx/actions/actions.tsx:1-200](file://frontend/antdx/actions/actions.tsx#L1-L200) +- [backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js:419-431](file://backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js#L419-L431) + +## Core Components + +- AntdXActionsActionItem (backend encapsulation): Responsible for mapping Python-layer configuration to frontend components and declaring event and slot capabilities. +- ActionsActionItem (frontend bridge): Dynamically imported and rendered by the Svelte wrapper layer, responsible for handling slots, additional attributes, event mapping, and visibility control. +- Actions (main component): The frontend implementation of AntdXActions, hosting multiple ActionItems and providing advanced features such as dropdowns and animations. + +Key responsibilities and relationships + +- Backend encapsulation: Defines ActionItem parameters, events, and slots; determines frontend resource paths. +- Frontend wrapper: Parses props, handles slots, and generates the final props and slots required for rendering. +- Runtime bridge: Connects the Svelte/React render tree with the Gradio context, supporting event forwarding and context merging. + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:10-62](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L10-L62) +- [frontend/antdx/actions/action-item/Index.svelte:19-84](file://frontend/antdx/actions/action-item/Index.svelte#L19-L84) +- [backend/modelscope_studio/components/antdx/actions/**init**.py:15-94](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L94) + +## Architecture Overview + +The complete call chain from Python to frontend for ActionItem is as follows: + +```mermaid +sequenceDiagram +participant Py as "Python : AntdXActionsActionItem" +participant Svelte as "Svelte : action-item/Index.svelte" +participant Runtime as "JS Runtime : actions.action-item-*.js" +participant React as "React : actions.tsx" +Py->>Svelte : Pass component configuration and event bindings +Svelte->>Runtime : Import and instantiate ActionsActionItem +Runtime->>React : Render React version of ActionItem +React-->>Runtime : Trigger event callbacks e.g. item_click +Runtime-->>Svelte : Events forwarded back to Gradio +Svelte-->>Py : Event result returned +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:15-21](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L15-L21) +- [frontend/antdx/actions/action-item/Index.svelte:14-98](file://frontend/antdx/actions/action-item/Index.svelte#L14-L98) +- [backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js:419-431](file://backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js#L419-L431) +- [frontend/antdx/actions/actions.tsx:1-200](file://frontend/antdx/actions/actions.tsx#L1-L200) + +## Detailed Component Analysis + +### Backend Encapsulation: AntdXActionsActionItem + +- Event binding + - item_click: Triggered when the operation item is clicked; the backend enables event binding via an internal flag. +- Slot support + - Supports slots such as label, icon, actionRender, and subItems for flexible extension. +- Key properties + - label, icon, danger, trigger_sub_menu_action, sub_items, action_render, as_item, key, etc. +- Resource location + - Uses resolve_frontend_dir("actions", "action-item", type="antdx") to specify the frontend resource directory. + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:10-62](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L10-L62) +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:15-21](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L15-L21) +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:24](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L24) + +### Frontend Wrapper: Svelte Wrapper Layer + +- Dynamic import + - Dynamically loads the React version of ActionItem via importComponent. +- Props handling + - Uses getProps/processProps to extract and transform props, mapping item_click to the frontend event name. + - Merges elem_id, elem_classes, elem_style, additionalProps, etc. +- Slot handling + - Retrieves slot content via getSlots, setting withParams and clone for actionRender. +- Visibility and index + - Controls rendering based on visible; passes itemIndex and itemSlotKey to work with context. + +Section Sources + +- [frontend/antdx/actions/action-item/Index.svelte:14-98](file://frontend/antdx/actions/action-item/Index.svelte#L14-L98) + +### Runtime Bridge: JS Runtime + +- Component bridge + - Creates a Svelte-React bridge instance via Ge(...), mounting the React component to a shared root node. +- Context and slots + - Uses createItemsContext to provide the items context, supporting default slots and sub-item rendering. +- Event and property forwarding + - Merges Gradio context with props to ensure events and styles are correctly forwarded. + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js:419-431](file://backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js#L419-L431) + +### Main Component: AntdXActions (Related) + +- Role + - Acts as the container for ActionItem, providing items list, variants, dropdown configuration, animations, and more. +- Events and slots + - Supports click, dropdown*open_change, dropdown_menu*\* event series, and multiple slots. + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/**init**.py:15-94](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L15-L94) + +## Dependency Analysis + +- Backend to frontend + - AntdXActionsActionItem points to frontend resources via FRONTEND_DIR; the Svelte wrapper layer dynamically imports the corresponding JS module. +- Frontend to runtime + - The Svelte wrapper layer passes props and slots to the runtime bridge module, which is responsible for rendering the React component and integrating with the Gradio context. +- Inter-component collaboration + - ActionItem typically exists as a sub-item of Actions; the two together form an operation panel. + +```mermaid +graph LR +PY_ITEM["Python: ActionItem Encapsulation"] --> SVELTE["Svelte: Wrapper Layer"] +SVELTE --> RUNTIME["JS: Bridge and Rendering"] +RUNTIME --> REACT_MAIN["React: Actions Main Component"] +REACT_MAIN --> ACTIONITEM["React: ActionItem Sub-item"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:62](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L62) +- [frontend/antdx/actions/action-item/Index.svelte:14-98](file://frontend/antdx/actions/action-item/Index.svelte#L14-L98) +- [backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js:419-431](file://backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js#L419-L431) +- [frontend/antdx/actions/actions.tsx:1-200](file://frontend/antdx/actions/actions.tsx#L1-L200) + +## Performance Considerations + +- Dynamic import and lazy loading + - The Svelte side implements on-demand loading via importComponent, reducing the initial bundle size and first-screen load pressure. +- Render optimization + - Uses $derived and useMemo strategies to avoid unnecessary re-renders. +- Event forwarding + - Events are handled uniformly in the runtime bridge layer, reducing redundant bindings and memory usage. +- Slot cloning + - Sets clone and withParams for actionRender, ensuring stable reuse and parameter passing for slot content. + +Section Sources + +- [frontend/antdx/actions/action-item/Index.svelte:14-98](file://frontend/antdx/actions/action-item/Index.svelte#L14-L98) +- [backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js:163-209](file://backend/modelscope_studio/components/antdx/actions/action_item/templates/component/actions.action-item-76joNQSL.js#L163-L209) + +## Troubleshooting Guide + +- Event not triggered + - Check if the backend has enabled item_click event binding; confirm that item_click is correctly mapped in the frontend props. +- Slot not working + - Confirm slot names match the supported list (label, icon, actionRender, subItems); check withParams and clone settings for actionRender. +- Style or class name anomalies + - Check if elem_id, elem_classes, and elem_style are correctly passed; confirm the style and class name merging logic in the runtime bridge layer. +- Sub-menu not displaying + - Check trigger_sub_menu_action (hover/click) and sub_items structure; confirm the dropdown configuration of the main Actions. + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:15-21](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L15-L21) +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:24](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L24) +- [frontend/antdx/actions/action-item/Index.svelte:61-84](file://frontend/antdx/actions/action-item/Index.svelte#L61-L84) + +## Conclusion + +ActionItem implements a highly configurable, extensible, and maintainable operation item component through backend Python encapsulation and frontend Svelte/React bridging. Its event, slot, style, and context integration capabilities enable it to meet the needs of operation panels in complex scenarios. Combined with the AntdXActions main component, beautiful and fully functional operation areas can be quickly built. + +## Appendix: Usage Examples and Parameter Reference + +The following are common usage scenarios and parameter descriptions (using paths instead of specific code): + +- Text operation item + - Parameters: label, danger, as_item + - Example path: [frontend/antdx/actions/action-item/Index.svelte:61-84](file://frontend/antdx/actions/action-item/Index.svelte#L61-L84) +- Icon operation item + - Parameters: icon, label, elem_classes + - Example path: [frontend/antdx/actions/action-item/Index.svelte:61-84](file://frontend/antdx/actions/action-item/Index.svelte#L61-L84) +- Custom rendering (actionRender) + - Parameters: actionRender (function string), slot withParams/clone + - Example path: [frontend/antdx/actions/action-item/Index.svelte:71-83](file://frontend/antdx/actions/action-item/Index.svelte#L71-L83) +- Danger state and trigger strategy + - Parameters: danger, trigger_sub_menu_action (hover/click) + - Example path: [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:26-61](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L26-L61) +- Sub-menu + - Parameters: sub_items, slot subItems + - Example path: [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:24](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L24) + +Section Sources + +- [frontend/antdx/actions/action-item/Index.svelte:61-84](file://frontend/antdx/actions/action-item/Index.svelte#L61-L84) +- [backend/modelscope_studio/components/antdx/actions/action_item/**init**.py:24-61](file://backend/modelscope_studio/components/antdx/actions/action_item/__init__.py#L24-L61) diff --git a/.wiki/en/Ant Design X Components/Feedback Components/Actions Overview.md b/.wiki/en/Ant Design X Components/Feedback Components/Actions Overview.md new file mode 100644 index 00000000..4723f684 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Feedback Components/Actions Overview.md @@ -0,0 +1,335 @@ +# Actions Overview + + +**Files referenced in this document** +- [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/antdx/actions/item/Index.svelte](file://frontend/antdx/actions/item/Index.svelte) +- [frontend/antdx/actions/action-item/Index.svelte](file://frontend/antdx/actions/action-item/Index.svelte) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [backend/modelscope_studio/components/antdx/actions/__init__.py](file://backend/modelscope_studio/components/antdx/actions/__init__.py) +- [docs/components/antdx/actions/README.md](file://docs/components/antdx/actions/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +Actions is a layout and interaction component from the Ant Design X component library in ModelScope Studio, used to quickly configure a set of reusable operation buttons or function entry points in AI scenarios. Through a unified "operation item" model and slots mechanism, it decouples static configuration from dynamic rendering, supporting both direct passing of an items list and declarative organization of operation items as sub-components, thereby improving development efficiency and maintainability. + +In the overall architecture of ModelScope Studio, Actions sits between the frontend Svelte layer and the backend Gradio component layer, serving as a "bridge and adapter": the frontend is responsible for rendering Ant Design X's Actions on the page; the backend exposes events and slot capabilities through a custom component class and forwards extra properties to the frontend, achieving a complete interaction loop from the Python side to the browser. + +## Project Structure + +The Actions component consists of two parts — frontend and backend: + +- Frontend (Svelte + React): Responsible for rendering Ant Design X's Actions as page elements, and collecting sub-items through the slot and context system. +- Backend (Python + Gradio): Defines the component interface, events, and slots, responsible for binding and forwarding properties and events. + +```mermaid +graph TB +subgraph "Frontend" +A_Index["frontend/antdx/actions/Index.svelte"] +A_Component["frontend/antdx/actions/actions.tsx"] +A_Context["frontend/antdx/actions/context.ts"] +A_Item["frontend/antdx/actions/item/Index.svelte"] +A_ActionItem["frontend/antdx/actions/action-item/Index.svelte"] +U_CreateItems["frontend/utils/createItemsContext.tsx"] +end +subgraph "Backend" +P_Init["backend/modelscope_studio/components/antdx/actions/__init__.py"] +end +A_Index --> A_Component +A_Component --> A_Context +A_Component --> U_CreateItems +A_Item --> A_Component +A_ActionItem --> A_Component +P_Init --> A_Index +``` + +**Diagram Sources** + +- [frontend/antdx/actions/Index.svelte:1-77](file://frontend/antdx/actions/Index.svelte#L1-L77) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/action-item/Index.svelte:1-99](file://frontend/antdx/actions/action-item/Index.svelte#L1-L99) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [backend/modelscope_studio/components/antdx/actions/**init**.py:1-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L1-L112) + +**Section Sources** + +- [frontend/antdx/actions/Index.svelte:1-77](file://frontend/antdx/actions/Index.svelte#L1-L77) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/action-item/Index.svelte:1-99](file://frontend/antdx/actions/action-item/Index.svelte#L1-L99) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [backend/modelscope_studio/components/antdx/actions/**init**.py:1-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L1-L112) + +## Core Components + +- Actions main component: Responsible for receiving items or operation items from slots, customizing dropdown menu rendering with dropdownProps, and rendering the final Ant Design X Actions on the page. +- Operation item context: Through the ItemsContext provided by createItemsContext, collects child operation items (including default slots and named slots), and supports merging and forwarding of props, slots, and children for sub-items. +- Sub-component wrappers: item and action-item wrap the "operation container" and "specific operation item" respectively, handling property forwarding, visibility control, style and ID injection, and event mapping (e.g., item_click is mapped to itemClick). + +**Section Sources** + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/action-item/Index.svelte:1-99](file://frontend/antdx/actions/action-item/Index.svelte#L1-L99) + +## Architecture Overview + +The Actions runtime flow is as follows: + +- The frontend Svelte layer dynamically imports the React wrapper actions.tsx via Index.svelte. +- actions.tsx uses context and slot utility functions to convert items and dropdownProps into the data structure required by Ant Design X. +- The backend component class declares events and slots on the Python side, forwarding extra properties and visibility information to the frontend. +- Finally, Ant Design X's Actions renders the UI and triggers callback events. + +```mermaid +sequenceDiagram +participant Py as "Backend Component Class\nAntdXActions" +participant FE_Index as "Frontend Index.svelte" +participant FE_Actions as "React Wrapper\nactions.tsx" +participant Ctx as "Items Context\ncreateItemsContext" +participant ADX as "Ant Design X Actions" +Py->>FE_Index : "Render request with properties and events" +FE_Index->>FE_Actions : "Dynamic import and forward props" +FE_Actions->>Ctx : "Read items slots and menu items" +FE_Actions->>ADX : "Generate items and dropdownProps" +ADX-->>FE_Actions : "Render result" +FE_Actions-->>FE_Index : "Return rendered node" +FE_Index-->>Py : "Render complete" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/actions/**init**.py:1-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L1-L112) +- [frontend/antdx/actions/Index.svelte:1-77](file://frontend/antdx/actions/Index.svelte#L1-L77) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +## Detailed Component Analysis + +### Actions Main Component (React Wrapper) + +- Responsibility: Integrates Ant Design X's Actions with the slot and context system, responsible for merging and rendering items and dropdownProps. +- Key points: + - Uses withItemsContextProvider and withMenuItemsContextProvider to inject items and menu item contexts. + - Converts slot content into the structure required by Ant Design X using utility functions such as renderItems, renderSlot, and renderParamsSlot. + - Conditionally merges dropdownProps, only injecting when valid values exist to avoid redundant configuration. + +```mermaid +flowchart TD +Start(["Enter Actions Wrapper"]) --> ReadItems["Read items or operation items from slots"] +ReadItems --> MergeDropdown["Merge dropdownProps\nMenu items/renderers/indicators"] +MergeDropdown --> BuildItems["Build final items using renderItems"] +BuildItems --> Render["Render Ant Design X Actions"] +Render --> End(["Complete"]) +``` + +**Diagram Sources** + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +**Section Sources** + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) + +### Operation Item Context (createItemsContext) + +- Responsibility: Provides ItemsContext for collecting and updating "operation item" data, supporting multiple slots (default and other named slots). +- Key points: + - setItem supports updating individual items by slot key and index, using an immutable update strategy internally, combined with useEffect to trigger the onChange callback. + - ItemHandler encapsulates the sub-component's props, slots, and children into a standard Item structure and writes it to the context. + - Optimizes rendering and callback overhead via useMemoizedEqualValue and useMemoizedFn. + +```mermaid +classDiagram +class ItemsContext { ++items : Record ++setItem(slotKey, index, item) ++initial : boolean +} +class ItemsContextProvider { ++allowedSlots : string[] ++onChange(items) ++children +} +class ItemHandler { ++itemIndex : number ++itemSlotKey : string ++itemProps(props, items) ++itemChildren(items) ++slots ++children +} +ItemsContextProvider --> ItemsContext : "Provides" +ItemHandler --> ItemsContext : "Writes single item" +``` + +**Diagram Sources** + +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +**Section Sources** + +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) + +### Sub-component Wrappers (item and action-item) + +- Responsibility: Wraps the "operation container" and "specific operation items", handling property forwarding, visibility control, style and ID injection, and event mapping. +- Key points: + - Index.svelte dynamically loads the corresponding React component via importComponent, ensuring on-demand loading. + - Unified handling of common properties such as additionalProps, elem\_\*, and visible. + - action-item maps the item_click event to ensure consistency with Ant Design X callback conventions. + +```mermaid +sequenceDiagram +participant Parent as "Parent Component Actions" +participant ItemWrap as "item/Index.svelte" +participant ActionWrap as "action-item/Index.svelte" +participant Child as "Child Component React Wrapper" +Parent->>ItemWrap : "Forward props and slots" +ItemWrap->>Child : "Dynamic import and render" +Parent->>ActionWrap : "Forward props and slots" +ActionWrap->>Child : "Dynamic import and render" +Child-->>Parent : "Render complete" +``` + +**Diagram Sources** + +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/action-item/Index.svelte:1-99](file://frontend/antdx/actions/action-item/Index.svelte#L1-L99) + +**Section Sources** + +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/action-item/Index.svelte:1-99](file://frontend/antdx/actions/action-item/Index.svelte#L1-L99) + +### Backend Component Class (AntdXActions) + +- Responsibility: Declares the Actions component interface, events, and slots on the Python side, responsible for forwarding extra properties and visibility information to the frontend. +- Key points: + - Defines EVENTS: click, dropdown_open_change, dropdown_menu_click, dropdown_menu_deselect, dropdown_menu_open_change, dropdown_menu_select. + - Defines SLOTS: items, dropdownProps.dropdownRender, dropdownProps.popupRender, dropdownProps.menu.expandIcon, dropdownProps.menu.overflowedIndicator, dropdownProps.menu.items. + - Provides variant, dropdown_props, fade_in, fade_in_left, and other properties for theme and animation control. + +```mermaid +classDiagram +class AntdXActions { ++EVENTS ++SLOTS ++variant ++dropdown_props ++fade_in ++fade_in_left ++additional_props ++items ++class_names ++styles ++as_item ++_internal +} +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/actions/**init**.py:1-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L1-L112) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/actions/**init**.py:1-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L1-L112) + +## Dependency Analysis + +- Frontend dependency chain: + - Index.svelte depends on actions.tsx. + - actions.tsx depends on createItemsContext, withItemsContextProvider, withMenuItemsContextProvider, renderItems, renderSlot, renderParamsSlot, createFunction. + - item/Index.svelte and action-item/Index.svelte depend on their respective React wrappers. +- Backend dependency chain: + - AntdXActions depends on the frontend directory resolution and the Gradio event system. + +```mermaid +graph LR +Py["AntdXActions\nBackend"] --> FE_Index["Index.svelte\nFrontend"] +FE_Index --> FE_Actions["actions.tsx\nFrontend"] +FE_Actions --> Ctx["createItemsContext\nUtility"] +FE_Actions --> Utils["renderItems/renderSlot/renderParamsSlot/createFunction"] +FE_Actions --> MenuCtx["withMenuItemsContextProvider"] +FE_Actions --> ItemsCtx["withItemsContextProvider"] +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/actions/**init**.py:1-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L1-L112) +- [frontend/antdx/actions/Index.svelte:1-77](file://frontend/antdx/actions/Index.svelte#L1-L77) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +**Section Sources** + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [backend/modelscope_studio/components/antdx/actions/**init**.py:1-112](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L1-L112) + +## Performance Considerations + +- On-demand loading: Index.svelte dynamically loads the React wrapper on demand via importComponent, reducing the initial bundle size. +- Immutable updates: createItemsContext uses an immutable update strategy to avoid unnecessary re-renders. +- Computation caching: actions.tsx uses useMemo to cache dropdownProps and the final items, reducing rendering costs. +- Event mapping: Converts string-form callbacks to functions via createFunction to avoid repeated binding. + +[This section contains general performance recommendations; no specific file references required] + +## Troubleshooting Guide + +- Cannot display operation items + - Check if slots are used correctly or if items are passed in; confirm that slot key names match component declarations. + - Reference: [frontend/antdx/actions/actions.tsx:31-116](file://frontend/antdx/actions/actions.tsx#L31-L116) +- Dropdown menu not working + - Confirm dropdownProps is correctly merged; check if menu items are empty. + - Reference: [frontend/antdx/actions/actions.tsx:39-96](file://frontend/antdx/actions/actions.tsx#L39-L96) +- Events not triggered + - Confirm that backend EVENTS are registered; check frontend event mapping (e.g., item_click -> itemClick). + - Reference: [backend/modelscope_studio/components/antdx/actions/**init**.py:26-46](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L26-L46) + - Reference: [frontend/antdx/actions/action-item/Index.svelte:54-57](file://frontend/antdx/actions/action-item/Index.svelte#L54-L57) + +**Section Sources** + +- [frontend/antdx/actions/actions.tsx:31-116](file://frontend/antdx/actions/actions.tsx#L31-L116) +- [backend/modelscope_studio/components/antdx/actions/**init**.py:26-46](file://backend/modelscope_studio/components/antdx/actions/__init__.py#L26-L46) +- [frontend/antdx/actions/action-item/Index.svelte:54-57](file://frontend/antdx/actions/action-item/Index.svelte#L54-L57) + +## Conclusion + +Actions plays the role of an "operation entry aggregator" in ModelScope Studio, achieving flexible, extensible, and high-performance operation list rendering through Ant Design X's powerful capabilities and slot/context mechanisms. It is suitable both for quickly building "one-click execute" functions in AI applications, and for implementing highly customized interaction experiences in complex scenarios through the slot and event system. + +[This section contains summary content; no specific file references required] + +## Appendix + +- For quick-start examples, refer to the official documentation example page. + - Reference: [docs/components/antdx/actions/README.md:1-8](file://docs/components/antdx/actions/README.md#L1-L8) + +**Section Sources** + +- [docs/components/antdx/actions/README.md:1-8](file://docs/components/antdx/actions/README.md#L1-L8) diff --git a/.wiki/en/Ant Design X Components/Feedback Components/Audio Component.md b/.wiki/en/Ant Design X Components/Feedback Components/Audio Component.md new file mode 100644 index 00000000..99771e6f --- /dev/null +++ b/.wiki/en/Ant Design X Components/Feedback Components/Audio Component.md @@ -0,0 +1,315 @@ +# Audio Component + + +**Files referenced in this document** +- [frontend/antdx/actions/audio/Index.svelte](file://frontend/antdx/actions/audio/Index.svelte) +- [frontend/antdx/actions/audio/actions.audio.tsx](file://frontend/antdx/actions/audio/actions.audio.tsx) +- [backend/modelscope_studio/components/antdx/actions/audio/__init__.py](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py) +- [frontend/pro/multimodal-input/utils.ts](file://frontend/pro/multimodal-input/utils.ts) +- [frontend/pro/multimodal-input/recorder.ts](file://frontend/pro/multimodal-input/recorder.ts) +- [frontend/antd/slider/Index.svelte](file://frontend/antd/slider/Index.svelte) +- [docs/components/pro/multimodal_input/README.md](file://docs/components/pro/multimodal_input/README.md) +- [docs/components/pro/multimodal_input/README-zh_CN.md](file://docs/components/pro/multimodal_input/README-zh_CN.md) +- [frontend/pro/multimodal-input/package.json](file://frontend/pro/multimodal-input/package.json) +- [frontend/antdx/actions/audio/package.json](file://frontend/antdx/actions/audio/package.json) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically organizes and explains the implementation and usage of the Audio component in the model library frontend, covering the following key areas: + +- Audio playback and control capabilities (play/pause/stop, progress, volume, loop) +- Audio file loading and processing (decoding, trimming, exporting) +- Recording and waveform visualization (microphone recording, waveform drawing) +- Integration practices in different business scenarios (voice broadcasting, sound effects playback, audio preview) +- Compatibility and performance optimization recommendations +- Design techniques for enhancing user experience + +## Project Structure + +Audio-related capabilities are primarily distributed in the following locations: + +- Frontend Svelte wrapper layer: Bridges Ant Design X's Actions.Audio component to the Gradio ecosystem +- Backend Python component: AntdXActionsAudio, responsible for property forwarding and rendering control +- Multimodal input Pro component: Provides recording, audio processing, and export capabilities +- General UI components: Such as Slider, for volume/progress control + +```mermaid +graph TB +subgraph "Frontend" +A["AntdX Actions.Audio Wrapper\nfrontend/antdx/actions/audio/Index.svelte"] +B["React Bridge Layer\nfrontend/antdx/actions/audio/actions.audio.tsx"] +C["Multimodal Input Utilities\nfrontend/pro/multimodal-input/utils.ts"] +D["Recording Hook\nfrontend/pro/multimodal-input/recorder.ts"] +E["Volume/Progress Slider\nfrontend/antd/slider/Index.svelte"] +end +subgraph "Backend" +F["AntdXActionsAudio Component Class\nbackend/.../antdx/actions/audio/__init__.py"] +end +A --> B +B --> F +C --> D +E --> A +``` + +**Diagram Sources** + +- [frontend/antdx/actions/audio/Index.svelte:1-59](file://frontend/antdx/actions/audio/Index.svelte#L1-L59) +- [frontend/antdx/actions/audio/actions.audio.tsx:1-17](file://frontend/antdx/actions/audio/actions.audio.tsx#L1-L17) +- [backend/modelscope_studio/components/antdx/actions/audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) +- [frontend/pro/multimodal-input/utils.ts:1-126](file://frontend/pro/multimodal-input/utils.ts#L1-L126) +- [frontend/pro/multimodal-input/recorder.ts:1-48](file://frontend/pro/multimodal-input/recorder.ts#L1-L48) +- [frontend/antd/slider/Index.svelte:62-84](file://frontend/antd/slider/Index.svelte#L62-L84) + +**Section Sources** + +- [frontend/antdx/actions/audio/Index.svelte:1-59](file://frontend/antdx/actions/audio/Index.svelte#L1-L59) +- [frontend/antdx/actions/audio/actions.audio.tsx:1-17](file://frontend/antdx/actions/audio/actions.audio.tsx#L1-L17) +- [backend/modelscope_studio/components/antdx/actions/audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) +- [frontend/pro/multimodal-input/utils.ts:1-126](file://frontend/pro/multimodal-input/utils.ts#L1-L126) +- [frontend/pro/multimodal-input/recorder.ts:1-48](file://frontend/pro/multimodal-input/recorder.ts#L1-L48) +- [frontend/antd/slider/Index.svelte:62-84](file://frontend/antd/slider/Index.svelte#L62-L84) + +## Core Components + +- AntdXActionsAudio (backend component class): Encapsulates Ant Design X's Actions.Audio, providing properties such as status, style, and visibility, and declares skip_api to directly render the frontend component. +- Actions.Audio (frontend wrapper): Bridges the React component to the Gradio ecosystem through Svelte wrapping, forwarding properties to Ant Design X's Actions.Audio. +- Audio processing utilities (Pro multimodal input): Provides capabilities for converting AudioBuffer to WAV, trimming audio by time range, decoding from Blob and exporting, etc. +- Recording Hook: Based on the record plugin for wavesurfer.js, provides recording start/end callbacks and recording state management. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/actions/audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) +- [frontend/antdx/actions/audio/actions.audio.tsx:1-17](file://frontend/antdx/actions/audio/actions.audio.tsx#L1-L17) +- [frontend/pro/multimodal-input/utils.ts:1-126](file://frontend/pro/multimodal-input/utils.ts#L1-L126) +- [frontend/pro/multimodal-input/recorder.ts:1-48](file://frontend/pro/multimodal-input/recorder.ts#L1-L48) + +## Architecture Overview + +The audio capability in the frontend bridges React components through the Svelte component; the backend passes properties to the frontend through a custom component class. It also provides recording and audio processing tools to complete the "recording → preview → export" loop in multimodal input scenarios. + +```mermaid +sequenceDiagram +participant Py as "Python Backend\nAntdXActionsAudio" +participant FE as "Frontend Wrapper\nIndex.svelte" +participant RA as "React Component\nActions.Audio" +participant AU as "Browser Audio API\nAudioContext/Web Audio API" +Py->>FE : Render component with property forwarding +FE->>RA : Pass props (status/style/visibility) +RA->>AU : Initialize audio context/load audio resources +AU-->>RA : Play/Pause/Stop/Progress/Volume/Loop +RA-->>FE : Trigger event callbacks (click, etc.) +FE-->>Py : Update state/trigger interactions +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/actions/audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) +- [frontend/antdx/actions/audio/Index.svelte:19-41](file://frontend/antdx/actions/audio/Index.svelte#L19-L41) +- [frontend/antdx/actions/audio/actions.audio.tsx:6-14](file://frontend/antdx/actions/audio/actions.audio.tsx#L6-L14) + +## Component Details + +### AntdXActionsAudio (Backend Component Class) + +- Responsibility boundary: Responsible for mapping frontend components to the Python side, providing properties such as status, style, and visibility; declares skip_api to avoid redundant processing. +- Key points: Event listener binding, property forwarding, render control. + +```mermaid +classDiagram +class AntdXActionsAudio { ++status ++additional_props ++class_names ++styles ++visible ++elem_id ++elem_classes ++elem_style ++skip_api ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/actions/audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/actions/audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) + +### Actions.Audio (Frontend Wrapper) + +- Responsibility boundary: Bridges Ant Design X's Actions.Audio to the Gradio ecosystem through Svelte wrapping, unifying properties and events. +- Key points: sveltify wrapping, slot forwarding, style and ID injection. + +```mermaid +flowchart TD +A["Index.svelte retrieves props"] --> B["processProps generates final properties"] +B --> C["Render Actions.Audio and inject styles/ID/events"] +C --> D["User interaction triggers event callbacks"] +``` + +**Diagram Sources** + +- [frontend/antdx/actions/audio/Index.svelte:19-41](file://frontend/antdx/actions/audio/Index.svelte#L19-L41) +- [frontend/antdx/actions/audio/actions.audio.tsx:6-14](file://frontend/antdx/actions/audio/actions.audio.tsx#L6-L14) + +**Section Sources** + +- [frontend/antdx/actions/audio/Index.svelte:1-59](file://frontend/antdx/actions/audio/Index.svelte#L1-L59) +- [frontend/antdx/actions/audio/actions.audio.tsx:1-17](file://frontend/antdx/actions/audio/actions.audio.tsx#L1-L17) + +### Audio Processing Utilities (Trim/Export) + +- Feature overview: Writes AudioBuffer to WAV header and PCM data; trims audio by start/end time; decodes from Blob and exports to WAV. +- Key flow: Decode → Create trimmed buffer → Write to WAV → Return binary data. + +```mermaid +flowchart TD +Start(["Start"]) --> Decode["Decode audio data\nAudioContext.decodeAudioData"] +Decode --> Trim{"Is trim range specified?"} +Trim --> |Yes| CreateBuf["Create trimmed AudioBuffer"] +Trim --> |No| KeepAll["Keep original length"] +CreateBuf --> Copy["Copy channel data to new buffer"] +KeepAll --> Copy +Copy --> ToWAV["Write WAV header and PCM data"] +ToWAV --> End(["End, return Uint8Array"]) +``` + +**Diagram Sources** + +- [frontend/pro/multimodal-input/utils.ts:1-126](file://frontend/pro/multimodal-input/utils.ts#L1-L126) + +**Section Sources** + +- [frontend/pro/multimodal-input/utils.ts:1-126](file://frontend/pro/multimodal-input/utils.ts#L1-L126) + +### Recording and Waveform Visualization + +- Recording: Based on the record plugin for wavesurfer.js, provides start/stop callbacks and recording state. +- Waveform: Initializes a WaveSurfer container and registers the record plugin to display waveforms in real time. + +```mermaid +sequenceDiagram +participant UI as "Interface" +participant WS as "WaveSurfer Instance" +participant REC as "Record Plugin" +participant CB as "Callback Function" +UI->>WS : Create instance and pass container +WS->>REC : Register record plugin +UI->>REC : Call startRecording() +REC-->>UI : Trigger record-start event +UI->>REC : Call stopRecording() +REC-->>CB : Trigger record-end and return Blob +UI-->>UI : Update recording state +``` + +**Diagram Sources** + +- [frontend/pro/multimodal-input/recorder.ts:24-41](file://frontend/pro/multimodal-input/recorder.ts#L24-L41) + +**Section Sources** + +- [frontend/pro/multimodal-input/recorder.ts:1-48](file://frontend/pro/multimodal-input/recorder.ts#L1-L48) + +### Volume/Progress Control (Slider) + +- Uses the Slider component to implement two-way control of volume and progress; the onValueChange event is used to synchronize state. +- Adapts to Gradio's property forwarding mechanism to ensure consistency with backend state. + +**Section Sources** + +- [frontend/antd/slider/Index.svelte:62-84](file://frontend/antd/slider/Index.svelte#L62-L84) + +## Dependency Analysis + +- Frontend package exports: Two key packages each export a Svelte entry point for loading by the Gradio runtime. +- Component coupling: AntdXActionsAudio and the frontend wrapper component are loosely coupled, interacting through property forwarding. +- Toolchain: Audio processing depends on the Web Audio API; recording depends on wavesurfer.js and its record plugin. + +```mermaid +graph LR +PkgA["pro/multimodal-input/package.json"] --> Utils["utils.ts\nAudio Processing"] +PkgB["antdx-actions.audio/package.json"] --> Wrap["actions.audio.tsx\nReact Wrapper"] +Wrap --> Fe["Index.svelte\nProperty Forwarding"] +Fe --> Py["AntdXActionsAudio\nBackend Component Class"] +Utils --> Recorder["recorder.ts\nRecording Hook"] +``` + +**Diagram Sources** + +- [frontend/pro/multimodal-input/package.json:1-14](file://frontend/pro/multimodal-input/package.json#L1-L14) +- [frontend/antdx/actions/audio/package.json:1-14](file://frontend/antdx/actions/audio/package.json#L1-L14) +- [frontend/pro/multimodal-input/utils.ts:1-126](file://frontend/pro/multimodal-input/utils.ts#L1-L126) +- [frontend/pro/multimodal-input/recorder.ts:1-48](file://frontend/pro/multimodal-input/recorder.ts#L1-L48) +- [frontend/antdx/actions/audio/Index.svelte:1-59](file://frontend/antdx/actions/audio/Index.svelte#L1-L59) +- [backend/modelscope_studio/components/antdx/actions/audio/**init**.py:10-71](file://backend/modelscope_studio/components/antdx/actions/audio/__init__.py#L10-L71) + +**Section Sources** + +- [frontend/pro/multimodal-input/package.json:1-14](file://frontend/pro/multimodal-input/package.json#L1-L14) +- [frontend/antdx/actions/audio/package.json:1-14](file://frontend/antdx/actions/audio/package.json#L1-L14) + +## Performance Considerations + +- Audio decoding and trimming: Prioritize browser-side processing to avoid the overhead of large file network transfers; for long audio files, consider segmented processing or deferred decoding. +- Buffer management: Copy only the necessary segments during trimming to reduce memory usage; confirm sample rate and channel count consistency before exporting. +- Recording performance: Set normalize and container size appropriately to avoid frequent redraws; be aware of background playback restrictions and permission requests on mobile devices. +- UI responsiveness: Use controlled component mode for volume/progress sliders to avoid unnecessary re-renders; use memoized functions for event callbacks to reduce jitter. + +## Troubleshooting Guide + +- Cannot play audio + - Check if the audio format is supported by the browser; try converting to common formats such as WAV/MP3. + - Confirm AudioContext initialization and permissions (some browsers require a user gesture to activate). +- No recording output + - Confirm device permissions are granted; check if the container is correctly mounted. + - Verify that the record-end callback is triggered and the Blob is not empty. +- Export failure + - Confirm the trim range is valid (start/end not out of bounds); check sample rate and channel count consistency. +- Slider not working + - Check if the onValueChange event is correctly updating state; confirm the synchronization logic between controlled value and fallback value. + +**Section Sources** + +- [frontend/pro/multimodal-input/utils.ts:60-126](file://frontend/pro/multimodal-input/utils.ts#L60-L126) +- [frontend/pro/multimodal-input/recorder.ts:24-41](file://frontend/pro/multimodal-input/recorder.ts#L24-L41) +- [frontend/antd/slider/Index.svelte:62-84](file://frontend/antd/slider/Index.svelte#L62-L84) + +## Conclusion + +The Audio component in the model library frontend implements full capabilities from playback control to recording export through a "backend component class + frontend wrapper + toolchain" approach. Combined with multimodal input scenarios, it enables quick construction of voice broadcasting, sound effects playback, and audio preview experiences. It is recommended to pay attention to format compatibility, performance optimization, and permission handling in actual projects to achieve a more stable user experience. + +## Appendix + +### Usage Examples (Scenarios) + +- Voice broadcasting + - Use AntdXActionsAudio to render a play button, control volume with Slider; trigger play/pause via event callbacks. +- Sound effects playback + - Load local sound effect files, set looping playback and volume; switch state in interaction events. +- Audio preview + - After recording, decode the Blob to an AudioBuffer, then export to WAV; play in the preview area and provide a download option. + +**Section Sources** + +- [docs/components/pro/multimodal_input/README.md:1-43](file://docs/components/pro/multimodal_input/README.md#L1-L43) +- [docs/components/pro/multimodal_input/README-zh_CN.md:1-43](file://docs/components/pro/multimodal_input/README-zh_CN.md#L1-L43) diff --git a/.wiki/en/Ant Design X Components/Feedback Components/Copy Component.md b/.wiki/en/Ant Design X Components/Feedback Components/Copy Component.md new file mode 100644 index 00000000..2bd0f88a --- /dev/null +++ b/.wiki/en/Ant Design X Components/Feedback Components/Copy Component.md @@ -0,0 +1,429 @@ +# Copy Component + + +**Files referenced in this document** +- [actions.copy.tsx](file://frontend/antdx/actions/copy/actions.copy.tsx) +- [Index.svelte](file://frontend/antdx/actions/copy/Index.svelte) +- [__init__.py](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py) +- [package.json](file://frontend/antdx/actions/copy/package.json) +- [gradio.config.js](file://frontend/antdx/actions/copy/gradio.config.js) +- [utils.ts](file://frontend/globals/components/markdown/utils.ts) +- [chatbot-footer.tsx](file://frontend/pro/chatbot/chatbot-footer.tsx) +- [utils.ts](file://frontend/pro/chatbot/utils.ts) +- [basic.py](file://docs/components/antdx/actions/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +The Copy Component is a component in ModelScope Studio for quickly configuring copy functionality, implemented based on Ant Design X's Actions.Copy. This component provides a unified copy operation interface, supporting copying of multiple data types including plain text, links, code snippets, and other common scenarios. + +The component adopts a front-end/back-end separation design pattern, with the frontend built using Svelte and the backend wrapped through Gradio components, implementing complete lifecycle management for copy functionality. + +## Project Structure + +The Copy Component is located in the Ant Design X component library with the following structure: + +```mermaid +graph TB +subgraph "Frontend Component Structure" +A[Index.svelte] --> B[actions.copy.tsx] +B --> C[Ant Design X Actions.Copy] +D[package.json] --> A +E[gradio.config.js] --> A +end +subgraph "Backend Component Structure" +F[__init__.py] --> G[ModelScopeLayoutComponent] +G --> H[Gradio Event Handling] +end +subgraph "Utility Functions" +I[utils.ts] --> J[Copy Functionality Implementation] +K[chatbot-footer.tsx] --> L[Chatbot Integration] +M[utils.ts] --> N[Message Content Processing] +end +A --> F +B --> I +L --> N +``` + +**Diagram Sources** + +- [Index.svelte:1-60](file://frontend/antdx/actions/copy/Index.svelte#L1-L60) +- [actions.copy.tsx:1-22](file://frontend/antdx/actions/copy/actions.copy.tsx#L1-L22) +- [**init**.py:1-72](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L1-L72) + +**Section Sources** + +- [Index.svelte:1-60](file://frontend/antdx/actions/copy/Index.svelte#L1-L60) +- [actions.copy.tsx:1-22](file://frontend/antdx/actions/copy/actions.copy.tsx#L1-L22) +- [**init**.py:1-72](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L1-L72) + +## Core Components + +The Copy Component consists of three main parts: + +### Frontend Component Layer + +- **Index.svelte**: The main frontend entry component, responsible for property handling and rendering logic +- **actions.copy.tsx**: React wrapper that adapts Ant Design X's Actions.Copy component to the Svelte environment + +### Backend Component Layer + +- \***\*init**.py\*\*: Python backend component definition, inheriting from ModelScopeLayoutComponent + +### Utility Function Layer + +- **utils.ts**: Provides the core implementation of copy functionality, including Clipboard API and fallback solutions + +**Section Sources** + +- [Index.svelte:19-44](file://frontend/antdx/actions/copy/Index.svelte#L19-L44) +- [actions.copy.tsx:7-19](file://frontend/antdx/actions/copy/actions.copy.tsx#L7-L19) +- [**init**.py:10-72](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L10-L72) + +## Architecture Overview + +The Copy Component adopts a layered architecture design, achieving clear separation of concerns: + +```mermaid +sequenceDiagram +participant User as User +participant Frontend as Frontend Component +participant Backend as Backend Component +participant Clipboard as Browser Clipboard +participant Utils as Utility Functions +User->>Frontend : Click copy button +Frontend->>Utils : Call copy function +Utils->>Clipboard : Write to clipboard +Clipboard-->>Utils : Return copy result +Utils-->>Frontend : Return success state +Frontend-->>User : Display feedback effect +Note over Frontend,Clipboard : Supports modern browsers and fallback solutions +``` + +**Diagram Sources** + +- [utils.ts:382-410](file://frontend/globals/components/markdown/utils.ts#L382-L410) +- [Index.svelte:46-59](file://frontend/antdx/actions/copy/Index.svelte#L46-L59) + +### Component Interaction Flow + +```mermaid +flowchart TD +Start([Component Initialization]) --> Props[Process Component Properties] +Props --> Slots[Parse Slot Content] +Slots --> Render{Component Visibility} +Render --> |Visible| Load[Load React Component] +Render --> |Not Visible| Hide[Hide Component] +Load --> Ready[Component Ready] +Ready --> Click[Wait for Click Event] +Click --> Copy[Execute Copy Operation] +Copy --> Feedback[Display Feedback Effect] +Feedback --> End([Complete]) +Hide --> End +``` + +**Diagram Sources** + +- [Index.svelte:19-44](file://frontend/antdx/actions/copy/Index.svelte#L19-L44) +- [actions.copy.tsx:8-18](file://frontend/antdx/actions/copy/actions.copy.tsx#L8-L18) + +## Detailed Component Analysis + +### Frontend Component Implementation + +#### Index.svelte Analysis + +Index.svelte is the main frontend entry for the copy component, responsible for the following key functions: + +```mermaid +classDiagram +class CopyComponent { ++props : ComponentProps ++slots : Slots ++proceedProps : ProcessedProps ++visible : boolean ++getProps() ComponentProps ++processProps() ProcessedProps ++getSlots() Slots ++render() JSX.Element +} +class ProcessProps { ++visible : boolean ++_internal : object ++as_item : string ++elem_classes : array ++elem_id : string ++elem_style : object ++restProps : object ++additionalProps : object +} +CopyComponent --> ProcessProps : Uses +``` + +**Diagram Sources** + +- [Index.svelte:12-44](file://frontend/antdx/actions/copy/Index.svelte#L12-L44) + +#### actions.copy.tsx Analysis + +actions.copy.tsx acts as a React wrapper, implementing seamless integration with Ant Design X: + +```mermaid +classDiagram +class ActionsCopyWrapper { ++slots : object ++children : any ++props : ActionsCopyProps ++sveltify() ReactComponent ++render() JSX.Element +} +class ReactSlot { ++slot : string ++render() ReactElement +} +class AntdXActionsCopy { ++text : string ++icon : string ++onClick : function ++tooltips : boolean ++onCopy : function +} +ActionsCopyWrapper --> ReactSlot : Uses +ActionsCopyWrapper --> AntdXActionsCopy : Wraps +``` + +**Diagram Sources** + +- [actions.copy.tsx:7-19](file://frontend/antdx/actions/copy/actions.copy.tsx#L7-L19) + +**Section Sources** + +- [Index.svelte:19-59](file://frontend/antdx/actions/copy/Index.svelte#L19-L59) +- [actions.copy.tsx:7-21](file://frontend/antdx/actions/copy/actions.copy.tsx#L7-L21) + +### Backend Component Implementation + +#### Python Component Analysis + +The backend component inherits from ModelScopeLayoutComponent, providing full Gradio integration: + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++visible : boolean ++elem_id : string ++elem_classes : array ++elem_style : object ++render : boolean ++preprocess() void ++postprocess() void ++example_payload() any ++example_value() any +} +class AntdXActionsCopy { ++EVENTS : array ++SLOTS : array ++text : string ++icon : string ++additional_props : object ++class_names : string|array ++styles : string|array ++skip_api : boolean ++FRONTEND_DIR : string +} +ModelScopeLayoutComponent <|-- AntdXActionsCopy : Inherits +``` + +**Diagram Sources** + +- [**init**.py:10-72](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L10-L72) + +**Section Sources** + +- [**init**.py:15-19](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L15-L19) +- [**init**.py:21-22](file://backend/modelscope_studio/components/antdx/actions/copy/__init__.py#L21-L22) + +### Copy Functionality Implementation + +#### Core Copy Logic + +The copy functionality is implemented through utility functions in utils.ts, supporting both modern browsers and legacy browsers: + +```mermaid +flowchart TD +Start([Start Copy]) --> CheckClipboard{Check Clipboard API} +CheckClipboard --> |Supported| Modern[Use navigator.clipboard] +CheckClipboard --> |Not Supported| Legacy[Use textarea fallback] +Modern --> WriteText[writeText method] +WriteText --> Success[Copy Successful] +Legacy --> CreateTextarea[Create textarea element] +CreateTextarea --> SetValue[Set text value] +SetValue --> Position[Position off-screen] +Position --> Select[Select text] +Select --> ExecCommand[Execute copy command] +ExecCommand --> RemoveTextarea[Remove textarea] +RemoveTextarea --> Success +Success --> Return[Return true] +``` + +**Diagram Sources** + +- [utils.ts:382-410](file://frontend/globals/components/markdown/utils.ts#L382-L410) + +**Section Sources** + +- [utils.ts:382-410](file://frontend/globals/components/markdown/utils.ts#L382-L410) + +## Dependency Analysis + +### Component Dependencies + +The dependency relationships of the Copy Component are relatively straightforward, primarily depending on the Ant Design X and Gradio ecosystems: + +```mermaid +graph TB +subgraph "External Dependencies" +A[@ant-design/x] --> B[Actions.Copy] +C[Gradio] --> D[Event System] +E[Svelte Preprocess React] --> F[Component Wrapper] +end +subgraph "Internal Dependencies" +G[utils.ts] --> H[Copy Functionality] +I[markdown component] --> J[Code Block Copy] +K[chatbot component] --> L[Message Copy] +end +subgraph "Copy Component" +B --> M[ActionsCopyWrapper] +F --> M +H --> M +M --> N[Index.svelte] +end +M --> O[Python Backend Component] +O --> D +``` + +**Diagram Sources** + +- [actions.copy.tsx:4](file://frontend/antdx/actions/copy/actions.copy.tsx#L4) +- [Index.svelte:10](file://frontend/antdx/actions/copy/Index.svelte#L10) + +### Version Compatibility + +Supported version requirements for the component: + +- Node.js: >= 14.0.0 +- Svelte: >= 3.0.0 +- Ant Design X: >= latest +- Gradio: >= latest + +**Section Sources** + +- [package.json:1-15](file://frontend/antdx/actions/copy/package.json#L1-L15) +- [gradio.config.js:1-4](file://frontend/antdx/actions/copy/gradio.config.js#L1-L4) + +## Performance Considerations + +### Render Optimization + +The copy component adopts a lazy loading strategy, loading React components only when needed: + +```mermaid +flowchart LR +A[Component Initialization] --> B{Check Visibility} +B --> |Not Visible| C[Return Empty Directly] +B --> |Visible| D[Async Load Component] +D --> E[Component Ready] +E --> F[Render Final Component] +``` + +**Diagram Sources** + +- [Index.svelte:46-59](file://frontend/antdx/actions/copy/Index.svelte#L46-L59) + +### Memory Management + +The component implements appropriate memory cleanup mechanisms: + +- Automatically removes event listeners +- Promptly clears temporary DOM elements +- Avoids memory leaks + +## Troubleshooting Guide + +### Common Issues and Solutions + +#### Copy Functionality Not Working + +**Problem Description**: User clicks the copy button but cannot copy to clipboard + +**Possible Causes**: + +1. Browser security policy restrictions +2. HTTPS environment issues +3. Insufficient permissions + +**Solutions**: + +1. Ensure the website is running in an HTTPS environment +2. Check browser permission settings +3. Try manually triggering the copy operation + +#### Component Rendering Anomaly + +**Problem Description**: Copy component cannot display or render normally + +**Possible Causes**: + +1. Frontend build configuration issues +2. Dependency package version conflicts +3. Slot content format errors + +**Solutions**: + +1. Check frontend build logs +2. Update dependency packages to compatible versions +3. Validate slot content format + +**Section Sources** + +- [utils.ts:382-410](file://frontend/globals/components/markdown/utils.ts#L382-L410) +- [Index.svelte:46-59](file://frontend/antdx/actions/copy/Index.svelte#L46-L59) + +## Conclusion + +The Copy Component is a well-designed general-purpose component with the following characteristics: + +### Technical Advantages + +- **Modular design**: Clear front-end/back-end separation architecture +- **Strong compatibility**: Supports multiple browser environments +- **Easy to extend**: Slot system supports flexible customization +- **Performance optimization**: Lazy loading and memory management + +### Use Cases + +- Text content copying +- Code snippet copying +- Link sharing +- File download link copying + +### Best Practices + +1. Reasonably use the slot system for customization +2. Pay attention to browser compatibility issues +3. Implement appropriate error handling mechanisms +4. Consider user experience feedback design + +This component provides a reliable copy functionality foundation for ModelScope Studio and can meet the needs of most application scenarios. diff --git a/.wiki/en/Ant Design X Components/Feedback Components/Feedback Component.md b/.wiki/en/Ant Design X Components/Feedback Components/Feedback Component.md new file mode 100644 index 00000000..32862858 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Feedback Components/Feedback Component.md @@ -0,0 +1,268 @@ +# Feedback Component + + +**Files referenced in this document** +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) +- [frontend/antdx/actions/feedback/Index.svelte](file://frontend/antdx/actions/feedback/Index.svelte) +- [frontend/antdx/actions/feedback/package.json](file://frontend/antdx/actions/feedback/package.json) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [backend/modelscope_studio/components/antdx/actions/feedback/__init__.py](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py) +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically explains the design and implementation of the Feedback component, focusing on user feedback collection, data flow, and processing mechanisms, and providing reusable usage patterns (such as satisfaction surveys, feature evaluations, issue reports, etc.). The component is based on Ant Design X's Actions.Feedback capability and achieves frontend-backend integrated integration through a Svelte wrapper layer in the Gradio ecosystem, with the following key features: + +- The frontend is exposed as a Svelte component, internally bridging a React implementation. +- The backend participates in interface rendering and event dispatching as a Gradio component. +- Supports three feedback values — "like"/"dislike"/"default" — for subsequent statistics and analysis. +- Oriented toward product improvement and user experience optimization, providing extensible feedback collection and response capabilities. + +## Project Structure + +The Feedback component is located in the frontend antdx/actions/feedback directory, and the backend is at backend/modelscope_studio/components/antdx/actions/feedback. It works in conjunction with the Actions main container component, forming a "container-sub-item" combination. + +```mermaid +graph TB +subgraph "Frontend" +A["Index.svelte\nFeedback component entry"] +B["actions.feedback.tsx\nReact bridge wrapper"] +C["actions.tsx\nActions container"] +D["context.ts\nContext provider"] +end +subgraph "Backend" +E["__init__.py\nGradio component definition"] +end +A --> B +B --> C +C --> D +A --> E +``` + +Diagram Sources + +- [frontend/antdx/actions/feedback/Index.svelte:1-62](file://frontend/antdx/actions/feedback/Index.svelte#L1-L62) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:1-16](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L1-L16) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py:25-73](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L25-L73) + +Section Sources + +- [frontend/antdx/actions/feedback/Index.svelte:1-62](file://frontend/antdx/actions/feedback/Index.svelte#L1-L62) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:1-16](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L1-L16) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py:25-73](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L25-L73) + +## Core Components + +- Frontend entry component: Index.svelte loads the feedback component on demand and injects properties and slots, supporting visibility control and style class name concatenation. +- React bridge wrapper: actions.feedback.tsx exports @ant-design/x's Actions.Feedback in Svelte form, simplifying the calling interface. +- Actions container: actions.tsx provides Actions container capabilities, responsible for unified handling of menu items, dropdown rendering, slots, and events. +- Context provider: context.ts provides the Items context, supporting the registration and rendering of Actions sub-items. +- Backend Gradio component: The feedback component backend defines basic capabilities such as properties, visibility, and styles, and declares to skip the standard API process, letting the frontend drive interactions directly. + +Section Sources + +- [frontend/antdx/actions/feedback/Index.svelte:10-61](file://frontend/antdx/actions/feedback/Index.svelte#L10-L61) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:5-13](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L5-L13) +- [frontend/antdx/actions/actions.tsx:17-120](file://frontend/antdx/actions/actions.tsx#L17-L120) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py:28-73](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L28-L73) + +## Architecture Overview + +The runtime architecture of the Feedback component is as follows: the frontend Svelte component dynamically loads the React wrapper layer via importComponent, which then calls @ant-design/x's Actions.Feedback; the backend component handles property forwarding and rendering control without participating in data API processing, with events handled by the frontend. + +```mermaid +sequenceDiagram +participant UI as "Page/Application" +participant FE_Index as "Index.svelte" +participant FE_Wrapper as "actions.feedback.tsx" +participant FE_Actions as "actions.tsx" +participant BE_Comp as "__init__.py (Backend)" +participant ADX as "@ant-design/x\nActions.Feedback" +UI->>FE_Index : Render feedback component +FE_Index->>FE_Wrapper : Dynamic import of wrapper layer +FE_Wrapper->>FE_Actions : Pass properties and slots +FE_Actions->>ADX : Render Actions.Feedback +ADX-->>UI : User interaction (like/dislike) +note over FE_Index,BE_Comp : Backend component skips API process, only handles rendering and property forwarding +``` + +Diagram Sources + +- [frontend/antdx/actions/feedback/Index.svelte:10-61](file://frontend/antdx/actions/feedback/Index.svelte#L10-L61) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:5-13](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L5-L13) +- [frontend/antdx/actions/actions.tsx:98-116](file://frontend/antdx/actions/actions.tsx#L98-L116) +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py:56-60](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L56-L60) + +## Detailed Component Analysis + +### Frontend Component Chain Analysis + +- Index.svelte + - Responsible for dynamically importing the wrapper layer, handling component property and extra property merging, and supporting forwarding of common properties such as visibility, styles, class names, and element IDs. + - Uses getSlots to retrieve slot content and renders children into the wrapper layer. +- actions.feedback.tsx + - Wraps the React component Actions.Feedback as a Svelte component via sveltify, maintaining property forwarding and event compatibility. +- actions.tsx (Actions container) + - Uniformly handles items, dropdownProps, slot rendering, and function parameterization to ensure Actions.Feedback renders correctly within the container. +- context.ts + - Provides the Items context, supporting Actions sub-item registration and rendering. + +```mermaid +flowchart TD +Start(["Enter Index.svelte"]) --> LoadWrapper["Dynamically import actions.feedback.tsx"] +LoadWrapper --> MergeProps["Merge component properties and additional properties"] +MergeProps --> VisibleCheck{"Is visible?"} +VisibleCheck --> |Yes| RenderWrapper["Render ActionsFeedback wrapper layer"] +VisibleCheck --> |No| Skip["Skip rendering"] +RenderWrapper --> PassSlots["Forward slots and children"] +PassSlots --> End(["Complete"]) +Skip --> End +``` + +Diagram Sources + +- [frontend/antdx/actions/feedback/Index.svelte:21-61](file://frontend/antdx/actions/feedback/Index.svelte#L21-L61) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:5-13](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L5-L13) + +Section Sources + +- [frontend/antdx/actions/feedback/Index.svelte:10-61](file://frontend/antdx/actions/feedback/Index.svelte#L10-L61) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:5-13](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L5-L13) +- [frontend/antdx/actions/actions.tsx:27-120](file://frontend/antdx/actions/actions.tsx#L27-L120) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) + +### Data Collection and Processing Mechanism + +- Feedback value types + - Supports three values for the value field: "like" (thumbs up), "dislike" (thumbs down), "default" (default), used to distinguish user feedback inclinations. +- Events and state + - The component itself does not execute backend API calls; interaction results are handled by the frontend. The backend component declares skip_api=True to avoid entering the standard API process. +- Slots and extensibility + - The feedback button group, custom text, or icons can be extended through the slot mechanism, combined with the Actions container to achieve richer interaction forms. + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py:30-54](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L30-L54) +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py:59-60](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L59-L60) + +### Usage Examples and Best Practices + +- Satisfaction survey + - Scenario: Provide "satisfied/dissatisfied" feedback buttons at the end of conversation records; clicking updates the metadata of the corresponding record. + - Implementation points: Use the Actions container to host feedback buttons, set value to "like"/"dislike", and combine with business state update logic. +- Feature evaluation + - Scenario: Provide a "useful/not useful" evaluation entry on feature module pages to collect feature usage feedback. + - Implementation points: Extend button text and icons through slots, combine with backend state management for statistical archiving. +- Issue reporting + - Scenario: Provide an "issue feedback" entry in error prompts or abnormal paths to guide users to provide problem descriptions. + - Implementation points: Combine form components with Actions to collect user input and context information, then submit uniformly to the issue tracking system. + +Note: The above are general usage patterns; specific implementation needs to be extended in combination with business state and backend services. + +### Analysis Methods, Statistical Display, and Response Handling + +- Analysis methods + - Aggregate statistics based on the value field (e.g., "like" percentage, "dislike" percentage). + - Perform cross-analysis combining time dimensions, session dimensions, and feature module dimensions. +- Statistical display + - The frontend can use chart components (such as bar charts, pie charts) to visually present feedback distribution. + - The backend can provide aggregation APIs that return statistical results for each dimension. +- Response handling + - For "dislike" feedback, consider triggering alerts or automatically escalating to manual customer service. + - Perform root cause analysis and repair priority sorting for high-frequency negative feedback. + +Note: The above are general analysis and processing approaches; specific implementation needs to be customized based on product requirements and data platform capabilities. + +## Dependency Analysis + +- Frontend dependencies + - @svelte-preprocess-react: Implements bridging of React components to Svelte. + - @ant-design/x: Provides the React implementation of Actions.Feedback. + - @utils/\*: Provides rendering utilities (renderItems, renderParamsSlot, createFunction) and context utilities. +- Backend dependencies + - Gradio component base class: Provides common properties such as visible, elem_id, elem_classes, and elem_style. + - Frontend directory resolution: Specifies the frontend resource path via resolve_frontend_dir. + +```mermaid +graph LR +FE_Index["Index.svelte"] --> FE_Wrapper["actions.feedback.tsx"] +FE_Wrapper --> FE_Actions["actions.tsx"] +FE_Actions --> Utils["@utils/*"] +FE_Actions --> ADX["@ant-design/x"] +BE_Init["Backend __init__.py"] --> FE_Index +``` + +Diagram Sources + +- [frontend/antdx/actions/feedback/Index.svelte:10-12](file://frontend/antdx/actions/feedback/Index.svelte#L10-L12) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L3) +- [frontend/antdx/actions/actions.tsx:1-10](file://frontend/antdx/actions/actions.tsx#L1-L10) +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L56) + +Section Sources + +- [frontend/antdx/actions/feedback/package.json:1-15](file://frontend/antdx/actions/feedback/package.json#L1-L15) +- [frontend/antdx/actions/feedback/actions.feedback.tsx:1-3](file://frontend/antdx/actions/feedback/actions.feedback.tsx#L1-L3) +- [frontend/antdx/actions/actions.tsx:1-10](file://frontend/antdx/actions/actions.tsx#L1-L10) +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L56) + +## Performance Considerations + +- On-demand loading: Index.svelte dynamically imports the wrapper layer via importComponent, reducing initial bundle size and first-screen rendering pressure. +- Property forwarding: Only necessary properties are forwarded, avoiding redundant calculations and DOM updates. +- Slot rendering: Using tools such as renderItems/renderParamsSlot ensures slot content is rendered and cloned on demand, reducing repetitive overhead. +- Event binding: The Actions container centrally handles events and rendering, avoiding event storms caused by multiple layers of nesting. + +## Troubleshooting Guide + +- Component not displayed + - Check if the visible property is true. + - Confirm whether elem_id, elem_classes, and elem_style are affecting the layout or being overridden. +- Interaction not working + - Confirm the Actions container is rendered correctly and that dropdownProps, items, and other properties are correctly passed. + - Check if slot key names match (e.g., dropdownProps.menu.items). +- Backend errors + - The backend component has skip_api=True; if API-related errors occur, check if the frontend is mistakenly using the backend API process. + - Confirm the frontend directory pointed to by FRONTEND_DIR exists and is accessible. + +Section Sources + +- [frontend/antdx/actions/feedback/Index.svelte:48-61](file://frontend/antdx/actions/feedback/Index.svelte#L48-L61) +- [frontend/antdx/actions/actions.tsx:39-96](file://frontend/antdx/actions/actions.tsx#L39-L96) +- [backend/modelscope_studio/components/antdx/actions/feedback/**init**.py:59-60](file://backend/modelscope_studio/components/antdx/actions/feedback/__init__.py#L59-L60) + +## Conclusion + +The Feedback component achieves efficient collection and extensibility of user feedback through a "Svelte entry + React wrapper + Actions container" architecture. Its design emphasizes front-backend decoupling, on-demand loading, and slot extensibility, making it suitable for satisfaction surveys, feature evaluations, issue reports, and many other scenarios. Combined with reasonable statistical analysis and response handling strategies, it can significantly improve product iteration efficiency and user experience quality. + +## Appendix + +- Component export and packaging + - In package.json, the exports mapping points both the Gradio and default entry points to the same Svelte file, facilitating loading in different environments. +- Related component index + - The backend antdx component index contains the Feedback component mapping for unified management and lookup. + +Section Sources + +- [frontend/antdx/actions/feedback/package.json:4-13](file://frontend/antdx/actions/feedback/package.json#L4-L13) +- [backend/modelscope_studio/components/antdx/**init**.py](file://backend/modelscope_studio/components/antdx/__init__.py#L5) diff --git a/.wiki/en/Ant Design X Components/Feedback Components/Feedback Components.md b/.wiki/en/Ant Design X Components/Feedback Components/Feedback Components.md new file mode 100644 index 00000000..3514d9e2 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Feedback Components/Feedback Components.md @@ -0,0 +1,340 @@ +# Feedback Components + + +**Files referenced in this document** +- [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/antdx/actions/action-item/Index.svelte](file://frontend/antdx/actions/action-item/Index.svelte) +- [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- [frontend/antdx/actions/feedback/Index.svelte](file://frontend/antdx/actions/feedback/Index.svelte) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the Ant Design X feedback component system, particularly the Actions operation list component and the ActionItem sub-component. Actions provides a unified operation entry point and feedback collection capability, supporting flexible configuration of menu items, dropdown rendering, overflow indicators, and more through slots and properties. ActionItem serves as a sub-item container, responsible for converting the subtree (default slot or sub-item slot) into structured data that can be parsed by Actions, and completing parent-child communication and state management through the context mechanism. The feedback component (ActionsFeedback) encapsulates Ant Design X's feedback capability for easy integration into conversation bubbles, message streams, and similar scenarios. + +The key value of this component system in improving user interaction experience includes: + +- Unified operation entry points and visual style, reducing cognitive load +- Flexible slot-based extensibility, supporting complex nesting and dynamic rendering +- Ensuring lifecycle and event propagation correctness for operation items through context and state management +- Embedding "feedback" capability within the operation list, improving information loop and usability + +## Project Structure + +The Ant Design X feedback components are located in the frontend directory under antdx/actions, containing the main Actions component, the ActionItem sub-component, the ActionsFeedback component, and the createItemsContext utility for building the operation item structure. + +```mermaid +graph TB +subgraph "Ant Design X Feedback Components" +A_Index["actions/Index.svelte"] +A_Tsx["actions/actions.tsx"] +A_Ctx["actions/context.ts"] +AI_Index["actions/action-item/Index.svelte"] +AI_Tsx["actions/action-item/actions.action-item.tsx"] +AF_Index["actions/feedback/Index.svelte"] +AF_Tsx["actions/feedback/actions.feedback.tsx"] +U_Ctx["utils/createItemsContext.tsx"] +end +A_Index --> A_Tsx +A_Tsx --> A_Ctx +A_Tsx --> U_Ctx +AI_Index --> AI_Tsx +AI_Tsx --> A_Ctx +AF_Index --> AF_Tsx +``` + +**Diagram Sources** + +- [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/antdx/actions/action-item/Index.svelte](file://frontend/antdx/actions/action-item/Index.svelte) +- [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- [frontend/antdx/actions/feedback/Index.svelte](file://frontend/antdx/actions/feedback/Index.svelte) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + +**Section Sources** + +- [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/antdx/actions/action-item/Index.svelte](file://frontend/antdx/actions/action-item/Index.svelte) +- [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- [frontend/antdx/actions/feedback/Index.svelte](file://frontend/antdx/actions/feedback/Index.svelte) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + +## Core Components + +- Actions main component: Responsible for receiving items or sub-items from slots, combining context and slot rendering to generate Ant Design X operation lists, and supporting advanced features like dropdown rendering and overflow indicators. +- ActionItem sub-component: Acts as a container for a single operation item, merging the default slot and sub-item slot into a unified data structure, which is collected and passed through the context. +- ActionsFeedback feedback component: A lightweight encapsulation of Ant Design X's feedback capability, enabling easy integration of feedback entry points in the interface. +- createItemsContext utility: Provides ItemsContext creation, Provider wrapping, useItems hooks, and ItemHandler components, supporting structured collection and recursive processing of operation items. + +**Section Sources** + +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + +## Architecture Overview + +The Actions rendering pipeline has two layers: + +- Svelte layer: Index.svelte is responsible for parsing properties, appending class names and IDs, handling slot mappings, and importing the React implementation on demand. +- React layer: actions.tsx converts slots and properties into the items structure required by Ant Design X, while handling advanced configurations such as dropdown menu rendering and overflow indicators. + +ActionItem's responsibility is to convert the subtree it wraps (default slot and subItems slot) into structured Item data, and write it to the parent Actions via context. + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant S as "actions/Index.svelte" +participant R as "actions/actions.tsx" +participant C as "actions/context.ts" +participant U as "utils/createItemsContext.tsx" +UI->>S : Pass properties and slots +S->>R : Import and forward props, slots, extra attributes +R->>C : Wrap with context Provider +R->>U : Use createItemsContext to collect items +R->>R : Render Ant Design X Actions +Note over R : Handle dropdownRender/popupRender/overflowedIndicator slots +``` + +**Diagram Sources** + +- [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + +## Detailed Component Analysis + +### Actions Main Component + +- Input and property handling: Uses Svelte's getProps/processProps for unified processing of visibility, element styles/class names, IDs, and extra attributes, mapping some events to the names required by Ant Design X. +- Slots and rendering: Supports children, dropdownRender, popupRender, overflowedIndicator, expandIcon, and other slots; converts slots into React-compatible render functions or nodes via renderSlot/renderParamsSlot. +- Dropdown enhancement: When dropdownProps.menu.items or a slot exists, slot-generated items take priority; also supports custom expandIcon and overflowedIndicator. +- State and events: Obtains items from context via useItems and useMenuItems to avoid redundant rendering; events such as openChange/select/deselect are forwarded to the underlying component via props. + +```mermaid +flowchart TD +Start(["Enter Actions Render"]) --> CheckVisible{"Is visible?"} +CheckVisible --> |No| End(["End"]) +CheckVisible --> |Yes| ResolveItems["Resolve items or slot sub-items"] +ResolveItems --> BuildDropdown["Build dropdownProps\nMerge slots and properties"] +BuildDropdown --> RenderX["Render Ant Design X Actions"] +RenderX --> End +``` + +**Diagram Sources** + +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) + +**Section Sources** + +- [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) + +### ActionItem Sub-Component + +- Slots and properties: Supports the actionRender slot and actionRender property, converting strings or functions into executable functions via createFunction; also retains the default slot and sub-item slot. +- Context writing: Uses ItemHandler to write the current item's props, slots, sub-items, and other structured data into the context for the parent Actions to consume. +- Sub-item selection strategy: If subItems exists, it takes priority; otherwise falls back to the default slot, forming a flexible hierarchical structure. + +```mermaid +sequenceDiagram +participant Parent as "Actions" +participant Child as "ActionItem" +participant Handler as "ItemHandler" +participant Ctx as "ItemsContext" +Parent->>Child : Pass props and slots +Child->>Handler : Wrap and set allowedSlots=['default','subItems'] +Handler->>Ctx : Write current item's props/slots/sub-items +Ctx-->>Parent : Provide items for Actions rendering +``` + +**Diagram Sources** + +- [frontend/antdx/actions/action-item/Index.svelte](file://frontend/antdx/actions/action-item/Index.svelte) +- [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + +**Section Sources** + +- [frontend/antdx/actions/action-item/Index.svelte](file://frontend/antdx/actions/action-item/Index.svelte) +- [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + +### ActionsFeedback Component + +- Role: A lightweight encapsulation of Ant Design X's Actions.Feedback, simplifying the calling interface. +- Slots and properties: Follows the same slot and property handling process as the parent layer, enabling direct use in conversation bubbles, message streams, and similar scenarios. + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant F_Index as "feedback/Index.svelte" +participant F_Tsx as "feedback/actions.feedback.tsx" +UI->>F_Index : Pass properties and slots +F_Index->>F_Tsx : Import and forward props, slots +F_Tsx-->>UI : Render Ant Design X Actions.Feedback +``` + +**Diagram Sources** + +- [frontend/antdx/actions/feedback/Index.svelte](file://frontend/antdx/actions/feedback/Index.svelte) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) + +**Section Sources** + +- [frontend/antdx/actions/feedback/Index.svelte](file://frontend/antdx/actions/feedback/Index.svelte) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) + +### Context and State Management (createItemsContext) + +- ItemsContext: Maintains the Item array under each slot, providing setItem to update items by index; the onChange callback notifies the parent of updates. +- ItemHandler: Writes the current item's props, slots, sub-items, and other structured data into the context when the component mounts; supports dynamic computation of itemProps and itemChildren. +- withItemsContextProvider: Provides an ItemsContextProvider for the subtree, allowing sub-items to continue writing their own sub-items, forming a recursive structure. + +```mermaid +classDiagram +class ItemsContextProvider { ++allowedSlots ++onChange(items) ++setItem(slotKey, index, item) +} +class ItemHandler { ++itemIndex ++itemSlotKey ++itemProps(props, items) ++itemChildren(items) ++allowedSlots +} +class ItemsContext { ++items ++setItem() ++initial +} +ItemsContextProvider --> ItemsContext : "Provides context" +ItemHandler --> ItemsContext : "Writes items" +``` + +**Diagram Sources** + +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + +**Section Sources** + +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + +## Dependency Analysis + +- Actions dependencies: + - Context: actions/context.ts and utils/createItemsContext.tsx together form the foundation for item collection and forwarding. + - Slot rendering: renderSlot/renderParamsSlot converts slots into React-executable functions or nodes. + - Ant Design X: Final rendering is handled by the Actions component from @ant-design/x. +- ActionItem dependencies: + - ItemHandler and context: Writes its own structure into the context for the parent to consume. + - Slot handling: Supports actionRender and default/sub-item slots. +- ActionsFeedback dependencies: + - Directly encapsulates Ant Design X's Actions.Feedback. + +```mermaid +graph LR +Actions["actions.tsx"] --> Ctx["actions/context.ts"] +Actions --> Utils["utils/createItemsContext.tsx"] +Actions --> ADX["@ant-design/x Actions"] +ActionItem["action-item/actions.action-item.tsx"] --> Ctx +ActionItem --> Utils +Feedback["feedback/actions.feedback.tsx"] --> ADX_F["@ant-design/x Actions.Feedback"] +``` + +**Diagram Sources** + +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) + +**Section Sources** + +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/antdx/actions/feedback/actions.feedback.tsx](file://frontend/antdx/actions/feedback/actions.feedback.tsx) + +## Performance Considerations + +- Render optimization: + - Uses useMemo to cache the result of dropdownProps construction, avoiding unnecessary re-renders. + - Only injects dropdownProps when valid values exist, reducing side effects from empty objects. +- Events and properties: + - Maps event names to the names required by underlying components via processProps, avoiding runtime conversion overhead. +- Slot handling: + - renderSlot/renderParamsSlot performs cloning and parameterized wrapping only when necessary, reducing DOM manipulation costs. +- Context writing: + - Uses useRef and isEqual to compare previous and current values, triggering setItem only when changes occur to avoid redundant writes. + +[This section contains general performance recommendations and does not analyze specific files directly] + +## Troubleshooting Guide + +- Issue: Operation items not displayed + - Troubleshooting: Confirm the visible property is true; check if items is empty; confirm slot key names match allowedSlots. + - Reference path: [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- Issue: Dropdown menu not working + - Troubleshooting: Check if dropdownProps.menu.items is passed correctly; confirm the dropdownProps.menu.items slot is being rendered. + - Reference path: [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- Issue: Sub-items not nested correctly + - Troubleshooting: Confirm the ActionItem's subItems slot is correctly named; check the ItemHandler's itemChildrenKey setting. + - Reference path: [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- Issue: Events not triggered + - Troubleshooting: Confirm event name mappings are correct; check if props are forwarded to the underlying component. + - Reference path: [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) + +**Section Sources** + +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/action-item/actions.action-item.tsx](file://frontend/antdx/actions/action-item/actions.action-item.tsx) +- [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) + +## Conclusion + +The Actions operation list component implements flexible, high-performance operation item management through a clear context and slot mechanism. ActionItem, as a sub-item container, provides stable structured data writing capability. ActionsFeedback seamlessly integrates feedback capability into the operation list. The overall design balances ease of use with extensibility and performance, significantly enhancing user interaction experience in conversation, message, and prompt scenarios. + +[This section contains summary content and does not analyze specific files directly] + +## Appendix + +- Usage examples (scenario guide) + - Feedback collection: Place ActionsFeedback in areas where user feedback needs to be collected, configuring feedback entry points through slots and properties. + - Operation execution: Configure items in Actions, combining dropdownRender/popupRender slots to customize menu appearance; handle clicks and selections through event callbacks. + - Result display: Use overflowedIndicator and expandIcon slots to control menu overflow and expand behavior, ensuring a good experience on small-screen devices. +- Best practices + - Divide slot key names reasonably to avoid conflicts; use unified naming conventions for maintainability. + - Use useMemo to cache complex calculations and reduce rendering pressure. + - Keep event handler functions stable to avoid re-renders caused by changes in function references. + +[This section contains conceptual content and does not analyze specific files directly] diff --git a/.wiki/en/Ant Design X Components/Feedback Components/Item Component.md b/.wiki/en/Ant Design X Components/Feedback Components/Item Component.md new file mode 100644 index 00000000..81b21157 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Feedback Components/Item Component.md @@ -0,0 +1,318 @@ +# Item Component + + +**Files referenced in this document** +- [frontend/antdx/actions/item/Index.svelte](file://frontend/antdx/actions/item/Index.svelte) +- [frontend/antdx/actions/item/actions.item.tsx](file://frontend/antdx/actions/item/actions.item.tsx) +- [backend/modelscope_studio/components/antdx/actions/item/__init__.py](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py) +- [frontend/antdx/actions/actions.tsx](file://frontend/antdx/actions/actions.tsx) +- [frontend/antdx/actions/context.ts](file://frontend/antdx/actions/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/antdx/actions/Index.svelte](file://frontend/antdx/actions/Index.svelte) +- [docs/components/antdx/actions/demos/basic.py](file://docs/components/antdx/actions/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the Item container (ActionItem) in the AntdX Actions component system, systematically explaining its responsibilities as an internal container within Actions, layout and style control, responsive design approach, collaboration mechanisms with sub-operation items, event forwarding and state synchronization, and providing practical recommendations and best practices for various layouts (horizontal, vertical, grid). This container plays a key role in "sub-item definition and rendering" in the overall component architecture, and is the foundational building block for constructing complex operation lists. + +## Project Structure + +- Frontend layer: The Svelte entry is responsible for property forwarding and visibility control; the React wrapper layer interfaces with Ant Design X's Actions.Item; the backend Python component handles Gradio integration and event binding. +- Utility layer: Universal items context and rendering pipeline, supporting multi-level sub-items, slots, and parameterized rendering. + +```mermaid +graph TB +subgraph "Frontend" +A["Index.svelte\nActions main entry"] +B["actions.tsx\nEncapsulates Ant Design X Actions"] +C["context.ts\nItems context"] +D["createItemsContext.tsx\nContext and ItemHandler implementation"] +E["renderItems.tsx\nRendering pipeline"] +F["item/Index.svelte\nItem container entry"] +G["item/actions.item.tsx\nReact wrapper and slot injection"] +end +subgraph "Backend" +H["backend/.../item/__init__.py\nGradio component definition and events"] +end +A --> B +B --> C +C --> D +D --> E +B --> E +F --> G +G --> |"Wraps"| B +H --> A +``` + +Diagram Sources + +- [frontend/antdx/actions/Index.svelte:1-77](file://frontend/antdx/actions/Index.svelte#L1-L77) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/item/actions.item.tsx:1-35](file://frontend/antdx/actions/item/actions.item.tsx#L1-L35) +- [backend/modelscope_studio/components/antdx/actions/item/**init**.py:1-77](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L1-L77) + +Section Sources + +- [frontend/antdx/actions/Index.svelte:1-77](file://frontend/antdx/actions/Index.svelte#L1-L77) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/antdx/actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/item/actions.item.tsx:1-35](file://frontend/antdx/actions/item/actions.item.tsx#L1-L35) +- [backend/modelscope_studio/components/antdx/actions/item/**init**.py:1-77](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L1-L77) + +## Core Components + +- Item container entry (Svelte) + - Responsible for receiving properties, extra properties, visibility, styles, and class names passed from the parent, and forwarding these to the React wrapper layer. + - Uses deferred derived computation for final properties, ensuring updates only occur when necessary. + - Supports slots and child node rendering for injecting icons, action renderers, etc. into sub-items. +- React wrapper layer (sveltify) + - Interfaces Ant Design X's Actions.Item with the slot system, supporting slots such as defaultIcon and runningIcon. + - Clones and injects Svelte slot content into corresponding positions via ReactSlot. +- Backend component (Python) + - Defines supported slots (defaultIcon, runningIcon), events (such as click), and properties (label, status, styles, etc.). + - Controls whether to skip API (skip_api) and preprocessing/postprocessing flows. + +Section Sources + +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/item/actions.item.tsx:1-35](file://frontend/antdx/actions/item/actions.item.tsx#L1-L35) +- [backend/modelscope_studio/components/antdx/actions/item/**init**.py:1-77](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L1-L77) + +## Architecture Overview + +The position of the Item container in the Actions system: as the "container" for sub-items, it is responsible for converting user-configured properties and slot content into the structure required by Ant Design X, and participates in overall rendering and event dispatching. + +```mermaid +sequenceDiagram +participant U as "User Code" +participant S as "Svelte Entry (Index.svelte)" +participant R as "React Wrapper (actions.item.tsx)" +participant A as "Ant Design X Actions.Item" +participant P as "Backend Component (__init__.py)" +U->>S : Configure ActionItem properties and slots +S->>R : Forward properties and slots +R->>A : Render and inject slots (defaultIcon/runningIcon) +A-->>U : Trigger event callbacks +U->>P : Event binding (click, etc.) +P-->>U : Event data returned +``` + +Diagram Sources + +- [frontend/antdx/actions/item/Index.svelte:1-60](file://frontend/antdx/actions/item/Index.svelte#L1-L60) +- [frontend/antdx/actions/item/actions.item.tsx:1-35](file://frontend/antdx/actions/item/actions.item.tsx#L1-L35) +- [backend/modelscope_studio/components/antdx/actions/item/**init**.py:1-77](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L1-L77) + +## Detailed Component Analysis + +### Component Relationships and Responsibilities + +- Actions main container: Responsible for aggregating sub-items, handling dropdown menus, overflow indicators, expansion icons, and other advanced capabilities. +- Item container: Responsible for rendering individual sub-items, slot injection, state (such as loading/error/running/default), and label display. +- Context and rendering pipeline: Uniformly manages item collection, sub-item tree construction, slots, and parameterized rendering. + +```mermaid +classDiagram +class ActionsMainContainer { ++Aggregate sub-items ++Handle dropdown menus ++Overflow indicators +} +class ItemContainer { ++Property forwarding ++Slot injection ++State rendering +} +class ContextAndRendering { ++Collect items ++Sub-item tree construction ++Slot/parameterized rendering +} +ActionsMainContainer --> ContextAndRendering : "Consumes" +ContextAndRendering --> ItemContainer : "Generates" +``` + +Diagram Sources + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/antdx/actions/item/actions.item.tsx:1-35](file://frontend/antdx/actions/item/actions.item.tsx#L1-L35) + +Section Sources + +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/antdx/actions/item/actions.item.tsx:1-35](file://frontend/antdx/actions/item/actions.item.tsx#L1-L35) + +### Layout Management and Style Control + +- Visibility control: Determines whether to render via the visible property, avoiding unnecessary DOM. +- Class names and IDs: elem_classes and elem_id are used for style overrides and positioning. +- Behavioral styles: elem_style is used for dynamic style injection, suitable for size and spacing adjustments in responsive scenarios. +- Container styles: In the Svelte entry, styles and class names are merged and applied to the root element, ensuring consistency with the parent layout. + +Section Sources + +- [frontend/antdx/actions/item/Index.svelte:19-60](file://frontend/antdx/actions/item/Index.svelte#L19-L60) +- [frontend/antdx/actions/Index.svelte:27-77](file://frontend/antdx/actions/Index.svelte#L27-L77) + +### Responsive Design + +- Based on Ant Design X's built-in Actions overflow and dropdown menu capabilities, the Item container can adapt to narrow screens without additional responsive logic. +- If custom responsive behavior is needed, widths and spacing can be set by breakpoints in elem_style; or layout constraints can be applied through outer containers (such as Space, Grid). + +Section Sources + +- [frontend/antdx/actions/actions.tsx:39-96](file://frontend/antdx/actions/actions.tsx#L39-L96) + +### Sub-operation Item Collaboration Mechanism + +- Slot injection: Slots such as defaultIcon and runningIcon are injected into corresponding fields of Ant Design X via ReactSlot, achieving differentiated display of icons and running state icons. +- Sub-item tree: Builds the sub-item tree through createItemsContext and renderItems, supporting nested ActionItem and subItems slots. +- Parameterized rendering: Slots can carry withParams to implement on-demand parameter-passing rendering. + +```mermaid +flowchart TD +Start(["Start"]) --> Collect["Collect slots and properties"] +Collect --> BuildTree["Build sub-item tree"] +BuildTree --> InjectSlots["Inject slots (defaultIcon/runningIcon)"] +InjectSlots --> Render["Render as Ant Design X structure"] +Render --> End(["End"]) +``` + +Diagram Sources + +- [frontend/utils/createItemsContext.tsx:190-261](file://frontend/utils/createItemsContext.tsx#L190-L261) +- [frontend/utils/renderItems.tsx:8-114](file://frontend/utils/renderItems.tsx#L8-L114) +- [frontend/antdx/actions/item/actions.item.tsx:10-32](file://frontend/antdx/actions/item/actions.item.tsx#L10-L32) + +Section Sources + +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/antdx/actions/item/actions.item.tsx:1-35](file://frontend/antdx/actions/item/actions.item.tsx#L1-L35) + +### Event Forwarding and State Synchronization + +- Event binding: The backend component declares click event listeners and enables event binding through internal flags. +- State synchronization: The Item's state (such as loading/error/running/default) is driven by backend properties; the frontend switches icons and interaction feedback according to state. +- Callback data: Key information such as keyPath and key can be obtained in event callbacks for branch processing on the business side. + +Section Sources + +- [backend/modelscope_studio/components/antdx/actions/item/**init**.py:15-19](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L15-L19) +- [docs/components/antdx/actions/demos/basic.py:7-10](file://docs/components/antdx/actions/demos/basic.py#L7-L10) + +### Complex Layout Practice Recommendations + +- Horizontal arrangement: Place multiple ActionItems directly under Actions, leveraging Ant Design X's default inline layout. +- Vertical arrangement: Control direction and alignment through outer containers (such as Flex, Space). +- Grid layout: In more complex scenarios, combine Grid or custom containers with elem_style to control column widths and spacing. +- Overflow strategy: When there are many sub-items, use Actions' dropdown menu and overflow indicator to automatically collapse items, keeping the interface tidy. + +Section Sources + +- [frontend/antdx/actions/actions.tsx:39-96](file://frontend/antdx/actions/actions.tsx#L39-L96) +- [frontend/antdx/actions/Index.svelte:27-77](file://frontend/antdx/actions/Index.svelte#L27-L77) + +## Dependency Analysis + +- Component coupling + - The Item container and the Actions main container are decoupled through context and the rendering pipeline, with dependencies arising only during the rendering phase. + - The slot system decouples slot content from the host component through ReactSlot and ContextPropsProvider. +- External dependencies + - Ant Design X: Provides the foundational capabilities of Actions and Actions.Item. + - Gradio: Backend component bridges frontend events and data flows. + +```mermaid +graph LR +Item["Item Container"] --> ADX["Ant Design X"] +Item --> Slots["Slot System"] +ADX --> Events["Event System"] +Slots --> Params["Parameterized Rendering"] +Events --> Backend["Backend Component"] +``` + +Diagram Sources + +- [frontend/antdx/actions/item/actions.item.tsx:10-32](file://frontend/antdx/actions/item/actions.item.tsx#L10-L32) +- [frontend/antdx/actions/actions.tsx:39-96](file://frontend/antdx/actions/actions.tsx#L39-L96) +- [backend/modelscope_studio/components/antdx/actions/item/**init**.py:15-19](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L15-L19) + +Section Sources + +- [frontend/antdx/actions/item/actions.item.tsx:1-35](file://frontend/antdx/actions/item/actions.item.tsx#L1-L35) +- [frontend/antdx/actions/actions.tsx:1-123](file://frontend/antdx/actions/actions.tsx#L1-L123) +- [backend/modelscope_studio/components/antdx/actions/item/**init**.py:1-77](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L1-L77) + +## Performance Considerations + +- Render optimization + - Uses deferred derived ($derived) and useMemo strategies to eliminate unnecessary re-renders. + - Controls cloning strategy through renderItems' clone/forceClone to reduce redundant rendering costs. +- Events and state + - Event binding is enabled only when needed, avoiding overhead from global listeners. + - State transitions (such as loading/error/running/default) are driven by properties as much as possible to reduce side effects. + +Section Sources + +- [frontend/antdx/actions/item/Index.svelte:19-41](file://frontend/antdx/actions/item/Index.svelte#L19-L41) +- [frontend/antdx/actions/actions.tsx:104-113](file://frontend/antdx/actions/actions.tsx#L104-L113) +- [frontend/utils/renderItems.tsx:8-114](file://frontend/utils/renderItems.tsx#L8-L114) + +## Troubleshooting Guide + +- Slot not working + - Check if slot key names are correct (e.g., defaultIcon, runningIcon). + - Confirm that slot content is a valid element or configuration object. +- Icons not displaying + - Ensure slot content is correctly injected via ReactSlot. + - Check if the corresponding Ant Design X field is being overridden. +- Events not triggered + - Confirm the backend component has declared the corresponding events (such as click). + - Check if event binding is enabled (the \_internal flag). +- Sub-items not displaying + - Check the visible property and rendering conditions. + - Confirm the items context is correctly collected and forwarded. + +Section Sources + +- [frontend/antdx/actions/item/actions.item.tsx:15-28](file://frontend/antdx/actions/item/actions.item.tsx#L15-L28) +- [backend/modelscope_studio/components/antdx/actions/item/**init**.py:15-19](file://backend/modelscope_studio/components/antdx/actions/item/__init__.py#L15-L19) +- [frontend/antdx/actions/item/Index.svelte:46-59](file://frontend/antdx/actions/item/Index.svelte#L46-L59) + +## Conclusion + +The Item container plays the core role of "sub-item definition and rendering" in the Actions system. Through the slot system and context rendering pipeline, it converts user configuration into the data structure required by Ant Design X, and collaborates with the event system to complete state synchronization and interaction feedback. With its decoupled design and flexible slot mechanism, developers can easily implement operation list layouts ranging from simple to complex, and achieve good compatibility in responsive scenarios. + +## Appendix + +- Usage example reference: Demonstrates how to add ActionItem in Actions and inject icons and action renderers through slots, while binding click events and sub-item deletion events. + +Section Sources + +- [docs/components/antdx/actions/demos/basic.py:17-53](file://docs/components/antdx/actions/demos/basic.py#L17-L53) diff --git a/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble Chat Bubble.md b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble Chat Bubble.md new file mode 100644 index 00000000..b32c20e5 --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble Chat Bubble.md @@ -0,0 +1,227 @@ +# Bubble Chat Bubble + + +**Files referenced in this document** +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [frontend/antdx/bubble/list/bubble.list.tsx](file://frontend/antdx/bubble/list/bubble.list.tsx) +- [frontend/antdx/bubble/list/item/bubble.list.item.tsx](file://frontend/antdx/bubble/list/item/bubble.list.item.tsx) +- [frontend/antdx/bubble/list/role/bubble.list.role.tsx](file://frontend/antdx/bubble/list/role/bubble.list.role.tsx) +- [frontend/antdx/bubble/list/context.ts](file://frontend/antdx/bubble/list/context.ts) +- [frontend/antdx/bubble/list/utils.tsx](file://frontend/antdx/bubble/list/utils.tsx) +- [frontend/utils/patchSlots.ts](file://frontend/utils/patchSlots.ts) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) + + +## Update Summary + +**Changes Made** + +- Updated performance optimization for Bubble component slot handling logic +- Removed unused unshift behavior to improve rendering performance +- Enhanced technical documentation for the slot patching mechanism + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance and Maintainability](#performance-and-maintainability) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document covers the Bubble chat bubble component system, outlining its overall architecture, core capabilities, and usage, including: + +- Bubble component rendering mechanism and slot/functional content adaptation +- BubbleList message display logic and role distribution +- BubbleListItem rendering rules and context injection +- BubbleListRole usage and dynamic assembly +- Divider component role in conversations and use cases +- Style customization, event handling, and best practices + +## Project Structure + +The Bubble component resides in the frontend antdx sub-package, using a Svelte wrapper to bridge @ant-design/x native components, with list rendering, role assignment, and slot rendering via contexts and utility functions. + +```mermaid +graph TB +subgraph "Bubble Frontend Implementation" +A["bubble.tsx
Exports Bubble Component"] +B["list/bubble.list.tsx
Exports BubbleList Component"] +C["list/item/bubble.list.item.tsx
Exports BubbleListItem Component"] +D["list/role/bubble.list.role.tsx
Exports BubbleListRole Component"] +E["list/context.ts
Items/Role Context"] +F["list/utils.tsx
useRole Utility and Slot Patching"] +G["utils/patchSlots.ts
Slot Patch Enhancement"] +H["utils/renderItems.tsx
Slot Rendering and Argument Passing"] +end +A --> |"Wraps and forwards props/slots"| X["@ant-design/x Bubble"] +B --> |"Combines Items/Role context"| X +C --> |"Injects ItemHandler"| X +D --> |"Injects RoleItemHandler"| X +E --> |"Provides useItems/useRoleItems"| B +F --> |"Computes role mapping/slot patches"| B +G --> |"Enhances slot patching"| F +H --> |"Normalizes slot rendering"| B +``` + +**Diagram Sources** + +- [frontend/antdx/bubble/bubble.tsx:1-120](file://frontend/antdx/bubble/bubble.tsx#L1-L120) +- [frontend/antdx/bubble/list/bubble.list.tsx:1-50](file://frontend/antdx/bubble/list/bubble.list.tsx#L1-L50) +- [frontend/antdx/bubble/list/item/bubble.list.item.tsx:1-14](file://frontend/antdx/bubble/list/item/bubble.list.item.tsx#L1-L14) +- [frontend/antdx/bubble/list/role/bubble.list.role.tsx:1-14](file://frontend/antdx/bubble/list/role/bubble.list.role.tsx#L1-L14) +- [frontend/antdx/bubble/list/context.ts:1-13](file://frontend/antdx/bubble/list/context.ts#L1-L13) +- [frontend/antdx/bubble/list/utils.tsx:1-135](file://frontend/antdx/bubble/list/utils.tsx#L1-L135) +- [frontend/utils/patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) + +## Core Components + +- **Bubble**: A Svelte wrapper around @ant-design/x's Bubble, supporting unified rendering of slots and functional props, compatible with editable text slots. +- **BubbleList**: List container responsible for merging external items and slot items, injecting role context, and delegating rendering to @ant-design/x's List. +- **BubbleListItem**: Message item wrapper that injects context via ItemHandler, enabling individual Bubbles to be aware of the list environment. +- **BubbleListRole**: Role item wrapper that injects role context via RoleItemHandler, allowing role configurations to be resolved by useRole. +- **useRole**: Core role resolution utility that supports default keys, pre-processing, post-processing, and slot patching, converting role mappings to the RoleType required by @ant-design/x. + +## Architecture Overview + +The Bubble system uses a "wrapper + context + utility functions" core design, bridging @ant-design/x's native capabilities with Gradio-style slots/functional props to form an extensible, role-based message list. + +```mermaid +sequenceDiagram +participant U as "Caller" +participant BL as "BubbleList" +participant Ctx as "Context (Items/Role)" +participant UR as "useRole Utility" +participant PS as "patchSlots Enhancement" +participant XBL as "@ant-design/x List" +participant BI as "BubbleListItem/BubbleListRole" +U->>BL : Provides items or slot items +BL->>Ctx : Injects Items/Role context +BL->>UR : Computes role mapping and slot patches +UR->>PS : Applies slot patch enhancement +PS-->>UR : Returns enhanced patches +UR-->>BL : Returns RoleType +BL->>XBL : Renders list with role +loop For each message +XBL->>BI : Renders message item +BI-->>XBL : Passes Bubble props/slots +end +``` + +## Component Details + +### Bubble Component + +- **Purpose**: Svelte wrapper around @ant-design/x's Bubble, handling slots and functional props uniformly, supporting editable text slots. +- **Key Points**: + - Slot-first: When a corresponding slot exists, it takes priority over attribute values or functions. + - Editable mode: Supports custom "OK/Cancel" text via editable configuration combined with slots. + - Functional props: Uses `useFunction` to convert passed functions into renderable React components. + - Hidden children: Puts children in an invisible container to avoid duplicate rendering. + +```mermaid +flowchart TD +Start(["Enter Bubble Rendering"]) --> CheckEditable["Detect editable config and slots"] +CheckEditable --> BuildEditable{"Editable enabled?"} +BuildEditable --> |Yes| MergeEditable["Merge slots and config"] +BuildEditable --> |No| PassEditable["Pass through editable"] +MergeEditable --> ResolveSlots["Resolve header/footer/avatar/extra/content/loadingRender/contentRender"] +PassEditable --> ResolveSlots +ResolveSlots --> RenderX["Render @ant-design/x Bubble"] +RenderX --> End(["Done"]) +``` + +### BubbleList Component + +- **Purpose**: Message list container responsible for: + - Merging external items with slot items + - Injecting Items and Role contexts + - Resolving role mappings via useRole + - Delegating final rendering to @ant-design/x List +- **Key Points**: + - Prioritizes `props.items`; falls back to slot items/default + - Normalizes slot content to arrays via `renderItems` + - Caches items with `useMemo` to reduce re-renders + +### BubbleListItem and BubbleListRole + +- **BubbleListItem**: Injects ItemHandler into a Bubble, giving individual message items list context awareness. +- **BubbleListRole**: Injects RoleItemHandler into role configuration, enabling role items to be resolved to RoleType by useRole. + +### useRole - Role Resolution Utility + +- **Purpose**: Converts role configuration (string, function, or object) to the RoleType required by @ant-design/x, with slot patching and index injection. +- **Key Points**: + - Supports `defaultRoleKeys` + - Supports `preProcess` and `defaultRolePostProcess` hooks + - Automatically patches header/footer/avatar/extra/loadingRender/contentRender slots + - Default `contentRender` serializes objects to strings + +### Divider Component + +- **Purpose**: Inserts dividers between chat bubbles for visual segmentation and rhythm control. +- **Use Cases**: Multi-turn conversations, modular display, time/topic transition hints. +- Note: Divider is a standalone component, typically used alongside BubbleList, controlled via slots or layout. + +## Dependency Analysis + +- **Component coupling**: + - Bubble acts only as a wrapper, depending on @ant-design/x's native capabilities, making it easy to upgrade or replace. + - BubbleList depends on context and utility functions with clear responsibilities, centralized in useRole and renderItems. +- **Context and utilities**: + - `createItemsContext` provides two context sets (Items/Role) for list items and role items respectively. + - `useRole` is the core of role resolution, handling the conversion from configuration to rendering parameters. + - `patchSlots` provides slot patching enhancement, supporting argument passing and function composition. +- **External dependencies**: + - @ant-design/x: Provides Bubble/List/Role types and rendering capabilities + - @svelte-preprocess-react: Bridges Svelte and React slots + - @utils/\*: Provides rendering and function encapsulation utilities + +## Performance and Maintainability + +- **Performance optimization**: + - Use `useMemo` to cache BubbleList's items to avoid unnecessary re-renders. + - Set appropriate dependency arrays in `useRole` to avoid recomputing role mappings. + - Break large slot content into reusable components to reduce closure and object creation. + - **Optimization**: Removed unused unshift behavior, reducing unnecessary argument reorganization overhead. +- **Maintainability**: + - Centralize role configuration management to avoid scattering across templates. + - Use preProcess/postProcess hooks to unify message preprocessing and postprocessing. + - Maintain consistent slot naming conventions for team collaboration and documentation. + +## Troubleshooting Guide + +- **Slots not working** + - Check slot names against component conventions (e.g., avatar/header/footer/extra/content) + - Ensure Bubble/BubbleList correctly wraps the slots +- **Role configuration invalid** + - Confirm BubbleListRole correctly injects RoleItemHandler + - Check useRole's defaultRoleKeys and preProcess/postProcess are working as expected +- **Editable text not showing** + - Confirm both editable config and slots exist; slots take priority + - Check that editable.okText/editable.cancelText slots are correctly passed +- **List rendering issues** + - Confirm BubbleListItem correctly injects ItemHandler + - Check that items and slot items data structures match requirements + +## Conclusion + +The Bubble chat bubble component system uses "wrapper + context + utility functions" as its core design, preserving @ant-design/x's powerful capabilities while providing flexible slot and role-based extensions. Through the collaboration of BubbleList, BubbleListItem, BubbleListRole, and useRole, developers can quickly build complex, customizable conversation interfaces with good balance between style, interaction, and maintainability. + +## Appendix: Usage Examples and Best Practices + +- **Basic chat bubble**: Use Bubble component for message content, pass text/rich content via content slot or prop; add avatar, title, action area, and extra info via avatar/header/footer/extra slots. +- **Complex message formats**: Use contentRender objects/arrays for structured rendering; handle message fields and styles uniformly via preProcess/postProcess hooks. +- **Custom styles**: Configure different roles via role mapping combined with slot patches; use Divider at key points to improve readability. +- **Best practices**: + - Centralize role configuration management + - Use `useMemo` to cache items and role mappings + - Maintain consistent slot naming conventions + - Use patchSlots enhancements wisely when passing slot arguments diff --git a/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble Component Overview.md b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble Component Overview.md new file mode 100644 index 00000000..b3002521 --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble Component Overview.md @@ -0,0 +1,188 @@ +# Bubble Component Overview + + +**Files referenced in this document** +- [frontend/antdx/bubble/Index.svelte](file://frontend/antdx/bubble/Index.svelte) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [frontend/antdx/bubble/list/Index.svelte](file://frontend/antdx/bubble/list/Index.svelte) +- [frontend/antdx/bubble/list/bubble.list.tsx](file://frontend/antdx/bubble/list/bubble.list.tsx) +- [frontend/antdx/bubble/system/Index.svelte](file://frontend/antdx/bubble/system/Index.svelte) +- [frontend/antdx/bubble/system/bubble.system.tsx](file://frontend/antdx/bubble/system/bubble.system.tsx) +- [frontend/antdx/bubble/divider/Index.svelte](file://frontend/antdx/bubble/divider/Index.svelte) +- [frontend/antdx/bubble/divider/bubble.divider.tsx](file://frontend/antdx/bubble/divider/bubble.divider.tsx) +- [backend/modelscope_studio/components/antdx/bubble/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/__init__.py) +- [backend/modelscope_studio/components/antdx/bubble/list/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/list/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +Bubble is a visual chat bubble component designed for machine learning conversation scenarios, built on Ant Design X's Bubble capabilities. It provides message bubble rendering, editing, typing animation, content distribution, and more, with a seamless frontend-backend development experience through the Gradio/ModelScope ecosystem. The component family includes single bubbles, bubble lists, system message dividers, and system-type bubbles, covering conversation patterns from basic display to complex interactions. + +## Project Structure + +The Bubble component consists of a frontend Svelte wrapper layer and a backend Python component layer, using a dual-layer design of "frontend React component + backend Gradio component" to ensure declarative usage of Ant Design X capabilities in Python environments. + +```mermaid +graph TB +subgraph "Frontend Svelte Layer" +A["Index.svelte
Wrapper Entry"] +B["bubble.tsx
Sveltify Wrapper"] +C["list/Index.svelte
List Wrapper"] +D["list/bubble.list.tsx
List Implementation"] +E["system/Index.svelte
System Bubble Wrapper"] +F["system/bubble.system.tsx
System Bubble Implementation"] +G["divider/Index.svelte
Divider Wrapper"] +H["divider/bubble.divider.tsx
Divider Implementation"] +end +subgraph "Backend Python Layer" +P1["antdx/bubble/__init__.py
Main Component Class"] +P2["antdx/bubble/list/__init__.py
List Component Class"] +end +A --> B +C --> D +E --> F +G --> H +P1 --> A +P2 --> C +``` + +## Core Components + +- **Single Bubble Component**: Renders a single message bubble, supporting avatar, title, content, extra actions, footer, loading/content custom rendering, editable mode, and typing animation. +- **Bubble List Component**: Hosts multiple bubbles, supporting role grouping, auto-scrolling, and injecting items/role via slots. +- **System Bubble Component**: Renders system prompts or status information, emphasizing semantic display. +- **Divider Component**: Inserts separation prompts in conversations, such as timestamps or session transition hints. + +## Architecture Overview + +The Bubble component uses a three-layer architecture of "Svelte wrapper + Ant Design X React component + Gradio/ModelScope backend bridge". The frontend implements on-demand loading via Svelte's `importComponent`, bridging React components to Svelte using `sveltify`; the backend abstracts via `ModelScopeLayoutComponent` to uniformly handle event binding, slot mapping, and property forwarding. + +```mermaid +sequenceDiagram +participant Py as "Python Backend Component" +participant Svelte as "Svelte Wrapper" +participant React as "Ant Design X React Component" +participant User as "Caller" +User->>Py : Initialize component params and events +Py->>Svelte : Render frontend wrapper +Svelte->>Svelte : importComponent dynamic import +Svelte->>React : Pass props and slots +React-->>Svelte : Render result +Svelte-->>User : Output final DOM +``` + +## Detailed Component Analysis + +### Single Bubble Component (Bubble) + +- **Design Philosophy**: Based on Ant Design X's Bubble as core, providing rich slot and callback extension points for diverse needs: avatar, title, content, action area, loading state, and editing state. +- **Key Features**: + - Slot system: avatar, content, header, footer, extra, loadingRender, contentRender, editable.okText, editable.cancelText. + - Edit capability: Supports editable boolean switch and configuration object, with custom text and rendering via slots. + - Typing animation: `typing` supports boolean and configuration objects, with `typingComplete` event for animation lifecycle management. + - Custom rendering: loadingRender and contentRender support function or slot injection for flexible loading and content rendering control. + - Avatar and extra areas: avatar and extra support functions or slots for extending icons, action buttons, etc. + +```mermaid +flowchart TD +Start(["Enter Bubble Rendering"]) --> CheckEditable{"Is editing enabled?"} +CheckEditable --> |Yes| MergeEditable["Merge editable config and slots"] +CheckEditable --> |No| PassEditable["Pass through editable"] +MergeEditable --> RenderAvatar{"Avatar slot exists?"} +PassEditable --> RenderAvatar +RenderAvatar --> |Yes| SlotAvatar["Render avatar slot"] +RenderAvatar --> |No| FuncAvatar["Render avatar function/prop"] +FuncAvatar --> RenderHeader{"Header slot exists?"} +SlotAvatar --> RenderHeader +RenderHeader --> |Yes| SlotHeader["Render header slot"] +RenderHeader --> |No| FuncHeader["Render header function/prop"] +FuncHeader --> RenderContent{"Content slot exists?"} +SlotHeader --> RenderContent +RenderContent --> |Yes| SlotContent["Render content slot"] +RenderContent --> |No| TextContent["Render text content"] +TextContent --> RenderFooter{"Footer slot exists?"} +SlotContent --> RenderFooter +RenderFooter --> |Yes| SlotFooter["Render footer slot"] +RenderFooter --> |No| FuncFooter["Render footer function/prop"] +FuncFooter --> End(["Render complete"]) +``` + +### Bubble List Component (BubbleList) + +- **Design Philosophy**: Builds on the single bubble to provide batch rendering and role grouping for multi-turn conversations and history message lists. +- **Key Features**: + - Role grouping: Define display strategies for different roles (user, system, assistant) via role slot or prop. + - Slot items/default: Support injecting list items via slots or passing items array directly. + - Auto-scroll: Configurable auto-scroll to latest message for better user experience. + - Context injection: Parse slots and defaults via `useItems` and `useRole` for flexibility and consistency. + +### System Bubble Component (BubbleSystem) + +- **Design Philosophy**: Used to display system-level prompts or status information, emphasizing semantic consistency, commonly used for "system notifications", "session start", "model switch" scenarios. +- **Key Features**: + - Content slot: The `content` slot takes priority over the content property for dynamic rendering. + - Semantic display: Based on Ant Design X's System type, maintaining consistent style and behavior. + +### Divider Component (BubbleDivider) + +- **Design Philosophy**: Inserts separation prompts in conversations such as timestamps or session transitions, helping users understand conversation structure. +- **Key Features**: + - Content slot: The `content` slot takes priority over the content property. + - Semantic separation: Based on Ant Design X's Divider type, maintaining consistent visual and interaction behavior. + +## Dependency Analysis + +- **Frontend dependencies**: + - @svelte-preprocess-react: Provides importComponent, processProps, slot context capabilities for Svelte-React bridging. + - @ant-design/x: Provides core components and type definitions for Bubble, List, System, Divider. + - @utils/\*: Provides utilities for useFunction, renderParamsSlot, renderItems, context Providers. +- **Backend dependencies**: + - ModelScopeLayoutComponent: Unified abstraction for frontend component rendering, event binding, and property forwarding. + - Gradio event system: Event bindings for typing, typing_complete, edit_confirm, edit_cancel. + +## Performance Considerations + +- **On-demand loading**: Frontend uses `importComponent` for dynamic imports to avoid large initial bundles and improve first-screen performance. +- **Slot and function rendering**: Use slots and function rendering judiciously to reduce unnecessary re-renders; use stable function references for contentRender/loadingRender. +- **List optimization**: BubbleList uses `useMemo` and `renderItems` to ensure only necessary parts are recalculated on items change; use `auto_scroll` cautiously with large datasets. +- **Event binding**: Events like typing_complete, edit_confirm, edit_cancel should only be bound when needed. + +## Troubleshooting Guide + +- **Slots not working**: Check slot names (avatar, content, header, footer, extra, loadingRender, contentRender, editable.okText, editable.cancelText). Slots take priority over props. +- **Editing not working**: Confirm editable is a boolean or config object, with cancelText/okText slots or props. Check edit_confirm and edit_cancel event binding. +- **Typing animation issues**: Confirm typing is a boolean or config object. Without typing, typing_complete fires immediately after render. +- **List scrolling problems**: Check if auto_scroll is enabled; consider delay or throttle for large message sets. +- **Style and theme conflicts**: Use root_class_name or class_names/styles for custom styles; ensure compatibility with Ant Design X theme variables. + +## Conclusion + +The Bubble component family, based on Ant Design X and combined with Svelte and Gradio/ModelScope ecosystem capabilities, provides a complete solution from single messages to multi-turn conversation lists. Its slot-based design and event system enable flexible presentation of different types of prompts and messages in machine learning conversation scenarios while maintaining good performance and maintainability. + +## Appendix + +### Basic Usage Examples + +- **Single bubble**: Set content text or inject complex content via content slot. For editing, set `editable` and provide editable.okText/editable.cancelText. For typing animation, set `typing` and listen for `typing_complete`. +- **Bubble list**: Pass message arrays via items/default slots or items prop. Define role grouping via role slot or prop. Enable `auto_scroll` for automatic scrolling. +- **System bubble and divider**: Use System component for system prompts; use Divider for separation hints. Both support content slot priority strategy. + +### Best Practices + +- Prefer slots over inline strings for better maintainability and testability. +- Use memoization for frequently changing content to reduce re-renders. +- In dense conversation scenarios, control auto-scroll and animation effects to avoid performance issues. +- Use root_class_name/class_names/styles for theme customization, ensuring consistency with the overall design. diff --git a/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Divider Component.md b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Divider Component.md new file mode 100644 index 00000000..daa008ea --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Divider Component.md @@ -0,0 +1,80 @@ +# Bubble.Divider Component + + +**Files referenced in this document** +- [frontend/antdx/bubble/divider/Index.svelte](file://frontend/antdx/bubble/divider/Index.svelte) +- [frontend/antdx/bubble/divider/bubble.divider.tsx](file://frontend/antdx/bubble/divider/bubble.divider.tsx) +- [backend/modelscope_studio/components/antdx/bubble/divider/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/divider/__init__.py) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) + + +## Introduction + +Bubble.Divider is a time separator and content partition component within the chat bubble system, used to clearly divide different time periods or logical blocks in long conversations, improving readability and user experience. It is built on Ant Design X's Bubble.Divider capabilities, supports custom title/label via content slots, and provides visibility control and style forwarding. + +## Project Structure + +Bubble.Divider resides within the antdx bubble system, using a layered design of "backend Python component + frontend Svelte wrapper + React component bridge": + +- Backend component: Responsible for property definitions, visibility and style forwarding, and lifecycle hooks (such as preprocessing/postprocessing) +- Frontend wrapper: Svelte component handles on-demand loading, property merging, class name and style injection, slot rendering +- React component bridge: Exposes Ant Design X's Bubble.Divider capability in Svelte form + +```mermaid +graph TB +subgraph "Backend" +PY["Python Component
antdx.bubble.divider.__init__.py"] +end +subgraph "Frontend Wrapper Layer" +IDX["Svelte Wrapper
bubble.divider/Index.svelte"] +end +subgraph "React Bridge Layer" +BD["React Component Bridge
bubble.divider.tsx"] +XBD["Ant Design X Bubble.Divider"] +end +PY --> IDX +IDX --> BD +BD --> XBD +``` + +## Core Component + +Bubble.Divider wraps Ant Design X's Bubble.Divider component, providing: + +- Content slot (`content`): Displays text labels or custom content in the divider +- Visibility control (`visible`): Show/hide the divider via backend configuration +- Style injection: Supports `elem_id`, `elem_classes`, `elem_style`, and `additional_props` + +## Rendering Flow + +```mermaid +flowchart TD +Enter(["Enter Divider Rendering"]) --> HasSlot{"Content slot exists?"} +HasSlot --> |Yes| RenderSlot["Render slot content"] +HasSlot --> |No| RenderProp["Render prop content"] +RenderSlot --> Done(["Render complete"]) +RenderProp --> Done +``` + +## Usage + +- **Time divider**: Insert time labels in conversation lists to help users understand temporal structure of the conversation. +- **Topic divider**: Separate content blocks between different topics or sessions for clearer navigation. +- **Status divider**: Display status changes (e.g., session start, model switch notifications) as divider content. + +## Configuration Options + +| Property | Description | +| ------------------ | -------------------------------- | +| `content` | Divider content (string or slot) | +| `visible` | Whether to render the divider | +| `elem_id` | Element ID | +| `elem_classes` | Element CSS classes | +| `elem_style` | Inline element styles | +| `additional_props` | Additional property set | + +## Best Practices + +- Prefer the `content` slot for flexibility over plain string props. +- Keep divider content concise and consistent for better visual rhythm. +- Use `elem_id` / `elem_classes` for precise style control, avoiding global pollution. diff --git a/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Item Component.md b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Item Component.md new file mode 100644 index 00000000..3306d05a --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Item Component.md @@ -0,0 +1,80 @@ +# Bubble.Item Component + + +**Files referenced in this document** +- [frontend/antdx/bubble/list/item/Item.svelte](file://frontend/antdx/bubble/list/item/Item.svelte) +- [frontend/antdx/bubble/list/item/bubble.list.item.tsx](file://frontend/antdx/bubble/list/item/bubble.list.item.tsx) +- [frontend/antdx/bubble/bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [frontend/antdx/bubble/list/bubble.list.tsx](file://frontend/antdx/bubble/list/bubble.list.tsx) +- [frontend/antdx/bubble/list/context.ts](file://frontend/antdx/bubble/list/context.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + + +## Introduction + +Bubble.Item is a message item wrapper component within the Bubble.List system. It injects the item context via `ItemHandler`, enabling individual message items to participate in the list rendering lifecycle. When used as a child of BubbleList, Bubble.Item passes its properties and slots to the parent list for unified rendering. + +## Architecture + +```mermaid +classDiagram +class BubbleListItem { ++props : BubbleProps and ItemHandlerProps ++render() : ReactNode +} +class ItemHandler { ++setItem(key, props, slots) ++collectProps() ++collectSlots() +} +class ItemsContext { ++items : map[] ++setItem() +} +BubbleListItem --> ItemHandler : "Injects" +ItemHandler --> ItemsContext : "Writes item" +``` + +## Key Design Points + +- **ItemHandler injection**: Bubble.Item wraps ItemHandler, writing its own props/slots/children to ItemsContext for the parent BubbleList to consume and render. +- **Context communication**: Data flows from Bubble.Item → ItemHandler → ItemsContext → BubbleList rendering, ensuring full decoupling. +- **Slot support**: Supports all Bubble slots: avatar, header, footer, extra, content, loadingRender, contentRender. + +## Data Flow + +```mermaid +sequenceDiagram +participant Item as "Bubble.Item" +participant Handler as "ItemHandler" +participant Ctx as "ItemsContext" +participant List as "BubbleList" +Item->>Handler : Pass props and slots +Handler->>Ctx : Write item data +List->>Ctx : Read items +Ctx-->>List : Return items array +List->>List : Render via @ant-design/x List +``` + +## Configuration + +Bubble.Item accepts all Bubble component properties and additionally: + +- **Slot support**: All Bubble slots (avatar, header, footer, extra, content, loadingRender, contentRender) +- **List context**: Automatically participates in parent list context when used as a child of BubbleList + +## Usage Example + +```python +import modelscope_studio as mgr + +with mgr.antdx.Bubble.List(): + mgr.antdx.Bubble.Item(content="Hello, how can I help you?") + mgr.antdx.Bubble.Item(content="I need assistance with deployment.") +``` + +## Troubleshooting + +- **Item not showing**: Check that `visible` is truthy and that Bubble.Item is correctly wrapped in a BubbleList context. +- **Item content not updating**: Confirm props are stable; ItemHandler compares previous values and only writes if they change. +- **Slot not working**: Ensure slot names match backend declarations. diff --git a/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.List Component.md b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.List Component.md new file mode 100644 index 00000000..10debd4c --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.List Component.md @@ -0,0 +1,66 @@ +# Bubble.List Component + + +**Files referenced in this document** +- [frontend/antdx/bubble/list/bubble.list.tsx](file://frontend/antdx/bubble/list/bubble.list.tsx) +- [frontend/antdx/bubble/list/Index.svelte](file://frontend/antdx/bubble/list/Index.svelte) +- [frontend/antdx/bubble/list/context.ts](file://frontend/antdx/bubble/list/context.ts) +- [frontend/antdx/bubble/list/utils.tsx](file://frontend/antdx/bubble/list/utils.tsx) +- [frontend/antdx/bubble/list/item/bubble.list.item.tsx](file://frontend/antdx/bubble/list/item/bubble.list.item.tsx) +- [frontend/antdx/bubble/list/role/bubble.list.role.tsx](file://frontend/antdx/bubble/list/role/bubble.list.role.tsx) + + +## Introduction + +Bubble.List is the message list container component in the Bubble system. It is responsible for collecting external items and slot items, injecting role context, resolving role mappings via `useRole`, and delegating final rendering to @ant-design/x's List. + +## Rendering Flow + +```mermaid +flowchart TD +Start(["Enter BubbleList"]) --> CheckItems["Check if props.items exists"] +CheckItems --> |Exists| UseItems["Use external items"] +CheckItems --> |Not exists| ReadSlot["Read context slotItems.items or default"] +ReadSlot --> ResolveItems["Use renderItems to parse as array"] +UseItems --> ResolveItems +ResolveItems --> ParseRole["useRole resolves role mapping"] +ParseRole --> PatchSlots["Apply slot patches to slots"] +PatchSlots --> RenderList["Render XBubble.List"] +RenderList --> End(["Done"]) +``` + +## Key Features + +- **Items merging**: Prioritizes `props.items`; if not provided, reads `slotItems.items` or `default` from context, then uses `renderItems` to normalize to an array. +- **Role resolution**: Uses `useRole` to support role as string, function, or object, with `preProcess` and `defaultRolePostProcess` hooks. +- **Slot patching**: Applies patches to slots so role's avatar/header/footer/extra/loadingRender/contentRender can be overridden in advance. +- **Render and scroll**: Renders via @ant-design/x's `XBubble.List`, with auto-scroll binding and scroll event callbacks. + +## Configuration Options + +| Property | Description | +| -------------- | ------------------------------------------------ | +| `items` | Message items array | +| `role` | Role configuration (string, function, or object) | +| `auto_scroll` | Whether to auto-scroll to the latest message | +| `visible` | Whether to render the component | +| `elem_id` | Element ID | +| `elem_classes` | Element CSS classes | + +## Collaboration with Bubble.Item and Bubble.Role + +- **Bubble.Item**: Wraps ItemHandler, injecting message item props and slots into context for BubbleList to read during rendering. +- **Bubble.Role**: Wraps RoleItemHandler, injecting role definitions into role context for useRole to resolve. +- **Data flow**: BubbleList reads items/default and role from context before rendering, then generates the complete items array and role configuration. + +## Performance Considerations + +- Uses `useMemo` to cache items, reducing unnecessary re-renders. +- `ItemHandler` uses `useMemoizedFn` and `useMemoizedEqualValue` to reduce duplicate computations and invalid updates. +- `ItemsContextProvider` updates the entire child items array in a single `setItem` call. + +## Troubleshooting + +- **Items not displayed**: Check if `visible` is truthy and that the parent component correctly wraps `withItemsContextProvider`. +- **Role configuration not working**: Ensure `Bubble.Role` correctly injects role context and that `useRole` receives the expected configuration. +- **Auto-scroll not working**: Confirm `auto_scroll` is enabled; consider performance implications with large message sets. diff --git a/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Role Component.md b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Role Component.md new file mode 100644 index 00000000..09d820e0 --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.Role Component.md @@ -0,0 +1,93 @@ +# Bubble.Role Component + + +**Files referenced in this document** +- [frontend/antdx/bubble/list/role/Role.svelte](file://frontend/antdx/bubble/list/role/Role.svelte) +- [frontend/antdx/bubble/list/role/bubble.list.role.tsx](file://frontend/antdx/bubble/list/role/bubble.list.role.tsx) +- [backend/modelscope_studio/components/antdx/bubble/list/role/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/list/role/__init__.py) +- [frontend/antdx/bubble/list/role/Index.svelte](file://frontend/antdx/bubble/list/role/Index.svelte) +- [frontend/antdx/bubble/list/context.ts](file://frontend/antdx/bubble/list/context.ts) +- [frontend/antdx/bubble/list/utils.tsx](file://frontend/antdx/bubble/list/utils.tsx) + + +## Introduction + +Bubble.Role is a role identifier component within the Bubble.List system. It injects role configurations into the role context via `RoleItemHandler`, so that `useRole` can resolve them into the `RoleType` required by @ant-design/x. Each Bubble.Role defines the visual style and behavior defaults for a specific role (e.g., user, assistant, system). + +## Architecture + +```mermaid +classDiagram +class BubbleListRole { ++props : BubbleProps and RoleItemHandlerProps ++render() : ReactNode +} +class RoleItemHandler { ++setRole(key, props, slots) +} +class RoleItemsContext { ++roles : map[] ++setRole() +} +class useRole { ++resolve(role) : RoleType +} +BubbleListRole --> RoleItemHandler : "Injects" +RoleItemHandler --> RoleItemsContext : "Writes role" +useRole --> RoleItemsContext : "Reads roles" +``` + +## Key Design Points + +- **RoleItemHandler injection**: Bubble.Role wraps RoleItemHandler, writing its own props/slots to RoleItemsContext for `useRole` to resolve. +- **Role key**: Each Bubble.Role must specify a unique role key matching the `role` field in message items. +- **Slot support**: Supports Bubble slots: avatar, header, footer, extra, content, loadingRender, contentRender. + +## Usage Example + +```python +import modelscope_studio as mgr + +with mgr.antdx.Bubble.List(): + with mgr.antdx.Bubble.Role(role="user"): + with mgr.Slot("avatar"): + mgr.antdx.Avatar(icon="UserOutlined") + with mgr.antdx.Bubble.Role(role="assistant"): + with mgr.Slot("avatar"): + mgr.antdx.Avatar(src="/bot-avatar.png") +``` + +## Role Resolution Flow + +```mermaid +flowchart TD +A["Input: role/defaultRoleKeys/preProcess/postProcess"] --> B["Read Role context items"] +B --> C{"Role config exists?"} +C --> |Yes| D["Render Role slots and aggregate as mapping"] +C --> |No| E["Use empty mapping"] +D --> F["Merge default keys and mapping keys"] +E --> F +F --> G["Iterate each key"] +G --> H{"Value is function?"} +H --> |Yes| I["Compile as function and cache"] +H --> |No| J["Generate default handler (with slot patches/index injection/default contentRender)"] +I --> K["Apply patchBubbleSlots enhancement"] +K --> L["Return RoleType"] +J --> L +``` + +## Configuration Options + +| Property | Description | +| ------------- | ---------------------------- | +| `role` | Unique role key identifier | +| `avatar` | Avatar configuration or slot | +| `placement` | Bubble placement (start/end) | +| `styles` | Style configuration | +| `class_names` | CSS class name configuration | + +## Best Practices + +- Define all roles used in messages before rendering BubbleList. +- Use consistent role key naming (e.g., "user", "assistant", "system") for better readability. +- Configure avatar, styles, and class_names via Bubble.Role slots for centralized role management. diff --git a/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.System Component.md b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.System Component.md new file mode 100644 index 00000000..c0cb397e --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Bubble Chat Bubble/Bubble.System Component.md @@ -0,0 +1,97 @@ +# Bubble.System Component + + +**Files referenced in this document** +- [frontend/antdx/bubble/system/Index.svelte](file://frontend/antdx/bubble/system/Index.svelte) +- [frontend/antdx/bubble/system/bubble.system.tsx](file://frontend/antdx/bubble/system/bubble.system.tsx) +- [backend/modelscope_studio/components/antdx/bubble/system/__init__.py](file://backend/modelscope_studio/components/antdx/bubble/system/__init__.py) + + +## Introduction + +Bubble.System is a system message component within the Bubble family, used for rendering system prompts, status notifications, and operational feedback. It integrates Ant Design X's system bubble capabilities into ModelScope Studio's component ecosystem through clear frontend-backend layered design. + +## Project Structure + +```mermaid +graph TB +PY["AntdXBubbleSystem
Backend Python Component"] --> IDX["Index.svelte
Frontend Svelte Wrapper"] +IDX --> TSX["bubble.system.tsx
React Bridge"] +TSX --> ADX["@ant-design/x Bubble.System"] +``` + +## Core Component + +The `AntdXBubbleSystem` backend class inherits from ModelScope Studio's layout component base class with the following key properties: + +```mermaid +classDiagram +class AntdXBubbleSystem { ++EVENTS ++SLOTS ++content ++shape ++variant ++styles ++class_names ++root_class_name ++additional_props ++visible ++elem_id ++elem_classes ++elem_style ++render ++skip_api ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +``` + +## Rendering Flow + +```mermaid +flowchart TD +Enter(["Enter System Rendering"]) --> HasSlot{"content slot exists?"} +HasSlot --> |Yes| RenderSlot["Render slot content"] +HasSlot --> |No| RenderProp["Render prop content"] +RenderSlot --> Done(["Render complete"]) +RenderProp --> Done +``` + +## Differences from Regular Bubble + +- **Role positioning**: Regular Bubble is used for user/bot conversation content rendering with rich slots (avatar, header, footer, extra, etc.); Bubble.System focuses on system prompts, status notifications, and non-conversational content. +- **Slots and properties**: Regular Bubble supports more slots; System Bubble only focuses on the `content` slot and basic properties, keeping it simple and consistent. +- **Rendering target**: Regular Bubble faces "person" and "role" interaction content; System Bubble faces information communicated by "system" to the user. + +## Configuration Options + +| Property | Description | +| -------------------------- | -------------------------------------------------- | +| `content` | System message content (string or slot) | +| `shape` | Bubble shape (round/corner/default) | +| `variant` | Visual variant (filled/borderless/outlined/shadow) | +| `styles` / `elem_style` | Inline styles | +| `elem_id` / `elem_classes` | Element ID and class names | +| `additional_props` | Additional property set | +| `visible` | Whether to render | + +## Usage Scenarios + +- **Welcome message**: Display welcome text when user first enters the page. +- **Error notification**: Notify user of network or service errors. +- **Progress notification**: Stage-by-stage prompts during background task execution. + +## Performance Considerations + +- `Index.svelte` uses dynamic imports, only loading the system bubble wrapper when visible, reducing initial render overhead. +- `ReactSlot` only renders when slots exist, avoiding unnecessary computations for empty content. +- Only passes necessary properties and slots, reducing unnecessary re-renders and style calculations. + +## Troubleshooting + +- **Content not showing**: Check that `content` is correctly passed via slot or property; slots take priority. Confirm `visible` is truthy. +- **Style abnormalities**: Check that `elem_id`, `elem_classes`, `elem_style` are injected as expected. +- **Slot not working**: Ensure slot name matches backend declaration (currently only supports `content` slot). diff --git a/.wiki/en/Ant Design X Components/General Components/Conversations/API Reference.md b/.wiki/en/Ant Design X Components/General Components/Conversations/API Reference.md new file mode 100644 index 00000000..1d0dc524 --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Conversations/API Reference.md @@ -0,0 +1,105 @@ +# API Reference + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antdx/conversations/__init__.py](file://backend/modelscope_studio/components/antdx/conversations/__init__.py) +- [backend/modelscope_studio/components/antdx/conversations/item/__init__.py](file://backend/modelscope_studio/components/antdx/conversations/item/__init__.py) + + +## Conversations Component API + +### Properties + +| Property | Type | Default | Description | +| -------------- | ---- | ------- | --------------------------------- | +| `items` | list | `[]` | Conversation items array | +| `active_key` | str | `None` | Currently active conversation key | +| `groupable` | bool | `False` | Whether to enable grouping | +| `menu` | dict | `None` | Context menu configuration | +| `visible` | bool | `True` | Whether to render the component | +| `elem_id` | str | `None` | Element ID | +| `elem_classes` | list | `None` | Element CSS class names | +| `elem_style` | dict | `None` | Element inline styles | + +### Events + +| Event | Description | +| ------------------ | ------------------------------------------ | +| `active_change` | Fired when the active conversation changes | +| `menu_click` | Fired when a menu item is clicked | +| `menu_select` | Fired when a menu item is selected | +| `menu_deselect` | Fired when a menu item is deselected | +| `menu_open_change` | Fired when menu open state changes | +| `groupable_expand` | Fired when a group expands or collapses | +| `creation_click` | Fired when the creation button is clicked | + +### Slots + +| Slot | Description | +| -------------------------- | ------------------------------------------------------ | +| `items` | Slot for injecting Conversations.Item child components | +| `menu.items` | Slot for injecting context menu items | +| `menu.trigger` | Slot for customizing menu trigger | +| `menu.expandIcon` | Slot for customizing menu expand icon | +| `menu.overflowedIndicator` | Slot for customizing overflow indicator | +| `groupable.label` | Slot for customizing group label | +| `creation.icon` | Slot for customizing creation button icon | +| `creation.label` | Slot for customizing creation button label | + +## Conversations.Item Component API + +### Properties + +| Property | Type | Default | Description | +| ---------- | ---- | -------- | ------------------------------------------- | +| `key` | str | required | Unique identifier for the conversation item | +| `label` | str | `None` | Display label (overridden by label slot) | +| `icon` | any | `None` | Icon (overridden by icon slot) | +| `disabled` | bool | `False` | Whether the item is disabled | +| `group` | str | `None` | Group label (required when groupable=True) | + +### Slots + +| Slot | Description | +| ------- | ----------------------------------------- | +| `label` | Slot for customizing item label rendering | +| `icon` | Slot for customizing item icon rendering | + +## Items Array Format + +Each item in the `items` array can contain: + +```python +{ + "key": "unique-key", # Required: unique identifier + "label": "Display Name", # Display label + "icon": None, # Icon configuration + "disabled": False, # Whether disabled + "group": "Group Name", # Group label (for groupable mode) +} +``` + +## Usage Example + +```python +import gradio as gr +import modelscope_studio as mgr + +with gr.Blocks() as demo: + state = gr.State(value=None) + + conversations = mgr.antdx.Conversations( + groupable=True, + items=[ + {"key": "1", "label": "Chat about Python", "group": "Today"}, + {"key": "2", "label": "ML model discussion", "group": "Today"}, + {"key": "3", "label": "Old conversation", "group": "Yesterday"}, + ] + ) + + conversations.active_change( + lambda key: print(f"Selected: {key}"), + inputs=[conversations], + outputs=[state] + ) +``` diff --git a/.wiki/en/Ant Design X Components/General Components/Conversations/Component Overview.md b/.wiki/en/Ant Design X Components/General Components/Conversations/Component Overview.md new file mode 100644 index 00000000..cbd26e9c --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Conversations/Component Overview.md @@ -0,0 +1,113 @@ +# Component Overview + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antdx/__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [backend/modelscope_studio/components/antdx/conversations/__init__.py](file://backend/modelscope_studio/components/antdx/conversations/__init__.py) +- [frontend/antdx/conversations/conversations.tsx](file://frontend/antdx/conversations/conversations.tsx) +- [frontend/antdx/conversations/context.ts](file://frontend/antdx/conversations/context.ts) +- [frontend/antdx/conversations/item/conversations.item.tsx](file://frontend/antdx/conversations/item/conversations.item.tsx) + + +## Introduction + +This overview covers the Conversations management component, systematically introducing its overall architecture, core functionality, and design philosophy. It explains its relationship with the Ant Design X component library and typical usage in machine learning and conversational applications, providing entry points and core concepts to help developers quickly understand and integrate this component. + +## Project Structure + +The Conversations component is located in the Ant Design X frontend ecosystem. The backend bridges to the Gradio ecosystem via Python wrappers; the frontend connects to Ant Design X's Conversations implementation as React components, extending menu, grouping, and other capabilities through context and slot mechanisms. + +```mermaid +graph TB +subgraph "Backend" +PY_API["Python Wrapper
AntdXConversations"] +BASE_COMP["Base Component Class
ModelScopeLayoutComponent"] +end +subgraph "Frontend" +REACT_COMP["React Component
@ant-design/x Conversations"] +CTX["Context and Slots
context.ts / conversations.tsx"] +ITEM["Item Wrapper
conversations.item.tsx"] +end +PY_API --> |"Call/Render"| REACT_COMP +BASE_COMP --> PY_API +CTX --> REACT_COMP +ITEM --> CTX +``` + +## Core Components + +### AntdXConversations (Backend) + +The Python-side wrapper class for the Conversations component: + +- Inherits from `ModelScopeLayoutComponent`, providing unified lifecycle and rendering strategy. +- Declares supported slots and events, ensuring frontend wrapper layer correctly interfaces. +- Property set covers common needs: `items`, `active_key`, `groupable`, `menu`. + +Key events: + +- `active_change`: Active conversation changed +- `menu_click` / `menu_select` / `menu_deselect` / `menu_open_change`: Menu interaction events +- `groupable_expand`: Group expand/collapse +- `creation_click`: Creation button click + +### conversations.tsx (Frontend) + +The frontend React wrapper implementation: + +- Uses `withItemsContextProvider` to provide items context to child `Conversations.Item` components. +- Uses `withMenuItemsContextProvider` to provide menu items context. +- Uniformly injects style class names to child items. +- Converts slot menu items to menu configuration required by @ant-design/x. + +### conversations.item.tsx (Frontend) + +The Conversations.Item bridge component: + +- Uses `ItemHandler` to write its own props/slots to `ItemsContext`. +- Supports `label`, `icon`, and other slots. + +## Architecture Overview + +```mermaid +graph LR +ConvTSX["conversations.tsx"] --> Ctx["context.ts"] +Ctx --> CIC["createItemsContext.tsx"] +ConvTSX --> X["@ant-design/x Conversations"] +ItemSvelte["Index.svelte"] --> ItemBridge["conversations.item.tsx"] +ItemBridge --> Ctx +Backend["AntdXConversations*"] --> ConvTSX +``` + +## Usage Patterns + +### Basic Usage + +```python +import modelscope_studio as mgr + +conversations = mgr.antdx.Conversations( + items=[ + {"key": "1", "label": "Conversation 1"}, + {"key": "2", "label": "Conversation 2"}, + ] +) +``` + +### With Grouping + +```python +conversations = mgr.antdx.Conversations( + groupable=True, + items=[ + {"key": "1", "label": "Conv 1", "group": "Today"}, + {"key": "2", "label": "Conv 2", "group": "Yesterday"}, + ] +) +``` + +## Key Design Concepts + +- **Context-driven**: The parent container provides context; child items write to context. This decouples parent-child communication and enables flexible composition. +- **Slot-first**: All display customization (icons, labels, menus) is achieved through slots for maximum flexibility. +- **Event-driven**: Key interactions (selection, menu operations, group toggle) are exposed as events for backend Python processing. diff --git a/.wiki/en/Ant Design X Components/General Components/Conversations/Conversation Item Component.md b/.wiki/en/Ant Design X Components/General Components/Conversations/Conversation Item Component.md new file mode 100644 index 00000000..b41444bd --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Conversations/Conversation Item Component.md @@ -0,0 +1,92 @@ +# Conversation Item Component + + +**Files referenced in this document** +- [frontend/antdx/conversations/item/Index.svelte](file://frontend/antdx/conversations/item/Index.svelte) +- [frontend/antdx/conversations/item/conversations.item.tsx](file://frontend/antdx/conversations/item/conversations.item.tsx) +- [backend/modelscope_studio/components/antdx/conversations/item/__init__.py](file://backend/modelscope_studio/components/antdx/conversations/item/__init__.py) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) + + +## Introduction + +`Conversations.Item` is an individual conversation item component within the Conversations system. It bridges slot content and properties to the parent `Conversations` container via `ItemHandler`, enabling the parent to render all items uniformly. This design ensures complete decoupling between parent and child while supporting rich slot customization. + +## Architecture + +```mermaid +graph LR +Item["Conversations.Item
Index.svelte"] --> Bridge["conversations.item.tsx
React Bridge"] +Bridge --> Handler["ItemHandler
createItemsContext.tsx"] +Handler --> Context["ItemsContext
context.ts"] +Parent["Conversations
conversations.tsx"] --> Context +``` + +## Key Design Points + +- **ItemHandler injection**: Conversations.Item writes its own props/slots to `ItemsContext` via ItemHandler for the parent Conversations to consume and render. +- **Lazy loading**: `Index.svelte` only renders the bridge component when `visible` is true. +- **Props comparison**: ItemHandler uses memoized comparison to avoid unnecessary writes. + +## Data Flow + +```mermaid +sequenceDiagram +participant Item as "Conversations.Item" +participant Handler as "ItemHandler" +participant Ctx as "ItemsContext" +participant Parent as "Conversations" +Item->>Handler : Pass key, props, slots +Handler->>Ctx : setItem(key, props, children) +Parent->>Ctx : Read items +Ctx-->>Parent : Return items map +Parent->>Parent : Render via @ant-design/x Conversations +``` + +## Properties + +| Property | Type | Default | Description | +| ---------- | ---- | -------- | --------------------------------------- | +| `key` | str | required | Unique conversation item identifier | +| `label` | str | `None` | Display text (overridden by label slot) | +| `icon` | any | `None` | Item icon (overridden by icon slot) | +| `disabled` | bool | `False` | Whether the item is disabled | +| `group` | str | `None` | Group this item belongs to | +| `visible` | bool | `True` | Whether to render this item | + +## Slots + +| Slot | Description | +| ------- | ---------------------- | +| `label` | Custom label rendering | +| `icon` | Custom icon rendering | + +## Usage Example + +```python +import modelscope_studio as mgr + +with mgr.antdx.Conversations() as conv: + # Simple text item + mgr.antdx.Conversations.Item(key="1", label="Project Alpha") + + # Item with custom icon and label + with mgr.antdx.Conversations.Item(key="2"): + with mgr.Slot("icon"): + mgr.antdx.Icon(type="StarOutlined") + with mgr.Slot("label"): + mgr.antdx.Typography.Text("★ Starred Chat", strong=True) + + # Item with context menu + with mgr.antdx.Conversations.Item(key="3", label="Chat with menu"): + with mgr.Slot("menu.items"): + mgr.antdx.MenuItem(key="pin", label="Pin") + mgr.antdx.MenuItem(key="delete", label="Delete", danger=True) +``` + +## Troubleshooting + +- **Item not visible**: Check `visible` property and confirm item is inside a Conversations container. +- **Label not showing**: Confirm the label slot or label property is correctly set. +- **Icon not showing**: Ensure icon slot content is a valid React/Svelte element. +- **Menu items not working**: Verify menu items are injected via `menu.items` slot and the parent handles `menu_click` events. diff --git a/.wiki/en/Ant Design X Components/General Components/Conversations/Conversations Management.md b/.wiki/en/Ant Design X Components/General Components/Conversations/Conversations Management.md new file mode 100644 index 00000000..468c1300 --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Conversations/Conversations Management.md @@ -0,0 +1,160 @@ +# Conversations Management + + +**Files referenced in this document** +- [frontend/antdx/conversations/Index.svelte](file://frontend/antdx/conversations/Index.svelte) +- [frontend/antdx/conversations/conversations.tsx](file://frontend/antdx/conversations/conversations.tsx) +- [frontend/antdx/conversations/context.ts](file://frontend/antdx/conversations/context.ts) +- [frontend/antdx/conversations/item/Index.svelte](file://frontend/antdx/conversations/item/Index.svelte) +- [frontend/antdx/conversations/item/conversations.item.tsx](file://frontend/antdx/conversations/item/conversations.item.tsx) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/antdx/conversations/index.less](file://frontend/antdx/conversations/index.less) +- [frontend/antdx/conversations/gradio.config.js](file://frontend/antdx/conversations/gradio.config.js) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically describes the design and implementation of the Conversations management component, covering: + +- Conversation list management: adding, deleting, sorting, state management +- Conversations.Item rendering logic, interaction behavior, and state control +- Component Context role and conversation state sharing mechanism +- Property configuration, event callbacks, style customization, and best practices +- Complete usage examples: basic usage, dynamic add/remove, state synchronization + +## Project Structure + +The Conversations component consists of three layers: "container layer + item handler + context", bridged to the runtime environment via Gradio configuration. + +```mermaid +graph TB +subgraph "Frontend Component Layer" +A["Index.svelte
Container Entry"] +B["conversations.tsx
Conversation Container Implementation"] +C["context.ts
Item Context Export"] +D["item/Index.svelte
Item Entry"] +E["item/conversations.item.tsx
Item Handler"] +F["index.less
Styles"] +end +subgraph "Shared Utility Layer" +G["createItemsContext.tsx
Item Context Factory"] +end +subgraph "Build Configuration" +H["gradio.config.js
Unified Configuration"] +end +A --> B +D --> E +B --> C +C --> G +E --> C +B --> F +A --> H +D --> H +``` + +## Core Components + +- **Conversations**: The parent container that manages the conversation list. Parses items and menu configuration, injects them into @ant-design/x's Conversations, wraps with `withItemsContextProvider` and `withMenuItemsContextProvider` to provide contexts. +- **Conversations.Item**: A single conversation item. Writes its own props/slots/children to ItemsContext via `ItemHandler` for the parent container to render. + +## Architecture Overview + +```mermaid +classDiagram +class Conversations { ++props : items, menu, groupable, active_key ++events : active_change, menu_click, ... +} +class ConversationsItem { ++props : key, label, icon, disabled, ... ++slots : label, icon +} +class ItemHandler { ++setItem() ++collectProps() ++collectSlots() +} +class ItemsContext { ++items : map[] ++setItem() +} +Conversations --> ItemsContext : "Provides context" +ConversationsItem --> ItemHandler : "Bridge rendering" +ItemHandler --> ItemsContext : "Writes item" +``` + +## Detailed Component Analysis + +### Conversations Container + +- Parses `items` and menu configuration, injects into @ant-design/x's Conversations. +- Wraps with `withItemsContextProvider` and `withMenuItemsContextProvider` for Items and menu contexts. +- Uniformly injects style class names (e.g., item class names) to ensure theme consistency. + +### Conversations.Item + +- Uses `ItemHandler` to write its own props/slots/children to `ItemsContext`. +- Parent container consumes and renders items uniformly. + +### Menu Operations (Add, Delete, Rename) + +- Inject menu items via Slot (`menu.items`), supporting icons, disabled state, and danger styling. +- The `menu_click` event callback provides the clicked item and menu information. + +### Conversation Grouping and Collapsible + +- Enable grouping by setting `groupable=True`. +- Each conversation item sets a `group` field for grouping. +- Supports group label slots and collapsible functions. + +### Events and State Management + +Key events: + +- `active_change`: Selected item changed +- `menu_click` / `menu_select` / `menu_deselect` / `menu_open_change`: Menu interactions +- `groupable_expand`: Group expand/collapse +- `creation_click`: Create button click + +## Dependency Analysis + +- **Component coupling**: Conversations.Item depends on `ItemHandler` and `ItemsContext` with low coupling, easy to reuse. The parent container centralizes items, menu, and grouping handling. +- **External dependencies**: @ant-design/x provides the core Conversations component; Gradio component system provides `AntdXConversations`/`AntdXConversationsItem` as bridges. + +## Performance Considerations + +- **Lazy loading and conditional rendering**: `Index.svelte` only renders child items when `visible` is true, avoiding unnecessary initialization overhead. +- **Context update minimization**: `ItemHandler` uses `useMemoizedFn` and `useMemoizedEqualValue` to reduce duplicate computations and invalid updates. +- **Batch writing**: `ItemsContextProvider` updates the entire child items array in a single `setItem` call, reducing re-render frequency. +- **Style injection**: Parent container uniformly injects style class names to avoid jitter from child items setting styles repeatedly. + +## Troubleshooting Guide + +- **Child items not showing**: Check if `visible` is truthy; confirm parent component correctly wraps `withItemsContextProvider`. +- **Child item content not updating**: Confirm props are stable; `ItemHandler` compares previous values and won't write if equal. +- **Menu not working**: Confirm parent component correctly injects `menu` configuration or injects menu items via Slot. +- **Style abnormalities**: Parent component has already injected item class names; confirm they haven't been externally overridden. + +## Conclusion + +Conversations.Item achieves flexible item collection and rendering through `ItemHandler` and `ItemsContext`. Combined with the parent `Conversations` container's unified configuration and event management, it can efficiently build complex conversation list scenarios with emphasis on decoupling and extensibility. + +## Appendix + +### Events and Slots Summary + +- **Events**: active_change, menu_click, menu_deselect, menu_open_change, menu_select, groupable_expand, creation_click +- **Slots**: menu.expandIcon, menu.overflowedIndicator, menu.trigger, groupable.label, items, creation.icon, creation.label diff --git a/.wiki/en/Ant Design X Components/General Components/Conversations/Usage Examples.md b/.wiki/en/Ant Design X Components/General Components/Conversations/Usage Examples.md new file mode 100644 index 00000000..4deefebd --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/Conversations/Usage Examples.md @@ -0,0 +1,140 @@ +# Usage Examples + + +**Files referenced in this document** +- [docs/components/antdx/conversations/demos/basic.py](file://docs/components/antdx/conversations/demos/basic.py) +- [docs/components/antdx/conversations/demos/operations.py](file://docs/components/antdx/conversations/demos/operations.py) +- [docs/components/antdx/conversations/demos/group.py](file://docs/components/antdx/conversations/demos/group.py) + + +## Basic Usage + +### Simple Conversation List + +```python +import gradio as gr +import modelscope_studio as mgr + +with gr.Blocks() as demo: + mgr.antdx.Conversations( + items=[ + {"key": "1", "label": "First conversation"}, + {"key": "2", "label": "Second conversation"}, + {"key": "3", "label": "Third conversation"}, + ] + ) +``` + +### With Icons and Labels + +Use Slots to define `label`/`icon` slots for custom rendering: + +```python +with gr.Blocks() as demo: + with mgr.antdx.Conversations() as conv: + with mgr.antdx.Conversations.Item(key="1"): + with mgr.Slot("icon"): + mgr.antdx.Icon(type="MessageOutlined") + with mgr.Slot("label"): + gr.Markdown("**Important Chat**") +``` + +## Menu Operations (Add, Delete, Rename) + +```python +import gradio as gr +import modelscope_studio as mgr + +with gr.Blocks() as demo: + with mgr.antdx.Conversations() as conv: + with mgr.antdx.Conversations.Item(key="chat-1", label="Chat 1"): + with mgr.Slot("menu.items"): + mgr.antdx.MenuItem(key="rename", label="Rename") + mgr.antdx.MenuItem(key="delete", label="Delete", danger=True) + + def handle_menu_click(key, menu_info): + print(f"Item: {key}, Menu: {menu_info}") + + conv.menu_click(handle_menu_click) +``` + +## Conversation Grouping with Collapsible + +```python +with gr.Blocks() as demo: + mgr.antdx.Conversations( + groupable=True, + items=[ + {"key": "1", "label": "Morning standup", "group": "Today"}, + {"key": "2", "label": "Code review", "group": "Today"}, + {"key": "3", "label": "Planning session", "group": "Yesterday"}, + {"key": "4", "label": "Bug discussion", "group": "Yesterday"}, + ] + ) +``` + +## Dynamic Conversation Management + +```python +import gradio as gr +import modelscope_studio as mgr + +def add_conversation(items, name): + new_key = f"conv-{len(items) + 1}" + return items + [{"key": new_key, "label": name}] + +def delete_conversation(items, key): + return [item for item in items if item["key"] != key] + +with gr.Blocks() as demo: + items_state = gr.State(value=[ + {"key": "1", "label": "Initial conversation"}, + ]) + + with gr.Row(): + new_name = gr.Textbox(placeholder="Conversation name") + add_btn = gr.Button("Add") + + conv = mgr.antdx.Conversations() + + add_btn.click( + add_conversation, + inputs=[items_state, new_name], + outputs=[items_state] + ) + + items_state.change( + lambda items: mgr.antdx.Conversations(items=items), + inputs=[items_state], + outputs=[conv] + ) +``` + +## Event Handling Examples + +### Handling Active Selection Change + +```python +def on_active_change(key): + print(f"Selected conversation: {key}") + # Load messages for selected conversation + +conversations.active_change( + on_active_change, + inputs=[conversations] +) +``` + +### Handling Creation Button Click + +```python +def on_creation_click(): + # Create new conversation + new_id = generate_id() + return [{"key": new_id, "label": "New Conversation"}] + +conversations.creation_click( + on_creation_click, + outputs=[conversations] +) +``` diff --git a/.wiki/en/Ant Design X Components/General Components/General Components.md b/.wiki/en/Ant Design X Components/General Components/General Components.md new file mode 100644 index 00000000..02cf25e2 --- /dev/null +++ b/.wiki/en/Ant Design X Components/General Components/General Components.md @@ -0,0 +1,310 @@ +# General Components + + +**Files referenced in this document** +- [bubble.tsx](file://frontend/antdx/bubble/bubble.tsx) +- [conversations.tsx](file://frontend/antdx/conversations/conversations.tsx) +- [context.ts](file://frontend/antdx/conversations/context.ts) +- [index.less](file://frontend/antdx/conversations/index.less) +- [__init__.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [README-zh_CN.md](file://README-zh_CN.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document covers the Ant Design X general components, focusing on the implementation and usage of the Bubble conversation bubble component and the Conversations conversation management component. Topics include: + +- Bubble's conversation display capabilities, message type differentiation, and style/content customization +- Conversations' conversation list management, state control, menu and grouping operation interfaces +- Collaboration relationships between components and best practices +- Complete usage examples (basic usage, advanced configuration, style customization) + +## Project Structure + +The Ant Design X general components are located in the antdx category of the frontend directory. They use a Svelte + React preprocessing bridge solution, wrapping native @ant-design/x components via sveltify to make them usable in Svelte. The backend Python package provides a unified export entry. + +```mermaid +graph TB +subgraph "Frontend antdx" +B["bubble.tsx"] +C["conversations.tsx"] +CTX["context.ts"] +L["index.less"] +end +subgraph "Backend" +PY_INIT["__init__.py"] +PY_COMP["components.py"] +end +subgraph "Third-party" +ADX["@ant-design/x"] +SveltePreprocess["@svelte-preprocess-react"] +Utils["@utils/*"] +end +B --> ADX +C --> ADX +B --> SveltePreprocess +C --> SveltePreprocess +B --> Utils +C --> Utils +PY_COMP --> B +PY_COMP --> C +PY_INIT --> PY_COMP +``` + +Diagram sources + +- [bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [context.ts:1-7](file://frontend/antdx/conversations/context.ts#L1-L7) +- [**init**.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [components.py](file://backend/modelscope_studio/components/antdx/components.py) + +Section sources + +- [bubble.tsx:1-119](file://frontend/antdx/bubble/bubble.tsx#L1-L119) +- [conversations.tsx:1-178](file://frontend/antdx/conversations/conversations.tsx#L1-L178) +- [context.ts:1-7](file://frontend/antdx/conversations/context.ts#L1-L7) +- [**init**.py](file://backend/modelscope_studio/components/antdx/__init__.py) +- [components.py](file://backend/modelscope_studio/components/antdx/components.py) + +## Core Components + +- Bubble: A conversation bubble display component that supports slot-based extensions for avatar, title, content, footer, extra area, editable text, loading state rendering, and content rendering. +- Conversations: A conversation list management component that supports menu injection, grouping configuration, item rendering, class name merging, and event pass-through. + +Section sources + +- [bubble.tsx:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) +- [conversations.tsx:59-175](file://frontend/antdx/conversations/conversations.tsx#L59-L175) + +## Architecture Overview + +Both Bubble and Conversations are bridged to native @ant-design/x components through sveltify. The bridge layer handles: + +- Slot-to-ReactSlot mapping +- useFunction wrapping of function-type properties +- Context and rendering tool integration for menu and grouping configuration +- Class name merging and overriding + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Conv as "Conversations(Bridge)" +participant XConv as "@ant-design/x.Conversations" +participant Ctx as "Context(Menu/Item)" +participant Bubble as "Bubble(Bridge)" +participant XBubble as "@ant-design/x.Bubble" +Dev->>Conv : Pass items/menu/groupable and other props +Conv->>Ctx : Parse menu/item context +Conv->>XConv : Render conversation list (with menu/grouping) +XConv-->>Dev : List rendering result +Dev->>Bubble : Pass avatar/content/footer/header, etc. +Bubble->>XBubble : Render conversation bubble (slot/function wrapping) +XBubble-->>Dev : Bubble rendering result +``` + +Diagram sources + +- [conversations.tsx:68-175](file://frontend/antdx/conversations/conversations.tsx#L68-L175) +- [bubble.tsx:27-116](file://frontend/antdx/bubble/bubble.tsx#L27-L116) + +## Detailed Component Analysis + +### Bubble Component Analysis + +- Key Features + - Supports slot-based extensions for avatar, title, content, footer, and extra area + - Supports editable mode (boolean or configuration object), with slots for customizing "confirm/cancel" text + - Supports typing callbacks and function-based configuration for loadingRender/contentRender + - Handles editable, avatar, header, footer, extra, loadingRender, contentRender uniformly with fallback +- Data Flow and Processing Logic + - Uses useFunction to wrap function-type properties, ensuring correct execution in the Svelte environment + - Renders slot content via ReactSlot; renderParamsSlot supports slots with parameters + - Performs configuration merging and conditional rendering for editable, compatible with both boolean and object configuration +- Complexity and Performance + - Primarily involves property mapping and rendering overhead; complexity scales with slot count and nesting depth + - Function wrapping avoids redundant rendering and improves interaction responsiveness + +```mermaid +flowchart TD +Start(["Enter Bubble rendering"]) --> CheckEditable["Detect editable configuration"] +CheckEditable --> EditableSupport{"Editing supported?"} +EditableSupport --> |Yes| MergeEditable["Merge edit config\nand process slot text"] +EditableSupport --> |No| PassEditable["Pass editable directly"] +MergeEditable --> RenderAvatar["Handle avatar slot/function"] +PassEditable --> RenderAvatar +RenderAvatar --> RenderHeader["Handle header slot/function"] +RenderHeader --> RenderFooter["Handle footer slot/function"] +RenderFooter --> RenderExtra["Handle extra area slot/function"] +RenderExtra --> RenderContent["Handle content slot/function"] +RenderContent --> RenderLoading["Handle loadingRender slot/function"] +RenderLoading --> RenderContentRender["Handle contentRender slot/function"] +RenderContentRender --> End(["Rendering complete"]) +``` + +Diagram sources + +- [bubble.tsx:27-116](file://frontend/antdx/bubble/bubble.tsx#L27-L116) + +Section sources + +- [bubble.tsx:8-116](file://frontend/antdx/bubble/bubble.tsx#L8-L116) + +### Conversations Component Analysis + +- Key Features + - Interfaces with @ant-design/x Conversations, providing menu injection, grouping configuration, item rendering, and class name merging + - Parses menu and item slots via useMenuItems and useItems context + - Supports string-form menu property and object configuration, automatically merges events and prevents bubbling + - Supports label slot for groupable and collapsible function configuration +- Data Flow and Processing Logic + - patchMenuEvents: Wraps menu events, injects the conversation parameter and prevents DOM event bubbling + - renderItems: Converts slot items into actual rendered items, supporting cloning and deep copying + - useMemo: Memoizes menu and items to reduce unnecessary re-renders +- Complexity and Performance + - Memoization and context parsing deliver stable performance; more slot items means greater renderItems overhead + - Menu event wrapping only takes effect when a menu exists, avoiding unnecessary overhead + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Conv as "Conversations(Bridge)" +participant Ctx as "useMenuItems/useItems" +participant XConv as "@ant-design/x.Conversations" +Dev->>Conv : Pass menu/items/groupable/classNames +Conv->>Ctx : Get menu/item context +Conv->>Conv : patchMenuEvents wraps menu events +Conv->>Conv : renderItems parses slot items +Conv->>XConv : Merge class names and render +XConv-->>Dev : Return conversation list +``` + +Diagram sources + +- [conversations.tsx:35-175](file://frontend/antdx/conversations/conversations.tsx#L35-L175) +- [context.ts:1-7](file://frontend/antdx/conversations/context.ts#L1-L7) + +Section sources + +- [conversations.tsx:28-175](file://frontend/antdx/conversations/conversations.tsx#L28-L175) +- [context.ts:1-7](file://frontend/antdx/conversations/context.ts#L1-L7) + +### Component Collaboration + +- Conversations serves as the container, responsible for rendering the conversation list and managing menu/grouping configuration +- Bubble serves as a child element, responsible for displaying and interacting with individual conversation bubbles +- Both work together through @ant-design/x's native components, with the bridge layer providing slot and function wrapping capabilities + +```mermaid +graph LR +Conv["Conversations(Bridge)"] --> XB["@ant-design/x.Conversations"] +XB --> Item["Conversation Item (driven by items/menu/groupable)"] +Item --> BB["Bubble(Bridge)"] +BB --> XBb["@ant-design/x.Bubble"] +``` + +Diagram sources + +- [conversations.tsx:139-171](file://frontend/antdx/conversations/conversations.tsx#L139-L171) +- [bubble.tsx:38-115](file://frontend/antdx/bubble/bubble.tsx#L38-L115) + +## Dependency Analysis + +- Third-party Dependencies + - @ant-design/x: Provides native conversation and bubble components + - @svelte-preprocess-react: Provides sveltify and ReactSlot capabilities + - @utils/\*: Provides tools like useFunction, renderItems, renderParamsSlot, createFunction + - classnames: Used for class name merging +- Backend Exports + - The Python package exposes antdx components through **init**.py and components.py, enabling use in Python environments + +```mermaid +graph TB +B["bubble.tsx"] --> ADX["@ant-design/x"] +B --> SPR["@svelte-preprocess-react"] +B --> U["@utils/*"] +C["conversations.tsx"] --> ADX +C --> SPR +C --> U +C --> CTX["context.ts"] +PY["components.py"] --> B +PY --> C +``` + +Diagram sources + +- [bubble.tsx:1-7](file://frontend/antdx/bubble/bubble.tsx#L1-L7) +- [conversations.tsx:1-17](file://frontend/antdx/conversations/conversations.tsx#L1-L17) +- [context.ts:1-7](file://frontend/antdx/conversations/context.ts#L1-L7) +- [components.py](file://backend/modelscope_studio/components/antdx/components.py) + +Section sources + +- [bubble.tsx:1-7](file://frontend/antdx/bubble/bubble.tsx#L1-L7) +- [conversations.tsx:1-17](file://frontend/antdx/conversations/conversations.tsx#L1-L17) +- [context.ts:1-7](file://frontend/antdx/conversations/context.ts#L1-L7) +- [components.py](file://backend/modelscope_studio/components/antdx/components.py) + +## Performance Considerations + +- Use useMemo to memoize menu and items, avoiding unnecessary re-renders +- Wrap function-type properties with useFunction to reduce closure creation and rendering jitter +- Clone slot items through renderItems to avoid side effects from shared state +- In high-volume conversation scenarios, consider lazy loading and virtual scrolling (such as capabilities provided by @ant-design/x) to reduce memory usage + +## Troubleshooting Guide + +- Slot not taking effect + - Verify that slot names are consistent with the bridge layer declarations (e.g., editable.okText, editable.cancelText, content, footer, header, extra, loadingRender, contentRender) + - Confirm that slot content is correctly rendered via ReactSlot +- Abnormal menu events + - Check that the useMenuItems context is being used correctly + - Confirm that patchMenuEvents correctly wraps onClick and similar events and prevents bubbling +- Class name conflicts + - Merge custom class names through classNames to avoid overriding default styles +- Edit mode not appearing + - Confirm that editable is an object containing the editing field, or provide custom text via slots + +Section sources + +- [bubble.tsx:36-64](file://frontend/antdx/bubble/bubble.tsx#L36-L64) +- [conversations.tsx:35-57](file://frontend/antdx/conversations/conversations.tsx#L35-L57) +- [conversations.tsx:145-151](file://frontend/antdx/conversations/conversations.tsx#L145-L151) + +## Conclusion + +Bubble and Conversations achieve complete capability encapsulation of @ant-design/x through the bridge layer, providing flexible slot-based and function-based configuration that meets diverse needs from basic conversation display to complex conversation management. It is recommended to combine context and utility functions in actual projects, and to organize slots and events appropriately for a better development experience and runtime performance. + +## Appendix + +- Usage Examples (based on existing repository files and component capabilities) + - Basic Usage + - Use Bubble to display a message, setting avatar, content, and footer + - Use Conversations to render a conversation list, passing items and menu configuration + - Advanced Configuration + - Enable edit mode in Bubble, customizing "confirm/cancel" text through slots + - Use groupable in Conversations to implement grouping and collapsing, customizing group labels through slots + - Style Customization + - Merge custom class names through classNames to override default styles + - Import index.less for theme customization (if needed) + +Section sources + +- [bubble.tsx:14-116](file://frontend/antdx/bubble/bubble.tsx#L14-L116) +- [conversations.tsx:59-175](file://frontend/antdx/conversations/conversations.tsx#L59-L175) +- [index.less](file://frontend/antdx/conversations/index.less) +- [README-zh_CN.md](file://README-zh_CN.md) diff --git a/.wiki/en/Ant Design X Components/Tool Components/CodeHighlighter Component.md b/.wiki/en/Ant Design X Components/Tool Components/CodeHighlighter Component.md new file mode 100644 index 00000000..12343c0a --- /dev/null +++ b/.wiki/en/Ant Design X Components/Tool Components/CodeHighlighter Component.md @@ -0,0 +1,335 @@ +# CodeHighlighter Component + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antdx/code_highlighter/__init__.py](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py) +- [frontend/antdx/code-highlighter/Index.svelte](file://frontend/antdx/code-highlighter/Index.svelte) +- [frontend/antdx/code-highlighter/code-highlighter.tsx](file://frontend/antdx/code-highlighter/code-highlighter.tsx) +- [frontend/antdx/code-highlighter/package.json](file://frontend/antdx/code-highlighter/package.json) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [docs/components/antdx/code_highlighter/README.md](file://docs/components/antdx/code_highlighter/README.md) +- [docs/components/antdx/code_highlighter/README-zh_CN.md](file://docs/components/antdx/code_highlighter/README-zh_CN.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +CodeHighlighter is a code highlighting component based on Ant Design X, used to provide syntax highlighting functionality in ModelScope Studio. This component supports syntax highlighting for multiple programming languages, including dark and light theme modes, and provides flexible configuration options to meet different use cases. + +The component is integrated with Gradio to achieve seamless frontend-backend connection, providing users with a powerful and easy-to-use code display tool. The component supports advanced features such as custom styles, language selection, and header content. + +## Project Structure + +The position of the CodeHighlighter component in the overall project architecture is as follows: + +```mermaid +graph TB +subgraph "Backend" +A[ModelScope Studio Backend] +B[AntdX Components] +C[CodeHighlighter Component] +end +subgraph "Frontend" +D[Svelte Component] +E[React Wrapper] +F[Ant Design X] +end +subgraph "Documentation" +G[Example Documentation] +H[Usage Instructions] +end +A --> B +B --> C +C --> D +D --> E +E --> F +A --> G +G --> H +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:1-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L1-L71) +- [frontend/antdx/code-highlighter/Index.svelte:1-65](file://frontend/antdx/code-highlighter/Index.svelte#L1-L65) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:1-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L1-L71) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) + +## Core Components + +### Backend Component Class + +The CodeHighlighter backend component inherits from `ModelScopeLayoutComponent`, providing complete component lifecycle management and property handling mechanisms. + +**Main Features:** + +- Supports syntax highlighting for multiple programming languages +- Automatic theme adaptation (dark/light mode) +- Customizable styles and class names +- Slot system supports header content +- API skip mechanism for performance optimization + +**Key Properties:** + +- `value`: Code content to highlight +- `lang`: Programming language type +- `header`: Header display content +- `highlight_props`: Highlight configuration properties +- `prism_light_mode`: Prism theme mode setting + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:15-52](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L15-L52) + +### Frontend Component Implementation + +The frontend adopts a mixed Svelte + React architecture, bridging components through the `sveltify` tool. + +**Technical Features:** + +- Dynamic import for optimized loading performance +- Slot system support +- Automatic theme detection and switching +- Custom style overrides + +**Section Sources** + +- [frontend/antdx/code-highlighter/Index.svelte:1-65](file://frontend/antdx/code-highlighter/Index.svelte#L1-L65) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) + +## Architecture Overview + +CodeHighlighter adopts a layered architecture design, achieving clear frontend-backend separation: + +```mermaid +sequenceDiagram +participant Client as Client Application +participant Backend as Backend Component +participant Frontend as Frontend Component +participant AntDX as Ant Design X +participant Prism as Prism Syntax Highlighter +Client->>Backend : Create CodeHighlighter instance +Backend->>Frontend : Resolve frontend directory +Frontend->>Frontend : Dynamically import React component +Frontend->>AntDX : Wrap as Svelte component +AntDX->>Prism : Apply syntax highlighting styles +Prism-->>AntDX : Return highlighted code +AntDX-->>Frontend : Render final result +Frontend-->>Client : Display highlighted code block +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:53-53](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L53-L53) +- [frontend/antdx/code-highlighter/Index.svelte:10-12](file://frontend/antdx/code-highlighter/Index.svelte#L10-L12) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:29-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L29-L51) + +## Detailed Component Analysis + +### Component Class Structure Diagram + +```mermaid +classDiagram +class AntdXCodeHighlighter { ++EVENTS : [] ++SLOTS : ["header"] ++additional_props : dict ++styles : dict|str ++class_names : dict|str ++root_class_name : str ++value : str|None ++lang : str|None ++header : str|bool|None ++highlight_props : dict|None ++prism_light_mode : bool|None ++FRONTEND_DIR : str ++skip_api : bool ++preprocess(payload) None ++postprocess(value) None ++example_payload() None ++example_value() None +} +class ModelScopeLayoutComponent { +<> ++visible : bool ++elem_id : str|None ++elem_classes : list[str]|str|None ++elem_style : dict|None ++render : bool ++as_item : str|None +} +AntdXCodeHighlighter --|> ModelScopeLayoutComponent : Inherits +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:6-71](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L6-L71) + +### Frontend Rendering Flow + +```mermaid +flowchart TD +Start([Component Initialization]) --> CheckVisible{Check Visibility} +CheckVisible --> |Not Visible| Hide[Hide Component] +CheckVisible --> |Visible| LoadComponent[Dynamically Load Component] +LoadComponent --> ImportReact[Import React Component] +ImportReact --> ProcessProps[Process Component Properties] +ProcessProps --> GetSlots[Get Slot Content] +GetSlots --> RenderComponent[Render CodeHighlighter] +RenderComponent --> ApplyTheme[Apply Theme Styles] +ApplyTheme --> Display[Display Highlighted Code] +Hide --> End([End]) +Display --> End +``` + +**Diagram Sources** + +- [frontend/antdx/code-highlighter/Index.svelte:50-64](file://frontend/antdx/code-highlighter/Index.svelte#L50-L64) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:35-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L35-L51) + +### Theme System Design + +The component supports custom styles for two theme modes: + +```mermaid +graph LR +subgraph "Theme Configuration" +A[Material Light] +B[Material Dark] +C[Custom Style Override] +end +subgraph "Style Application" +D[Preprocessor] +E[Runtime Switching] +F[Component Rendering] +end +A --> D +B --> D +C --> D +D --> E +E --> F +``` + +**Diagram Sources** + +- [frontend/antdx/code-highlighter/code-highlighter.tsx:13-27](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L13-L27) + +**Section Sources** + +- [frontend/antdx/code-highlighter/code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) + +## Dependency Analysis + +### Component Dependency Diagram + +```mermaid +graph TB +subgraph "External Dependencies" +A[@ant-design/x] +B[react-syntax-highlighter] +C[classnames] +D[svelte-preprocess-react] +end +subgraph "Internal Dependencies" +E[ModelScopeLayoutComponent] +F[resolve_frontend_dir] +G[Gradio Integration] +end +subgraph "Component Hierarchy" +H[AntdXCodeHighlighter] +I[Index.svelte] +J[code-highlighter.tsx] +end +H --> E +H --> F +H --> G +I --> H +I --> D +I --> C +J --> A +J --> B +J --> D +``` + +**Diagram Sources** + +- [frontend/antdx/code-highlighter/code-highlighter.tsx:1-11](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L11) +- [frontend/antdx/code-highlighter/Index.svelte:1-8](file://frontend/antdx/code-highlighter/Index.svelte#L1-L8) +- [backend/modelscope_studio/components/antdx/code_highlighter/**init**.py:3-3](file://backend/modelscope_studio/components/antdx/code_highlighter/__init__.py#L3-L3) + +### Package Management Configuration + +The component's package configuration supports multi-entry exports: + +**Section Sources** + +- [frontend/antdx/code-highlighter/package.json:1-15](file://frontend/antdx/code-highlighter/package.json#L1-L15) + +## Performance Considerations + +### Loading Optimization Strategy + +1. **Dynamic import**: Uses `importComponent` and `import()` to implement on-demand loading +2. **Lazy loading**: Components are only rendered when needed +3. **Caching mechanism**: Already resolved components are cached to improve repeated access performance + +### Memory Management + +- Event listeners are cleaned up when components are destroyed +- Slot content is properly released when no longer needed +- Theme style objects are reasonably reused + +## Troubleshooting Guide + +### Common Issues and Solutions + +**Issue 1: Code not displaying with highlighting** + +- Check if the `value` property is correctly set +- Confirm the language identifier in the `lang` property is valid +- Verify the `highlightProps` configuration is correct + +**Issue 2: Theme display anomalies** + +- Check the `themeMode` property setting +- Confirm shared theme configuration is correct +- Verify custom style overrides are not conflicting + +**Issue 3: Component not rendering** + +- Check the `visible` property status +- Confirm `elem_id` and `elem_classes` configuration +- Verify Gradio integration is functioning normally + +**Section Sources** + +- [frontend/antdx/code-highlighter/Index.svelte:50-64](file://frontend/antdx/code-highlighter/Index.svelte#L50-L64) +- [frontend/antdx/code-highlighter/code-highlighter.tsx:35-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L35-L51) + +## Conclusion + +The CodeHighlighter component is a fully functional, clearly architected code highlighting solution. It successfully combines the powerful capabilities of Ant Design X with the Gradio ecosystem, providing users with an excellent code display experience. + +**Main Advantages:** + +- Complete syntax highlighting support +- Flexible theme configuration +- Good performance +- Easy-to-use API interface +- Comprehensive documentation support + +This component provides powerful code display capabilities for ModelScope Studio and can meet the needs of various development and presentation scenarios. Through reasonable architecture design and performance optimization, it ensures stable operation in different environments. diff --git a/.wiki/en/Ant Design X Components/Tool Components/Mermaid Component.md b/.wiki/en/Ant Design X Components/Tool Components/Mermaid Component.md new file mode 100644 index 00000000..c245870b --- /dev/null +++ b/.wiki/en/Ant Design X Components/Tool Components/Mermaid Component.md @@ -0,0 +1,334 @@ +# Mermaid Component + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antdx/mermaid/__init__.py](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py) +- [frontend/antdx/mermaid/Index.svelte](file://frontend/antdx/mermaid/Index.svelte) +- [frontend/antdx/mermaid/mermaid.tsx](file://frontend/antdx/mermaid/mermaid.tsx) +- [frontend/antdx/mermaid/gradio.config.js](file://frontend/antdx/mermaid/gradio.config.js) +- [frontend/antdx/mermaid/package.json](file://frontend/antdx/mermaid/package.json) +- [frontend/globals/components/markdown/utils.ts](file://frontend/globals/components/markdown/utils.ts) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +The Mermaid flowchart component in ModelScope Studio is a visualization chart rendering component based on Ant Design X, specifically designed to display flowcharts, sequence diagrams, Gantt charts, and other diagrams in Mermaid format within Gradio applications. This component provides complete frontend rendering capabilities, supporting theme switching, custom action buttons, and a slot system. + +## Project Structure + +The Mermaid component adopts a layered architecture design, primarily containing the following layers: + +```mermaid +graph TB +subgraph "Backend Layer" +Backend[Python Backend Component] +DevUtils[Development Utility Class] +end +subgraph "Frontend Layer" +SvelteUI[Svelte Frontend Component] +ReactAdapter[React Adapter] +AntDX[Ant Design X Component] +end +subgraph "Utility Layer" +MarkdownRenderer[Markdown Renderer] +ThemeManager[Theme Manager] +SlotSystem[Slot System] +end +Backend --> SvelteUI +SvelteUI --> ReactAdapter +ReactAdapter --> AntDX +Backend --> DevUtils +SvelteUI --> MarkdownRenderer +SvelteUI --> ThemeManager +SvelteUI --> SlotSystem +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/mermaid/**init**.py:1-77](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L1-L77) +- [frontend/antdx/mermaid/Index.svelte:1-69](file://frontend/antdx/mermaid/Index.svelte#L1-L69) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/mermaid/**init**.py:1-77](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L1-L77) +- [frontend/antdx/mermaid/Index.svelte:1-69](file://frontend/antdx/mermaid/Index.svelte#L1-L69) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) + +## Core Components + +### AntdXMermaid Python Component + +AntdXMermaid is the core backend component class, inheriting from `ModelScopeLayoutComponent`, providing complete Gradio integration capabilities. + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++EVENTS : List ++SLOTS : List ++skip_api : bool ++FRONTEND_DIR : str ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class AntdXMermaid { ++value : str ++highlight_props : dict ++config : dict ++actions : dict ++prefix_cls : str ++styles : dict ++class_names : dict ++additional_props : dict ++root_class_name : str +} +ModelScopeLayoutComponent <|-- AntdXMermaid +``` + +**Diagram Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-127](file://backend/modelscope_studio/utils/dev/component.py#L11-L127) +- [backend/modelscope_studio/components/antdx/mermaid/**init**.py:8-77](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L8-L77) + +### Frontend Rendering Component + +The frontend layer adopts a mixed Svelte + React architecture, wrapping React components as Svelte components through the `sveltify` adapter. + +**Section Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-127](file://backend/modelscope_studio/utils/dev/component.py#L11-L127) +- [backend/modelscope_studio/components/antdx/mermaid/**init**.py:8-77](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L8-L77) + +## Architecture Overview + +The overall architecture of the Mermaid component adopts a layered design, achieving frontend-backend separation and modular management: + +```mermaid +sequenceDiagram +participant User as User +participant Backend as Backend Component +participant Frontend as Frontend Component +participant AntDX as Ant Design X +participant MermaidLib as Mermaid Library +User->>Backend : Create component instance +Backend->>Frontend : Resolve frontend directory +Frontend->>AntDX : Load Mermaid component +AntDX->>MermaidLib : Initialize rendering engine +MermaidLib-->>AntDX : Return rendering result +AntDX-->>Frontend : Output chart element +Frontend-->>Backend : Update component state +Backend-->>User : Display rendered chart +``` + +**Diagram Sources** + +- [frontend/antdx/mermaid/Index.svelte:10-68](file://frontend/antdx/mermaid/Index.svelte#L10-L68) +- [frontend/antdx/mermaid/mermaid.tsx:50-79](file://frontend/antdx/mermaid/mermaid.tsx#L50-L79) + +## Detailed Component Analysis + +### Backend Component Implementation + +The backend component inherits from `ModelScopeLayoutComponent`, implementing the following key features: + +#### Component Property Configuration + +- `value`: Chart content string +- `highlight_props`: Syntax highlighting configuration +- `config`: Mermaid configuration options +- `actions`: Custom action buttons +- `styles/class_names`: Style configuration + +#### Event Handling Mechanism + +The component supports the `render_type_change` event, binding render type change events via callback functions. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/mermaid/**init**.py:12-16](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L12-L16) +- [backend/modelscope_studio/components/antdx/mermaid/**init**.py:21-58](file://backend/modelscope_studio/components/antdx/mermaid/__init__.py#L21-L58) + +### Frontend Component Architecture + +The frontend adopts a three-layer architecture design: + +#### Svelte Layer (Index.svelte) + +Responsible for component lifecycle management and property forwarding, using `importComponent` to dynamically load React components. + +#### React Adapter Layer (mermaid.tsx) + +Wraps React components into Svelte-compatible components via `sveltify`, implementing property transformation and event handling. + +#### Ant Design X Integration + +Directly uses `@ant-design/x`'s `Mermaid` component, providing rich chart rendering capabilities. + +**Section Sources** + +- [frontend/antdx/mermaid/Index.svelte:1-69](file://frontend/antdx/mermaid/Index.svelte#L1-L69) +- [frontend/antdx/mermaid/mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) + +### Theme and Style System + +The component supports both dark and light theme modes, controlled by the `themeMode` property: + +```mermaid +flowchart TD +Start([Component Initialization]) --> CheckTheme{"Check Theme Mode"} +CheckTheme --> |Dark| DarkTheme["Apply Dark Theme"] +CheckTheme --> |Light| LightTheme["Apply Light Theme"] +DarkTheme --> CustomStyles["Apply Custom Styles"] +LightTheme --> CustomStyles +CustomStyles --> HighlightProps["Configure Syntax Highlighting"] +HighlightProps --> RenderChart["Render Chart"] +RenderChart --> End([Complete]) +``` + +**Diagram Sources** + +- [frontend/antdx/mermaid/mermaid.tsx:17-31](file://frontend/antdx/mermaid/mermaid.tsx#L17-L31) +- [frontend/antdx/mermaid/mermaid.tsx:56-61](file://frontend/antdx/mermaid/mermaid.tsx#L56-L61) + +**Section Sources** + +- [frontend/antdx/mermaid/mermaid.tsx:17-31](file://frontend/antdx/mermaid/mermaid.tsx#L17-L31) +- [frontend/antdx/mermaid/mermaid.tsx:56-61](file://frontend/antdx/mermaid/mermaid.tsx#L56-L61) + +### Slot System + +The component supports two main slots: + +- `header`: Header content slot +- `actions.customActions`: Custom action button slot + +The slot system is implemented via `getSlots()` and `ReactSlot`, supporting dynamic content rendering. + +**Section Sources** + +- [frontend/antdx/mermaid/Index.svelte:51-51](file://frontend/antdx/mermaid/Index.svelte#L51-L51) +- [frontend/antdx/mermaid/mermaid.tsx:38-38](file://frontend/antdx/mermaid/mermaid.tsx#L38-L38) + +## Dependency Analysis + +The component's dependency relationships exhibit a clear layered structure: + +```mermaid +graph TB +subgraph "External Dependencies" +AntDX["@ant-design/x"] +MermaidLib["mermaid"] +ReactSyntax["react-syntax-highlighter"] +ClassNames["classnames"] +end +subgraph "Internal Dependencies" +Utils["@utils/renderItems"] +ActionsCtx["../actions/context"] +Preprocess["@svelte-preprocess-react"] +end +subgraph "Component Layer" +AntdXMermaid["AntdXMermaid"] +SvelteComponent["Svelte Component"] +ReactComponent["React Component"] +end +AntdXMermaid --> SvelteComponent +SvelteComponent --> ReactComponent +ReactComponent --> AntDX +ReactComponent --> MermaidLib +ReactComponent --> ReactSyntax +ReactComponent --> Utils +ReactComponent --> ActionsCtx +SvelteComponent --> Preprocess +SvelteComponent --> ClassNames +``` + +**Diagram Sources** + +- [frontend/antdx/mermaid/mermaid.tsx:1-15](file://frontend/antdx/mermaid/mermaid.tsx#L1-L15) +- [frontend/antdx/mermaid/Index.svelte:2-8](file://frontend/antdx/mermaid/Index.svelte#L2-L8) + +**Section Sources** + +- [frontend/antdx/mermaid/mermaid.tsx:1-15](file://frontend/antdx/mermaid/mermaid.tsx#L1-L15) +- [frontend/antdx/mermaid/Index.svelte:2-8](file://frontend/antdx/mermaid/Index.svelte#L2-L8) + +## Performance Considerations + +### On-demand Loading Optimization + +The component uses a dynamic import (`importComponent`) mechanism, loading React components only when needed to reduce the initial bundle size. + +### Rendering Performance Optimization + +- Uses `useMemo` to cache calculation results, avoiding unnecessary re-renders +- Uses `tick()` to ensure correct DOM update timing +- Supports asynchronous rendering for improved user experience + +### Memory Management + +- Automatically cleans up event listeners when components are destroyed +- Promptly releases no-longer-needed resources + +## Troubleshooting Guide + +### Common Issues and Solutions + +#### Chart Rendering Failure + +When Mermaid chart rendering fails, the system automatically degrades to code display mode: + +```mermaid +flowchart TD +TryRender["Attempt to render chart"] --> Success{"Render successful?"} +Success --> |Yes| ShowChart["Display chart"] +Success --> |No| CheckError["Check error type"] +CheckError --> HasDiagram{"Chart element exists?"} +HasDiagram --> |Yes| KeepOriginal["Keep original content"] +HasDiagram --> |No| ShowCode["Display code block"] +KeepOriginal --> AddErrorClass["Add error style"] +ShowCode --> AddErrorClass +AddErrorClass --> ShowError["Display error message"] +``` + +**Diagram Sources** + +- [frontend/globals/components/markdown/utils.ts:191-222](file://frontend/globals/components/markdown/utils.ts#L191-L222) + +#### Theme Mismatch Issue + +Ensure the `themeMode` property is correctly passed to the component; use `dark` in dark mode and `base` in light mode. + +#### Slot Content Not Displaying + +Check if slot names are correct (`header` or `actions.customActions`) and if slot content is correctly passed. + +**Section Sources** + +- [frontend/globals/components/markdown/utils.ts:191-222](file://frontend/globals/components/markdown/utils.ts#L191-L222) + +## Conclusion + +The Mermaid flowchart component in ModelScope Studio achieves a high-performance, extensible chart rendering solution through its carefully designed layered architecture. The component has the following advantages: + +1. **Complete Gradio integration**: Provides native Gradio support through `ModelScopeLayoutComponent` +2. **Flexible theme system**: Supports automatic switching between dark and light themes +3. **Powerful slot system**: Provides flexible configuration of header content and custom action buttons +4. **Excellent error handling**: Intelligent degradation mechanism ensures user experience +5. **Efficient rendering performance**: On-demand loading and caching optimization improve performance + +This component provides developers with a powerful and easy-to-use chart rendering tool, applicable to various data visualization scenarios. diff --git a/.wiki/en/Ant Design X Components/Tool Components/Notification Component.md b/.wiki/en/Ant Design X Components/Tool Components/Notification Component.md new file mode 100644 index 00000000..a6c861f2 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Tool Components/Notification Component.md @@ -0,0 +1,367 @@ +# Notification Component + + +**Files referenced in this document** +- [backend/modelscope_studio/components/antd/notification/__init__.py](file://backend/modelscope_studio/components/antd/notification/__init__.py) +- [frontend/antd/notification/notification.tsx](file://frontend/antd/notification/notification.tsx) +- [frontend/antd/notification/Index.svelte](file://frontend/antd/notification/Index.svelte) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [frontend/antd/notification/package.json](file://frontend/antd/notification/package.json) +- [frontend/antd/notification/gradio.config.js](file://frontend/antd/notification/gradio.config.js) +- [docs/components/antd/notification/README.md](file://docs/components/antd/notification/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) + +## Introduction + +The Notification component in ModelScope Studio is a global notification component based on Ant Design, used to display various types of notification messages in applications. This component supports multiple notification types (success, info, warning, error) and provides customizable notification position, duration, progress bar, and other features. + +The component adopts a frontend-backend separated architecture design, with the backend implementing component definitions in Python and the frontend built with React and TypeScript, integrated through the Gradio framework. + +## Project Structure + +The ModelScope Studio project adopts modular organization, with the Notification component located in the following directory structure: + +```mermaid +graph TB +subgraph "Backend (Python)" +A[backend/modelscope_studio/] --> B[components/] +B --> C[antd/] +C --> D[notification/] +D --> E[__init__.py] +end +subgraph "Frontend (TypeScript/React)" +F[frontend/] --> G[antd/] +G --> H[notification/] +H --> I[Index.svelte] +H --> J[notification.tsx] +H --> K[package.json] +H --> L[gradio.config.js] +end +subgraph "Documentation" +M[docs/] --> N[components/] +N --> O[antd/] +O --> P[notification/] +end +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antd/notification/**init**.py:1-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L1-L109) +- [frontend/antd/notification/Index.svelte:1-80](file://frontend/antd/notification/Index.svelte#L1-L80) + +**Section Sources** + +- [backend/modelscope_studio/components/antd/notification/**init**.py:1-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L1-L109) +- [frontend/antd/notification/notification.tsx:1-106](file://frontend/antd/notification/notification.tsx#L1-L106) + +## Core Components + +The core implementation of the Notification component includes three main parts: + +### Backend Component Class + +The backend uses the `AntdNotification` class inheriting from `ModelScopeLayoutComponent`, providing complete component functionality definitions: + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++EVENTS : list ++SLOTS : list ++skip_api : bool ++visible : bool ++elem_id : str ++elem_classes : list ++elem_style : dict ++render : bool +} +class AntdNotification { ++message : str ++description : str ++title : str ++type : str ++duration : float ++placement : str ++key : str ++FRONTEND_DIR : str ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +ModelScopeLayoutComponent <|-- AntdNotification +``` + +**Diagram Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/components/antd/notification/**init**.py:10-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L10-L109) + +### Frontend React Component + +The frontend uses React Hooks and Ant Design's notification API to implement notification functionality: + +```mermaid +sequenceDiagram +participant Svelte as Svelte Component +participant React as React Component +participant Antd as Antd Notification API +participant User as User +Svelte->>React : Render component +React->>React : Initialize useNotification hook +React->>React : Listen for visible state changes +React->>Antd : notificationApi.open() +Antd-->>React : Return notification instance +React->>User : Display notification +User->>React : Click to close +React->>Antd : notificationApi.destroy() +Antd-->>React : Close complete +``` + +**Diagram Sources** + +- [frontend/antd/notification/notification.tsx:31-95](file://frontend/antd/notification/notification.tsx#L31-L95) +- [frontend/antd/notification/Index.svelte:59-79](file://frontend/antd/notification/Index.svelte#L59-L79) + +**Section Sources** + +- [backend/modelscope_studio/components/antd/notification/**init**.py:10-109](file://backend/modelscope_studio/components/antd/notification/__init__.py#L10-L109) +- [frontend/antd/notification/notification.tsx:8-106](file://frontend/antd/notification/notification.tsx#L8-L106) + +## Architecture Overview + +The Notification component adopts a layered architecture design, ensuring clear frontend-backend separation and good maintainability: + +```mermaid +graph TB +subgraph "User Interface Layer" +UI[User Interface] +end +subgraph "Frontend Application Layer" +Svelte[Svelte Component] +React[React Component] +Hooks[React Hooks] +end +subgraph "Component Library Layer" +Antd[Ant Design] +NotificationAPI[Notification API] +end +subgraph "Backend Service Layer" +Python[Python Component] +Gradio[Gradio Framework] +end +subgraph "Data Layer" +Props[Property Forwarding] +State[State Management] +end +UI --> Svelte +Svelte --> React +React --> Hooks +Hooks --> Antd +Antd --> NotificationAPI +Svelte --> Python +Python --> Gradio +Gradio --> Props +Props --> State +State --> Hooks +``` + +**Diagram Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [frontend/antd/notification/notification.tsx:31-95](file://frontend/antd/notification/notification.tsx#L31-L95) + +## Detailed Component Analysis + +### Backend Component Implementation + +The backend `AntdNotification` class provides complete component definitions, including event handling, slot support, and property configuration: + +#### Main Features + +1. **Event system**: Supports click and close event listeners +2. **Slot system**: Supports multiple slots (actions, closeIcon, description, icon, message, title) +3. **Property configuration**: Provides rich configuration options such as type, placement, duration, etc. + +#### Key Method Descriptions + +- `EVENTS`: Defines the list of supported events +- `SLOTS`: Defines supported slot names +- `preprocess()`: Preprocesses input data +- `postprocess()`: Processes output results +- `example_payload()`: Provides sample payload data + +**Section Sources** + +- [backend/modelscope_studio/components/antd/notification/**init**.py:14-21](file://backend/modelscope_studio/components/antd/notification/__init__.py#L14-L21) +- [backend/modelscope_studio/components/antd/notification/**init**.py:24](file://backend/modelscope_studio/components/antd/notification/__init__.py#L24) +- [backend/modelscope_studio/components/antd/notification/**init**.py:97-108](file://backend/modelscope_studio/components/antd/notification/__init__.py#L97-L108) + +### Frontend React Component Implementation + +The frontend component uses modern React development patterns, combined with Ant Design's notification functionality: + +#### Core Functionality + +1. **State management**: Uses React Hooks to manage notification state +2. **Lifecycle**: Automatically handles notification creation and destruction +3. **Slot rendering**: Supports dynamic slot content rendering +4. **Event handling**: Handles user interaction events + +#### Component Flow + +```mermaid +flowchart TD +Start([Component Initialization]) --> CheckVisible{Check visible state} +CheckVisible --> |true| CreateNotification[Create notification] +CheckVisible --> |false| DestroyNotification[Destroy notification] +CreateNotification --> RenderSlots[Render slot content] +RenderSlots --> ShowNotification[Show notification] +ShowNotification --> UserAction{User action} +UserAction --> |Close| HandleClose[Handle close event] +UserAction --> |Click| HandleClick[Handle click event] +HandleClose --> DestroyNotification +HandleClick --> DestroyNotification +DestroyNotification --> Cleanup[Clean up resources] +Cleanup --> End([Component unmounted]) +``` + +**Diagram Sources** + +- [frontend/antd/notification/notification.tsx:38-95](file://frontend/antd/notification/notification.tsx#L38-L95) + +**Section Sources** + +- [frontend/antd/notification/notification.tsx:8-106](file://frontend/antd/notification/notification.tsx#L8-L106) + +### Svelte Component Bridge + +The Svelte component serves as the bridge between frontend and backend, responsible for property forwarding and event handling: + +#### Main Responsibilities + +1. **Property handling**: Converts Python properties to React-compatible format +2. **Event binding**: Handles user interaction events +3. **Slot management**: Manages component slot content +4. **State synchronization**: Synchronizes component state to the backend + +**Section Sources** + +- [frontend/antd/notification/Index.svelte:19-79](file://frontend/antd/notification/Index.svelte#L19-L79) + +## Dependency Analysis + +The dependency relationships of the Notification component are relatively simple, primarily depending on the Ant Design and Gradio frameworks: + +```mermaid +graph TB +subgraph "External Dependencies" +Antd[Ant Design] +Gradio[Gradio Framework] +React[React] +Typescript[TypeScript] +end +subgraph "Internal Dependencies" +ComponentBase[Component Base Class] +Utils[Utility Functions] +Config[Configuration Files] +end +subgraph "Notification Component" +Backend[Backend Component] +Frontend[Frontend Component] +Bridge[Svelte Bridge] +end +Antd --> Frontend +Gradio --> Backend +React --> Frontend +Typescript --> Frontend +ComponentBase --> Backend +Utils --> Backend +Config --> Frontend +Backend --> Bridge +Bridge --> Frontend +``` + +**Diagram Sources** + +- [frontend/antd/notification/package.json:1-15](file://frontend/antd/notification/package.json#L1-L15) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +**Section Sources** + +- [backend/modelscope_studio/components/antd/**init**.py:82](file://backend/modelscope_studio/components/antd/__init__.py#L82) +- [backend/modelscope_studio/components/antd/components.py:79](file://backend/modelscope_studio/components/antd/components.py#L79) + +## Performance Considerations + +The Notification component incorporates the following performance optimizations in its design: + +### Memory Management + +- Automatically destroys notification instances that are no longer in use +- Reasonable component unmounting handling +- Avoids memory leaks + +### Render Optimization + +- Conditional rendering avoids unnecessary updates +- Effective state management +- Lazy loading of slot content + +### User Experience + +- Appropriate notification duration +- Smooth animation effects +- Responsive layout + +## Troubleshooting Guide + +### Common Issues and Solutions + +#### Notification Not Displaying + +1. Check if the `visible` property is set to `True` +2. Confirm that `message` or `description` is correctly set +3. Verify that the component is rendering correctly + +#### Events Not Responding + +1. Check if event listeners are correctly bound +2. Confirm callback functions are correctly implemented +3. Verify event parameter passing + +#### Style Issues + +1. Check if CSS class names are correct +2. Verify style override rules +3. Confirm theme configuration + +**Section Sources** + +- [frontend/antd/notification/notification.tsx:65-68](file://frontend/antd/notification/notification.tsx#L65-L68) +- [backend/modelscope_studio/components/antd/notification/**init**.py:14-21](file://backend/modelscope_studio/components/antd/notification/__init__.py#L14-L21) + +## Conclusion + +The Notification component in ModelScope Studio is a well-designed component with the following characteristics: + +1. **Complete feature support**: Supports multiple notification types and rich configuration options +2. **Good architecture design**: Frontend-backend separation, easy to maintain and extend +3. **Excellent user experience**: Provides smooth interactions and visual effects +4. **Performance optimization**: Considers memory management and rendering optimization +5. **Comprehensive documentation**: Provides clear usage instructions and examples + +This component provides developers with a powerful and flexible notification solution that can meet the needs of various application scenarios. diff --git a/.wiki/en/Ant Design X Components/Tool Components/Tool Components.md b/.wiki/en/Ant Design X Components/Tool Components/Tool Components.md new file mode 100644 index 00000000..d1031332 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Tool Components/Tool Components.md @@ -0,0 +1,374 @@ +# Tool Components + + +**Files referenced in this document** +- [XProvider.svelte](file://frontend/antdx/x-provider/XProvider.svelte) +- [Index.svelte (XProvider export wrapper)](file://frontend/antdx/x-provider/Index.svelte) +- [config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [code-highlighter.tsx](file://frontend/antdx/code-highlighter/code-highlighter.tsx) +- [mermaid.tsx](file://frontend/antdx/mermaid/mermaid.tsx) +- [notification.tsx](file://frontend/antdx/notification/notification.tsx) +- [actions/context.ts](file://frontend/antdx/actions/context.ts) +- [backend/__init__.py (antdx aggregated exports)](file://backend/modelscope_studio/components/antdx/__init__.py) +- [x_provider documentation](file://docs/components/antdx/x_provider/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Best Practices](#appendix-usage-examples-and-best-practices) + +## Introduction + +This document is oriented toward Ant Design X tool components, systematically organizing the design and usage of the following components: + +- XProvider: Global configuration and context provider, extending antd's ConfigProvider to uniformly provide global capabilities such as theme, language, and popup container for @ant-design/x components. +- CodeHighlighter: Code highlighting display component, supporting theme customization, header slots, and syntax highlighting style overrides. +- Mermaid: Flowchart/mind map component, integrating highlighting and action item rendering, supporting light/dark theme switching and custom actions. +- Notification: Browser notification encapsulation, providing permission requests, open/close, visibility control, and callbacks. + +## Project Structure + +Key directories and files around the tool components are as follows: + +- Frontend Svelte wrapper layer: Component wrapper files under frontend/antdx, responsible for integrating @ant-design/x components into the Gradio ecosystem in a Svelte manner. +- antd ConfigProvider extension: frontend/antd/config-provider provides global capabilities such as theme, language, and popup containers. +- Action item context: frontend/antdx/actions/context provides action item context injection and rendering utilities. +- Backend aggregated exports: backend/modelscope_studio/components/antdx/**init**.py uniformly exports antdx components for use in the Python layer. + +```mermaid +graph TB +subgraph "Frontend Wrapper Layer" +XP["XProvider.svelte"] +CH["code-highlighter.tsx"] +MG["mermaid.tsx"] +NT["notification.tsx"] +end +subgraph "antd Extension" +CP["config-provider.tsx"] +end +subgraph "Action Item Context" +ACT["actions/context.ts"] +end +subgraph "Backend Exports" +BE["backend/__init__.py"] +end +XP --> CP +MG --> ACT +BE --> XP +BE --> CH +BE --> MG +BE --> NT +``` + +**Diagram Sources** + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) +- [config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) +- [mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [backend/**init**.py (antdx aggregated exports):1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) + +**Section Sources** + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) +- [config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) +- [mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [backend/**init**.py (antdx aggregated exports):1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) + +## Core Components + +- XProvider: In Svelte, asynchronously loads and injects ConfigProvider via importComponent, uniformly forwarding properties such as theme, themeMode, slots, and container functions, serving as the global context root node for @ant-design/x components. +- CodeHighlighter: A secondary encapsulation of @ant-design/x's CodeHighlighter, supporting header slots, theme mode switching, and highlightProps overrides. +- Mermaid: A secondary encapsulation of @ant-design/x's Mermaid, supporting header, actions.customActions slots and context injection, and automatically switching mermaid themes and highlighting styles based on themeMode. +- Notification: A secondary encapsulation of @ant-design/x's notification, exposing visible control, permission callbacks, tag-based closing, and other capabilities. + +**Backend Export Entry Description** +All of the above tool components are uniformly exported through [backend/modelscope_studio/components/antdx/**init**.py](file://backend/modelscope_studio/components/antdx/__init__.py), with the following export names: + +- `XProvider`: `from modelscope_studio.components.antdx import XProvider` +- `CodeHighlighter`: `from modelscope_studio.components.antdx import CodeHighlighter` +- `Mermaid`: `from modelscope_studio.components.antdx import Mermaid` +- `Notification`: `from modelscope_studio.components.antdx import Notification` + +**Section Sources** + +- [XProvider.svelte:12-74](file://frontend/antdx/x-provider/XProvider.svelte#L12-L74) +- [config-provider.tsx:53-151](file://frontend/antd/config-provider/config-provider.tsx#L53-L151) +- [code-highlighter.tsx:29-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L29-L51) +- [mermaid.tsx:33-84](file://frontend/antdx/mermaid/mermaid.tsx#L33-L84) +- [notification.tsx:6-50](file://frontend/antdx/notification/notification.tsx#L6-L50) + +## Architecture Overview + +The following diagram shows how XProvider connects antd's ConfigProvider with @ant-design/x components, completing the forwarding of properties and content through the Svelte context and slots mechanism. + +```mermaid +sequenceDiagram +participant App as "Application Root Node" +participant XP as "XProvider.svelte" +participant CP as "config-provider.tsx" +participant X as "@ant-design/x Component Tree" +App->>XP : Pass props (theme/themeMode/slots/container functions) +XP->>CP : Render ConfigProvider and inject themeMode/locale/getPopupContainer, etc. +CP-->>XP : Return Provider with global styles injected +XP->>X : Render children inside Provider +X-->>App : Child components take effect with global configuration +``` + +**Diagram Sources** + +- [XProvider.svelte:56-74](file://frontend/antdx/x-provider/XProvider.svelte#L56-L74) +- [config-provider.tsx:108-149](file://frontend/antd/config-provider/config-provider.tsx#L108-L149) + +**Section Sources** + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) +- [config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) + +## Component Details + +### XProvider Global Configuration and Context Providing Mechanism + +- Design points + - Uses importComponent to asynchronously load the antd ConfigProvider wrapper component, avoiding first-screen blocking. + - Extracts and merges Gradio extra properties, theme configuration, and common layout properties through getProps/processProps to form the final forwarded props. + - setConfigType('antd') specifies the configuration type, ensuring subsequent components consume a consistent context. + - Supports slot injection, converting Svelte slots into React-recognizable structures. +- Key behavior + - theme and themeMode: theme is preferentially obtained from additionalProps or restProps; themeMode comes from the shared theme state. + - Container functions: getPopupContainer and getTargetContainer are wrapped via useFunction, ensuring stable availability within the component lifecycle. + - Visibility control: Only renders the Provider when visible is true, enabling on-demand mounting. +- Best practices + - Place XProvider at the application root to ensure child components inherit global theme and language settings. + - If antd.ConfigProvider is already in use, replace it with antdx.XProvider to maintain configuration consistency. + +```mermaid +flowchart TD +Start(["Enter XProvider"]) --> GetProps["Extract props and additional properties"] +GetProps --> MergeTheme["Merge theme and themeMode"] +MergeTheme --> Slots["Process slots and inject into components"] +Slots --> Container["Bind container functions and style properties"] +Container --> Visible{"visible is true?"} +Visible -- No --> End(["Do not render"]) +Visible -- Yes --> Render["Render ConfigProvider wrapper"] +Render --> End +``` + +**Diagram Sources** + +- [XProvider.svelte:25-74](file://frontend/antdx/x-provider/XProvider.svelte#L25-L74) +- [config-provider.tsx:93-149](file://frontend/antd/config-provider/config-provider.tsx#L93-L149) + +**Section Sources** + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) +- [Index.svelte (XProvider export wrapper):1-20](file://frontend/antdx/x-provider/Index.svelte#L1-L20) +- [config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [x_provider documentation:1-19](file://docs/components/antdx/x_provider/README.md#L1-L19) + +### CodeHighlighter Code Highlighting Component + +- Design points + - Interfaces with @ant-design/x's CodeHighlighter, supporting header slots and highlightProps customization. + - Theme customization: Based on materialDark/materialLight, uniformly removes code block outer margins to adapt to card/conversation scenarios. + - Value source: Supports passing code strings directly via the value property, or through children. +- Usage recommendations + - Use customDarkStyle in dark themes and customLightStyle in light themes. + - Override default styles via highlightProps.style, or append other react-syntax-highlighter supported properties. + - Use the header slot to add title/action areas. + +```mermaid +flowchart TD +Enter(["Enter CodeHighlighter"]) --> Theme{"themeMode is dark?"} +Theme -- Yes --> Dark["Use customDarkStyle"] +Theme -- No --> Light["Use customLightStyle"] +Dark --> Render["Render XCodeHighlighter with header/value"] +Light --> Render +Render --> Exit(["Complete"]) +``` + +**Diagram Sources** + +- [code-highlighter.tsx:29-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L29-L51) + +**Section Sources** + +- [code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) + +### Mermaid Flowchart Component + +- Design points + - Interfaces with @ant-design/x's Mermaid, supporting header, actions.customActions slots and context injection. + - Theme and highlighting: Switches mermaid theme (dark/base) based on themeMode, while synchronizing highlighting styles. + - Action items: Injects action item context via withItemsContextProvider, supporting dynamic rendering of custom actions. +- Usage recommendations + - Enable mermaid dark theme in dark mode, use base theme in light mode. + - Pass custom action items via actions.customActions or use slot injection. + - Forward mermaid rendering configuration (such as direction, theme colors, etc.) through config. + +```mermaid +sequenceDiagram +participant U as "Caller" +participant M as "mermaid.tsx" +participant Ctx as "actions/context.ts" +participant X as "@ant-design/x.Mermaid" +U->>M : Pass value/config/actions/themeMode/header +M->>Ctx : Get action item context +Ctx-->>M : Return action item list +M->>X : Pass highlightProps/config/actions/header +X-->>U : Render flowchart +``` + +**Diagram Sources** + +- [mermaid.tsx:40-84](file://frontend/antdx/mermaid/mermaid.tsx#L40-L84) +- [actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) + +**Section Sources** + +- [mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) + +### Notification Component + +- Design points + - Interfaces with @ant-design/x's notification.useNotification, exposing visible control and permission callbacks. + - Automatic permission request: When visible is true and permission is not granted, triggers a permission request; if granted, opens the notification. + - Tag-based management: Supports closing specific notifications by tag for multi-instance management. + - Lifecycle: Automatically cleans up notifications on visible changes and component unmounting. +- Usage recommendations + - Link visible and onVisible with the parent state to achieve controlled show/hide. + - Monitor permission changes via onPermission to guide users to grant permissions. + - Use tag to distinguish different notification instances to avoid mutual interference. + +```mermaid +flowchart TD +Start(["visible changes"]) --> Check{"visible is true?"} +Check -- No --> Close["Close notification by tag or all"] +Close --> End(["End"]) +Check -- Yes --> Perm{"Permission granted?"} +Perm -- No --> Request["Request permission"] +Request --> Granted{"Granted successfully?"} +Granted -- No --> End +Granted -- Yes --> Open["open(...)"] +Perm -- Yes --> Open +Open --> BindClose["Bind onClose and update onVisible"] +BindClose --> End +``` + +**Diagram Sources** + +- [notification.tsx:17-46](file://frontend/antdx/notification/notification.tsx#L17-L46) + +**Section Sources** + +- [notification.tsx:1-51](file://frontend/antdx/notification/notification.tsx#L1-L51) + +## Dependency Analysis + +- Component coupling + - XProvider depends on antd's ConfigProvider wrapper to form the global context root node. + - Mermaid depends on the action item context provided by actions/context to implement dynamic action rendering. + - CodeHighlighter/Mermaid both depend on react-syntax-highlighter's theme styles for unified highlighting style. +- External dependencies + - @ant-design/x: Core component library, providing CodeHighlighter, Mermaid, Notification, and other capabilities. + - antd: Provides ConfigProvider, theme algorithms, language packs, and dayjs internationalization support. + - svelte-preprocess-react: Bridges Svelte and React, supporting slots and function wrapping. + +```mermaid +graph LR +XP["XProvider.svelte"] --> CP["config-provider.tsx"] +MG["mermaid.tsx"] --> ACT["actions/context.ts"] +CH["code-highlighter.tsx"] --> RS["react-syntax-highlighter themes"] +MG --> RS +XP --> ANTD["@ant-design/x"] +CH --> ANTD +MG --> ANTD +NT["notification.tsx"] --> ANTD +``` + +**Diagram Sources** + +- [XProvider.svelte:12-14](file://frontend/antdx/x-provider/XProvider.svelte#L12-L14) +- [config-provider.tsx:1-11](file://frontend/antd/config-provider/config-provider.tsx#L1-L11) +- [code-highlighter.tsx:4-11](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L4-L11) +- [mermaid.tsx:4-15](file://frontend/antdx/mermaid/mermaid.tsx#L4-L15) +- [actions/context.ts:1-4](file://frontend/antdx/actions/context.ts#L1-L4) +- [notification.tsx:3-4](file://frontend/antdx/notification/notification.tsx#L3-L4) + +**Section Sources** + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) +- [config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [code-highlighter.tsx:1-54](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L1-L54) +- [mermaid.tsx:1-87](file://frontend/antdx/mermaid/mermaid.tsx#L1-L87) +- [actions/context.ts:1-7](file://frontend/antdx/actions/context.ts#L1-L7) +- [notification.tsx:1-51](file://frontend/antdx/notification/notification.tsx#L1-L51) + +## Performance Considerations + +- Asynchronous loading: XProvider uses importComponent to asynchronously load the ConfigProvider wrapper component, reducing the first-screen load burden. +- Function stabilization: Container functions are wrapped via useFunction, avoiding re-renders caused by function reference changes on each render. +- Memoization: Mermaid uses useMemo for actions.customActions and config, reducing unnecessary recalculations and renders. +- Theme styles: Unified highlighting style objects avoid the overhead of repeatedly constructing style objects. + +[This section contains general guidance; no specific file sources need to be listed] + +## Troubleshooting Guide + +- XProvider not taking effect + - Confirm XProvider is placed at the application root and that visible is true. + - Check if theme and themeMode are correctly passed; use theme_config when theme conflicts with Gradio presets. +- Mermaid chart not displaying + - Confirm value is valid and themeMode and config are correct. + - Check if actions.customActions is correctly injected via context or passed through slots. +- CodeHighlighter style anomalies + - Confirm the combination of themeMode and highlightProps.style is correct. + - Check if the header slot is being accidentally overridden. +- Notification cannot pop up + - Check browser permission status and confirm whether the onPermission callback is triggered. + - Confirm that the usage of visible and tag is as expected. + +**Section Sources** + +- [XProvider.svelte:56-74](file://frontend/antdx/x-provider/XProvider.svelte#L56-L74) +- [mermaid.tsx:40-84](file://frontend/antdx/mermaid/mermaid.tsx#L40-L84) +- [code-highlighter.tsx:29-51](file://frontend/antdx/code-highlighter/code-highlighter.tsx#L29-L51) +- [notification.tsx:17-46](file://frontend/antdx/notification/notification.tsx#L17-L46) + +## Conclusion + +This document systematically organizes the implementation and usage of four tool components: XProvider, CodeHighlighter, Mermaid, and Notification. Through unified global configuration (XProvider), theme and highlighting strategies (CodeHighlighter/Mermaid), and browser notification capabilities (Notification), they provide a stable, extensible foundation for Ant Design X's deployment in the frontend ecosystem. It is recommended to introduce XProvider uniformly at the application root, combined with theme and language configuration, to ensure child components receive a consistent global experience. + +[This section contains summary content; no specific file sources need to be listed] + +## Appendix: Usage Examples and Best Practices + +- XProvider + - Place XProvider at the application root, passing theme_config or theme and themeMode to ensure child components inherit global configuration. + - If antd.ConfigProvider is already in use, replace it with antdx.XProvider to maintain configuration consistency. +- CodeHighlighter + - Pass code content via value or children; use the header slot to add title/action areas. + - Select the corresponding highlighting style based on themeMode, and override details via highlightProps.style when necessary. +- Mermaid + - Pass value as mermaid syntax text; adjust rendering parameters via config; inject custom actions via actions.customActions. + - Switch mermaid theme (dark/base) based on themeMode to maintain consistency with the page theme. +- Notification + - Use visible and onVisible to achieve controlled display; monitor onPermission to get permission status; manage multiple instances via tag. + +**Section Sources** + +- [x_provider documentation:1-19](file://docs/components/antdx/x_provider/README.md#L1-L19) +- [backend/**init**.py (antdx aggregated exports):1-42](file://backend/modelscope_studio/components/antdx/__init__.py#L1-L42) diff --git a/.wiki/en/Ant Design X Components/Tool Components/XProvider Component.md b/.wiki/en/Ant Design X Components/Tool Components/XProvider Component.md new file mode 100644 index 00000000..d876a445 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Tool Components/XProvider Component.md @@ -0,0 +1,284 @@ +# XProvider Global Configuration + + +**Files Referenced in This Document** +- [XProvider.svelte](file://frontend/antdx/x-provider/XProvider.svelte) +- [Index.svelte](file://frontend/antdx/x-provider/Index.svelte) +- [config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [locales.ts](file://frontend/antd/config-provider/locales.ts) +- [__init__.py](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py) +- [README.md](file://README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically describes the design and usage of the XProvider global configuration component, focusing on the following aspects: + +- Context provision mechanism: How XProvider injects a unified configuration context (theme, internationalization, component default behavior, etc.) into the entire application. +- Theme configuration: Supports light/dark mode with compact algorithm synchronization, and integration with Gradio's shared theme state. +- Internationalization settings: Automatically detects browser language and dynamically loads the corresponding language pack as needed. +- Best practices for collaboration with ANTDX components: How to configure uniformly at the application level to avoid repetitive settings. + +## Project Structure + +XProvider adopts a "wrapper + synchronous rendering" pattern on the frontend, while the backend uses a Python component to bridge the frontend, forming a complete configuration provision chain. + +```mermaid +graph TB +subgraph "Frontend" +XP["XProvider.svelte"] +CI["Index.svelte"] +CP["config-provider.tsx"] +LO["locales.ts"] +end +subgraph "Backend" +PY["__init__.py(AntdXXProvider)"] +end +CI --> XP +XP --> CP +CP --> LO +PY --> CI +``` + +Diagram sources + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) +- [Index.svelte:1-20](file://frontend/antdx/x-provider/Index.svelte#L1-L20) +- [config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [**init**.py:1-101](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L1-L101) + +Section sources + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) +- [Index.svelte:1-20](file://frontend/antdx/x-provider/Index.svelte#L1-L20) +- [config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [locales.ts:1-863](file://frontend/antd/config-provider/locales.ts#L1-L863) +- [**init**.py:1-101](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L1-L101) + +## Core Components + +- Frontend Components + - XProvider Wrapper: Responsible for receiving props, handling additional attributes, passing through to ConfigProvider, and injecting theme and internationalization capabilities. + - ConfigProvider Implementation: Based on Ant Design's ConfigProvider, extended with theme mode and internationalization loading logic. + - locales Language Mapping: Provides on-demand loading of multi-language resources and dayjs locale synchronization. +- Backend Components + - AntdXXProvider: A Python-level layout component that declares optional slots and configuration items, bridges the frontend component, and bypasses API calls. + +Section sources + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) +- [config-provider.tsx:51-151](file://frontend/antd/config-provider/config-provider.tsx#L51-L151) +- [locales.ts:12-87](file://frontend/antd/config-provider/locales.ts#L12-L87) +- [**init**.py:10-101](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L10-L101) + +## Architecture Overview + +The XProvider runtime flow is as follows: + +```mermaid +sequenceDiagram +participant App as "Application" +participant Py as "AntdXXProvider(Python)" +participant CI as "Index.svelte" +participant XP as "XProvider.svelte" +participant CP as "ConfigProvider(React)" +participant LO as "locales.ts" +App->>Py : Render XProvider configuration +Py-->>CI : Load frontend component +CI->>XP : Pass props/children +XP->>CP : Pass through config + inject themeMode/locale +CP->>LO : Dynamically load language pack by locale +CP-->>App : Provide theme/i18n context +``` + +Diagram sources + +- [XProvider.svelte:12-74](file://frontend/antdx/x-provider/XProvider.svelte#L12-L74) +- [config-provider.tsx:71-149](file://frontend/antd/config-provider/config-provider.tsx#L71-L149) +- [locales.ts:89-105](file://frontend/antd/config-provider/locales.ts#L89-L105) +- [**init**.py:83-101](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L83-L101) + +## Detailed Component Analysis + +### XProvider Wrapper (Frontend) + +Responsibilities and Key Points + +- Receive and process props: Filter internal fields, retain restProps and additionalProps, and support priority merging of theme_config and theme. +- Dynamic import of ConfigProvider: Ensures on-demand loading via async components, reducing initial load overhead. +- Theme and i18n injection: Obtains light/dark mode from Gradio's shared theme, injects theme configuration from props or theme_config; internationalization is handled by the underlying ConfigProvider. +- Slots and styles: Pass through slots, elem_id, elem_classes, elem_style, and other common attributes. + +```mermaid +flowchart TD +Start(["Enter XProvider"]) --> GetProps["Parse props
Filter internal fields"] +GetProps --> MergeTheme["Merge theme priority
theme_config > restProps.theme > additionalProps.theme"] +MergeTheme --> SetMode["Read Gradio shared theme
Determine themeMode"] +SetMode --> ImportCP["Async import ConfigProvider"] +ImportCP --> Render["Render ConfigProvider and inject context"] +Render --> End(["Done"]) +``` + +Diagram sources + +- [XProvider.svelte:17-74](file://frontend/antdx/x-provider/XProvider.svelte#L17-L74) + +Section sources + +- [XProvider.svelte:1-75](file://frontend/antdx/x-provider/XProvider.svelte#L1-L75) + +### ConfigProvider Implementation (Frontend) + +Responsibilities and Key Points + +- Theme algorithm: Automatically combines dark and compact algorithms based on themeMode and props.theme.algorithm. +- Internationalization: Supports locale string or automatic browser language detection, dynamically loads the corresponding language pack and dayjs locale on demand. +- Container mounting: Provides function wrappers for getPopupContainer and getTargetContainer, enabling custom popup container configuration. +- Slot integration: Converts nested key paths in slots into corresponding React component trees, supporting slots like renderEmpty. + +```mermaid +flowchart TD +A["Receive props/themeMode/locale"] --> B["Compute algorithm list"] +B --> C["Dynamically load locale resources"] +C --> D["Compose props and slots"] +D --> E["Render StyleProvider + ConfigProvider"] +E --> F["Provide theme/locale/container strategy downstream"] +``` + +Diagram sources + +- [config-provider.tsx:71-149](file://frontend/antd/config-provider/config-provider.tsx#L71-L149) +- [locales.ts:89-105](file://frontend/antd/config-provider/locales.ts#L89-L105) + +Section sources + +- [config-provider.tsx:51-151](file://frontend/antd/config-provider/config-provider.tsx#L51-L151) +- [locales.ts:12-87](file://frontend/antd/config-provider/locales.ts#L12-L87) + +### Backend Component (AntdXXProvider) + +Responsibilities and Key Points + +- Parameter declaration: Includes configuration items such as component disable, size, direction, prefix class, locale, theme, variant, virtualization, and warnings. +- Slot declaration: Declares injectable slots such as renderEmpty. +- Frontend directory: Points to the frontend x-provider component directory. +- API skip: skip_api=True to avoid generating redundant APIs. + +Section sources + +- [**init**.py:10-101](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L10-L101) + +## Dependency Analysis + +- Frontend Dependencies + - @ant-design/x: XProvider React component source. + - @ant-design/cssinjs: Style injection and hash control. + - dayjs: Date localization. + - svelte-i18n: Browser language detection. + - immer: Immutable update utility. +- Backend Dependencies + - ModelScopeLayoutComponent: Layout component base class. + - resolve_frontend_dir: Locates the frontend component directory. + +```mermaid +graph LR +XP["XProvider.svelte"] --> CP["config-provider.tsx"] +CP --> AD["@ant-design/x"] +CP --> CSS["@ant-design/cssinjs"] +CP --> DJ["dayjs"] +CP --> I18N["svelte-i18n"] +CP --> IM["immer"] +PY["AntdXXProvider(__init__.py)"] --> CI["Index.svelte"] +CI --> XP +``` + +Diagram sources + +- [XProvider.svelte:1-14](file://frontend/antdx/x-provider/XProvider.svelte#L1-L14) +- [config-provider.tsx:1-11](file://frontend/antd/config-provider/config-provider.tsx#L1-L11) +- [**init**.py:6-8](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L6-L8) + +Section sources + +- [XProvider.svelte:1-14](file://frontend/antdx/x-provider/XProvider.svelte#L1-L14) +- [config-provider.tsx:1-11](file://frontend/antd/config-provider/config-provider.tsx#L1-L11) +- [**init**.py:6-8](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L6-L8) + +## Performance Considerations + +- Async loading: XProvider uses dynamic imports for ConfigProvider to avoid blocking the initial render and improve startup speed. +- Theme algorithm: Recomputes the algorithm array only when themeMode or props.theme.algorithm changes, reducing re-render cost. +- Language packs: Loads language packs and dayjs locale on demand, avoiding loading all language resources at once. +- Style injection: Uses a high-priority hash strategy to minimize style conflicts and reflows. + +## Troubleshooting Guide + +- Theme conflict warning + - Symptom: Triggered when both theme and a Gradio preset theme are set simultaneously. + - Resolution: Use theme_config uniformly to avoid conflicts with Gradio preset properties. + - Reference: [**init**.py:74-77](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L74-L77) +- Light/dark mode not taking effect + - Confirm that the Gradio shared theme has correctly set themeMode. + - Reference: [XProvider.svelte](file://frontend/antdx/x-provider/XProvider.svelte#L69) +- Language not switching as expected + - Check whether the locale string format matches the mapping rules (e.g., zh_CN, en_US), or rely on automatic detection. + - Reference: [locales.ts:12-87](file://frontend/antd/config-provider/locales.ts#L12-L87) +- Slot not taking effect + - Ensure the slot key path is correct (e.g., renderEmpty) and the corresponding content is provided in slots. + - Reference: [config-provider.tsx:29-49](file://frontend/antd/config-provider/config-provider.tsx#L29-L49) + +Section sources + +- [**init**.py:74-77](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L74-L77) +- [XProvider.svelte](file://frontend/antdx/x-provider/XProvider.svelte#L69) +- [locales.ts:12-87](file://frontend/antd/config-provider/locales.ts#L12-L87) +- [config-provider.tsx:29-49](file://frontend/antd/config-provider/config-provider.tsx#L29-L49) + +## Conclusion + +Through a "frontend wrapper + backend bridge" design, XProvider provides a unified theme and internationalization context for the application, with good extensibility and performance. It is recommended to configure XProvider centrally at the application entry point to avoid repetitive settings across components, thereby achieving a consistent user experience and lower maintenance cost. + +## Appendix + +### Configuration Options Summary + +- Component-level Configuration + - component_disabled: Component disable toggle + - component_size: Component size (small/middle/large) + - direction: Text direction (ltr/rtl) + - prefix_cls/icon_prefix_cls: Prefix class names + - variant: Component appearance variant (outlined/filled/borderless) + - virtual: Virtual scrolling + - warning: Warning configuration +- Container and Popup + - get_popup_container/get_target_container: Popup and target container functions +- Internationalization + - locale: Language code (e.g., zh_CN, en_US), supports automatic detection +- Theme + - theme/theme_config: Theme object and configuration; prefer theme_config + - themeMode: Provided by Gradio shared theme (light/dark) +- Other + - render_empty: Empty state rendering slot + - Element attributes: elem_id, elem_classes, elem_style + - Visibility: visible controls rendering + +Section sources + +- [**init**.py:19-82](file://backend/modelscope_studio/components/antdx/x_provider/__init__.py#L19-L82) +- [config-provider.tsx:53-70](file://frontend/antd/config-provider/config-provider.tsx#L53-L70) +- [locales.ts:12-87](file://frontend/antd/config-provider/locales.ts#L12-L87) +- [XProvider.svelte:25-74](file://frontend/antdx/x-provider/XProvider.svelte#L25-L74) diff --git a/.wiki/en/Ant Design X Components/Wake Components/Prompts Component.md b/.wiki/en/Ant Design X Components/Wake Components/Prompts Component.md new file mode 100644 index 00000000..6be74dfa --- /dev/null +++ b/.wiki/en/Ant Design X Components/Wake Components/Prompts Component.md @@ -0,0 +1,408 @@ +# Prompts Component + + +**Files Referenced in This Document** +- [frontend/antdx/prompts/prompts.tsx](file://frontend/antdx/prompts/prompts.tsx) +- [frontend/antdx/prompts/context.ts](file://frontend/antdx/prompts/context.ts) +- [frontend/antdx/prompts/item/Index.svelte](file://frontend/antdx/prompts/item/Index.svelte) +- [frontend/antdx/prompts/item/prompts.item.tsx](file://frontend/antdx/prompts/item/prompts.item.tsx) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [backend/modelscope_studio/components/antdx/prompts/__init__.py](file://backend/modelscope_studio/components/antdx/prompts/__init__.py) +- [backend/modelscope_studio/components/antdx/prompts/item/__init__.py](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py) +- [docs/components/antdx/prompts/README.md](file://docs/components/antdx/prompts/README.md) +- [docs/components/antdx/prompts/demos/basic.py](file://docs/components/antdx/prompts/demos/basic.py) +- [docs/components/antdx/prompts/demos/nest_usage.py](file://docs/components/antdx/prompts/demos/nest_usage.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix: Usage Examples and Configuration](#appendix-usage-examples-and-configuration) + +## Introduction + +The Prompts component is used to display a set of preset questions or suggestion items, helping users quickly select an input direction and enhancing the naturalness and efficiency of conversational guidance. This component is based on Ant Design X's Prompts implementation, bridged in the frontend via a Svelte/React hybrid framework. It supports: + +- Prompt template management: Flexibly organize sub-content such as titles, icons, tags, and descriptions via slots +- Preset instruction configuration: Supports vertical layout, wrapping, style overrides, class names, and other configurations +- Nested usage: Supports nesting prompt items inside other prompt items to create hierarchical suggestions +- Dynamic content generation: Collects child items via context and renders them into the data structure required by Ant Design X +- Event handling: Provides an item_click callback to execute business logic when a prompt item is clicked + +## Project Structure + +This component is located under the frontend antdx category and uses a layered design of "container component + item handler": + +- Container Component: Responsible for collecting slot content, resolving context, and rendering into the items structure required by Ant Design X +- Item Handler: Responsible for wrapping each prompt item into a structure recognizable by the container, supporting nesting +- Utility Functions: Provides general "item context" and "render child items" capabilities, reused across multiple components + +```mermaid +graph TB +subgraph "Frontend antdx" +P["Prompts Container
frontend/antdx/prompts/prompts.tsx"] +Ctx["Items Context
frontend/antdx/prompts/context.ts"] +Item["Item Handler
frontend/antdx/prompts/item/prompts.item.tsx"] +ItemUI["Item UI Wrapper
frontend/antdx/prompts/item/Index.svelte"] +Utils1["createItemsContext
frontend/utils/createItemsContext.tsx"] +Utils2["renderItems
frontend/utils/renderItems.tsx"] +end +subgraph "Backend" +BP["Backend Container Component
backend/.../prompts/__init__.py"] +BI["Backend Item Component
backend/.../prompts/item/__init__.py"] +end +P --> Ctx +P --> Utils2 +Ctx --> Utils1 +Item --> Ctx +ItemUI --> Item +P --> BP +Item --> BI +``` + +Diagram Sources + +- [frontend/antdx/prompts/prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [frontend/antdx/prompts/context.ts:1-7](file://frontend/antdx/prompts/context.ts#L1-L7) +- [frontend/antdx/prompts/item/prompts.item.tsx:1-22](file://frontend/antdx/prompts/item/prompts.item.tsx#L1-L22) +- [frontend/antdx/prompts/item/Index.svelte:1-69](file://frontend/antdx/prompts/item/Index.svelte#L1-L69) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:1-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L1-L88) +- [backend/modelscope_studio/components/antdx/prompts/item/**init**.py:1-48](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py#L1-L48) + +Section Sources + +- [frontend/antdx/prompts/prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [frontend/antdx/prompts/context.ts:1-7](file://frontend/antdx/prompts/context.ts#L1-L7) +- [frontend/antdx/prompts/item/prompts.item.tsx:1-22](file://frontend/antdx/prompts/item/prompts.item.tsx#L1-L22) +- [frontend/antdx/prompts/item/Index.svelte:1-69](file://frontend/antdx/prompts/item/Index.svelte#L1-L69) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:1-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L1-L88) +- [backend/modelscope_studio/components/antdx/prompts/item/**init**.py:1-48](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py#L1-L48) + +## Core Components + +- Container Component: Prompts + - Responsibility: Collects slot content (title, items) and child items, resolves context, converts child items into the items data structure required by Ant Design X, and renders them + - Key Points: Supports passing external items data; if not provided, parses child items from the default or named slots in context; the title slot takes priority over props.title +- Item Handler: Prompts.Item + - Responsibility: Wraps each prompt item into a structure recognizable by the container, supporting slots (label, icon, description) and visibility control + - Key Points: Only allows the default slot as item content; supports extra property forwarding and passes internal index and slot key +- Item Context: createItemsContext + - Responsibility: Provides ItemsContext, uniformly collecting and updating child items across slots, supporting nested sub-contexts + - Key Points: setItem supports updates by slot key and index; onChange callback notifies the parent context +- Render Utility: renderItems + - Responsibility: Renders Item structures from context into a React-usable object tree, automatically handling slots, cloning, and parameterized rendering + - Key Points: Supports children key, withParams parameterized rendering, forceClone forced cloning + +Section Sources + +- [frontend/antdx/prompts/prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) +- [frontend/antdx/prompts/item/prompts.item.tsx:7-19](file://frontend/antdx/prompts/item/prompts.item.tsx#L7-L19) +- [frontend/antdx/prompts/item/Index.svelte:16-68](file://frontend/antdx/prompts/item/Index.svelte#L16-L68) +- [frontend/utils/createItemsContext.tsx:97-273](file://frontend/utils/createItemsContext.tsx#L97-L273) +- [frontend/utils/renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +## Architecture Overview + +The runtime architecture of Prompts consists of "frontend container + item handler + context collection + render utility", with the backend bridging to the frontend through Gradio components. + +```mermaid +sequenceDiagram +participant U as "User" +participant F as "Frontend Container (Prompts)" +participant C as "Items Context" +participant R as "Render Utility (renderItems)" +participant X as "Ant Design X (Prompts)" +U->>F : Create Prompts with props/slots +F->>C : useItems to get items context +C-->>F : Return child items from default/named slots +F->>R : Convert child items to Ant Design X required structure +R-->>F : Return items array +F->>X : Render with items/title/other config +X-->>U : Display Prompts UI +``` + +Diagram Sources + +- [frontend/antdx/prompts/prompts.tsx:16-38](file://frontend/antdx/prompts/prompts.tsx#L16-L38) +- [frontend/utils/renderItems.tsx:23-38](file://frontend/utils/renderItems.tsx#L23-L38) +- [frontend/utils/createItemsContext.tsx:108-170](file://frontend/utils/createItemsContext.tsx#L108-L170) + +## Detailed Component Analysis + +### Container Component: Prompts + +- Slots and Properties + - Supported slots: title, items + - Supported properties: vertical, wrap, styles, class_names, root_class_name, fade_in, fade_in_left, etc. +- Context Resolution + - If external items are provided, use them directly; otherwise parse from default or items slots in context + - The title slot takes priority over props.title +- Rendering Strategy + - Uses renderItems to convert Item structures from context into the object array required by Ant Design X + - Clones and parameterizes slot content to ensure correct React rendering + +```mermaid +flowchart TD +Start(["Enter Prompts"]) --> CheckItems["Are items provided?"] +CheckItems --> |Yes| UseExternal["Use external items"] +CheckItems --> |No| ResolveCtx["Resolve items/default from context"] +ResolveCtx --> Render["Call renderItems to convert"] +UseExternal --> Render +Render --> PassProps["Pass to Ant Design X component"] +PassProps --> End(["Render complete"]) +``` + +Diagram Sources + +- [frontend/antdx/prompts/prompts.tsx:16-38](file://frontend/antdx/prompts/prompts.tsx#L16-L38) +- [frontend/utils/renderItems.tsx:23-38](file://frontend/utils/renderItems.tsx#L23-L38) + +Section Sources + +- [frontend/antdx/prompts/prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:28-69](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L28-L69) + +### Item Handler: Prompts.Item + +- Slots and Properties + - Supported slots: label, icon, description + - Supported properties: key, label, description, icon, disabled, visible, elem_id, elem_classes, elem_style, etc. +- Internal Processing + - Registers child items into context via ItemHandler, supporting recursive rendering of item children + - Only allows the default slot as item content to avoid ambiguity from multi-level slots +- Visibility and Styles + - visible controls rendering; elem_id/elem_classes/elem_style support style customization + +```mermaid +classDiagram +class PromptsItem { ++props : Partial[number]> ++itemIndex : number ++itemSlotKey : string ++slots : Record ++render() +} +class ItemHandler { ++itemIndex : number ++itemSlotKey : string ++itemProps(props, items) ++itemChildren(items) ++allowedSlots : ["default"] ++render() +} +PromptsItem --> ItemHandler : "uses" +``` + +Diagram Sources + +- [frontend/antdx/prompts/item/prompts.item.tsx:7-19](file://frontend/antdx/prompts/item/prompts.item.tsx#L7-L19) +- [frontend/antdx/prompts/item/Index.svelte:16-68](file://frontend/antdx/prompts/item/Index.svelte#L16-L68) + +Section Sources + +- [frontend/antdx/prompts/item/prompts.item.tsx:1-22](file://frontend/antdx/prompts/item/prompts.item.tsx#L1-L22) +- [frontend/antdx/prompts/item/Index.svelte:1-69](file://frontend/antdx/prompts/item/Index.svelte#L1-L69) +- [backend/modelscope_studio/components/antdx/prompts/item/**init**.py:18-48](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py#L18-L48) + +### Item Context and Render Utility + +- createItemsContext + - Provides ItemsContextProvider, withItemsContextProvider, useItems, ItemHandler + - Supports updating child items by slot key and index; onChange callback notifies the parent context +- renderItems + - Converts Item structures into a React object tree, automatically handling slots, cloning, and parameterized rendering + - Supports children key, withParams, forceClone, itemPropsTransformer, and other options + +```mermaid +flowchart TD +A["Collect child items (Item)"] --> B["Write to ItemsContext"] +B --> C["Parent context subscribes to onChange"] +C --> D["renderItems converts to React objects"] +D --> E["Ant Design X renders"] +``` + +Diagram Sources + +- [frontend/utils/createItemsContext.tsx:108-170](file://frontend/utils/createItemsContext.tsx#L108-L170) +- [frontend/utils/renderItems.tsx:23-98](file://frontend/utils/renderItems.tsx#L23-L98) + +Section Sources + +- [frontend/utils/createItemsContext.tsx:97-273](file://frontend/utils/createItemsContext.tsx#L97-L273) +- [frontend/utils/renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) + +### Backend Bridge + +- AntdXPrompts + - Supported events: item_click + - Supported slots: title, items + - Supported properties: items, prefix_cls, title, vertical, wrap, styles, class_names, root_class_name, fade_in, fade_in_left, etc. +- AntdXPromptsItem + - Supported slots: label, icon, description + - Supported properties: label, key, description, icon, disabled, visible, elem_id, elem_classes, elem_style, etc. + +Section Sources + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-69](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L69) +- [backend/modelscope_studio/components/antdx/prompts/item/**init**.py:18-48](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py#L18-L48) + +## Dependency Analysis + +- Component Coupling + - Prompts depends on Items context and render utility; child items register to context via ItemHandler + - Backend components serve as the bridge layer for frontend components, exposing events and properties +- External Dependencies + - Ant Design X's Prompts component for actual rendering + - Svelte/React hybrid toolchain for bridging and slot rendering + +```mermaid +graph LR +Prompts["Prompts Container"] --> Ctx["Items Context"] +Prompts --> Render["renderItems"] +Item["Prompts.Item"] --> Ctx +Ctx --> Utils["createItemsContext"] +Prompts --> Backend["Backend Container Component"] +Item --> BackendItem["Backend Item Component"] +``` + +Diagram Sources + +- [frontend/antdx/prompts/prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) +- [frontend/antdx/prompts/item/prompts.item.tsx:7-19](file://frontend/antdx/prompts/item/prompts.item.tsx#L7-L19) +- [frontend/utils/createItemsContext.tsx:97-273](file://frontend/utils/createItemsContext.tsx#L97-L273) +- [frontend/utils/renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-69](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L69) +- [backend/modelscope_studio/components/antdx/prompts/item/**init**.py:8-48](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py#L8-L48) + +Section Sources + +- [frontend/antdx/prompts/prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) +- [frontend/antdx/prompts/item/prompts.item.tsx:7-19](file://frontend/antdx/prompts/item/prompts.item.tsx#L7-L19) +- [frontend/utils/createItemsContext.tsx:97-273](file://frontend/utils/createItemsContext.tsx#L97-L273) +- [frontend/utils/renderItems.tsx:8-113](file://frontend/utils/renderItems.tsx#L8-L113) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-69](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L69) +- [backend/modelscope_studio/components/antdx/prompts/item/**init**.py:8-48](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py#L8-L48) + +## Performance Considerations + +- Render Optimization + - Uses useMemo to cache items computation results, avoiding unnecessary re-renders + - renderItems enables cloning by default (clone: true) to ensure safe React rendering and state isolation +- Context Updates + - setItem only triggers updates when the value changes, reducing invalid renders + - onChange callback fires when items update, enabling external listeners +- Nested Rendering + - When child item children are rendered recursively, stable keys are generated by index to avoid list re-ordering + +Section Sources + +- [frontend/antdx/prompts/prompts.tsx:27-34](file://frontend/antdx/prompts/prompts.tsx#L27-L34) +- [frontend/utils/renderItems.tsx:30-38](file://frontend/utils/renderItems.tsx#L30-L38) +- [frontend/utils/createItemsContext.tsx:124-153](file://frontend/utils/createItemsContext.tsx#L124-L153) + +## Troubleshooting Guide + +- Issue: Prompt items not displaying + - Check whether visible is true + - Check whether slot names are correct (label, icon, description) +- Issue: Nested prompt items not working + - Ensure child items use the default slot as content + - Confirm child items are not using invalid slot keys +- Issue: No response on click + - Confirm the item_click event has been bound + - Check whether the backend event mapping is effective +- Issue: Styles not taking effect + - Check whether elem_id, elem_classes, and elem_style are correctly passed + - Check whether styles and class_names are overriding the target styles + +Section Sources + +- [frontend/antdx/prompts/item/Index.svelte:53-68](file://frontend/antdx/prompts/item/Index.svelte#L53-L68) +- [frontend/antdx/prompts/item/prompts.item.tsx:11-18](file://frontend/antdx/prompts/item/prompts.item.tsx#L11-L18) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-23](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L23) + +## Conclusion + +The Prompts component, through its "container + item handler + context + render utility" architecture, achieves seamless bridging and extension of Ant Design X. It not only supports basic prompt set creation and style customization, but also provides powerful nesting capabilities and event handling interfaces that effectively improve the conversational guidance experience. Combined with the backend event bridge, developers can easily implement the complete loop from clicking a prompt item to executing business logic. + +## Appendix: Usage Examples and Configuration + +### Basic Prompt Set Creation + +- Example Path: [docs/components/antdx/prompts/demos/basic.py:24-72](file://docs/components/antdx/prompts/demos/basic.py#L24-L72) +- Key Points + - Wrap with XProvider + - Set title, vertical, wrap, and other properties + - Use slots (icon, label, description) in each prompt item + +Section Sources + +- [docs/components/antdx/prompts/demos/basic.py:24-72](file://docs/components/antdx/prompts/demos/basic.py#L24-L72) + +### Nested Usage Scenarios + +- Example Path: [docs/components/antdx/prompts/demos/nest_usage.py:16-83](file://docs/components/antdx/prompts/demos/nest_usage.py#L16-L83) +- Key Points + - Nest prompt items inside prompt items to create hierarchical suggestions + - Use styles and class_names for style customization + - Use item_click to capture click events and handle them + +Section Sources + +- [docs/components/antdx/prompts/demos/nest_usage.py:16-83](file://docs/components/antdx/prompts/demos/nest_usage.py#L16-L83) + +### Component Configuration Options (Frontend Container) + +- Properties + - items: Externally provided array of prompt items + - title: Title text or slot + - vertical: Whether to arrange vertically + - wrap: Whether to wrap + - styles: Style overrides + - class_names: Class name mapping + - root_class_name: Root class name + - fade_in/fade_in_left: Entry animations +- Slots + - title: Custom title + - items: Custom prompt item collection + +Section Sources + +- [frontend/antdx/prompts/prompts.tsx:24-34](file://frontend/antdx/prompts/prompts.tsx#L24-L34) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:28-69](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L28-L69) + +### Event Handling + +- item_click: Triggered when a prompt item is clicked +- Example bindings: [docs/components/antdx/prompts/demos/basic.py:72](file://docs/components/antdx/prompts/demos/basic.py#L72), [docs/components/antdx/prompts/demos/nest_usage.py:83](file://docs/components/antdx/prompts/demos/nest_usage.py#L83) + +Section Sources + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-23](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L23) +- [docs/components/antdx/prompts/demos/basic.py:72](file://docs/components/antdx/prompts/demos/basic.py#L72) +- [docs/components/antdx/prompts/demos/nest_usage.py:83](file://docs/components/antdx/prompts/demos/nest_usage.py#L83) + +### Style Customization + +- Use elem_id, elem_classes, elem_style for style customization of individual prompt items +- Use styles, class_names, root_class_name for customization of the overall layout and theme +- Example reference: [docs/components/antdx/prompts/demos/nest_usage.py:19-29](file://docs/components/antdx/prompts/demos/nest_usage.py#L19-L29) + +Section Sources + +- [frontend/antdx/prompts/item/Index.svelte:56-58](file://frontend/antdx/prompts/item/Index.svelte#L56-L58) +- [backend/modelscope_studio/components/antdx/prompts/item/**init**.py:30-35](file://backend/modelscope_studio/components/antdx/prompts/item/__init__.py#L30-L35) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:38-69](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L38-L69) diff --git a/.wiki/en/Ant Design X Components/Wake Components/Wake Components.md b/.wiki/en/Ant Design X Components/Wake Components/Wake Components.md new file mode 100644 index 00000000..0c0486e0 --- /dev/null +++ b/.wiki/en/Ant Design X Components/Wake Components/Wake Components.md @@ -0,0 +1,293 @@ +# Wake Components + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/antdx/welcome/__init__.py](file://backend/modelscope_studio/components/antdx/welcome/__init__.py) +- [frontend/antdx/welcome/Index.svelte](file://frontend/antdx/welcome/Index.svelte) +- [frontend/antdx/welcome/welcome.tsx](file://frontend/antdx/welcome/welcome.tsx) +- [backend/modelscope_studio/components/antdx/prompts/__init__.py](file://backend/modelscope_studio/components/antdx/prompts/__init__.py) +- [frontend/antdx/prompts/Index.svelte](file://frontend/antdx/prompts/Index.svelte) +- [frontend/antdx/prompts/prompts.tsx](file://frontend/antdx/prompts/prompts.tsx) +- [frontend/antdx/prompts/item/Index.svelte](file://frontend/antdx/prompts/item/Index.svelte) +- [frontend/antdx/prompts/item/prompts.item.tsx](file://frontend/antdx/prompts/item/prompts.item.tsx) +- [frontend/pro/chatbot/chatbot.tsx](file://frontend/pro/chatbot/chatbot.tsx) +- [docs/layout_templates/chatbot/demos/fine_grained_control.py](file://docs/layout_templates/chatbot/demos/fine_grained_control.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document covers the Ant Design X Wake Components, systematically describing the design and usage of the Welcome component and the Prompts component. It helps developers quickly build high-quality initial user experiences: Welcome handles the display and personalization of the welcome page; Prompts handles the organization of prompt templates, preset instructions, and intelligent recommendations. The documentation covers component responsibilities, data flow, interaction logic, extension points, and complete usage examples to support real-world project integration. + +## Project Structure + +The Ant Design X Wake Components are implemented through a collaboration between backend Python components and a frontend Svelte/React layer: + +- The backend component handles parameter parsing, static resource processing, event binding, and rendering control +- The frontend Svelte layer handles property forwarding, slot resolution, and async loading of React components +- The React layer directly interfaces with the native components of @ant-design/x for final rendering + +```mermaid +graph TB +subgraph "Backend" +B_Wel["AntdXWelcome
Python Component"] +B_Pro["AntdXPrompts
Python Component"] +end +subgraph "Frontend" +F_SvWel["welcome/Index.svelte"] +F_SvPro["prompts/Index.svelte"] +F_RcWel["welcome/welcome.tsx"] +F_RcPro["prompts/prompts.tsx"] +F_Item["prompts/item/Index.svelte"] +end +subgraph "Third-party" +X["@ant-design/x
React Component Library"] +end +B_Wel --> F_SvWel --> F_RcWel --> X +B_Pro --> F_SvPro --> F_RcPro --> X +F_Item --> F_RcPro +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L55) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-70](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L70) +- [frontend/antdx/welcome/Index.svelte:1-65](file://frontend/antdx/welcome/Index.svelte#L1-L65) +- [frontend/antdx/prompts/Index.svelte:1-70](file://frontend/antdx/prompts/Index.svelte#L1-L70) +- [frontend/antdx/welcome/welcome.tsx:1-44](file://frontend/antdx/welcome/welcome.tsx#L1-L44) +- [frontend/antdx/prompts/prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [frontend/antdx/prompts/item/Index.svelte:1-68](file://frontend/antdx/prompts/item/Index.svelte#L1-L68) + +Section Sources + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) +- [frontend/antdx/welcome/Index.svelte:1-65](file://frontend/antdx/welcome/Index.svelte#L1-L65) +- [frontend/antdx/prompts/Index.svelte:1-70](file://frontend/antdx/prompts/Index.svelte#L1-L70) + +## Core Components + +- Welcome Component: Used for displaying the welcome page. Supports slot-based customization of title, description, icon, and extra content, along with style and variant configuration. +- Prompts Component: Used for displaying a set of prompt templates. Supports title slot, item slots, vertical layout, fade-in animations, wrapping, and provides an item_click callback event. + +Section Sources + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L55) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-70](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L70) + +## Architecture Overview + +The diagram below shows the data and control flow from the backend to the frontend and then to the third-party component library: + +```mermaid +sequenceDiagram +participant Py as "Backend Component
Python" +participant S as "Frontend Svelte
Index.svelte" +participant R as "Frontend React Wrapper
welcome.tsx / prompts.tsx" +participant X as "@ant-design/x
React Component" +Py->>S : Pass visibility/styles/additional props +S->>R : Forward props and slots +R->>X : Render native component handling icon/title/description/items +X-->>R : Component output +R-->>S : Return render result +S-->>Py : Complete one render cycle +``` + +Diagram Sources + +- [frontend/antdx/welcome/Index.svelte:49-64](file://frontend/antdx/welcome/Index.svelte#L49-L64) +- [frontend/antdx/welcome/welcome.tsx:16-41](file://frontend/antdx/welcome/welcome.tsx#L16-L41) +- [frontend/antdx/prompts/Index.svelte:56-69](file://frontend/antdx/prompts/Index.svelte#L56-L69) +- [frontend/antdx/prompts/prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) + +## Detailed Component Analysis + +### Welcome Component + +- Component Responsibilities + - Displays the welcome page with slot-based customization of title, description, icon, and extra content + - Supports style and class name injection, along with multiple variant styles + - Icon supports static resource paths or file objects, uniformly converted to accessible URLs via utility functions +- Key Properties + - Slots: extra, icon, description, title + - Variants: filled, borderless + - Styles: styles, class_names, root_class_name + - Metadata: elem_id, elem_classes, elem_style, visible, render +- Data Flow + - Backend receives parameters and processes static resource paths + - Frontend Svelte forwards props and slots to the React wrapper layer + - React layer determines rendering content based on slot priority strategy and converts icons to accessible URLs +- Interaction Logic + - Serves as the welcome page entry point, typically displayed during application initialization + - Can be hidden or transitioned to the conversation area after the user selects a prompt, based on business logic + +```mermaid +flowchart TD +Start(["Enter Welcome Render"]) --> CheckIcon["Is a slot icon provided?"] +CheckIcon --> |Yes| RenderSlotIcon["Render slot icon"] +CheckIcon --> |No| ConvertIcon["Convert icon to accessible URL"] +RenderSlotIcon --> RenderTitle["Render title slot/text"] +ConvertIcon --> RenderTitle +RenderTitle --> RenderDesc["Render description slot/text"] +RenderDesc --> RenderExtra["Render extra content slot/text"] +RenderExtra --> ApplyStyles["Apply styles and class names"] +ApplyStyles --> End(["Render complete"]) +``` + +Diagram Sources + +- [frontend/antdx/welcome/welcome.tsx:16-41](file://frontend/antdx/welcome/welcome.tsx#L16-L41) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:47-53](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L47-L53) + +Section Sources + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) +- [frontend/antdx/welcome/Index.svelte:1-65](file://frontend/antdx/welcome/Index.svelte#L1-L65) +- [frontend/antdx/welcome/welcome.tsx:1-44](file://frontend/antdx/welcome/welcome.tsx#L1-L44) + +### Prompts Component + +- Component Responsibilities + - Displays a set of prompt templates with support for title and item slots + - Provides item click event callbacks to trigger subsequent interactions + - Supports visual configurations such as vertical layout, fade-in animations, and wrapping +- Key Properties + - Slots: title, items + - List configuration: items, vertical, fade_in, fade_in_left, wrap + - Styles and class names: styles, class_names, root_class_name + - Metadata: elem_id, elem_classes, elem_style, visible, render +- Data Flow + - Backend defines event listeners, mapping item_click to frontend events + - Frontend Svelte forwards props and slots to the React wrapper layer + - React layer merges external items with slot items, cloning on demand to avoid side effects +- Interaction Logic + - A callback is triggered when the user clicks a prompt item; specific behaviors can be bound at the business layer (e.g., filling the input box, initiating a request) + +```mermaid +sequenceDiagram +participant U as "User" +participant P as "Prompts Component" +participant Ctx as "Item Context" +participant X as "@ant-design/x
Prompts" +U->>P : Click a prompt item +P->>Ctx : Trigger item_click event +Ctx-->>P : Callback notification +P->>X : Render prompt list with merged items +X-->>U : Display click feedback +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-23](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L23) +- [frontend/antdx/prompts/Index.svelte:48-49](file://frontend/antdx/prompts/Index.svelte#L48-L49) +- [frontend/antdx/prompts/prompts.tsx:13-40](file://frontend/antdx/prompts/prompts.tsx#L13-L40) + +Section Sources + +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-88](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L88) +- [frontend/antdx/prompts/Index.svelte:1-70](file://frontend/antdx/prompts/Index.svelte#L1-L70) +- [frontend/antdx/prompts/prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) +- [frontend/antdx/prompts/item/Index.svelte:1-68](file://frontend/antdx/prompts/item/Index.svelte#L1-L68) +- [frontend/antdx/prompts/item/prompts.item.tsx:1-21](file://frontend/antdx/prompts/item/prompts.item.tsx#L1-L21) + +## Dependency Analysis + +- Component Coupling + - Backend components are only responsible for parameter and static resource handling — low coupling + - Frontend Svelte layer handles prop forwarding and slot resolution — low coupling + - React wrapper layer is tightly coupled to @ant-design/x, but transparent to upper layers +- External Dependencies + - @ant-design/x: Provides native implementations of Welcome and Prompts + - Utility functions: File URL conversion, slot rendering, item rendering, etc. +- Event Mapping + - The backend maps the item_click event to frontend event names to ensure cross-layer consistency + +```mermaid +graph LR +Py["Backend Component"] --> Svelte["Frontend Svelte"] +Svelte --> ReactWrap["React Wrapper Layer"] +ReactWrap --> ADX["@ant-design/x"] +Py --> Utils["Utility Functions"] +Svelte --> Utils +ReactWrap --> Utils +``` + +Diagram Sources + +- [frontend/antdx/welcome/welcome.tsx:6-7](file://frontend/antdx/welcome/welcome.tsx#L6-L7) +- [frontend/antdx/prompts/prompts.tsx:9-11](file://frontend/antdx/prompts/prompts.tsx#L9-L11) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-23](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L23) + +Section Sources + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L55) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:11-70](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L11-L70) +- [frontend/antdx/welcome/welcome.tsx:1-44](file://frontend/antdx/welcome/welcome.tsx#L1-L44) +- [frontend/antdx/prompts/prompts.tsx:1-43](file://frontend/antdx/prompts/prompts.tsx#L1-L43) + +## Performance Considerations + +- Render Optimization + - Use async component imports to avoid blocking the initial render + - Delay slot content rendering to reduce unnecessary computation +- Resource Optimization + - Icons go through a unified URL conversion to avoid repeated downloads + - Item rendering uses a cloning strategy to reduce re-renders caused by shared state +- Event Handling + - Event mapping is completed in the frontend to reduce backend overhead + +## Troubleshooting Guide + +- Icon Not Displaying + - Check whether the icon path is correct and confirm it has been converted to an accessible URL via the utility function + - If using a slot icon, verify the slot content is rendering correctly +- Slot Content Not Taking Effect + - Confirm the slot name matches the slots supported by the component (Welcome: extra, icon, description, title; Prompts: title, items) + - Verify that the slot content is correctly wrapped in the React wrapper layer +- Click Events Not Firing + - Confirm the backend event listener is enabled and the frontend event mapping is correct + - Check whether the upper business layer has correctly bound the callback + +Section Sources + +- [frontend/antdx/welcome/welcome.tsx:23-37](file://frontend/antdx/welcome/welcome.tsx#L23-L37) +- [frontend/antdx/prompts/Index.svelte:48-49](file://frontend/antdx/prompts/Index.svelte#L48-L49) +- [backend/modelscope_studio/components/antdx/prompts/**init**.py:18-23](file://backend/modelscope_studio/components/antdx/prompts/__init__.py#L18-L23) + +## Conclusion + +The Welcome and Prompts components provide high customizability and good extensibility for the initial user experience through clear responsibility separation and slot-based design. Combined with the native capabilities of @ant-design/x, they can satisfy both basic display requirements and complex interaction and recommendation scenarios. It is recommended to configure styles and events according to business objectives in real projects for a better user experience. + +## Appendix + +### Usage Examples and Best Practices + +- Welcome Page Design + - Use the Welcome component as the entry point for the first screen, configuring title, description, and icon via slots + - Configure variants and styles to match the overall design style + - Hide the welcome page and enter the conversation area after the user selects a prompt +- Prompts Configuration + - Use the Prompts component to display a set of prompt templates, supporting grouping and hierarchies + - Combine slots with external items for flexible prompt content management + - Bind the item_click event to enable click-to-use interactions +- User Onboarding Flow + - Display the welcome page during application initialization + - Show curated prompt sets to guide users to get started quickly + - Dynamically adjust prompt content and ordering based on user behavior + +Section Sources + +- [frontend/pro/chatbot/chatbot.tsx:108-115](file://frontend/pro/chatbot/chatbot.tsx#L108-L115) +- [docs/layout_templates/chatbot/demos/fine_grained_control.py:603-619](file://docs/layout_templates/chatbot/demos/fine_grained_control.py#L603-L619) diff --git a/.wiki/en/Ant Design X Components/Wake Components/Welcome Component.md b/.wiki/en/Ant Design X Components/Wake Components/Welcome Component.md new file mode 100644 index 00000000..c4dd1c7c --- /dev/null +++ b/.wiki/en/Ant Design X Components/Wake Components/Welcome Component.md @@ -0,0 +1,424 @@ +# Welcome Component + + +**Files Referenced in This Document** +- [frontend/antdx/welcome/Index.svelte](file://frontend/antdx/welcome/Index.svelte) +- [frontend/antdx/welcome/welcome.tsx](file://frontend/antdx/welcome/welcome.tsx) +- [backend/modelscope_studio/components/antdx/welcome/__init__.py](file://backend/modelscope_studio/components/antdx/welcome/__init__.py) +- [docs/components/antdx/welcome/README.md](file://docs/components/antdx/welcome/README.md) +- [docs/components/antdx/welcome/demos/basic.py](file://docs/components/antdx/welcome/demos/basic.py) +- [frontend/antdx/welcome/package.json](file://frontend/antdx/welcome/package.json) +- [frontend/antdx/welcome/gradio.config.js](file://frontend/antdx/welcome/gradio.config.js) +- [docs/components/antdx/welcome/app.py](file://docs/components/antdx/welcome/app.py) +- [docs/helper/Docs.py](file://docs/helper/Docs.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) + + +## Update Summary + +**Changes Made** + +- Enhanced style support system with improved layout control capabilities +- Added flexShrink control for the icon area to optimize responsive layout behavior +- Improved style merging mechanism with support for more granular style customization + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Style Enhancement Features](#style-enhancement-features) +7. [Dependency Analysis](#dependency-analysis) +8. [Performance Considerations](#performance-considerations) +9. [Troubleshooting Guide](#troubleshooting-guide) +10. [Conclusion](#conclusion) +11. [Appendix](#appendix) + +## Introduction + +The Welcome component is designed to clearly communicate the intended purpose and expected functionality of an interface, targeting "AI agent product interface" scenarios. This component is based on Ant Design X's Welcome implementation, wrapped by a Python backend and bridged through a Svelte frontend. It provides slot-based extension capabilities, icon and copy customization, variant style control, and can be used as a layout element in Gradio applications. + +**Update** This update enhances the style support system, providing improved layout control capabilities and responsive design optimizations. + +## Project Structure + +The Welcome component consists of a backend Python wrapper class and a frontend Svelte/React bridge layer. The documentation system renders examples and descriptions through the Docs helper. + +```mermaid +graph TB +subgraph "Backend" +PY_INIT["Python Wrapper Class
__init__.py"] +DEV_COMP["Base Component Class
component.py"] +end +subgraph "Frontend" +SV_INDEX["Svelte Entry
Index.svelte"] +TS_WELCOME["React Bridge Component
welcome.tsx"] +PKG["Package Export Config
package.json"] +CFG["Gradio Build Config
gradio.config.js"] +end +subgraph "Documentation" +DOC_README["Component Docs
README.md"] +DOC_DEMOS["Demo Scripts
demos/basic.py"] +DOC_APP["Docs App Entry
app.py"] +DOC_HELPER["Docs Renderer
Docs.py"] +end +PY_INIT --> DEV_COMP +PY_INIT --> SV_INDEX +SV_INDEX --> TS_WELCOME +PKG --> SV_INDEX +CFG --> SV_INDEX +DOC_README --> DOC_APP +DOC_DEMOS --> DOC_APP +DOC_HELPER --> DOC_APP +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:1-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L1-L73) +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [frontend/antdx/welcome/Index.svelte:1-65](file://frontend/antdx/welcome/Index.svelte#L1-L65) +- [frontend/antdx/welcome/welcome.tsx:1-51](file://frontend/antdx/welcome/welcome.tsx#L1-L51) +- [frontend/antdx/welcome/package.json:1-15](file://frontend/antdx/welcome/package.json#L1-L15) +- [frontend/antdx/welcome/gradio.config.js:1-4](file://frontend/antdx/welcome/gradio.config.js#L1-L4) +- [docs/components/antdx/welcome/README.md:1-8](file://docs/components/antdx/welcome/README.md#L1-L8) +- [docs/components/antdx/welcome/demos/basic.py:1-37](file://docs/components/antdx/welcome/demos/basic.py#L1-L37) +- [docs/components/antdx/welcome/app.py:1-7](file://docs/components/antdx/welcome/app.py#L1-L7) +- [docs/helper/Docs.py:1-178](file://docs/helper/Docs.py#L1-L178) + +## Core Components + +- Backend Wrapper Class: Responsible for declaring supported slots, properties, styles, and rendering lifecycle, while converting static resource paths to accessible URLs. +- Frontend Bridge Layer: Encapsulates Ant Design X React components in Svelte style, supporting slot rendering and static resource URL resolution. +- Documentation and Examples: Provides minimal viable examples and documentation pages for quick onboarding. + +Key Responsibilities and Behaviors + +- Slot Support: title, description, icon, extra. +- Property Configuration: icon, title, description, variant (filled/borderless), style and class name injection, visibility and DOM attribute forwarding. +- Resource Handling: Resolves icon paths passed from the backend to ensure they can be correctly loaded in the Gradio environment. +- Rendering Strategy: Controls whether to render based on visible; injects shared rootUrl and apiPrefix in the Gradio context. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:14-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L14-L55) +- [frontend/antdx/welcome/welcome.tsx:8-41](file://frontend/antdx/welcome/welcome.tsx#L8-L41) +- [frontend/antdx/welcome/Index.svelte:12-44](file://frontend/antdx/welcome/Index.svelte#L12-L44) + +## Architecture Overview + +The Welcome component uses a layered design of "backend component + frontend bridge + documentation examples". The backend handles component semantics and resource processing, the frontend handles UI rendering and slot integration, and the documentation system handles the unified presentation of examples and descriptions. + +```mermaid +sequenceDiagram +participant U as "User" +participant G as "Gradio App" +participant PY as "Backend Wrapper Class
AntdXWelcome" +participant SV as "Svelte Entry
Index.svelte" +participant RX as "React Component Bridge
welcome.tsx" +participant ADX as "Ant Design X
Welcome" +U->>G : Open page +G->>PY : Initialize and pass properties and slots +PY-->>SV : Inject extra properties and static resources +SV->>SV : Evaluate visible and render conditionally +SV->>RX : Pass properties, slots, and shared context +RX->>ADX : Render Ant Design X Welcome +ADX-->>U : Display title/description/icon/extra actions +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:37-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L37-L55) +- [frontend/antdx/welcome/Index.svelte:49-64](file://frontend/antdx/welcome/Index.svelte#L49-L64) +- [frontend/antdx/welcome/welcome.tsx:16-41](file://frontend/antdx/welcome/welcome.tsx#L16-L41) + +## Detailed Component Analysis + +### Backend Wrapper Class (Python) + +- Supported Slots: extra, icon, description, title. +- Key Properties: + - Icon: icon (supports local static file paths; converted to accessible URLs by the backend). + - Title and Description: title, description. + - Variant: variant (filled or borderless). + - Styles and Class Names: styles, class_names, elem_id, elem_classes, elem_style. + - Render Control: visible, render, as_item. +- Lifecycle: + - Placeholder implementations for preprocess/postprocess/example_payload/example_value; skip_api returns True, indicating this component does not participate in the standard API flow. +- Frontend Directory Resolution: Uses resolve_frontend_dir("welcome", type="antdx") to point to the frontend implementation. + +```mermaid +classDiagram +class ModelScopeLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__exit__() ++__init__(visible, elem_id, elem_classes, elem_style, render, ...) +} +class AntdXWelcome { ++EVENTS ++SLOTS ++additional_props ++extra ++icon ++styles ++class_names ++description ++variant ++title ++root_class_name ++FRONTEND_DIR ++skip_api ++preprocess() ++postprocess() ++example_payload() ++example_value() +} +AntdXWelcome --|> ModelScopeLayoutComponent : "inherits" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:8-73](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L8-L73) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:14-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L14-L55) +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) + +### Frontend Bridge Layer (Svelte + React) + +- Svelte Entry Responsibilities: + - Retrieves component properties and extra properties, filters out internally reserved fields (e.g., visible, \_internal), and forwards the remaining properties to the React component. + - Uses conditional rendering to load and render the React component only when visible is true. + - Passes Gradio's shared rootUrl and apiPrefix to the React component for resolving static resources. +- React Bridge Responsibilities: + - Wraps Ant Design X's Welcome component with sveltify to support slot rendering. + - Handles icon with priority: if a slot exists, renders the slot content; otherwise resolves the static resource URL. + - Supports both slot and string value dual-mode for title, description, and extra. + - **New**: Enhanced style support system providing better layout control capabilities. + +```mermaid +flowchart TD +Start(["Enter Svelte Entry"]) --> GetProps["Get component properties and extra props"] +GetProps --> Filter["Filter internal fields and forward"] +Filter --> Visible{"visible is true?"} +Visible --> |No| Skip["Skip rendering"] +Visible --> |Yes| Load["Dynamically import React component"] +Load --> Render["Render React bridge component"] +Render --> Styles["Apply style enhancement system"] +Styles --> Slots{"Slots exist?"} +Slots --> |Yes| SlotRender["Render slot content with ReactSlot"] +Slots --> |No| StaticURL["Resolve static resource URL"] +SlotRender --> Done(["Complete"]) +StaticURL --> Done +Skip --> End(["End"]) +Done --> End +``` + +**Diagram Sources** + +- [frontend/antdx/welcome/Index.svelte:22-44](file://frontend/antdx/welcome/Index.svelte#L22-L44) +- [frontend/antdx/welcome/welcome.tsx:16-41](file://frontend/antdx/welcome/welcome.tsx#L16-L41) + +**Section Sources** + +- [frontend/antdx/welcome/Index.svelte:12-44](file://frontend/antdx/welcome/Index.svelte#L12-L44) +- [frontend/antdx/welcome/welcome.tsx:8-41](file://frontend/antdx/welcome/welcome.tsx#L8-L41) + +### Documentation and Examples (Docs System) + +- The documentation app uses the Docs class to scan the README and demos directories, automatically rendering example code and run results. +- The demo scripts demonstrate two variants (default and borderless) and inject extra action buttons via slots. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant DocApp as "Docs App
app.py" +participant Helper as "Docs Renderer
Docs.py" +participant Demo as "Demo Script
basic.py" +participant Comp as "Welcome Component" +Dev->>DocApp : Start documentation service +DocApp->>Helper : Initialize and load docs and examples +Helper->>Demo : Dynamically import demo module +Demo->>Comp : Create Welcome instance and configure properties +Comp-->>Dev : Display result in documentation page +``` + +**Diagram Sources** + +- [docs/components/antdx/welcome/app.py:1-7](file://docs/components/antdx/welcome/app.py#L1-L7) +- [docs/helper/Docs.py:58-75](file://docs/helper/Docs.py#L58-L75) +- [docs/components/antdx/welcome/demos/basic.py:6-36](file://docs/components/antdx/welcome/demos/basic.py#L6-L36) + +**Section Sources** + +- [docs/components/antdx/welcome/README.md:1-8](file://docs/components/antdx/welcome/README.md#L1-L8) +- [docs/components/antdx/welcome/demos/basic.py:1-37](file://docs/components/antdx/welcome/demos/basic.py#L1-L37) +- [docs/components/antdx/welcome/app.py:1-7](file://docs/components/antdx/welcome/app.py#L1-L7) +- [docs/helper/Docs.py:58-75](file://docs/helper/Docs.py#L58-L75) + +## Style Enhancement Features + +### Enhanced Style Support System + +The Welcome component now provides more powerful style support and layout control capabilities, primarily in the following areas: + +#### Icon Area Layout Optimization + +- **flexShrink Control**: Sets `flexShrink: 0` for the icon area to ensure the icon maintains a fixed size in responsive layouts +- **Style Merging Mechanism**: Supports intelligent merging of user-defined styles with default styles +- **Responsive Adaptation**: Optimizes layout behavior across different screen sizes + +#### Style Customization Capabilities + +- **styles Parameter Support**: Fully supports passing the styles parameter from Ant Design X +- **Independent Icon Style Control**: Allows separate style customization for the icon area +- **Theme Consistency**: Maintains compatibility with the Ant Design X theme system + +#### Layout Control Enhancements + +- **Container Style Forwarding**: Supports container-level style control via elem_style and elem_classes +- **Flexbox Optimization**: Uses Flexbox layout for better content arrangement +- **Spacing Control**: Optimizes spacing between icon, title, and description + +```mermaid +graph LR +Styles["Style System"] --> IconStyle["Icon Style Control"] +Styles --> ContainerStyle["Container Style Forwarding"] +Styles --> LayoutControl["Layout Control Enhancement"] +IconStyle --> FlexShrink["flexShrink: 0"] +IconStyle --> CustomStyling["Custom Style Merging"] +ContainerStyle --> ElemStyle["elem_style Support"] +ContainerStyle --> ElemClasses["elem_classes Support"] +LayoutControl --> Responsive["Responsive Layout"] +LayoutControl --> Spacing["Spacing Optimization"] +``` + +**Diagram Sources** + +- [frontend/antdx/welcome/welcome.tsx:23-29](file://frontend/antdx/welcome/welcome.tsx#L23-L29) +- [frontend/antdx/welcome/Index.svelte:52-53](file://frontend/antdx/welcome/Index.svelte#L52-L53) + +**Section Sources** + +- [frontend/antdx/welcome/welcome.tsx:23-29](file://frontend/antdx/welcome/welcome.tsx#L23-L29) +- [frontend/antdx/welcome/Index.svelte:52-53](file://frontend/antdx/welcome/Index.svelte#L52-L53) + +## Dependency Analysis + +- Backend Dependencies: + - Base Component Class: Provides common layout component capabilities and context management. + - Frontend Directory Resolution: Uses resolve_frontend_dir to locate the frontend implementation. +- Frontend Dependencies: + - Ant Design X React component library. + - Gradio client tools: For static resource URL resolution. + - Svelte preprocessing toolchain: Bridges React components with Svelte. + - **New**: Style system enhancement dependencies providing better layout control capabilities. +- Documentation System Dependencies: + - Docs renderer responsible for scanning and rendering README and demos. + +```mermaid +graph LR +PY["AntdXWelcome
__init__.py"] --> BASE["ModelScopeLayoutComponent
component.py"] +PY --> FE_DIR["resolve_frontend_dir('welcome','antdx')"] +SV["Index.svelte"] --> PREACT["@svelte-preprocess-react/*"] +SV --> CLS["classnames"] +SV --> RX["welcome.tsx"] +RX --> ADX["@ant-design/x"] +RX --> GRCL["@gradio/client"] +RX --> PREACT +RX --> STYLES["Style Enhancement System"] +DOC["Docs.py"] --> APP["app.py"] +DOC --> DEMO["demos/basic.py"] +DOC --> READ["README.md"] +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:55-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L55-L55) +- [backend/modelscope_studio/utils/dev/component.py:11-50](file://backend/modelscope_studio/utils/dev/component.py#L11-L50) +- [frontend/antdx/welcome/Index.svelte:1-10](file://frontend/antdx/welcome/Index.svelte#L1-L10) +- [frontend/antdx/welcome/welcome.tsx:1-7](file://frontend/antdx/welcome/welcome.tsx#L1-L7) +- [docs/helper/Docs.py:58-75](file://docs/helper/Docs.py#L58-L75) +- [docs/components/antdx/welcome/demos/basic.py:1-5](file://docs/components/antdx/welcome/demos/basic.py#L1-L5) + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:55-55](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L55-L55) +- [frontend/antdx/welcome/Index.svelte:1-10](file://frontend/antdx/welcome/Index.svelte#L1-L10) +- [frontend/antdx/welcome/welcome.tsx:1-7](file://frontend/antdx/welcome/welcome.tsx#L1-L7) +- [docs/helper/Docs.py:58-75](file://docs/helper/Docs.py#L58-L75) + +## Performance Considerations + +- Conditional Rendering: Only loads and renders the React component when visible is true, avoiding unnecessary initialization and network requests. +- Dynamic Import: Async import of the React component reduces initial load. +- Resource Resolution: Resolves static resource URLs uniformly in the frontend, avoiding repeated computation and cross-origin issues. +- Slot Rendering: Prioritizes slot content, reducing string concatenation and template rendering costs. +- **New**: The style enhancement system uses an efficient style merging algorithm to avoid redundant renders and style conflicts. + +## Troubleshooting Guide + +- Icon Not Displaying + - Check whether the icon passed from the backend is a valid path or URL. + - Confirm that Gradio's shared rootUrl and apiPrefix have been correctly passed to the frontend. +- Slot Not Taking Effect + - Confirm the slot name is one of: title, description, icon, extra. + - Ensure slot content is correctly mounted at runtime. +- Component Not Rendering + - Check whether visible is true. + - Confirm the frontend implementation pointed to by FRONTEND_DIR exists and can be built. +- Documentation Examples Not Running + - Check whether the component nesting and Provider usage in demos/basic.py are correct. + - Confirm the documentation app entry and Docs renderer configuration are correct. +- **New**: Style Display Issues + - Check that the styles parameter format is correct. + - Confirm the style merging logic does not cause conflicts. + - Verify that the flexShrink property is not adversely affecting layout behavior. + +**Section Sources** + +- [frontend/antdx/welcome/Index.svelte:49-64](file://frontend/antdx/welcome/Index.svelte#L49-L64) +- [frontend/antdx/welcome/welcome.tsx:16-41](file://frontend/antdx/welcome/welcome.tsx#L16-L41) +- [docs/components/antdx/welcome/demos/basic.py:6-36](file://docs/components/antdx/welcome/demos/basic.py#L6-L36) +- [docs/helper/Docs.py:58-75](file://docs/helper/Docs.py#L58-L75) + +## Conclusion + +The Welcome component, through the collaboration of backend and frontend, provides concise yet powerful welcome page display capabilities. Its slot-based design and resource resolution mechanism enable flexible personalization and integration in diverse scenarios. Combined with the documentation system's example and rendering capabilities, developers can quickly understand and use this component. + +**Update** This style enhancement further improves the component's layout control capabilities and responsive design performance, providing developers with more granular style customization options and a better user experience. + +## Appendix + +### Usage Examples (Overview) + +- Create a basic welcome page with icon, title, and description. +- Use the borderless variant for a lighter interface style. +- Inject extra action buttons via slots to enhance user guidance. +- **New**: Leverage the enhanced style system for more granular layout control. + +Reference Example Script Path + +- [docs/components/antdx/welcome/demos/basic.py:6-36](file://docs/components/antdx/welcome/demos/basic.py#L6-L36) + +**Section Sources** + +- [docs/components/antdx/welcome/demos/basic.py:1-37](file://docs/components/antdx/welcome/demos/basic.py#L1-L37) + +### Properties and Events Reference (Overview) + +- Supported Slots: extra, icon, description, title. +- Key Properties: icon, title, description, variant (filled/borderless), styles and class names, visibility and DOM attributes. +- Events: No events defined in the current version. +- Lifecycle: skip_api is true; does not participate in the standard API flow. +- **New**: Style enhancement support providing richer layout control options. + +**Section Sources** + +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:12-15](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L12-L15) +- [backend/modelscope_studio/components/antdx/welcome/**init**.py:31-37](file://backend/modelscope_studio/components/antdx/welcome/__init__.py#L31-L37) diff --git a/.wiki/en/Base Components/Application Component.md b/.wiki/en/Base Components/Application Component.md new file mode 100644 index 00000000..846a7e50 --- /dev/null +++ b/.wiki/en/Base Components/Application Component.md @@ -0,0 +1,424 @@ +# Application Component + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/base/application/__init__.py](file://backend/modelscope_studio/components/base/application/__init__.py) +- [frontend/base/application/Application.svelte](file://frontend/base/application/Application.svelte) +- [frontend/base/application/Index.svelte](file://frontend/base/application/Index.svelte) +- [backend/modelscope_studio/utils/dev/app_context.py](file://backend/modelscope_studio/utils/dev/app_context.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [docs/components/base/application/README-zh_CN.md](file://docs/components/base/application/README-zh_CN.md) +- [docs/components/base/application/README.md](file://docs/components/base/application/README.md) +- [docs/app.py](file://docs/app.py) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The Application component is the application root container for modelscope-studio, responsible for hosting and uniformly managing all components and dependencies exported from `modelscope_studio`. It not only provides the fundamental runtime environment for applications, but also helps developers implement page behavior monitoring, theme and language adaptation, and custom event bridging through lifecycle event and browser environment data collection capabilities. + +- As an application root container: Ensures all `modelscope_studio` components are properly wrapped; otherwise the page may fail to preview. +- Lifecycle and environment awareness: Provides events for page mount, window resize, page unload, etc.; can retrieve language, theme, UA, screen size, and scroll position. +- Custom event bridging: Trigger custom events on the frontend via `window.ms_globals.dispatch`; Python side can receive them through the `ms.Application.custom` event. + +Section Sources + +- [docs/components/base/application/README-zh_CN.md:1-11](file://docs/components/base/application/README-zh_CN.md#L1-L11) +- [docs/components/base/application/README.md:1-11](file://docs/components/base/application/README.md#L1-L11) + +## Project Structure + +The Application component consists of a backend Python component class and a frontend Svelte implementation, with tool modules providing context and base class support. Documentation and examples are located in the docs directory for demonstration and explanation. + +```mermaid +graph TB +subgraph "Backend" +PY_APP["ModelScopeApplication
Python Component Class"] +APP_CTX["AppContext
Application Context"] +BASE_META["ModelScopeDataLayoutComponent
Base Class"] +end +subgraph "Frontend" +IDX["Index.svelte
Async Import Entry"] +CMP["Application.svelte
Core Implementation"] +end +subgraph "Docs & Examples" +DOCS_ZH["README-zh_CN.md"] +DOCS_EN["README.md"] +DOCS_APP["docs/app.py"] +end +PY_APP --> BASE_META +PY_APP --> APP_CTX +IDX --> CMP +DOCS_APP --> DOCS_ZH +DOCS_APP --> DOCS_EN +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) +- [frontend/base/application/Application.svelte:1-149](file://frontend/base/application/Application.svelte#L1-L149) +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) +- [backend/modelscope_studio/utils/dev/component.py:101-169](file://backend/modelscope_studio/utils/dev/component.py#L101-L169) +- [docs/components/base/application/README-zh_CN.md:1-56](file://docs/components/base/application/README-zh_CN.md#L1-L56) +- [docs/components/base/application/README.md:1-56](file://docs/components/base/application/README.md#L1-L56) +- [docs/app.py:1-595](file://docs/app.py#L1-L595) + +Section Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) +- [frontend/base/application/Application.svelte:1-149](file://frontend/base/application/Application.svelte#L1-L149) +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) +- [backend/modelscope_studio/utils/dev/component.py:101-169](file://backend/modelscope_studio/utils/dev/component.py#L101-L169) +- [docs/components/base/application/README-zh_CN.md:1-56](file://docs/components/base/application/README-zh_CN.md#L1-L56) +- [docs/components/base/application/README.md:1-56](file://docs/components/base/application/README.md#L1-L56) +- [docs/app.py:1-595](file://docs/app.py#L1-L595) + +## Core Components + +- Backend component class: `ModelScopeApplication` inherits from `ModelScopeDataLayoutComponent`, providing event registration, data model, example data, and frontend directory resolution capabilities. +- Frontend implementation: `Application.svelte` initializes page data on mount, binds resize/unload events, and exposes `window.ms_globals.dispatch` for custom event bridging. +- Context and base class: `AppContext` provides application instance setting and assertion; `ModelScopeDataLayoutComponent` provides layout context and internal state management. + +Section Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [frontend/base/application/Application.svelte:1-149](file://frontend/base/application/Application.svelte#L1-L149) +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) +- [backend/modelscope_studio/utils/dev/component.py:101-169](file://backend/modelscope_studio/utils/dev/component.py#L101-L169) + +## Architecture Overview + +The Application component's runtime flow is as follows: the backend component class records the application instance during initialization; the frontend collects environment data and binds events during the mount phase; a custom event bridging channel is also provided. + +```mermaid +sequenceDiagram +participant Py as "Backend
ModelScopeApplication" +participant Ctx as "Context
AppContext" +participant FE as "Frontend
Application.svelte" +participant Win as "Browser
window" +Py->>Ctx : Set application instance +FE->>FE : onMount initialization +FE->>FE : Collect screen/language/theme/UA +FE->>Win : Bind resize/unload events +FE->>Py : Trigger mount/resize/unmount events +Win-->>FE : User calls window.ms_globals.dispatch(...) +FE->>Py : Trigger custom event +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:72-82](file://backend/modelscope_studio/components/base/application/__init__.py#L72-L82) +- [frontend/base/application/Application.svelte:87-129](file://frontend/base/application/Application.svelte#L87-L129) + +Section Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:72-82](file://backend/modelscope_studio/components/base/application/__init__.py#L72-L82) +- [frontend/base/application/Application.svelte:87-129](file://frontend/base/application/Application.svelte#L87-L129) + +## Detailed Component Analysis + +### Backend Component Class: ModelScopeApplication + +- Design philosophy + - As the application root container, uniformly injects the application context, ensuring all subsequent components depend on an existing Application instance. + - Registers `mount`/`resized`/`unmount`/`custom` event listeners through the Gradio event system, enabling frontend-backend coordination. + - Uses `ApplicationPageData` as the data model, carrying screen, language, theme, UA, and other environment information. +- Key features + - Event registration: EVENTS defines four event listeners corresponding to page lifecycle and custom events. + - Data model: `data_model` points to `ApplicationPageData`; example data `example_payload`/`example_value` provides defaults. + - Frontend directory: `FRONTEND_DIR` is resolved to the `base/application` frontend implementation via `resolve_frontend_dir`. +- Lifecycle and context + - Sets `AppContext` in `__init__`, then calls the parent constructor, ensuring context is available when the component tree is being built. + - `preprocess`/`postprocess` pass data through unchanged, allowing the frontend to consume directly. + +```mermaid +classDiagram +class ModelScopeApplication { ++EVENTS ++SLOTS ++FRONTEND_DIR ++data_model ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class ModelScopeDataLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__exit__() ++__init__(...) +} +class AppContext { ++set_app(app) ++has_app() ++assert_app() ++get_app() +} +ModelScopeApplication --|> ModelScopeDataLayoutComponent +ModelScopeApplication --> AppContext : "set/assert" +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/utils/dev/component.py:101-169](file://backend/modelscope_studio/utils/dev/component.py#L101-L169) +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) + +Section Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/utils/dev/component.py:101-169](file://backend/modelscope_studio/utils/dev/component.py#L101-L169) +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) + +### Frontend Implementation: Application.svelte + +- Key highlights + - onMount initialization: Updates value and dispatches mount event; then binds resize and beforeunload events. + - resize event: Uses debounce (default 500ms) to update value and dispatch resize event, avoiding high-frequency repaints. + - beforeunload: Updates value and dispatches unmount event before the page unloads. + - Custom event: `window.ms_globals.dispatch(...)` forwards the argument array as a custom event. + - Visibility and styles: Controls rendering based on `visible`; `elem_id`/`elem_classes`/`elem_style` support external style injection. +- Data model + - `ApplicationPageData` contains `language`, `userAgent`, `theme`, `screen` (width/height/scrollX/scrollY). +- Event model + - Four event types: `mount`/`resized`/`unmount`/`custom`, corresponding to page lifecycle and custom events. + +```mermaid +flowchart TD +Start(["Mount Start"]) --> Init["Initialize value
Collect language/theme/UA/screen"] +Init --> Bind["Bind resize/unload events"] +Bind --> MountEvt{"Is mount event bound?"} +MountEvt --> |Yes| DispatchMount["Dispatch mount event"] +MountEvt --> |No| Wait["Wait for user interaction"] +Wait --> ResizeEvt{"Window resized?"} +ResizeEvt --> |Yes| Debounce["Debounce (default 500ms)"] +Debounce --> UpdateResize["Update value and dispatch resize"] +ResizeEvt --> |No| UnloadEvt{"Page about to unload?"} +UnloadEvt --> |Yes| UpdateUnload["Update value and dispatch unmount"] +UnloadEvt --> |No| CustomEvt{"window.ms_globals.dispatch called?"} +CustomEvt --> |Yes| DispatchCustom["Dispatch custom event"] +CustomEvt --> |No| End(["End"]) +``` + +Diagram Sources + +- [frontend/base/application/Application.svelte:87-129](file://frontend/base/application/Application.svelte#L87-L129) + +Section Sources + +- [frontend/base/application/Application.svelte:1-149](file://frontend/base/application/Application.svelte#L1-L149) + +### Entry Wrapper: Index.svelte + +- Purpose: Asynchronously imports `Application.svelte` to delay component loading and reduce initial screen burden. +- Rendering: Passes `children` through to the Application component, ensuring content rendering. + +Section Sources + +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) + +### Context and Base Class Support + +- AppContext + - `set_app`: Sets the current application instance during backend initialization. + - `assert_app`: Issues a warning if not set, prompting that Application was not imported. + - `get_app`: Gets the current application instance. +- ModelScopeDataLayoutComponent + - Provides layout context and internal state (`_internal`), ensuring the component tree structure is correct. + - Inherits the Gradio component metaclass, supporting events and data flow. + +Section Sources + +- [backend/modelscope_studio/utils/dev/app_context.py:4-25](file://backend/modelscope_studio/utils/dev/app_context.py#L4-L25) +- [backend/modelscope_studio/utils/dev/component.py:101-169](file://backend/modelscope_studio/utils/dev/component.py#L101-L169) + +### Usage Examples and Scenarios + +- Basic usage: Wrap all `modelscope_studio` components inside Application to ensure preview and interaction work correctly. +- Language adaptation: Get the user's language via `value.language`, dynamically switching text or formatting. +- Theme adaptation: Return content or styles with different weights based on `value.theme`. +- Custom events: Call `window.ms_globals.dispatch(...)` in any JS logic; receive on the Python side via `ms.Application.custom`. + +**Python Code Examples** + +```python +import gradio as gr +import modelscope_studio.components.base as ms +import modelscope_studio.components.antd as antd + +# Example 1: Basic wrapping usage +with gr.Blocks() as demo: + with ms.Application(): + with antd.ConfigProvider(): + with ms.AutoLoading(): + antd.Button("Hello ModelScope Studio") + +demo.launch() +``` + +```python +import gradio as gr +import modelscope_studio.components.base as ms +import modelscope_studio.components.antd as antd + +# Example 2: Listen to page mount event and adapt language/theme +with gr.Blocks() as demo: + with ms.Application() as app: + with antd.ConfigProvider(): + output = gr.Textbox(label="Page Info") + + @app.mount + def on_mount(data: ms.ApplicationData): + # Get user language and theme + lang = data.value.language + theme = data.value.theme + return gr.update(value=f"Language: {lang}, Theme: {theme}") + +demo.launch() +``` + +```python +import gradio as gr +import modelscope_studio.components.base as ms +import modelscope_studio.components.antd as antd + +# Example 3: Listen to custom events (combined with window.ms_globals.dispatch) +with gr.Blocks() as demo: + with ms.Application() as app: + with antd.ConfigProvider(): + output = gr.Textbox(label="Custom Event") + # Frontend can trigger via window.ms_globals.dispatch({type: 'my_event', payload: {...}}) + + @app.custom + def on_custom(data: ms.ApplicationData): + event_type = data.value.type if data.value else None + return gr.update(value=f"Received custom event: {event_type}") + +demo.launch() +``` + +Section Sources + +- [docs/components/base/application/README-zh_CN.md:12-20](file://docs/components/base/application/README-zh_CN.md#L12-L20) +- [docs/components/base/application/README.md:12-20](file://docs/components/base/application/README.md#L12-L20) + +### API and Type Descriptions + +- Properties + - value: `ApplicationPageData`, page data. +- Events + - mount: Triggered when the page mounts. + - resize: Triggered when the window size changes. + - unmount: Triggered when the page unloads. + - custom: Triggered via `window.ms_globals.dispatch(...)`. +- Types + - `ApplicationPageScreenData`: width, height, scrollX, scrollY. + - `ApplicationPageData`: screen, language, theme, userAgent. + +Section Sources + +- [docs/components/base/application/README-zh_CN.md:24-55](file://docs/components/base/application/README-zh_CN.md#L24-L55) +- [docs/components/base/application/README.md:24-55](file://docs/components/base/application/README.md#L24-L55) +- [backend/modelscope_studio/components/base/application/**init**.py:12-115](file://backend/modelscope_studio/components/base/application/__init__.py#L12-L115) + +## Dependency Analysis + +- Backend dependencies + - Gradio data classes and event system: Used for event listener registration and data models. + - Utility modules: `AppContext`, `ModelScopeDataLayoutComponent` provide context and base class capabilities. +- Frontend dependencies + - Svelte lifecycle hooks: `onMount`/`onDestroy`. + - `svelte-i18n`: Gets localized language. + - Style utilities: `styleObject2String`, `classnames`. +- Documentation and examples + - `docs/app.py` builds the site menu and documentation index, locating the Application component documentation. + +```mermaid +graph LR +PY["ModelScopeApplication"] --> GR["Gradio Events/Data Classes"] +PY --> CTX["AppContext"] +PY --> META["ModelScopeDataLayoutComponent"] +FE["Application.svelte"] --> SV["Svelte Lifecycle"] +FE --> I18N["svelte-i18n"] +FE --> STY["Style Utilities"] +DOC["docs/app.py"] --> DZ["README-zh_CN.md"] +DOC --> DE["README.md"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:5-9](file://backend/modelscope_studio/components/base/application/__init__.py#L5-L9) +- [frontend/base/application/Application.svelte:1-149](file://frontend/base/application/Application.svelte#L1-L149) +- [docs/app.py:1-595](file://docs/app.py#L1-L595) + +Section Sources + +- [backend/modelscope_studio/components/base/application/**init**.py:5-9](file://backend/modelscope_studio/components/base/application/__init__.py#L5-L9) +- [frontend/base/application/Application.svelte:1-149](file://frontend/base/application/Application.svelte#L1-L149) +- [docs/app.py:1-595](file://docs/app.py#L1-L595) + +## Performance Considerations + +- Debounce strategy: The resize event uses 500ms debounce by default, reducing the risk of frequent reflows and event storms. +- Lazy loading: `Index.svelte` uses async imports, reducing initial screen resource pressure. +- Event binding: Dispatches events only when needed (`bind_*_event` or `attached_events` contains the corresponding event name), avoiding unnecessary event dispatches. +- Style and visibility: Controls rendering through `visible`; `elem_style` supports both string and object forms for flexible injection on demand. + +Section Sources + +- [frontend/base/application/Application.svelte:96-103](file://frontend/base/application/Application.svelte#L96-L103) +- [frontend/base/application/Index.svelte:5-7](file://frontend/base/application/Index.svelte#L5-L7) + +## Troubleshooting Guide + +- Page cannot preview + - Symptom: Components cannot render normally because Application is not wrapped. + - Resolution: Ensure all `modelscope_studio` components are wrapped by Application. +- Application instance not detected + - Symptom: Console warning appears, indicating Application component not found. + - Resolution: Check if Application is correctly imported and initialized from `modelscope_studio.components.base`. +- Events not triggering + - Symptom: `resize`/`mount`/`unmount`/`custom` events not triggering as expected. + - Resolution: Confirm the frontend has bound the corresponding event (`bind_*_event` or `attached_events` contains the event name); custom events must be triggered via `window.ms_globals.dispatch(...)`. +- Language/theme not taking effect + - Symptom: Language or theme not changing according to user environment. + - Resolution: Ensure the frontend correctly reads `navigator` and shared theme; if necessary, handle branching on the Python side based on `value.language`/`value.theme`. + +Section Sources + +- [docs/components/base/application/README-zh_CN.md:3-11](file://docs/components/base/application/README-zh_CN.md#L3-L11) +- [docs/components/base/application/README.md:3-11](file://docs/components/base/application/README.md#L3-L11) +- [backend/modelscope_studio/utils/dev/app_context.py:16-21](file://backend/modelscope_studio/utils/dev/app_context.py#L16-L21) +- [frontend/base/application/Application.svelte:91-115](file://frontend/base/application/Application.svelte#L91-L115) + +## Conclusion + +The Application component, as the application root container for modelscope-studio, bears the key responsibilities of context injection, lifecycle events, and environment data collection. Through the collaboration of the backend component class and frontend implementation, it provides a stable fundamental runtime environment for the entire application and supports flexible theme/language adaptation and custom event bridging. Following the best practices and troubleshooting recommendations in this document can effectively improve development efficiency and runtime stability. + +## Appendix + +- Version information: v2.0.0 +- Related documentation: English and Chinese documentation for the Application component, including examples and API descriptions. + +Section Sources + +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [docs/components/base/application/README-zh_CN.md:1-56](file://docs/components/base/application/README-zh_CN.md#L1-L56) +- [docs/components/base/application/README.md:1-56](file://docs/components/base/application/README.md#L1-L56) diff --git a/.wiki/en/Base Components/AutoLoading Component.md b/.wiki/en/Base Components/AutoLoading Component.md new file mode 100644 index 00000000..d81e030e --- /dev/null +++ b/.wiki/en/Base Components/AutoLoading Component.md @@ -0,0 +1,339 @@ +# AutoLoading Component + + +**Files Referenced in This Document** +- [auto-loading.tsx](file://frontend/base/auto-loading/auto-loading.tsx) +- [Index.svelte](file://frontend/base/auto-loading/Index.svelte) +- [useLoadingStatus.ts](file://frontend/base/auto-loading/useLoadingStatus.ts) +- [auto-loading.less](file://frontend/base/auto-loading/auto-loading.less) +- [package.json](file://frontend/base/auto-loading/package.json) +- [gradio.config.js](file://frontend/base/auto-loading/gradio.config.js) +- [__init__.py](file://backend/modelscope_studio/components/base/auto_loading/__init__.py) +- [loading-status.svelte.ts](file://frontend/svelte-preprocess-react/svelte-contexts/loading-status.svelte.ts) +- [import.ts](file://frontend/svelte-preprocess-react/component/import.ts) +- [README.md](file://docs/components/base/auto_loading/README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +The AutoLoading component automatically adds loading feedback and error notifications to wrapped content when the Gradio frontend makes requests to the backend. It automatically collects the loading states of child components and displays loading animations or error information at the appropriate time, enhancing user experience. The component supports custom rendering slots, mask layers, timer display, and various configuration options, suitable for global fallback and fine-grained local control. + +## Project Structure + +AutoLoading's frontend implementation is located in the base component directory and includes a Svelte entry, React wrapper component, state hook, and style file; the backend Python component is responsible for declaring the frontend resource path and skipping API calls. The documentation provides component descriptions and example entries. + +```mermaid +graph TB +subgraph "Frontend (base/auto-loading)" +A["Index.svelte
Svelte Entry"] --> B["auto-loading.tsx
React Wrapper Component"] +B --> C["useLoadingStatus.ts
Loading State Hook"] +B --> D["auto-loading.less
Styles"] +A --> E["package.json
Export Config"] +A --> F["gradio.config.js
Build Config"] +end +subgraph "Backend (modelscope_studio/components/base/auto_loading)" +G["__init__.py
Declare Frontend Directory / Skip API"] +end +subgraph "Docs (docs/components/base/auto_loading)" +H["README.md
Usage Instructions & Examples"] +end +A -. integrates .-> B +A -. configures .-> E +A -. builds .-> F +G -. resources .-> A +H -. uses .-> A +``` + +**Diagram Sources** + +- [Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [auto-loading.tsx:1-179](file://frontend/base/auto-loading/auto-loading.tsx#L1-L179) +- [useLoadingStatus.ts:1-94](file://frontend/base/auto-loading/useLoadingStatus.ts#L1-L94) +- [auto-loading.less:1-28](file://frontend/base/auto-loading/auto-loading.less#L1-L28) +- [package.json:1-15](file://frontend/base/auto-loading/package.json#L1-L15) +- [gradio.config.js:1-4](file://frontend/base/auto-loading/gradio.config.js#L1-L4) +- [**init**.py:47-64](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L47-L64) +- [README.md:1-36](file://docs/components/base/auto_loading/README.md#L1-L36) + +**Section Sources** + +- [Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [auto-loading.tsx:1-179](file://frontend/base/auto-loading/auto-loading.tsx#L1-L179) +- [useLoadingStatus.ts:1-94](file://frontend/base/auto-loading/useLoadingStatus.ts#L1-L94) +- [auto-loading.less:1-28](file://frontend/base/auto-loading/auto-loading.less#L1-L28) +- [package.json:1-15](file://frontend/base/auto-loading/package.json#L1-L15) +- [gradio.config.js:1-4](file://frontend/base/auto-loading/gradio.config.js#L1-L4) +- [**init**.py:47-64](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L47-L64) +- [README.md:1-36](file://docs/components/base/auto_loading/README.md#L1-L36) + +## Core Components + +- Svelte entry (Index.svelte): Parses properties, gets configuration type and slots, injects loading state context, and renders the React wrapper component on demand. +- React wrapper component (auto-loading.tsx): Decides whether to show loading animation, mask, timer, and queue information based on loading state; displays closable error notifications in error state. +- Loading state hook (useLoadingStatus.ts): Maintains timer, ETA, and formatted time, deriving display data based on `ILoadingStatus`. +- Styles (auto-loading.less): Controls loading layer positioning, mask z-index, and error popup centering styles. +- Backend component (**init**.py): Declares the frontend directory, skips API calls, enabling direct use via frontend resource exports. +- Documentation (README.md): Explains the component's role, state meanings, default behavior, and example entry. + +**Section Sources** + +- [Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [auto-loading.tsx:25-176](file://frontend/base/auto-loading/auto-loading.tsx#L25-L176) +- [useLoadingStatus.ts:5-93](file://frontend/base/auto-loading/useLoadingStatus.ts#L5-L93) +- [auto-loading.less:1-28](file://frontend/base/auto-loading/auto-loading.less#L1-L28) +- [**init**.py:47-64](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L47-L64) +- [README.md:1-36](file://docs/components/base/auto_loading/README.md#L1-L36) + +## Architecture Overview + +AutoLoading's workflow revolves around "state collection — conditional rendering — UI display". The Svelte entry collects `ILoadingStatus` from child components via context; the React component selects loading animations or error notifications based on state and presents them via Ant Design components. + +```mermaid +sequenceDiagram +participant Child as "Child Component" +participant Bridge as "Loading State Bridge" +participant Auto as "AutoLoading (React)" +participant UI as "Ant Design Components" +Child->>Bridge : "setLoadingStatus(ILoadingStatus)" +Bridge-->>Auto : "loadingStatus (aggregated)" +Auto->>Auto : "useLoadingStatus() calculates ETA/timer" +Auto->>UI : "Render loading/error based on state" +UI-->>Auto : "User interaction (e.g. close error)" +Auto-->>Child : "Continue rendering child content" +``` + +**Diagram Sources** + +- [loading-status.svelte.ts:47-75](file://frontend/svelte-preprocess-react/svelte-contexts/loading-status.svelte.ts#L47-L75) +- [auto-loading.tsx:48-175](file://frontend/base/auto-loading/auto-loading.tsx#L48-L175) +- [useLoadingStatus.ts:17-81](file://frontend/base/auto-loading/useLoadingStatus.ts#L17-L81) + +## Detailed Component Analysis + +### Svelte Entry (Index.svelte) + +- Retrieves component properties, configuration type, and slots from the preprocessing context. +- Injects the generated `loadingStatus` context via `getLoadingStatus`, for consumption by the internal React component. +- Uses `importComponent` for lazy loading, ensuring the component loads only after global initialization is complete. +- Passes visibility, styles, class names, and other properties to the React wrapper component. + +Key points + +- On-demand rendering: Renders only when `visible` is true. +- Slots and configuration: `slots`, `configType`, `loadingStatus` passed as props. +- Key generation: Assigns a unique key to each loading state via `window.ms_globals.loadingKey`. + +**Section Sources** + +- [Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [import.ts:1-20](file://frontend/svelte-preprocess-react/component/import.ts#L1-L20) +- [loading-status.svelte.ts:47-75](file://frontend/svelte-preprocess-react/svelte-contexts/loading-status.svelte.ts#L47-L75) + +### React Wrapper Component (auto-loading.tsx) + +Responsibilities + +- Parses configuration type (currently supports `antd`), determining loading animation and error notification UI. +- Renders loading animation based on state (including mask, timer, progress/queue information). +- In error state, renders a closable error notification, clearing the internal instance after closing to avoid duplicate rendering. +- Supports custom slots: `render` (custom loading content), `errorRender` (custom error content), `loadingText` (custom loading text). + +Loading State Determination + +- `pending`/`generating` treated as loading; `completed`/`error` treated as ended. +- Dynamically displays progress and queue information when `progress` or `queue_position`/`queue_size` is present. +- Optional timer and ETA display. + +Style and Z-Index + +- Loading layer is absolutely positioned and covers the parent container; error notification is fixed and centered. +- Sets z-index based on theme token, ensuring mask and error notification layers are properly ordered. + +**Section Sources** + +- [auto-loading.tsx:25-176](file://frontend/base/auto-loading/auto-loading.tsx#L25-L176) +- [auto-loading.less:1-28](file://frontend/base/auto-loading/auto-loading.less#L1-L28) + +### Loading State Hook (useLoadingStatus.ts) + +Functionality + +- Maintains timer: Starts timing in `pending` state, stops in non-`pending` state. +- Calculates ETA and formats time: Combines `performance.now` and ETA field to calculate remaining time and elapsed time. +- Tracks old ETA: Records the old value when ETA updates and formats the new ETA. +- Returns state fields: `status`, `message`, `progress`, `queuePosition`, `queueSize`, `formattedEta`, `formattedTimer`. + +Performance Notes + +- Uses `requestAnimationFrame` loop to update timing, avoiding blocking the main thread. +- Uses `useMemoizedFn` to cache callbacks, reducing re-renders. + +**Section Sources** + +- [useLoadingStatus.ts:5-93](file://frontend/base/auto-loading/useLoadingStatus.ts#L5-L93) + +### Styles (auto-loading.less) + +Key points + +- Loading layer is absolutely positioned, covering the parent container, ensuring mask effect. +- Error notification is fixed-positioned and centered, avoiding layout jitter. +- Controls z-index and appearance via Ant Design class names and theme token. + +**Section Sources** + +- [auto-loading.less:1-28](file://frontend/base/auto-loading/auto-loading.less#L1-L28) + +### Backend Component (**init**.py) + +Key points + +- Declares frontend directory as `base/auto-loading`. +- Skips API calls; component is used only for frontend rendering and state collection. + +**Section Sources** + +- [**init**.py:47-64](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L47-L64) + +### Documentation (README.md) + +Key points + +- Component role: Automatically adds loading animations and error notifications to wrapped content. +- State descriptions: Four states — `pending`/`generating`/`completed`/`error`. +- Default behavior: `pending` starts loading; `generating`/`completed` ends; `error` ends loading (optionally shows error). +- API parameters: `generating`, `show_error`, `show_mask`, `show_timer`, `loading_text`, etc. + +**Section Sources** + +- [README.md:1-36](file://docs/components/base/auto_loading/README.md#L1-L36) + +## Dependency Analysis + +AutoLoading's dependencies are mainly reflected in the following aspects: + +- The Svelte entry depends on loading state context and import utilities, implementing lazy loading and state aggregation. +- The React component depends on Ant Design's Spin and Alert, and the theme token. +- `useLoadingStatus` depends on browser performance API and React hooks, implementing timing and state formatting. +- The backend component declares the frontend resource path, enabling the frontend component to load correctly through package exports. + +```mermaid +graph LR +Index["Index.svelte"] --> Import["import.ts
Lazy Loading"] +Index --> Ctx["loading-status.svelte.ts
Loading State Context"] +Index --> Auto["auto-loading.tsx"] +Auto --> Hook["useLoadingStatus.ts"] +Auto --> Less["auto-loading.less"] +Backend["__init__.py"] --> Index +Doc["README.md"] --> Index +``` + +**Diagram Sources** + +- [Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [import.ts:1-20](file://frontend/svelte-preprocess-react/component/import.ts#L1-L20) +- [loading-status.svelte.ts:1-75](file://frontend/svelte-preprocess-react/svelte-contexts/loading-status.svelte.ts#L1-L75) +- [auto-loading.tsx:1-179](file://frontend/base/auto-loading/auto-loading.tsx#L1-L179) +- [useLoadingStatus.ts:1-94](file://frontend/base/auto-loading/useLoadingStatus.ts#L1-L94) +- [auto-loading.less:1-28](file://frontend/base/auto-loading/auto-loading.less#L1-L28) +- [**init**.py:47-64](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L47-L64) +- [README.md:1-36](file://docs/components/base/auto_loading/README.md#L1-L36) + +**Section Sources** + +- [Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [auto-loading.tsx:1-179](file://frontend/base/auto-loading/auto-loading.tsx#L1-L179) +- [useLoadingStatus.ts:1-94](file://frontend/base/auto-loading/useLoadingStatus.ts#L1-L94) +- [auto-loading.less:1-28](file://frontend/base/auto-loading/auto-loading.less#L1-L28) +- [**init**.py:47-64](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L47-L64) +- [README.md:1-36](file://docs/components/base/auto_loading/README.md#L1-L36) + +## Performance Considerations + +- Deferred initialization: Using `importComponent` and the global initialization Promise avoids loading the component before it's ready, reducing initial screen pressure. +- Timer optimization: Uses `requestAnimationFrame` loop to update timing, reducing main thread usage; only starts timing in `pending` state. +- State aggregation: Only the innermost AutoLoading collects child component states, avoiding duplicate rendering and state conflicts. +- Style z-index: Ensures mask and error notifications don't cause layout reflows through z-index and absolute positioning. +- Custom rendering: Through `render` and `errorRender` slots, business teams can optimize loading and error UI themselves, reducing unnecessary component overhead. + +[This section is general performance recommendations; no "Section Sources" needed] + +## Troubleshooting Guide + +Common Issues and Solutions + +- Multiple nested AutoLoading: According to the documentation, only the innermost layer can collect child component states and display loading animations. If outer layers don't work, check the nesting level. +- Error notification not disappearing: The error notification is a closable component; the internal instance is cleared after closing. If still displayed, check if the close logic or styles are causing visual residue. +- Loading animation not appearing: Confirm whether `loadingStatus` enters `pending`/`generating` state; check if `generating`/`show_error` configuration meets expectations. +- Timer not updating: Timing only starts in `pending` state; if there's no `pending` state for a long time, the timer won't start. +- Mask z-index anomalies: Styles control z-index via theme token; if custom styles override `z-index`, check style priority. + +**Section Sources** + +- [README.md:5-19](file://docs/components/base/auto_loading/README.md#L5-L19) +- [auto-loading.tsx:139-166](file://frontend/base/auto-loading/auto-loading.tsx#L139-L166) +- [useLoadingStatus.ts:44-50](file://frontend/base/auto-loading/useLoadingStatus.ts#L44-L50) + +## Conclusion + +AutoLoading provides unified and customizable loading and error feedback capabilities for Gradio applications through the "state collection — conditional rendering — UI display" mechanism. Its deferred initialization and timer optimization help improve performance and experience; slots and configuration options meet diverse business needs. Combined with documentation and examples, it can be used flexibly in both global and local scenarios. + +[This section is summary content; no "Section Sources" needed] + +## Appendix + +### API Definitions (Parameters and Behavior) + +- generating: Whether to include `generating` state handling. +- show_error: Whether to display error information. +- show_mask: Whether to display the mask. +- show_timer: Whether to display the timer. +- loading_text: Custom loading text; when empty, uses the default text provided by Gradio (including elapsed time, queue position, etc.). + +Default Behavior + +- pending: Show loading animation. +- generating/completed: End loading animation. +- error: End loading animation; optionally show error information. + +**Section Sources** + +- [README.md:27-36](file://docs/components/base/auto_loading/README.md#L27-L36) +- [auto-loading.tsx:65-138](file://frontend/base/auto-loading/auto-loading.tsx#L65-L138) + +### Usage Examples (Scenarios and Recommendations) + +- Global fallback: Place one AutoLoading at the application root to ensure any request gets loading feedback. +- Fine-grained local control: Use separately in areas that need richer loading information, with custom display via `render` and `loadingText` slots. +- Error visibility: Control error information display via `show_error`; use `errorRender` to customize error UI when necessary. +- Queue and progress: When the backend uses `yield` for streaming returns, use `progress` and queue information to enhance user perception. + +**Section Sources** + +- [README.md:21-25](file://docs/components/base/auto_loading/README.md#L21-L25) +- [auto-loading.tsx:72-138](file://frontend/base/auto-loading/auto-loading.tsx#L72-L138) + +### Collaboration Patterns with Other Components + +- Collaboration with forms/lists: Using AutoLoading inside these components provides consistent loading and error feedback. +- Collaboration with the theme system: Controls mask and error notification z-index and appearance via Ant Design theme token. +- Collaboration with state context: Through the loading state context, states from multiple child components are aggregated; the nearest AutoLoading decides what to display. + +**Section Sources** + +- [Index.svelte:56-62](file://frontend/base/auto-loading/Index.svelte#L56-L62) +- [loading-status.svelte.ts:47-75](file://frontend/svelte-preprocess-react/svelte-contexts/loading-status.svelte.ts#L47-L75) +- [auto-loading.tsx:68-134](file://frontend/base/auto-loading/auto-loading.tsx#L68-L134) diff --git a/.wiki/en/Base Components/Base Components.md b/.wiki/en/Base Components/Base Components.md new file mode 100644 index 00000000..cecdd060 --- /dev/null +++ b/.wiki/en/Base Components/Base Components.md @@ -0,0 +1,505 @@ +# Base Components + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/base/application/__init__.py](file://backend/modelscope_studio/components/base/application/__init__.py) +- [backend/modelscope_studio/components/base/auto_loading/__init__.py](file://backend/modelscope_studio/components/base/auto_loading/__init__.py) +- [backend/modelscope_studio/components/base/slot/__init__.py](file://backend/modelscope_studio/components/base/slot/__init__.py) +- [backend/modelscope_studio/components/base/fragment/__init__.py](file://backend/modelscope_studio/components/base/fragment/__init__.py) +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [frontend/base/application/Index.svelte](file://frontend/base/application/Index.svelte) +- [frontend/base/auto-loading/Index.svelte](file://frontend/base/auto-loading/Index.svelte) +- [frontend/base/slot/Index.svelte](file://frontend/base/slot/Index.svelte) +- [frontend/base/fragment/Index.svelte](file://frontend/base/fragment/Index.svelte) +- [frontend/base/each/Index.svelte](file://frontend/base/each/Index.svelte) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [frontend/utils/renderParamsSlot.tsx](file://frontend/utils/renderParamsSlot.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the "Base Components" system of ModelScope Studio, systematically explaining the design philosophy, data and control flow, role and collaboration within the overall component system, as well as providing usage examples, best practices, performance optimization suggestions, and solutions to common issues for core components such as Application, AutoLoading, Slot, and Fragment. The goal is to help developers quickly understand and correctly use these base components to build complex interfaces. + +## Project Structure + +The base components sit between the backend Python modules and the frontend Svelte implementations, bridged through a unified component base class and context mechanism. The backend is responsible for defining component classes, event and slot capabilities, data models, and lifecycle hooks; the frontend handles rendering, slot parsing, state management, and async loading. + +```mermaid +graph TB +subgraph "Backend" +PY_APP["Application Component
application/__init__.py"] +PY_AUTO["AutoLoading Component
auto_loading/__init__.py"] +PY_SLOT["Slot Component
slot/__init__.py"] +PY_FRAG["Fragment Component
fragment/__init__.py"] +PY_BASE_INIT["Base Component Exports
base/__init__.py"] +PY_DEV_COMP["Component Base Class
utils/dev/component.py"] +end +subgraph "Frontend" +FE_APP["Application Frontend Entry
base/application/Index.svelte"] +FE_AUTO["AutoLoading Frontend Entry
base/auto-loading/Index.svelte"] +FE_SLOT["Slot Frontend Entry
base/slot/Index.svelte"] +FE_FRAG["Fragment Frontend Entry
base/fragment/Index.svelte"] +FE_EACH["Each Frontend Entry
base/each/Index.svelte"] +FE_RENDER_SLOT["renderSlot Utility
utils/renderSlot.tsx"] +FE_RENDER_PARAMS_SLOT["renderParamsSlot Utility
utils/renderParamsSlot.tsx"] +end +PY_APP --> FE_APP +PY_AUTO --> FE_AUTO +PY_SLOT --> FE_SLOT +PY_FRAG --> FE_FRAG +PY_BASE_INIT --> PY_APP +PY_BASE_INIT --> PY_AUTO +PY_BASE_INIT --> PY_SLOT +PY_BASE_INIT --> PY_FRAG +PY_DEV_COMP --> PY_APP +PY_DEV_COMP --> PY_AUTO +PY_DEV_COMP --> PY_SLOT +PY_DEV_COMP --> PY_FRAG +FE_SLOT --> FE_RENDER_SLOT +FE_SLOT --> FE_RENDER_PARAMS_SLOT +FE_AUTO --> FE_EACH +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:8-65](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L8-L65) +- [backend/modelscope_studio/components/base/slot/**init**.py:8-50](file://backend/modelscope_studio/components/base/slot/__init__.py#L8-L50) +- [backend/modelscope_studio/components/base/fragment/**init**.py:8-49](file://backend/modelscope_studio/components/base/fragment/__init__.py#L8-L49) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +**Section Sources** + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +## Core Components + +This section provides an overview of the roles, features, and usage of Application, AutoLoading, Slot, Fragment, and Each. + +- Application (Application Container) + - Role: Acts as the top-level layout container, handling page-level event bindings (custom events, mount, window resize, unmount) and providing page environment data (screen size, language, theme, UA). + - Key points: Supports event listener registration; serves as the application context root node, ensuring all child components are created within a valid application context. + - Typical usage: Placed at the application entry point, with other base or business components nested inside; event listeners handle browser lifecycle and interaction events. + +- AutoLoading (Auto-Loading Placeholder) + - Role: Automatically switches between loading state, error state, and content rendering based on generation state, error state, and mask/timer configurations; supports named slots (render, errorRender, loadingText) for flexible customization. + - Key points: `skip_api` is marked true to avoid duplicate API calls; reads loading state from the frontend context and links to slot rendering. + - Typical usage: Wraps content areas that need lazy loading or conditional rendering; dynamically set `generating`/`showError` based on business logic. + +- Slot (Slot) + - Role: Declares and registers named slots, supports parameter mapping functions, bridges DOM slots with React/JSX content; can be nested to form hierarchical slot keys. + - Key points: Sets slot key and parameter mapping via context; at render time, utility functions clone and inject slot content into target elements. + - Typical usage: Declare slots in parent components and render them on demand in child components; used for complex layouts and conditional rendering. + +- Fragment (Fragment) + - Role: Lightweight container that does not introduce additional DOM wrappers; only holds child nodes and slots; commonly used for conditional rendering, list item wrapping, etc. + - Key points: `skip_api` is marked true; does not trigger extra rendering overhead; can be used with Each/Slot. + - Typical usage: Used as list item containers in Each; wraps multiple child nodes in conditional branches without adding extra levels. + +- Each (List Rendering) + - Role: Provides bulk rendering capabilities for list or array data, mapping each element in the list with corresponding slots/Fragments for parameter mapping and rendering. + - Key points: Frontend-only rendering component with no corresponding backend Python class; used with Fragment for list item rendering, and with Slot for parameter-mapped slots. + - Parameter mapping: Through the Slot's `params_mapping` property, injects the current item and index of list elements into child component slots. + - Typical usage: Wrap `ms.Each` inside parent components that support item rendering, using `ms.Fragment` and `ms.Slot` (with `params_mapping`) to achieve dynamic list rendering. + +**Section Sources** + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:8-65](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L8-L65) +- [backend/modelscope_studio/components/base/slot/**init**.py:8-50](file://backend/modelscope_studio/components/base/slot/__init__.py#L8-L50) +- [backend/modelscope_studio/components/base/fragment/**init**.py:8-49](file://backend/modelscope_studio/components/base/fragment/__init__.py#L8-L49) +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + +## Architecture Overview + +The diagram below shows the overall call chain and collaboration relationships between base components from backend to frontend. + +```mermaid +sequenceDiagram +participant PyApp as "Backend Application" +participant PyAuto as "Backend AutoLoading" +participant PySlot as "Backend Slot" +participant PyFrag as "Backend Fragment" +participant FeApp as "Frontend Application" +participant FeAuto as "Frontend AutoLoading" +participant FeSlot as "Frontend Slot" +participant FeFrag as "Frontend Fragment" +participant Utils as "Render Utilities (renderSlot/renderParamsSlot)" +PyApp->>FeApp : Initialize and bind events +PyAuto->>FeAuto : Configure generate/error/mask/text +PySlot->>FeSlot : Register slot key and parameter mapping +FeSlot->>Utils : Render slot (cloneable/force clone/with params) +Utils-->>FeSlot : Return ReactSlot render result +PyFrag->>FeFrag : Act as container for child nodes +FeAuto->>FeFrag : Switch between loading/error/content +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:8-65](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L8-L65) +- [backend/modelscope_studio/components/base/slot/**init**.py:8-50](file://backend/modelscope_studio/components/base/slot/__init__.py#L8-L50) +- [backend/modelscope_studio/components/base/fragment/**init**.py:8-49](file://backend/modelscope_studio/components/base/fragment/__init__.py#L8-L49) +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +## Detailed Component Analysis + +### Application Component + +- Design philosophy + - As the application-level root container, centrally handles browser lifecycle events and page environment information, providing a consistent runtime context for upper-layer components. + - Extends application behavior boundaries through event listeners, such as custom event dispatch, mount/unmount callbacks, and window resize responses. +- Data model + - Page screen data (width/height, scroll position), language, theme, user agent, etc., enabling frontend adaptation to different devices and themes. +- Frontend implementation highlights + - Asynchronously imports the actual component, delaying rendering to improve initial screen performance. + - Passes `children` through to child components, maintaining flexibility in the tree structure. +- Usage example path + - Create Application at the application entry and organize the page layout and business components inside it. + - Example reference: [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) + +```mermaid +classDiagram +class ModelScopeApplication { ++EVENTS ++SLOTS ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class ModelScopeDataLayoutComponent { ++skip_api ++__exit__() ++__init__(...) +} +ModelScopeApplication --|> ModelScopeDataLayoutComponent : "inherits" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [backend/modelscope_studio/utils/dev/component.py:101-169](file://backend/modelscope_studio/utils/dev/component.py#L101-L169) + +**Section Sources** + +- [backend/modelscope_studio/components/base/application/**init**.py:26-115](file://backend/modelscope_studio/components/base/application/__init__.py#L26-L115) +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) + +### AutoLoading Component + +- Design philosophy + - Automates handling of "generating/error/loading text" states, reducing boilerplate code on the business side; highly customizable through slots. +- Key properties + - generating: Whether currently in generating state + - show_error: Whether to display error state + - show_mask/show_timer: Mask and timer toggles + - loading_text: Custom loading text + - Supported slots: render, errorRender, loadingText +- Frontend implementation highlights + - Reads loading state from context to determine which type of content to render. + - Maps backend-passed properties and slots to frontend components via `processProps` and `getSlots`. +- Usage example path + - Wrap areas that need lazy loading or conditional rendering with AutoLoading, and switch `generating`/`showError` based on business state. + - Example reference: [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) + +```mermaid +flowchart TD +Start(["Enter AutoLoading"]) --> CheckVisible["Check Visibility"] +CheckVisible --> |Not Visible| End(["End"]) +CheckVisible --> |Visible| ReadCtx["Read Loading State (generating/error)"] +ReadCtx --> Decide{"Choose Content to Render"} +Decide --> |Generating| RenderLoading["Render loadingText Slot"] +Decide --> |Error| RenderError["Render errorRender Slot"] +Decide --> |Normal| RenderContent["Render render Slot / Default Content"] +RenderLoading --> End +RenderError --> End +RenderContent --> End +``` + +**Diagram Sources** + +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) + +**Section Sources** + +- [backend/modelscope_studio/components/base/auto_loading/**init**.py:8-65](file://backend/modelscope_studio/components/base/auto_loading/__init__.py#L8-L65) +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) + +### Slot Component + +- Design philosophy + - Provides named slot and parameter mapping capabilities, bridging Svelte slots with React/JSX rendering; supports nested slot keys and dynamic parameters. +- Key properties + - value: Slot key name (supports nesting) + - params_mapping: Parameter mapping function string, converted to a function at runtime +- Frontend implementation highlights + - Sets the current slot key and parameter mapping function via context. + - Uses `renderSlot`/`renderParamsSlot` to clone and inject slot content into target elements, supporting force clone and multi-target rendering. +- Usage example path + - Declare Slot in parent components and render on demand in child components; or use with parameter mapping in Each for dynamic rendering. + - Example references: [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68), [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29), [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +```mermaid +sequenceDiagram +participant Parent as "Parent Component (Slot)" +participant Ctx as "Slot Context" +participant Utils as "renderSlot/renderParamsSlot" +participant Child as "Child Component" +Parent->>Ctx : Set slot key and parameter mapping +Parent->>Utils : Request slot rendering (cloneable/force clone/with params) +Utils-->>Parent : Return ReactSlot render result +Parent->>Child : Pass through render result +``` + +**Diagram Sources** + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +**Section Sources** + +- [backend/modelscope_studio/components/base/slot/**init**.py:8-50](file://backend/modelscope_studio/components/base/slot/__init__.py#L8-L50) +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +### Fragment Component + +- Design philosophy + - Acts as a lightweight container without introducing additional DOM wrappers; only holds child nodes and slots; suitable for conditional rendering and list item wrapping. +- Frontend implementation highlights + - Asynchronously imports the actual component via lazy loading; renders only when visibility is true. + - Does not reset the slot key, avoiding impact on sibling nodes' slot state. +- Usage example path + - Used as list item container in Each or conditional rendering; prefer Fragment when a wrapper-free container is needed. + - Example reference: [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) + +```mermaid +flowchart TD +Enter(["Enter Fragment"]) --> Visible{"Is Visible?"} +Visible --> |No| Exit(["Exit"]) +Visible --> |Yes| AsyncLoad["Async Load Fragment Component"] +AsyncLoad --> Render["Render Child Nodes / Slots"] +Render --> Exit +``` + +**Diagram Sources** + +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) + +**Section Sources** + +- [backend/modelscope_studio/components/base/fragment/**init**.py:8-49](file://backend/modelscope_studio/components/base/fragment/__init__.py#L8-L49) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) + +### Each Component + +- Design philosophy + - Each is a lightweight frontend component designed for list rendering with no corresponding backend Python class. It allows batch instantiation of child components based on array data, and with Fragment and Slot can achieve parameterized dynamic rendering. +- Using with Fragment + - Use Fragment as a lightweight container for each item in Each, avoiding the introduction of additional DOM wrapper levels. + - Fragment's `visible` controls whether the current item renders, suitable for conditional lists. + - Typical usage: When displaying list elements, render each item in the list container into a Fragment. +- Parameter Mapping (params_mapping) + - Set the `params_mapping` property on the Slot component to inject the current item value (item) and index (index) into the slot content. + - `params_mapping` is a JavaScript string function, converted to a function at runtime, accepting `(item, index)` and returning a slot parameter object. + - Example: `params_mapping="lambda item, index: {'children': item['label']}"` renders each item's label field as children. +- Frontend implementation highlights + - Each passes list elements to child component slots by merging context values with item values. + - Supports nested Each; inner layers use `subIndex` to prevent slot key conflicts. + - Can configure `forceClone` when needed, ensuring each item has an independent slot instance. + - Example reference: [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + +```mermaid +sequenceDiagram +participant PY as "Backend Parent Component (items property)" +participant Each as "Each (Frontend)" +participant Frag as "Fragment (Frontend)" +participant Slot as "Slot (params_mapping)" +participant Child as "Child Component Slot" +PY->>Each : Pass in items array +Each->>Frag : Create Fragment for each item +Frag->>Slot : Enter named slot +Slot->>Child : params_mapping injects item/index into child component +Child-->>Each : Render list item UI +``` + +**Diagram Sources** + +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + +**Section Sources** + +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) + +### Component Base Classes and Context + +- ModelScopeLayoutComponent / ModelScopeComponent / ModelScopeDataLayoutComponent + - Uniformly handles component lifecycle, styles, and internal indices; participates in layout tree management under BlockContext. + - `skip_api` controls whether to skip API-level duplicate rendering or processing. +- AppContext + - Ensures all base components are created within a valid application context, avoiding runtime errors. + +```mermaid +classDiagram +class ModelScopeComponent { ++EVENTS ++skip_api ++__init__(...) +} +class ModelScopeLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__exit__() ++__init__(...) +} +class ModelScopeDataLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__exit__() ++__init__(...) +} +ModelScopeLayoutComponent --|> ModelScopeComponent : "inherits" +ModelScopeDataLayoutComponent --|> ModelScopeComponent : "inherits" +ModelScopeDataLayoutComponent --|> BlockContext : "mixes in" +``` + +**Diagram Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +**Section Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +## Dependency Analysis + +- Backend exports + - Base components are exported via `base/__init__.py`, providing a unified external interface for upper modules to import as needed. +- Inter-component coupling + - Application acts as the root container, with other components organized around it; AutoLoading and Fragment are commonly used as generic containers; Slot is the core for cross-component slot bridging. +- External dependencies + - Frontend uses `@svelte-preprocess-react` and the context system to bridge Svelte and React; rendering utilities provide slot cloning and parameter injection capabilities. + +```mermaid +graph LR +Export["base/__init__.py Exports"] --> App["Application"] +Export --> Auto["AutoLoading"] +Export --> Slot["Slot"] +Export --> Frag["Fragment"] +App --> FeApp["frontend/base/application/Index.svelte"] +Auto --> FeAuto["frontend/base/auto-loading/Index.svelte"] +Slot --> FeSlot["frontend/base/slot/Index.svelte"] +Frag --> FeFrag["frontend/base/fragment/Index.svelte"] +FeSlot --> RenderSlot["utils/renderSlot.tsx"] +FeSlot --> RenderParams["utils/renderParamsSlot.tsx"] +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +**Section Sources** + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +## Performance Considerations + +- Lazy loading and visibility control + - Application/AutoLoading/Fragment all use async import and visibility checks, reducing initial screen rendering pressure. +- Slot rendering optimization + - When using `renderSlot`/`renderParamsSlot`, properly set `clone`/`forceClone` and `params` to avoid unnecessary duplicate rendering. +- Each list rendering + - Each supports merged values and context; force clone when necessary to ensure independent state; maintain `slotKey` and `subIndex` in nested Each to avoid slot key conflicts. +- Event binding + - Application's event listeners are only enabled when needed, avoiding unnecessary event handling overhead. + +[This section is general guidance; no specific file references needed] + +## Troubleshooting Guide + +- Slot not working + - Check if the Slot's `value` is correctly set, and if the parent component has registered the corresponding slot key. + - Confirm that `renderSlot`/`renderParamsSlot` parameters are correctly passed (`clone`/`forceClone`/`params`). + - Reference: [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68), [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29), [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- AutoLoading not switching as expected + - Confirm that `generating`/`showError` state is correctly passed to the frontend; check if slot names match (render/errorRender/loadingText). + - Reference: [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- Fragment not rendering + - Check `visible` property and whether async loading is complete; confirm `shouldResetSlotKey` is not misused, causing slot key loss. + - Reference: [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) +- Each list misalignment or slot conflicts + - Ensure Each's context values and item values are correctly merged; maintain `subIndex` and `slotKey` in nested Each. + - Reference: [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + +**Section Sources** + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) +- [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) +- [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) +- [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + +## Conclusion + +The base component system uses Application as the root, AutoLoading as the generic container, Slot as the cross-component bridge, and Fragment as the lightweight container, combined with a unified component base class and context mechanism. This achieves an architecture design with frontend-backend coordination, decoupled events and slots, and controllable rendering performance. By following the best practices and troubleshooting recommendations in this document, developers can efficiently use these components to build complex, high-performance interfaces. + +[This section is summary content; no specific file references needed] + +## Appendix + +- Quick Start Checklist + - Place Application at the application entry to ensure global context is available. + - Use AutoLoading for areas that need lazy loading, and switch between generate/error states based on business logic. + - Use Slot to declare named slots, and render them with `renderSlot`/`renderParamsSlot`. + - Use Fragment as a wrapper-free container in list or conditional rendering. +- Related Implementation Reference Paths + - [frontend/base/application/Index.svelte:1-17](file://frontend/base/application/Index.svelte#L1-L17) + - [frontend/base/auto-loading/Index.svelte:1-81](file://frontend/base/auto-loading/Index.svelte#L1-L81) + - [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) + - [frontend/base/fragment/Index.svelte:1-50](file://frontend/base/fragment/Index.svelte#L1-L50) + - [frontend/base/each/Index.svelte:1-111](file://frontend/base/each/Index.svelte#L1-L111) + - [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) + - [frontend/utils/renderParamsSlot.tsx:1-51](file://frontend/utils/renderParamsSlot.tsx#L1-L51) + +[This section is supplementary material; no specific file references needed] diff --git a/.wiki/en/Base Components/Fragment Component.md b/.wiki/en/Base Components/Fragment Component.md new file mode 100644 index 00000000..9a4677fb --- /dev/null +++ b/.wiki/en/Base Components/Fragment Component.md @@ -0,0 +1,328 @@ +# Fragment Component + + +**Files Referenced in This Document** +- [frontend/base/fragment/fragment.tsx](file://frontend/base/fragment/fragment.tsx) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js) +- [backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js](file://backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js) +- [docs/components/base/fragment/README.md](file://docs/components/base/fragment/README.md) +- [docs/components/base/fragment/README-zh_CN.md](file://docs/components/base/fragment/README-zh_CN.md) +- [docs/components/base/fragment/demos/basic.py](file://docs/components/base/fragment/demos/basic.py) +- [frontend/svelte-preprocess-react/react-slot.tsx](file://frontend/svelte-preprocess-react/react-slot.tsx) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [frontend/utils/renderItems.tsx](file://frontend/utils/renderItems.tsx) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/utils/style.ts](file://frontend/utils/style.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +Fragment is a "fragment" container component designed to combine multiple child elements into a whole without introducing additional DOM nodes, allowing them to be used as insertable content in slots that only accept model-internal components. It is commonly used to wrap components from external ecosystems (such as Gradio buttons) into forms that comply with model-internal component specifications, enabling them to enter the component tree smoothly. + +- Design purpose: Avoid introducing redundant container nodes in the layout while maintaining the logical grouping and passing of child nodes. +- Use cases: When a component slot only supports components exported from a specific ecosystem, wrap the unsupported component with Fragment before passing it in. +- Advantages: Reduces unnecessary DOM levels, lowering layout overhead; maintains the directness and maintainability of child nodes. + +## Project Structure + +Fragment has corresponding implementations and templates in both the frontend and backend, combined with the React Slot mechanism to complete cross-framework bridging and rendering. + +```mermaid +graph TB +subgraph "Frontend" +FE_Fragment["frontend/base/fragment/fragment.tsx"] +FE_ReactSlot["frontend/svelte-preprocess-react/react-slot.tsx"] +FE_RenderSlot["frontend/utils/renderSlot.tsx"] +FE_RenderItems["frontend/utils/renderItems.tsx"] +FE_Style["frontend/utils/style.ts"] +end +subgraph "Backend Templates" +BE_Fragment["backend/.../fragment-sXw8Jnlf.js"] +BE_EachFragment["backend/.../fragment-BaGnla3s.js"] +end +subgraph "Docs & Examples" +DOC_Readme["docs/components/base/fragment/README.md"] +DOC_ReadmeCN["docs/components/base/fragment/README-zh_CN.md"] +DEMO_Basic["docs/components/base/fragment/demos/basic.py"] +end +FE_Fragment --> BE_Fragment +FE_Fragment --> BE_EachFragment +FE_ReactSlot --> FE_RenderSlot +FE_RenderItems --> FE_ReactSlot +FE_RenderSlot --> FE_ReactSlot +FE_Style --> FE_ReactSlot +DOC_Readme --> DEMO_Basic +DOC_ReadmeCN --> DEMO_Basic +``` + +Diagram Sources + +- [frontend/base/fragment/fragment.tsx:1-11](file://frontend/base/fragment/fragment.tsx#L1-L11) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:437-445](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L437-L445) +- [backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js:1-11](file://backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js#L1-L11) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/style.ts:1-77](file://frontend/utils/style.ts#L1-L77) +- [docs/components/base/fragment/README.md:1-10](file://docs/components/base/fragment/README.md#L1-L10) +- [docs/components/base/fragment/README-zh_CN.md:1-10](file://docs/components/base/fragment/README-zh_CN.md#L1-L10) +- [docs/components/base/fragment/demos/basic.py:1-22](file://docs/components/base/fragment/demos/basic.py#L1-L22) + +Section Sources + +- [frontend/base/fragment/fragment.tsx:1-11](file://frontend/base/fragment/fragment.tsx#L1-L11) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:437-445](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L437-L445) +- [docs/components/base/fragment/README.md:1-10](file://docs/components/base/fragment/README.md#L1-L10) + +## Core Components + +- Frontend Fragment (React wrapper) + - Bridges Svelte component capabilities to the React ecosystem via `sveltify`, passing `children` through as a React Fragment internally without introducing extra DOM. + - Typical path: [frontend/base/fragment/fragment.tsx:4-8](file://frontend/base/fragment/fragment.tsx#L4-L8) + +- Backend Fragment (runtime template) + - Generates a runtime wrapper for React Fragment for the bridging layer to render, ensuring `children` are mounted as a fragment. + - Typical path: [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:437-441](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L437-L441) + +- Backend Each Fragment (Svelte template) + - Fragment implementation for Svelte, enabling reuse of fragment semantics in Svelte scenarios. + - Typical path: [backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js:2-6](file://backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js#L2-L6) + +Section Sources + +- [frontend/base/fragment/fragment.tsx:1-11](file://frontend/base/fragment/fragment.tsx#L1-L11) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:437-445](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L437-L445) +- [backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js:1-11](file://backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js#L1-L11) + +## Architecture Overview + +Fragment's workflow revolves around "fragment container + React Slot + context bridging": the frontend Fragment passes `children` through as a React Fragment; ReactSlot clones Svelte/HTML structures and mounts them to the React subtree in a "display contents" manner, avoiding extra container nodes; the rendering utility chain handles merging and application of parameters, events, and styles during bridging. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant MS as "Model Component Tree" +participant Frag as "Fragment (React)" +participant RS as "ReactSlot" +participant Bridge as "Bridging Layer (Backend Template)" +participant DOM as "Browser DOM" +Dev->>MS : "Place Fragment in slot" +MS->>Frag : "Receive children" +Frag->>Frag : "Pass children through as React Fragment" +Frag->>RS : "Create Slot rendering via bridging layer" +RS->>Bridge : "Request cloning/mounting of Svelte/HTML structure" +Bridge-->>RS : "Return fragmented children" +RS->>DOM : "Mount with display: contents, no extra container" +RS-->>Dev : "Rendering complete" +``` + +Diagram Sources + +- [frontend/base/fragment/fragment.tsx:4-8](file://frontend/base/fragment/fragment.tsx#L4-L8) +- [frontend/svelte-preprocess-react/react-slot.tsx:109-223](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L223) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:437-441](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L437-L441) + +## Detailed Component Analysis + +### Component Class Diagram (Code Level) + +```mermaid +classDiagram +class Fragment_Frontend { ++children? : ReactNode ++renders : React.Fragment(children) +} +class ReactSlot { ++slot : HTMLElement ++clone? : boolean ++className? : string ++style? : CSSProperties ++render() : ReactElement[] +} +class BridgeRuntime { ++reactComponent : React.FC ++props : any ++children : ReactNode[] ++createPortal(node, target) +} +Fragment_Frontend --> ReactSlot : "renders via bridging layer" +ReactSlot --> BridgeRuntime : "clone/mount fragment" +BridgeRuntime --> ReactSlot : "return fragment children" +``` + +Diagram Sources + +- [frontend/base/fragment/fragment.tsx:4-8](file://frontend/base/fragment/fragment.tsx#L4-L8) +- [frontend/svelte-preprocess-react/react-slot.tsx:109-223](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L223) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:305-328](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L305-L328) + +Section Sources + +- [frontend/base/fragment/fragment.tsx:1-11](file://frontend/base/fragment/fragment.tsx#L1-L11) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:250-328](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L250-L328) + +### Rendering Flow (Fragment Mounting) + +- ReactSlot clones the target element as a "display contents" node during mounting, avoiding extra container levels. +- If clone mode is enabled, recursively clones child nodes and event listeners, mounting the React subtree into the cloned node via Portal. +- Finally presented as `display: contents`, allowing child nodes to directly participate in the parent container's layout calculations. + +```mermaid +flowchart TD +Start(["Start"]) --> CheckClone{"Clone enabled?"} +CheckClone --> |No| MountDirect["Mount directly with display: contents"] +CheckClone --> |Yes| CloneTree["Clone node tree
Copy event listeners"] +CloneTree --> PortalAttach["Mount React subtree via Portal"] +PortalAttach --> MountDirect +MountDirect --> ApplyStyles["Apply styles/class names"] +ApplyStyles --> End(["End"]) +``` + +Diagram Sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:158-202](file://frontend/svelte-preprocess-react/react-slot.tsx#L158-L202) +- [frontend/utils/style.ts:39-76](file://frontend/utils/style.ts#L39-L76) + +Section Sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:109-223](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L223) +- [frontend/utils/style.ts:1-77](file://frontend/utils/style.ts#L1-L77) + +### API/Service Component Call Sequence (Fragment Bridging) + +```mermaid +sequenceDiagram +participant Caller as "Caller" +participant Bridge as "Bridge Runtime" +participant ReactComp as "React Component" +participant Slot as "ReactSlot" +participant DOM as "DOM" +Caller->>Bridge : "Pass Fragment + children" +Bridge->>ReactComp : "Render as Fragment" +ReactComp->>Slot : "Create Slot and request clone" +Slot->>DOM : "Clone node and set display: contents" +Slot-->>ReactComp : "Return fragment children" +ReactComp-->>Caller : "Rendering complete" +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:305-328](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L305-L328) +- [frontend/svelte-preprocess-react/react-slot.tsx:109-223](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L223) + +Section Sources + +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:250-328](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L250-L328) + +### Complex Logic Component (Fragment and Context Merging) + +- During bridging, fragments merge multiple contexts (such as styles, class names, events, etc.) and skip context influence under ignore flags. +- Supports parameter mapping and force cloning, ensuring stable passing of properties and events in complex layouts. + +```mermaid +flowchart TD +Params["Collect params/context"] --> MergeCtx["Merge styles/class names/events"] +MergeCtx --> IgnoreFlag{"Ignore context?"} +IgnoreFlag --> |Yes| SkipCtx["Skip context influence"] +IgnoreFlag --> |No| ApplyCtx["Apply context"] +ApplyCtx --> Render["Render fragment children"] +SkipCtx --> Render +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:286-304](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L286-L304) + +Section Sources + +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:228-328](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L228-L328) + +## Dependency Analysis + +- The Fragment frontend implementation depends on React and `sveltify`; the backend template depends on the runtime renderer and bridging utilities. +- ReactSlot depends on style utilities and debounce hooks to ensure cloning and mounting stability. +- The rendering utility chain (renderSlot, renderItems, createItemsContext) provides a unified entry for handling parameters, events, and context. + +```mermaid +graph LR +FragTS["fragment.tsx"] --> BE_JS["fragment-sXw8Jnlf.js"] +FragTS --> BE_Svelte["fragment-BaGnla3s.js"] +ReactSlot["react-slot.tsx"] --> StyleUtils["style.ts"] +RenderSlot["renderSlot.tsx"] --> ReactSlot +RenderItems["renderItems.tsx"] --> ReactSlot +CreateItems["createItemsContext.tsx"] --> RenderItems +``` + +Diagram Sources + +- [frontend/base/fragment/fragment.tsx:1-11](file://frontend/base/fragment/fragment.tsx#L1-L11) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:1-446](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L1-L446) +- [backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js:1-11](file://backend/modelscope_studio/components/base/each/templates/component/fragment-BaGnla3s.js#L1-L11) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/utils/style.ts:1-77](file://frontend/utils/style.ts#L1-L77) + +Section Sources + +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/renderItems.tsx:1-114](file://frontend/utils/renderItems.tsx#L1-L114) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +## Performance Considerations + +- Reducing DOM levels: Fragment passes `children` through as React Fragment, avoiding extra container nodes and reducing layout and reflow costs. +- Clone strategy: Enable cloning when needed, but avoid frequent cloning of large numbers of nodes; combine with parameter mapping and force cloning when necessary to reduce invalid updates. +- Mutation observation: ReactSlot uses MutationObserver to observe changes, combined with debounce and minimal re-rendering, avoiding excessive refresh. +- Styles and class names: Converted uniformly via style utilities, avoiding repeated calculation and string concatenation overhead. +- Event binding: Copy event listeners during cloning to ensure interaction consistency, while paying attention to removal timing to prevent memory leaks. + +## Troubleshooting Guide + +- Slot not working + - Confirm that the slot only supports components from a specific ecosystem; the component needs to be wrapped with Fragment before being passed in. + - Reference example: [docs/components/base/fragment/demos/basic.py:14-19](file://docs/components/base/fragment/demos/basic.py#L14-L19) + +- Child elements not rendering correctly or styles missing + - Check if clone mode is enabled; if not, styles and class names may not be correctly applied. + - Reference implementation: [frontend/svelte-preprocess-react/react-slot.tsx:158-202](file://frontend/svelte-preprocess-react/react-slot.tsx#L158-L202) + +- Events not triggering or binding repeatedly + - Confirm event listeners have been copied during cloning; check if cleanup occurs on unmount. + - Reference implementation: [frontend/svelte-preprocess-react/react-slot.tsx:67-95](file://frontend/svelte-preprocess-react/react-slot.tsx#L67-L95) + +- Parameter mapping and context conflicts + - Use parameter mapping and force cloning to ensure context merge order and override rules meet expectations. + - Reference implementation: [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:286-304](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L286-L304) + +Section Sources + +- [docs/components/base/fragment/demos/basic.py:1-22](file://docs/components/base/fragment/demos/basic.py#L1-L22) +- [frontend/svelte-preprocess-react/react-slot.tsx:67-202](file://frontend/svelte-preprocess-react/react-slot.tsx#L67-L202) +- [backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js:286-304](file://backend/modelscope_studio/components/base/fragment/templates/component/fragment-sXw8Jnlf.js#L286-L304) + +## Conclusion + +The Fragment component implements combination and passing of multiple child elements without introducing extra DOM nodes, through the "fragment container + React Slot + context bridging" mechanism. It is particularly suitable for layout needs that require injecting unsupported components into strictly constrained slot scenarios. Combined with parameter mapping, event merging, and style utilities, Fragment has good stability and maintainability in complex layouts. + +## Appendix + +- Usage examples (documentation and demos) + - Basic usage and comparison: [docs/components/base/fragment/demos/basic.py:14-19](file://docs/components/base/fragment/demos/basic.py#L14-L19) + - Chinese documentation: [docs/components/base/fragment/README-zh_CN.md:1-10](file://docs/components/base/fragment/README-zh_CN.md#L1-L10) + - English documentation: [docs/components/base/fragment/README.md:1-10](file://docs/components/base/fragment/README.md#L1-L10) diff --git a/.wiki/en/Base Components/Layout Components.md b/.wiki/en/Base Components/Layout Components.md new file mode 100644 index 00000000..e6ba0e3e --- /dev/null +++ b/.wiki/en/Base Components/Layout Components.md @@ -0,0 +1,386 @@ +# Layout Components + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/components/base/div/__init__.py](file://backend/modelscope_studio/components/base/div/__init__.py) +- [backend/modelscope_studio/components/base/span/__init__.py](file://backend/modelscope_studio/components/base/span/__init__.py) +- [backend/modelscope_studio/components/base/text/__init__.py](file://backend/modelscope_studio/components/base/text/__init__.py) +- [backend/modelscope_studio/components/base/markdown/__init__.py](file://backend/modelscope_studio/components/base/markdown/__init__.py) +- [frontend/base/package.json](file://frontend/base/package.json) +- [frontend/base/div/Index.svelte](file://frontend/base/div/Index.svelte) +- [frontend/base/span/Index.svelte](file://frontend/base/span/Index.svelte) +- [frontend/base/text/Index.svelte](file://frontend/base/text/Index.svelte) +- [frontend/base/markdown/Index.svelte](file://frontend/base/markdown/Index.svelte) +- [frontend/base/div/div.tsx](file://frontend/base/div/div.tsx) +- [frontend/base/span/span.tsx](file://frontend/base/span/span.tsx) +- [frontend/base/text/text.tsx](file://frontend/base/text/text.tsx) +- [frontend/base/markdown/markdown.tsx](file://frontend/base/markdown/markdown.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically covers the "Layout Components" series in ModelScope Studio, focusing on the four foundational layout and content components: Div, Span, Text, and Markdown. The documentation provides in-depth explanations from the perspectives of architecture, data flow, processing logic, styling and theme adaptation, composition and nesting best practices, performance characteristics and optimization recommendations, as well as common issues and debugging techniques — helping developers efficiently and reliably use these components for page layout and content rendering. + +## Project Structure + +The layout components sit between the backend Python component layer and the frontend Svelte/React layer, following a layered design of "Python component definition + Svelte wrapper + React implementation": + +- Backend: Defines component behavior, event bindings, pre/post-processing logic, and declares frontend resource directories via Python classes. +- Frontend Svelte layer: Handles property passthrough, visibility control, style and class name composition, and slot resolution/rendering. +- React layer: Wraps specific HTML elements (e.g., div/span), or renders based on a global component (e.g., Markdown). + +```mermaid +graph TB +subgraph "Backend" +PY_DIV["Python: Div Component"] +PY_SPAN["Python: Span Component"] +PY_TEXT["Python: Text Component"] +PY_MD["Python: Markdown Component"] +end +subgraph "Frontend (Svelte)" +SV_DIV["Svelte: div/Index.svelte"] +SV_SPAN["Svelte: span/Index.svelte"] +SV_TEXT["Svelte: text/Index.svelte"] +SV_MD["Svelte: markdown/Index.svelte"] +end +subgraph "Frontend (React)" +RX_DIV["React: div.tsx"] +RX_SPAN["React: span.tsx"] +RX_TEXT["React: text.tsx"] +RX_MD["React: markdown.tsx"] +end +PY_DIV --> SV_DIV --> RX_DIV +PY_SPAN --> SV_SPAN --> RX_SPAN +PY_TEXT --> SV_TEXT --> RX_TEXT +PY_MD --> SV_MD --> RX_MD +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/div/**init**.py:10-86](file://backend/modelscope_studio/components/base/div/__init__.py#L10-L86) +- [backend/modelscope_studio/components/base/span/**init**.py:10-87](file://backend/modelscope_studio/components/base/span/__init__.py#L10-L87) +- [backend/modelscope_studio/components/base/text/**init**.py:8-57](file://backend/modelscope_studio/components/base/text/__init__.py#L8-L57) +- [backend/modelscope_studio/components/base/markdown/**init**.py:11-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L11-L174) +- [frontend/base/div/Index.svelte:1-65](file://frontend/base/div/Index.svelte#L1-L65) +- [frontend/base/span/Index.svelte:1-64](file://frontend/base/span/Index.svelte#L1-L64) +- [frontend/base/text/Index.svelte:1-42](file://frontend/base/text/Index.svelte#L1-L42) +- [frontend/base/markdown/Index.svelte:1-64](file://frontend/base/markdown/Index.svelte#L1-L64) +- [frontend/base/div/div.tsx:1-18](file://frontend/base/div/div.tsx#L1-L18) +- [frontend/base/span/span.tsx:1-20](file://frontend/base/span/span.tsx#L1-L20) +- [frontend/base/text/text.tsx:1-11](file://frontend/base/text/text.tsx#L1-L11) +- [frontend/base/markdown/markdown.tsx:1-35](file://frontend/base/markdown/markdown.tsx#L1-L35) + +Section Sources + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [frontend/base/package.json:1-6](file://frontend/base/package.json#L1-L6) + +## Core Components + +This section provides a functional and usage overview of the four foundational layout components, highlighting their roles and responsibilities in page layout and content rendering. + +- Div + - Role: Block-level container for holding child elements or text values; supports generic interaction events such as mouse and scroll events. + - Key Points: Accepts extra prop passthrough; supports visibility, element ID, class names, and inline styles as common attributes. + - Use Cases: Card backgrounds, section divisions, and outer containers for complex nested layouts. + +- Span + - Role: Inline container suitable for wrapping short text or inline elements; also supports generic interaction events. + - Key Points: Prioritizes child node rendering when children exist; falls back to `value` or an empty span otherwise. + - Use Cases: Inline highlights, labels, and text fragments within button groups. + +- Text + - Role: Pure text output component with no extra container wrapper; directly renders a string. + - Key Points: No event bindings; only handles `value`; suitable for minimal-cost text rendering. + - Use Cases: Headings, paragraphs, and lightweight hint text. + +- Markdown + - Role: Rich text rendering component supporting copyButtons slots, LaTeX math delimiters, HTML sanitization policy, line break and header link options. + - Key Points: Supports `copyButtons` slot; post-processing cleans input indentation; theme mode and root path are passed through to the underlying component. + - Use Cases: Help documentation, descriptive text, and dynamically generated rich text content. + +Section Sources + +- [backend/modelscope_studio/components/base/div/**init**.py:10-86](file://backend/modelscope_studio/components/base/div/__init__.py#L10-L86) +- [backend/modelscope_studio/components/base/span/**init**.py:10-87](file://backend/modelscope_studio/components/base/span/__init__.py#L10-L87) +- [backend/modelscope_studio/components/base/text/**init**.py:8-57](file://backend/modelscope_studio/components/base/text/__init__.py#L8-L57) +- [backend/modelscope_studio/components/base/markdown/**init**.py:11-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L11-L174) + +## Architecture Overview + +The diagram below illustrates the overall call chain and data flow from backend components to frontend rendering: + +```mermaid +sequenceDiagram +participant Py as "Backend Component (Python)" +participant Svelte as "Frontend Wrapper (Svelte)" +participant React as "React Implementation" +participant DOM as "DOM" +Py->>Svelte : Initialize and pass properties (visible/elem_*/value, etc.) +Svelte->>Svelte : Handle property passthrough / visibility / styles / class names +Svelte->>React : Render the corresponding React component +React->>DOM : Output final HTML nodes (div/span/text/markdown) +DOM-->>React : Event callbacks (e.g., click/mouseover/scroll) +React-->>Svelte : Trigger event updates +Svelte-->>Py : Event callback triggered (bound by backend event listeners) +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/div/**init**.py:14-39](file://backend/modelscope_studio/components/base/div/__init__.py#L14-L39) +- [backend/modelscope_studio/components/base/span/**init**.py:14-39](file://backend/modelscope_studio/components/base/span/__init__.py#L14-L39) +- [backend/modelscope_studio/components/base/markdown/**init**.py:15-46](file://backend/modelscope_studio/components/base/markdown/__init__.py#L15-L46) +- [frontend/base/div/Index.svelte:22-47](file://frontend/base/div/Index.svelte#L22-L47) +- [frontend/base/span/Index.svelte:21-46](file://frontend/base/span/Index.svelte#L21-L46) +- [frontend/base/text/Index.svelte:15-29](file://frontend/base/text/Index.svelte#L15-L29) +- [frontend/base/markdown/Index.svelte:19-44](file://frontend/base/markdown/Index.svelte#L19-L44) +- [frontend/base/div/div.tsx:12-15](file://frontend/base/div/div.tsx#L12-L15) +- [frontend/base/span/span.tsx:12-17](file://frontend/base/span/span.tsx#L12-L17) +- [frontend/base/text/text.tsx:4-8](file://frontend/base/text/text.tsx#L4-L8) +- [frontend/base/markdown/markdown.tsx:8-32](file://frontend/base/markdown/markdown.tsx#L8-L32) + +## Detailed Component Analysis + +### Div Component + +- Design Highlights + - As a block-level container, it prioritizes child node rendering; falls back to the `value` string when no children are present. + - Supports binding of generic interaction events (click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove, scroll). + - Extra props can be passed through; `elem_id`, `elem_classes`, and `elem_style` provide styling and positioning control. +- Data Flow and Processing Logic + - Pre/post-processing leaves strings unchanged; visibility is uniformly controlled by the Svelte layer. +- Usage Recommendations + - Suitable for large-scale layout divisions and complex nesting; avoid using in contexts where inline semantics are required. + - When combined with Grid/Flex layouts, be mindful not to introduce unnecessary hierarchy. + +```mermaid +flowchart TD +Start(["Enter Div Rendering"]) --> CheckChildren["Check if child nodes exist"] +CheckChildren --> HasChildren{"Children present?"} +HasChildren --> |Yes| RenderChildren["Render child nodes"] +HasChildren --> |No| UseValue["Use value as text content"] +RenderChildren --> End(["Done"]) +UseValue --> End +``` + +Diagram Sources + +- [frontend/base/div/div.tsx:12-15](file://frontend/base/div/div.tsx#L12-L15) +- [frontend/base/div/Index.svelte:50-63](file://frontend/base/div/Index.svelte#L50-L63) + +Section Sources + +- [backend/modelscope_studio/components/base/div/**init**.py:10-86](file://backend/modelscope_studio/components/base/div/__init__.py#L10-L86) +- [frontend/base/div/Index.svelte:1-65](file://frontend/base/div/Index.svelte#L1-L65) +- [frontend/base/div/div.tsx:1-18](file://frontend/base/div/div.tsx#L1-L18) + +### Span Component + +- Design Highlights + - Inline container that prioritizes child node rendering; falls back to `value` or an empty span when no children are present. + - Supports the same set of interaction event bindings as Div. +- Usage Recommendations + - Suitable for inline text fragments, labels, and text within buttons. + - Not recommended in contexts that require block-level line breaks. + +```mermaid +flowchart TD +Start(["Enter Span Rendering"]) --> CheckChildren["Check if child nodes exist"] +CheckChildren --> HasChildren{"Children present?"} +HasChildren --> |Yes| RenderChildren["Render child nodes"] +HasChildren --> |No| UseValueOrEmpty["Use value or empty span"] +RenderChildren --> End(["Done"]) +UseValueOrEmpty --> End +``` + +Diagram Sources + +- [frontend/base/span/span.tsx:12-17](file://frontend/base/span/span.tsx#L12-L17) +- [frontend/base/span/Index.svelte:49-63](file://frontend/base/span/Index.svelte#L49-L63) + +Section Sources + +- [backend/modelscope_studio/components/base/span/**init**.py:10-87](file://backend/modelscope_studio/components/base/span/__init__.py#L10-L87) +- [frontend/base/span/Index.svelte:1-64](file://frontend/base/span/Index.svelte#L1-L64) +- [frontend/base/span/span.tsx:1-20](file://frontend/base/span/span.tsx#L1-L20) + +### Text Component + +- Design Highlights + - Minimal wrapper that directly renders a string; no event bindings. + - Suitable for pure text output with low performance overhead. +- Usage Recommendations + - Do not mix with rich text or interactive scenarios; control styling via `elem_classes`/`elem_style` when needed. + +```mermaid +flowchart TD +Start(["Enter Text Rendering"]) --> GetValue["Read value"] +GetValue --> RenderText["Render text node"] +RenderText --> End(["Done"]) +``` + +Diagram Sources + +- [frontend/base/text/text.tsx:4-8](file://frontend/base/text/text.tsx#L4-L8) +- [frontend/base/text/Index.svelte:32-41](file://frontend/base/text/Index.svelte#L32-L41) + +Section Sources + +- [backend/modelscope_studio/components/base/text/**init**.py:8-57](file://backend/modelscope_studio/components/base/text/__init__.py#L8-L57) +- [frontend/base/text/Index.svelte:1-42](file://frontend/base/text/Index.svelte#L1-L42) +- [frontend/base/text/text.tsx:1-11](file://frontend/base/text/text.tsx#L1-L11) + +### Markdown Component + +- Design Highlights + - Supports the `copyButtons` slot to allow custom copy buttons; supports LaTeX math delimiters, HTML sanitization policy, line break and header link options. + - Post-processing cleans input indentation to ensure rendering consistency. + - Theme mode and root path are passed through via props to the underlying Markdown component. +- Data Flow and Processing Logic + - The Svelte layer parses slots and injects `copyButtons` targets into the React layer. + - The React layer hides children, delegating rendering and interaction to the global Markdown component. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte: markdown/Index.svelte" +participant React as "React: markdown.tsx" +participant GlobalMD as "Global Markdown Component" +participant User as "User" +Svelte->>React : Pass through value/styles/class names/theme/root path +React->>React : Resolve copyButtons slot targets +React->>GlobalMD : Render Markdown and inject copyButtons +User->>GlobalMD : Trigger copy/click events +GlobalMD-->>React : Event callback +React-->>Svelte : Update state +Svelte-->>Svelte : Trigger backend event listeners +``` + +Diagram Sources + +- [frontend/base/markdown/Index.svelte:19-44](file://frontend/base/markdown/Index.svelte#L19-L44) +- [frontend/base/markdown/markdown.tsx:8-32](file://frontend/base/markdown/markdown.tsx#L8-L32) +- [backend/modelscope_studio/components/base/markdown/**init**.py:15-46](file://backend/modelscope_studio/components/base/markdown/__init__.py#L15-L46) + +Section Sources + +- [backend/modelscope_studio/components/base/markdown/**init**.py:11-174](file://backend/modelscope_studio/components/base/markdown/__init__.py#L11-L174) +- [frontend/base/markdown/Index.svelte:1-64](file://frontend/base/markdown/Index.svelte#L1-L64) +- [frontend/base/markdown/markdown.tsx:1-35](file://frontend/base/markdown/markdown.tsx#L1-L35) + +## Dependency Analysis + +- Inter-Component Coupling + - All four components are derived from a unified backend base class (layout/data-layout/plain component), sharing a consistent lifecycle and event mechanism. + - The frontend Svelte layer uses the same property passthrough and visibility control patterns, reducing maintenance cost. +- External Dependencies + - The React wrapper layer depends on `sveltify` and slot capabilities provided by `@svelte-preprocess-react`. + - The Markdown component depends on the global Markdown component and ReactSlot for slot rendering. +- Potential Circular Dependencies + - The current structure follows a unidirectional dependency (Backend → Svelte → React); no circular dependency has been observed. + +```mermaid +graph LR +PY_BASE["Backend Base Component Class"] --> PY_DIV["Div"] +PY_BASE --> PY_SPAN["Span"] +PY_BASE --> PY_TEXT["Text"] +PY_DATA_LAYOUT["Data Layout Base Class"] --> PY_MD["Markdown"] +SV_DIV["Svelte: div/Index.svelte"] --> RX_DIV["React: div.tsx"] +SV_SPAN["Svelte: span/Index.svelte"] --> RX_SPAN["React: span.tsx"] +SV_TEXT["Svelte: text/Index.svelte"] --> RX_TEXT["React: text.tsx"] +SV_MD["Svelte: markdown/Index.svelte"] --> RX_MD["React: markdown.tsx"] +RX_MD --> GLOBAL_MD["Global Markdown Component"] +``` + +Diagram Sources + +- [backend/modelscope_studio/components/base/div/**init**.py](file://backend/modelscope_studio/components/base/div/__init__.py#L7) +- [backend/modelscope_studio/components/base/span/**init**.py](file://backend/modelscope_studio/components/base/span/__init__.py#L7) +- [backend/modelscope_studio/components/base/text/**init**.py](file://backend/modelscope_studio/components/base/text/__init__.py#L5) +- [backend/modelscope_studio/components/base/markdown/**init**.py](file://backend/modelscope_studio/components/base/markdown/__init__.py#L8) +- [frontend/base/markdown/markdown.tsx:4-5](file://frontend/base/markdown/markdown.tsx#L4-L5) + +Section Sources + +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [frontend/base/package.json:1-6](file://frontend/base/package.json#L1-L6) + +## Performance Considerations + +- Rendering Path + - Text outputs plain text directly with the lowest overhead; Div/Span traverse the React subtree when children are present — pay attention to subtree size. + - Markdown reuses global rendering capability by hiding children, reducing repeated parsing. +- Event Bindings + - All layout components support multiple mouse/scroll event bindings; enable only as needed to avoid unnecessary callback overhead. +- Styles and Class Names + - Control styling via `elem_classes`/`elem_style`; prefer atomic class names to minimize style recalculation. +- Theme and Resources + - Markdown theme mode and root path are passed through to ensure static asset paths are correct, avoiding redundant requests. + +[This section contains general performance recommendations; no specific file references required] + +## Troubleshooting Guide + +- Text Not Displayed + - Check whether `value` is empty or contains only whitespace; the Text component falls back to an empty span when `value` is missing. + - For Div/Span, verify whether child nodes have been passed in, causing `value` to be ignored. +- Events Not Firing + - Confirm that event listeners are registered on the backend; check that `visible` is `true` — events will not fire when the component is invisible. +- Markdown Copy Button Not Working + - Confirm that the `copyButtons` slot is correctly mounted; the React layer determines whether to replace the default button based on the slot target. +- Styles Not Applied + - Check the composition order and precedence of `elem_id`/`elem_classes`/`elem_style`; use more specific CSS selectors if necessary. +- Theme Mismatch + - Confirm that `themeMode` and `rootUrl` are correctly passed through to the Markdown component. + +Section Sources + +- [backend/modelscope_studio/components/base/text/**init**.py:45-50](file://backend/modelscope_studio/components/base/text/__init__.py#L45-L50) +- [backend/modelscope_studio/components/base/div/**init**.py:14-39](file://backend/modelscope_studio/components/base/div/__init__.py#L14-L39) +- [backend/modelscope_studio/components/base/span/**init**.py:14-39](file://backend/modelscope_studio/components/base/span/__init__.py#L14-L39) +- [backend/modelscope_studio/components/base/markdown/**init**.py:49-52](file://backend/modelscope_studio/components/base/markdown/__init__.py#L49-L52) +- [frontend/base/markdown/markdown.tsx:14-31](file://frontend/base/markdown/markdown.tsx#L14-L31) + +## Conclusion + +Div, Span, Text, and Markdown form the foundational capabilities for layout and content rendering in ModelScope Studio. Under the design of unified backend abstraction, consistent frontend wrapping, and precise React rendering, they achieve both ease of use and extensibility alongside solid performance. Choosing the appropriate component type, enabling events and slots only as needed, and following style and theme conventions are key to building high-quality interfaces. + +[This section contains summary content; no specific file references required] + +## Appendix + +### Component Properties and Behavior Quick Reference + +- Div + - Events: click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove, scroll + - Properties: value, additional_props, elem_id, elem_classes, elem_style, visible, render +- Span + - Events: click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove, scroll + - Properties: value, additional_props, elem_id, elem_classes, elem_style, visible, render +- Text + - Events: None + - Properties: value, elem_id, elem_classes, elem_style, visible, render +- Markdown + - Events: change, copy, click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove, scroll + - Slots: copyButtons + - Properties: value, rtl, latex_delimiters, sanitize_html, line_breaks, header_links, allow_tags, show_copy_button, copy_buttons, elem_id, elem_classes, elem_style, visible, render + +Section Sources + +- [backend/modelscope_studio/components/base/div/**init**.py:14-68](file://backend/modelscope_studio/components/base/div/__init__.py#L14-L68) +- [backend/modelscope_studio/components/base/span/**init**.py:14-69](file://backend/modelscope_studio/components/base/span/__init__.py#L14-L69) +- [backend/modelscope_studio/components/base/text/**init**.py:12-39](file://backend/modelscope_studio/components/base/text/__init__.py#L12-L39) +- [backend/modelscope_studio/components/base/markdown/**init**.py:15-143](file://backend/modelscope_studio/components/base/markdown/__init__.py#L15-L143) diff --git a/.wiki/en/Base Components/Rendering Components.md b/.wiki/en/Base Components/Rendering Components.md new file mode 100644 index 00000000..7e1893fd --- /dev/null +++ b/.wiki/en/Base Components/Rendering Components.md @@ -0,0 +1,371 @@ +# Rendering Components + + +**Files Referenced in This Document** +- [each.tsx](file://frontend/base/each/each.tsx) +- [Index.svelte (Each)](file://frontend/base/each/Index.svelte) +- [EachItem.svelte](file://frontend/base/each/EachItem.svelte) +- [each.placeholder.tsx](file://frontend/base/each/each.placeholder.tsx) +- [useTargets.ts](file://frontend/utils/hooks/useTargets.ts) +- [useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [filter.tsx](file://frontend/base/filter/filter.tsx) +- [Index.svelte (Filter)](file://frontend/base/filter/Index.svelte) +- [each/__init__.py](file://backend/modelscope_studio/components/base/each/__init__.py) +- [filter/__init__.py](file://backend/modelscope_studio/components/base/filter/__init__.py) +- [base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [filter/README-zh_CN.md](file://docs/components/base/filter/README-zh_CN.md) +- [filter/demos/basic.py](file://docs/components/base/filter/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Component Details](#component-details) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document focuses on the Each and Filter components in the rendering component series, systematically explaining their key roles in data rendering and conditional display. Each is responsible for rendering list data item by item and injecting context into each item; Filter is responsible for filtering or extracting context, supporting both key-based sub-object extraction and custom filtering via function strings. The documentation provides comprehensive coverage of architecture, data flow, processing logic, integration and state management, performance optimization, and debugging techniques, along with multi-scenario usage examples and best practices. + +## Project Structure + +The rendering components reside in the frontend `base` package, each composed of a Svelte entry component and a React implementation, with corresponding Python component classes in the backend to interface with the Gradio data flow. The core files are organized as follows: + +- Frontend Each: The Svelte entry component handles property processing and placeholder coordination; the React implementation handles loop rendering and context injection. +- Frontend Filter: The Svelte entry component handles property processing; the React implementation handles context filtering and passthrough. +- Backend Each/Filter: Python component classes that define properties, visibility, pre/post-processing, and frontend directory mappings. + +```mermaid +graph TB +subgraph "Frontend base" +EIdx["Each Entry Index.svelte"] +EImpl["Each Implementation each.tsx"] +EItem["Each Item EachItem.svelte"] +EPh["Each Placeholder each.placeholder.tsx"] +FIdx["Filter Entry Index.svelte"] +FImpl["Filter Implementation filter.tsx"] +UT["Utility: useTargets.ts"] +UF["Utility: useFunction.ts"] +end +subgraph "Backend Python" +PYE["ModelScopeEach each/__init__.py"] +PYF["ModelScopeFilter filter/__init__.py"] +PYPkg["base/__init__.py Exports"] +end +EIdx --> EImpl +EIdx --> EPh +EIdx --> EItem +EImpl --> UT +FIdx --> FImpl +FImpl --> UF +PYE --> EIdx +PYF --> FIdx +PYPkg --> PYE +PYPkg --> PYF +``` + +Diagram Sources + +- [Index.svelte (Each):1-111](file://frontend/base/each/Index.svelte#L1-L111) +- [each.tsx:1-61](file://frontend/base/each/each.tsx#L1-L61) +- [EachItem.svelte:1-37](file://frontend/base/each/EachItem.svelte#L1-L37) +- [each.placeholder.tsx:1-31](file://frontend/base/each/each.placeholder.tsx#L1-L31) +- [Index.svelte (Filter):1-52](file://frontend/base/filter/Index.svelte#L1-L52) +- [filter.tsx:1-41](file://frontend/base/filter/filter.tsx#L1-L41) +- [useTargets.ts:1-52](file://frontend/utils/hooks/useTargets.ts#L1-L52) +- [useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [each/**init**.py:1-73](file://backend/modelscope_studio/components/base/each/__init__.py#L1-L73) +- [filter/**init**.py:1-45](file://backend/modelscope_studio/components/base/filter/__init__.py#L1-L45) +- [base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +Section Sources + +- [Index.svelte (Each):1-111](file://frontend/base/each/Index.svelte#L1-L111) +- [filter.tsx:1-41](file://frontend/base/filter/filter.tsx#L1-L41) +- [each.tsx:1-61](file://frontend/base/each/each.tsx#L1-L61) +- [each/**init**.py:1-73](file://backend/modelscope_studio/components/base/each/__init__.py#L1-L73) +- [filter/**init**.py:1-45](file://backend/modelscope_studio/components/base/filter/__init__.py#L1-L45) +- [base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +## Core Components + +- Each: Receives list data and context, renders child nodes item by item, and merges each item's value into the context for downstream component consumption. +- Filter: Filters or extracts the current context, supporting two modes: + - as_item: Extracts a sub-object from the context by key name to serve as the new context passed downstream. + - params_mapping: Accepts a JS function string to perform custom filtering on the context and returns a new context. + - When neither is provided, context propagation is blocked and subsequent property overrides become ineffective. + +Section Sources + +- [each.tsx:8-13](file://frontend/base/each/each.tsx#L8-L13) +- [filter.tsx:9-13](file://frontend/base/filter/filter.tsx#L9-L13) +- [filter/README-zh_CN.md:1-22](file://docs/components/base/filter/README-zh_CN.md#L1-L22) + +## Architecture Overview + +The execution flow of Each and Filter can be summarized as: the frontend entry component parses properties and prepares the React implementation; the React implementation generates the child tree based on data and context; Filter filters the context before rendering to ensure downstream components receive only the required data. + +```mermaid +sequenceDiagram +participant Py as "Backend Component Each/Filter" +participant S as "Entry Component Each/Filter" +participant R as "React Implementation Each/Filter" +participant U as "Utility Hooks useTargets/useFunction" +Py->>S : Initialize and set properties +S->>R : Pass processed properties and slots +R->>U : Resolve slot targets (Each) / Resolve function (Filter) +U-->>R : Return targets/function +R->>R : Each iterates over value and injects context +R->>R : Filter filters context based on as_item or params_mapping +R-->>S : Render result +S-->>Py : Visibility and render control +``` + +Diagram Sources + +- [Index.svelte (Each):1-111](file://frontend/base/each/Index.svelte#L1-L111) +- [each.tsx:35-58](file://frontend/base/each/each.tsx#L35-L58) +- [Index.svelte (Filter):1-52](file://frontend/base/filter/Index.svelte#L1-L52) +- [filter.tsx:15-38](file://frontend/base/filter/filter.tsx#L15-L38) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) + +## Component Details + +### Each Component + +Each's responsibility is to render list data item by item and inject context into each child item. Key points include: + +- Input Properties: `value` (array), `contextValue` (initial context), `children` (subtree), internal slot keys. +- Rendering Strategy: First renders an "isolated" hidden container to prevent external context from polluting internal slots; then maps over `value` to create an Item for each entry. +- Context Injection: Item merges the incoming `value` into `contextValue` to form the final context, then injects it into the child tree via `ContextPropsProvider`. +- Slot Resolution: Uses `useTargets` to extract nodes in `children` that match the `slotKey`, ensuring correct rendering order and target mounting. + +```mermaid +flowchart TD +Start(["Enter Each Rendering"]) --> Parse["Parse children slots
Extract targets via useTargets"] +Parse --> Isolate["Render isolated container (hidden)"] +Isolate --> Loop{"Iterate over value"} +Loop --> |Yes| Item["Create Item for each entry
Merge context"] +Item --> Render["Clone and render target slots"] +Render --> Next["Next element"] +Next --> Loop +Loop --> |No| End(["Rendering complete"]) +``` + +Diagram Sources + +- [each.tsx:35-58](file://frontend/base/each/each.tsx#L35-L58) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) + +Section Sources + +- [each.tsx:8-13](file://frontend/base/each/each.tsx#L8-L13) +- [each.tsx:35-58](file://frontend/base/each/each.tsx#L35-L58) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [Index.svelte (Each):66-104](file://frontend/base/each/Index.svelte#L66-L104) +- [each.placeholder.tsx:15-28](file://frontend/base/each/each.placeholder.tsx#L15-L28) +- [EachItem.svelte:23-27](file://frontend/base/each/EachItem.svelte#L23-L27) + +### Filter Component + +Filter's responsibility is to filter or extract the current context, supporting two modes: + +- as_item: Extracts a sub-object from the context by key name to serve as the new context passed downstream. +- params_mapping: Accepts a JS function string, resolved via `useFunction`, to perform custom filtering on the context. +- When no parameters are provided: context propagation is blocked, making subsequent property overrides ineffective. + +```mermaid +flowchart TD +Enter(["Enter Filter"]) --> ReadCtx["Read current context"] +ReadCtx --> CheckAs{"Is as_item provided?"} +CheckAs --> |Yes| Extract["Extract ctx[as_item] as new context"] +CheckAs --> |No| CheckMap{"Is params_mapping provided?"} +CheckMap --> |Yes| Exec["Execute params_mapping(ctx) as new context"] +CheckMap --> |No| Block["Do not update context (block propagation)"] +Extract --> Provide["Pass through via ContextPropsProvider"] +Exec --> Provide +Block --> Provide +Provide --> Exit(["Done"]) +``` + +Diagram Sources + +- [filter.tsx:15-38](file://frontend/base/filter/filter.tsx#L15-L38) +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) + +Section Sources + +- [filter.tsx:9-13](file://frontend/base/filter/filter.tsx#L9-L13) +- [filter.tsx:15-38](file://frontend/base/filter/filter.tsx#L15-L38) +- [Index.svelte (Filter):33-45](file://frontend/base/filter/Index.svelte#L33-L45) +- [filter/README-zh_CN.md:1-22](file://docs/components/base/filter/README-zh_CN.md#L1-L22) + +### Properties and Events + +- Each (Frontend Entry Index.svelte) + - Key Properties: `value`, `context_value`, `visible`, `elem_id`, `elem_classes`, `elem_style`, `_internal.index`, etc. + - Internal Behavior: The placeholder component collects changes (e.g., `forceClone`, merged `value`/`context_value`) and decides whether to use the React implementation or render directly with EachItem. +- Each (React Implementation each.tsx) + - Key Properties: `value`, `contextValue`, `children`, `__internal_slot_key`. + - Internal Behavior: Isolates external context, resolves slot targets, renders each item, and injects context. +- Filter (Frontend Entry Index.svelte) + - Key Properties: `params_mapping`, `as_item`, `visible`. + - Internal Behavior: Passes `params_mapping` and `as_item` to the React implementation. +- Filter (React Implementation filter.tsx) + - Key Properties: `paramsMapping`, `asItem`. + - Internal Behavior: Selects key extraction or function filtering based on the parameters, updates context, and passes it through. + +Section Sources + +- [Index.svelte (Each):17-57](file://frontend/base/each/Index.svelte#L17-L57) +- [Index.svelte (Each):66-104](file://frontend/base/each/Index.svelte#L66-L104) +- [each.tsx:8-13](file://frontend/base/each/each.tsx#L8-L13) +- [Index.svelte (Filter):16-31](file://frontend/base/filter/Index.svelte#L16-L31) +- [filter.tsx:9-13](file://frontend/base/filter/filter.tsx#L9-L13) + +### Integration with State Management + +- Each merges `contextValue` with each item's `value` to form a per-item context consumable by downstream components. +- Filter uses `useContextPropsContext` to retrieve the current context, then generates a new context via `as_item` or `params_mapping`, enabling "conditional display / data filtering". +- The backend component's `visible` flag can be used to control render visibility; the frontend entry component will not load the React implementation when invisible, reducing overhead. + +Section Sources + +- [each.tsx:15-33](file://frontend/base/each/each.tsx#L15-L33) +- [filter.tsx:19-27](file://frontend/base/filter/filter.tsx#L19-L27) +- [Index.svelte (Each):66-104](file://frontend/base/each/Index.svelte#L66-L104) +- [Index.svelte (Filter):33-45](file://frontend/base/filter/Index.svelte#L33-L45) + +### Usage Examples and Scenarios + +- Basic Usage (Without Filter) + - Scenario: Loop-render list data; child components such as buttons directly consume the context injected by Each. + - Reference Example: [filter/demos/basic.py:1-20](file://docs/components/base/filter/demos/basic.py#L1-L20) +- Using as_item + - Scenario: The context output by Each contains multiple fields, and only one field needs to be passed as the new context to child components. + - Reference: [filter/README-zh_CN.md:1-22](file://docs/components/base/filter/README-zh_CN.md#L1-L22) +- Using params_mapping + - Scenario: Perform complex filtering or transformation on the context via a JS function, such as filtering, composing derived fields, etc. + - Reference: [filter/README-zh_CN.md:1-22](file://docs/components/base/filter/README-zh_CN.md#L1-L22) + +Section Sources + +- [filter/demos/basic.py:1-20](file://docs/components/base/filter/demos/basic.py#L1-L20) +- [filter/README-zh_CN.md:1-22](file://docs/components/base/filter/README-zh_CN.md#L1-L22) + +## Dependency Analysis + +- Each Dependencies + - Utility Hook: `useTargets` resolves slot targets to ensure correct rendering order and mounting. + - Context: `ContextPropsProvider` is used for context isolation and merging. +- Filter Dependencies + - Utility Hook: `useFunction` parses a string function into an executable function. + - Context: `ContextPropsProvider` is used to pass through the filtered context. +- Backend Components + - Each/Filter both inherit from the layout component base class, defining properties, visibility, pre/post-processing, and frontend directory mappings. + +```mermaid +graph LR +UT["useTargets.ts"] --> EImpl["each.tsx"] +UF["useFunction.ts"] --> FImpl["filter.tsx"] +EIdx["Each Index.svelte"] --> EImpl +FIdx["Filter Index.svelte"] --> FImpl +PYE["ModelScopeEach Python"] --> EIdx +PYF["ModelScopeFilter Python"] --> FIdx +``` + +Diagram Sources + +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [each.tsx:1-7](file://frontend/base/each/each.tsx#L1-L7) +- [filter.tsx:1-7](file://frontend/base/filter/filter.tsx#L1-L7) +- [Index.svelte (Each):1-16](file://frontend/base/each/Index.svelte#L1-L16) +- [Index.svelte (Filter):1-8](file://frontend/base/filter/Index.svelte#L1-L8) +- [each/**init**.py:1-73](file://backend/modelscope_studio/components/base/each/__init__.py#L1-L73) +- [filter/**init**.py:1-45](file://backend/modelscope_studio/components/base/filter/__init__.py#L1-L45) + +Section Sources + +- [each.tsx:1-7](file://frontend/base/each/each.tsx#L1-L7) +- [filter.tsx:1-7](file://frontend/base/filter/filter.tsx#L1-L7) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [each/**init**.py:1-73](file://backend/modelscope_studio/components/base/each/__init__.py#L1-L73) +- [filter/**init**.py:1-45](file://backend/modelscope_studio/components/base/filter/__init__.py#L1-L45) + +## Performance Considerations + +- List Rendering + - Each maps over `value` for rendering; avoid heavy computations inside `children` — move calculations upstream or cache them. + - Using stable keys (indices) helps React/Svelte diff optimization, but when the list has insertions/deletions, unique IDs are recommended as keys. +- Context Merging + - When Each/EachItem merge contexts, keep the `value` structure simple to avoid repeated rendering caused by deep nesting. +- Conditional Filtering + - `params_mapping` in Filter should avoid creating new functions on every render; define the function string at a higher level and pass it in. +- Visibility Control + - Use `visible` to control component rendering; the React implementation is not loaded when invisible, reducing unnecessary initialization and rendering. +- Large Data Sets + - Prefer pagination, virtual scrolling, or lazy loading strategies; avoid rendering oversized lists all at once. + - Reasonably flatten nested Each levels to reduce context depth and render tree complexity. + +## Troubleshooting Guide + +- Child Component Cannot Read Context + - Check whether Each has correctly passed in `contextValue` and `value`; confirm that the EachItem merge logic is effective. + - If using Filter, confirm that the `as_item` key name is correct or that `params_mapping` returns the expected object. +- Slot Rendering Order Abnormal + - Confirm that the slot key (`slotKey`) is consistent and that `useTargets` can correctly identify the target nodes. +- Filter Not Taking Effect + - Confirm that the `params_mapping` string can be parsed as a function, or that the `as_item` key exists in the current context. + - If no parameters are provided, Filter will block context propagation — this is expected behavior. +- Rendering Lag + - Check whether the `value` of Each is too large; paginate or virtualize as necessary. + - Avoid expensive operations inside `children`; move computations upstream or use memoization. + +Section Sources + +- [each.tsx:15-33](file://frontend/base/each/each.tsx#L15-L33) +- [filter.tsx:15-38](file://frontend/base/filter/filter.tsx#L15-L38) +- [useTargets.ts:5-51](file://frontend/utils/hooks/useTargets.ts#L5-L51) +- [Index.svelte (Each):66-104](file://frontend/base/each/Index.svelte#L66-L104) +- [Index.svelte (Filter):33-45](file://frontend/base/filter/Index.svelte#L33-L45) + +## Conclusion + +Each and Filter form the core capabilities of "loop rendering" and "conditional filtering" in the rendering component series. Each provides a consistent data environment for every item in a list through context merging and slot resolution; Filter extracts or custom-filters the context before rendering to satisfy diverse conditional display and data filtering requirements. Combined with the backend component's visibility control and frontend utility hooks, flexible rendering strategies can be achieved while maintaining performance. + +## Appendix + +- API Overview (Summary) + - Each (Frontend Entry) + - Properties: `value`, `context_value`, `visible`, `elem_id`, `elem_classes`, `elem_style`, `_internal.index`, etc. + - Behavior: Placeholder component collects changes and decides whether to use the React implementation or EachItem rendering. + - Each (React Implementation) + - Properties: `value`, `contextValue`, `children`, `__internal_slot_key`. + - Behavior: Isolates external context, resolves slot targets, renders each item, and injects context. + - Filter (Frontend Entry) + - Properties: `params_mapping`, `as_item`, `visible`. + - Behavior: Passes parameters to the React implementation. + - Filter (React Implementation) + - Properties: `paramsMapping`, `asItem`. + - Behavior: Updates context based on `as_item` or `params_mapping` and passes it through. +- Backend Components + - Both Each and Filter inherit from the layout component base class, defining properties, visibility, pre/post-processing, and frontend directory mappings. + +Section Sources + +- [Index.svelte (Each):17-57](file://frontend/base/each/Index.svelte#L17-L57) +- [each.tsx:8-13](file://frontend/base/each/each.tsx#L8-L13) +- [Index.svelte (Filter):16-31](file://frontend/base/filter/Index.svelte#L16-L31) +- [filter.tsx:9-13](file://frontend/base/filter/filter.tsx#L9-L13) +- [each/**init**.py:23-51](file://backend/modelscope_studio/components/base/each/__init__.py#L23-L51) +- [filter/**init**.py:13-25](file://backend/modelscope_studio/components/base/filter/__init__.py#L13-L25) diff --git a/.wiki/en/Base Components/Slot Component.md b/.wiki/en/Base Components/Slot Component.md new file mode 100644 index 00000000..b16ccb4e --- /dev/null +++ b/.wiki/en/Base Components/Slot Component.md @@ -0,0 +1,333 @@ +# Slot Component + + +**Files Referenced in This Document** +- [frontend/base/slot/Index.svelte](file://frontend/base/slot/Index.svelte) +- [frontend/svelte-preprocess-react/react-slot.tsx](file://frontend/svelte-preprocess-react/react-slot.tsx) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [frontend/utils/patchSlots.ts](file://frontend/utils/patchSlots.ts) +- [docs/components/base/slot/README.md](file://docs/components/base/slot/README.md) +- [docs/components/base/slot/README-zh_CN.md](file://docs/components/base/slot/README-zh_CN.md) +- [docs/components/base/slot/demos/basic.py](file://docs/components/base/slot/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document systematically explains the Slot component, covering design philosophy, content distribution mechanism, dynamic insertion and custom rendering, slot types and scopes, parameter passing and data binding, communication with parent components, usage examples, best practices, performance optimization suggestions, differences and advantages over template systems, and debugging tips and solutions to common issues. Based on the Slot component implementation and documentation in the repository, combined with the frontend rendering pipeline and context mechanism, this document helps readers fully master the slot system from principles to practice. + +## Project Structure + +The Slot component is implemented in Svelte on the frontend, responsible for collecting the child tree and registering it into the parent component's slot context; during the rendering phase, ReactSlot clones and mounts the DOM structure rendered by Svelte into the React environment, implementing cross-framework content distribution and dynamic updates. + +```mermaid +graph TB +subgraph "Frontend (Svelte)" +A["Index.svelte
Slot Component"] +B["svelte context
slot.svelte"] +end +subgraph "Utility Layer" +C["patchSlots.ts
Parameter Patching"] +D["renderSlot.tsx
Render Entry"] +end +subgraph "React Side" +E["react-slot.tsx
ReactSlot Component"] +end +A --> B +A --> C +D --> E +C --> D +B --> D +D --> E +``` + +Diagram Sources + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/utils/patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) + +Section Sources + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) + +## Core Components + +- Slot (Svelte): Receives the slot name and optional parameter mapping function from the parent component, registers itself as a "slot container" into the context, and renders child nodes when visibility allows. +- ReactSlot (React): In the React environment, receives the DOM fragment generated by Svelte, supports cloning, event copying, style and class name injection, and uses MutationObserver to observe changes and dynamically re-render. +- renderSlot: Provides a unified rendering entry, supporting force cloning, parameter passing, and context wrapping. +- patchSlots: Wraps slot rendering functions, prepending or appending additional parameters to slot callbacks in order, enabling parent components to pass context parameters to child slots. + +Section Sources + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) + +## Architecture Overview + +Slot's workflow is divided into a "registration phase" and a "rendering phase". Parent components register slot keys and parameter mappings via the context API; the Slot component collects the child tree in Svelte and binds it to the DOM; finally, ReactSlot clones and mounts in the React environment while maintaining event and style consistency. + +```mermaid +sequenceDiagram +participant Parent as "Parent Component" +participant SlotComp as "Slot (Index.svelte)" +participant Ctx as "Svelte Context (slot.svelte)" +participant Utils as "patchSlots/renderSlot" +participant RSlot as "ReactSlot (react-slot.tsx)" +Parent->>SlotComp : Pass value/params_mapping +SlotComp->>Ctx : setSlotKey/setSlotParamsMapping +SlotComp->>Ctx : setSlot(prevKey, currentKey, slotDom) +SlotComp-->>Parent : Render child nodes (hidden svelte-slot) +Utils->>RSlot : renderSlot(el, options) +RSlot->>RSlot : Clone element/copy events/inject styles/class names +RSlot-->>Parent : Mount to React environment +``` + +Diagram Sources + +- [frontend/base/slot/Index.svelte:32-54](file://frontend/base/slot/Index.svelte#L32-L54) +- [frontend/utils/patchSlots.ts:15-31](file://frontend/utils/patchSlots.ts#L15-L31) +- [frontend/utils/renderSlot.tsx:13-28](file://frontend/utils/renderSlot.tsx#L13-L28) +- [frontend/svelte-preprocess-react/react-slot.tsx:109-223](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L223) + +## Detailed Component Analysis + +### Slot Component (Svelte) + +- Responsibilities + - Receives slot name and parameter mapping function string. + - Writes the current slot key and parameter mapping to the context for parent component consumption. + - Renders child nodes when visible, but hides the actual `svelte-slot` container to avoid affecting layout. +- Key points + - Uses context API to set slot key and parameter mapping. + - Monitors slot name changes via `effect`, triggering `setSlot` registration. + - Child nodes are bound to DOM via `svelte-slot bind:this`, enabling ReactSlot to clone and mount later. + +```mermaid +flowchart TD +Start(["Enter Component"]) --> ReadProps["Read value/params_mapping"] +ReadProps --> SetCtx["setSlotKey / setSlotParamsMapping"] +SetCtx --> Effect["$effect monitors value changes"] +Effect --> HasSlot{"slot exists and value is valid?"} +HasSlot --> |Yes| Register["setSlot(prevKey, currentKey, slotDom)"] +HasSlot --> |No| Wait["Wait / stay unchanged"] +Register --> Render["Render child nodes (hidden svelte-slot)"] +Wait --> Render +Render --> End(["Complete"]) +``` + +Diagram Sources + +- [frontend/base/slot/Index.svelte:31-61](file://frontend/base/slot/Index.svelte#L31-L61) + +Section Sources + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) + +### ReactSlot (React) + +- Responsibilities + - Receives the slot DOM generated by Svelte, supports cloning and event copying. + - Injects styles and class names, handles React Portal for correct subtree mounting. + - Uses MutationObserver to monitor slot changes and automatically re-clones and renders. +- Key points + - `cloneElementWithEvents`: Recursively clones nodes, copies event listeners, handles nested `svelte-slot`. + - `mountElementProps`: Mounts class names and inline styles after cloning. + - `observeAttributes`: Optionally observes attribute changes, combined with debounce for improved stability. + +```mermaid +flowchart TD +Enter(["ReactSlot Mount"]) --> CheckClone{"Clone?"} +CheckClone --> |Yes| Observe["MutationObserver watches slot changes"] +Observe --> Render["cloneElementWithEvents clones and generates portals"] +Render --> Inject["Inject class names/styles/mount props"] +Inject --> Append["Append to ref.current"] +CheckClone --> |No| DirectMount["Mount slot directly"] +DirectMount --> Append +Append --> Cleanup["On unmount: clean styles/remove nodes/disconnect observer"] +``` + +Diagram Sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:109-223](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L223) + +Section Sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) + +### Parameter Patching and Render Entry + +- patchSlots + - Wraps slot rendering functions, supporting prepending/appending external parameters to slot callbacks. + - Used for parent components to pass context parameters to child slots, enhancing slot configurability. +- renderSlot + - Provides a unified entry, supporting force cloning, parameter passing, and context wrapping. + - When `params` or `forceClone` is passed, wraps ReactSlot with `ContextPropsProvider` to ensure rendering consistency. + +```mermaid +sequenceDiagram +participant Caller as "Caller" +participant Patch as "patchSlots" +participant Render as "renderSlot" +participant RSlot as "ReactSlot" +Caller->>Patch : Pass params and transform +Patch-->>Caller : Return wrapped rendering function +Caller->>Render : Pass el and options (params/forceClone/clone) +Render->>Render : Determine if ContextPropsProvider wrapping is needed +Render-->>Caller : Return ReactSlot component +Caller->>RSlot : Render ReactSlot +RSlot-->>Caller : Clone and mount slot +``` + +Diagram Sources + +- [frontend/utils/patchSlots.ts:15-31](file://frontend/utils/patchSlots.ts#L15-L31) +- [frontend/utils/renderSlot.tsx:13-28](file://frontend/utils/renderSlot.tsx#L13-L28) +- [frontend/svelte-preprocess-react/react-slot.tsx:109-223](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L223) + +Section Sources + +- [frontend/utils/patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) + +## Dependency Analysis + +- Component coupling + - Slot depends on the Svelte context API for slot registration and parameter mapping setting. + - ReactSlot depends on the structural characteristics of the slot DOM (such as internal portals and `svelte-slot` tags) for correct parsing and cloning. + - `renderSlot` and `patchSlots` provide general capabilities for the rendering pipeline, decoupled from specific components. +- External dependencies + - React, ReactDOM (Portal), MutationObserver, lodash-es (debounce and object judgment). +- Potential circular dependencies + - Avoided through utility layer and context layer separation, preventing direct circular references between components. + +```mermaid +graph LR +Slot["Slot (Index.svelte)"] --> Ctx["Svelte Context (slot.svelte)"] +Slot --> Patch["patchSlots.ts"] +Render["renderSlot.tsx"] --> RSlot["ReactSlot (react-slot.tsx)"] +Patch --> Render +Ctx --> Render +``` + +Diagram Sources + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/utils/patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) + +Section Sources + +- [frontend/base/slot/Index.svelte:1-68](file://frontend/base/slot/Index.svelte#L1-L68) +- [frontend/utils/patchSlots.ts:1-32](file://frontend/utils/patchSlots.ts#L1-L32) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) + +## Performance Considerations + +- Clone strategy + - Cloning brings extra DOM operations and event copying costs. Only enable `clone` when necessary to avoid unnecessary re-renders. +- Observer and debounce + - MutationObserver combined with debounce can reduce repeated cloning caused by frequent changes; it is recommended to enable `observeAttributes` and set a reasonable debounce interval in complex tables or high-frequency update scenarios. +- Style and class name injection + - Batch injecting styles and class names is better than individual operations, avoiding multiple reflows. +- Parameter passing + - Using `patchSlots` to prepend/append parameters reduces extra wrapping in intermediate layers, lowering the function call stack depth. + +## Troubleshooting Guide + +- Slot not working + - Check if the parent component has correctly registered the slot key and parameter mapping. + - Confirm if the Slot component's `value` is empty or unchanged (the `effect` only registers on change). +- Styles missing or class names not taking effect + - Confirm if ReactSlot correctly injected `className` and inline styles. + - Check for style isolation or overriding. +- Events not responding + - Confirm if `clone` is enabled; event copying logic depends on the cloning path. + - Check if event listeners have been overridden or removed. +- Updates not taking effect + - Confirm if `observeAttributes` is enabled, and if MutationObserver has been disconnected. + - Check if external code directly modified slot content without triggering observation. + +Section Sources + +- [frontend/svelte-preprocess-react/react-slot.tsx:156-212](file://frontend/svelte-preprocess-react/react-slot.tsx#L156-L212) +- [frontend/base/slot/Index.svelte:31-61](file://frontend/base/slot/Index.svelte#L31-L61) + +## Conclusion + +The Slot component implements cross-framework content distribution and dynamic rendering through Svelte and React bridging. Its design emphasizes: + +- Clear slot registration and parameter mapping mechanism; +- Stable rendering based on cloning and event copying; +- Optional observer and debounce strategies, balancing flexibility and performance; +- Utility layer abstraction (patchSlots, renderSlot) improving reusability and maintainability. + +## Appendix + +### Slot Types and Scopes + +- Slot types + - Named slots: Specify slot name via `value`; parent component receives by name. + - Nested slots: Child slots can contain slots again, forming multi-level content distribution. +- Scopes + - `params_mapping` supports mapping parent component context parameters to slot scope, enabling parameter-driven rendering. + +Section Sources + +- [docs/components/base/slot/README.md:13-16](file://docs/components/base/slot/README.md#L13-L16) +- [docs/components/base/slot/README-zh_CN.md:13-16](file://docs/components/base/slot/README-zh_CN.md#L13-L16) + +### Data Binding and Parent Component Communication + +- Parent components register slot keys and parameter mappings via the context API. +- The Slot component collects the child tree in Svelte and completes registration through `setSlot`. +- ReactSlot clones and mounts during the rendering phase, maintaining event and style consistency. + +Section Sources + +- [frontend/base/slot/Index.svelte:32-54](file://frontend/base/slot/Index.svelte#L32-L54) +- [frontend/svelte-preprocess-react/react-slot.tsx:109-223](file://frontend/svelte-preprocess-react/react-slot.tsx#L109-L223) + +### Usage Examples + +- Basic example: Insert title and extra button and icon slots into a Card component. +- Example path: [docs/components/base/slot/demos/basic.py:1-23](file://docs/components/base/slot/demos/basic.py#L1-L23) + +Section Sources + +- [docs/components/base/slot/demos/basic.py:1-23](file://docs/components/base/slot/demos/basic.py#L1-L23) + +### Best Practices + +- Only enable `clone` and `observeAttributes` when necessary, avoiding excessive rendering. +- Use `patchSlots` to prepend/append parameters, reducing intermediate wrapping. +- For complex tables and other high-frequency update scenarios, enable `observeAttributes` with debounce. +- Maintain the uniqueness and stability of slot keys, avoiding conflicts caused by duplicate registration. + +### Differences and Advantages Over Template Systems + +- Differences + - Template systems usually determine structure at compile time; the slot system dynamically distributes content at runtime. +- Advantages + - Stronger composability and extensibility, suitable for cross-framework and multi-component collaboration. + - Parameter mapping and context injection give slots stronger expressiveness and control. diff --git a/.wiki/en/Deployment Guide/Build Process.md b/.wiki/en/Deployment Guide/Build Process.md new file mode 100644 index 00000000..7de18962 --- /dev/null +++ b/.wiki/en/Deployment Guide/Build Process.md @@ -0,0 +1,405 @@ +# Build Process + + +**Files referenced in this document** +- [package.json](file://package.json) +- [pyproject.toml](file://pyproject.toml) +- [frontend/package.json](file://frontend/package.json) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [frontend/plugin.js](file://frontend/plugin.js) +- [frontend/tsconfig.json](file://frontend/tsconfig.json) +- [svelte-tsconfig.json](file://svelte-tsconfig.json) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) +- [frontend/antd/button/package.json](file://frontend/antd/button/package.json) +- [frontend/antd/button/gradio.config.js](file://frontend/antd/button/gradio.config.js) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) +- [frontend/svelte-preprocess-react/index.ts](file://frontend/svelte-preprocess-react/index.ts) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is intended for developers and operators who need to understand and maintain the build mechanism of ModelScope Studio. It systematically covers the following topics: + +- Frontend component build process: Vite configuration, Svelte component compilation, and React component bridging (svelte-preprocess-react). +- Python package build process: dependency installation, packaging configuration, version management, and publish scripts. +- Local build environment setup: key points for installing and configuring Node.js, Python, and pnpm. +- Build optimization techniques and performance tuning recommendations. +- Common build failure causes and solutions. + +## Project Structure + +The project is organized as a multi-package workspace (pnpm workspace). Core directories and their responsibilities: + +- **Root-level scripts and configuration**: package.json, pyproject.toml, pnpm-workspace.yaml, tsconfig.json, svelte-tsconfig.json. +- **Frontend**: the `frontend` directory and its sub-packages (antd, antdx, base, pro), plus the svelte-preprocess-react bridging layer. +- **Backend Python package**: backend/modelscope_studio, containing numerous component templates and version information. +- **Publish script**: scripts/publish-to-pypi.mts, used for building and publishing in CI. + +```mermaid +graph TB +subgraph "Root Workspace" +RootPkg["Root package.json"] +RootPy["Root pyproject.toml"] +WS["pnpm-workspace.yaml"] +TSRoot["tsconfig.json"] +SvelteTS["svelte-tsconfig.json"] +end +subgraph "Frontend" +FE_PKG["frontend/package.json"] +FE_CFG["frontend/defineConfig.js"] +FE_PLG["frontend/plugin.js"] +FE_TS["frontend/tsconfig.json"] +BTN_PKG["@modelscope-studio/antd-button/package.json"] +BTN_CFG["frontend/antd/button/gradio.config.js"] +BTN_IDX["frontend/antd/button/Index.svelte"] +BTN_TSX["frontend/antd/button/button.tsx"] +SPR_IDX["frontend/svelte-preprocess-react/index.ts"] +end +subgraph "Backend Python Package" +Backend["backend/modelscope_studio/..."] +VerPy["backend/modelscope_studio/version.py"] +end +subgraph "Publish Script" +Pub["scripts/publish-to-pypi.mts"] +end +RootPkg --> FE_PKG +RootPkg --> RootPy +WS --> FE_PKG +FE_CFG --> FE_PLG +FE_PKG --> BTN_PKG +BTN_CFG --> BTN_IDX +BTN_IDX --> BTN_TSX +BTN_TSX --> SPR_IDX +RootPy --> Backend +Pub --> RootPy +Pub --> RootPkg +``` + +**Diagram sources** + +- [package.json:1-55](file://package.json#L1-L55) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [frontend/defineConfig.js:1-19](file://frontend/defineConfig.js#L1-L19) +- [frontend/plugin.js:1-168](file://frontend/plugin.js#L1-L168) +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) +- [svelte-tsconfig.json:1-4](file://svelte-tsconfig.json#L1-L4) +- [frontend/antd/button/package.json:1-15](file://frontend/antd/button/package.json#L1-L15) +- [frontend/antd/button/gradio.config.js:1-4](file://frontend/antd/button/gradio.config.js#L1-L4) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +**Section sources** + +- [package.json:1-55](file://package.json#L1-L55) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [frontend/defineConfig.js:1-19](file://frontend/defineConfig.js#L1-L19) +- [frontend/plugin.js:1-168](file://frontend/plugin.js#L1-L168) +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) +- [svelte-tsconfig.json:1-4](file://svelte-tsconfig.json#L1-L4) + +## Core Components + +- **Root build scripts and commands**: Defined in the root `package.json`, providing a unified entry point for build, dev, version, and publish-related scripts. +- **Frontend Vite plugin**: `ModelScopeStudioVitePlugin` handles alias resolution, externalization, global variable mapping, and code transformation. +- **Svelte component bridge**: `svelte-preprocess-react` enables React components to be used in a Svelte style, handling slot and prop pass-through. +- **Python packaging**: `pyproject.toml` uses hatchling as the build backend, declaring `artifacts` and wheel inclusion paths to ensure template assets are correctly packaged. +- **Version management**: The Python package version is kept in sync with the frontend version, reflected jointly by `backend/modelscope_studio/version.py` and the root `package.json` version field. + +**Section sources** + +- [package.json:8-25](file://package.json#L8-L25) +- [frontend/plugin.js:41-168](file://frontend/plugin.js#L41-L168) +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) +- [pyproject.toml:45-257](file://pyproject.toml#L45-L257) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) + +## Architecture Overview + +The diagram below shows the overall flow from "build command" to "artifact output", covering frontend Vite builds, React component bridging, Python packaging, and the publish script. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Root as "Root package.json" +participant Vite as "Vite Build" +participant Plugin as "ModelScopeStudioVitePlugin" +participant Svelte as "Svelte Compiler" +participant React as "React Component" +participant Py as "Python Packaging (hatch)" +participant Pub as "Publish Script (publish-to-pypi.mts)" +Dev->>Root : Run build script +Root->>Vite : Call gradio cc build +Vite->>Plugin : Apply plugin configuration and externalization +Vite->>Svelte : Compile Svelte components +Svelte->>React : Bridge via svelte-preprocess-react +Vite-->>Root : Generate dist +Root->>Py : Package using hatchling +Py-->>Root : Generate wheel/sdist +Dev->>Pub : Trigger publish process +Pub->>Py : Check whether version already exists +Pub->>Root : Run build and check +Pub->>Py : Upload with twine +``` + +**Diagram sources** + +- [package.json:8-25](file://package.json#L8-L25) +- [frontend/defineConfig.js:5-18](file://frontend/defineConfig.js#L5-L18) +- [frontend/plugin.js:41-76](file://frontend/plugin.js#L41-L76) +- [frontend/antd/button/Index.svelte:10-55](file://frontend/antd/button/Index.svelte#L10-L55) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [pyproject.toml:45-257](file://pyproject.toml#L45-L257) +- [scripts/publish-to-pypi.mts:22-55](file://scripts/publish-to-pypi.mts#L22-L55) + +## Detailed Component Analysis + +### Frontend Vite Build and Plugin + +- **Configuration entry**: `defineConfig.js` exports a function that returns a Vite default config object, integrating the React plugin and the custom `ModelScopeStudioVitePlugin`. +- **Plugin capabilities**: + - **Alias resolution**: `@utils`, `@globals`, `svelte-preprocess-react`. + - **Externalization strategy**: Marks a predefined set of modules as `external` during the build phase and injects global variable mappings, reducing bundle size. + - **Code transformation**: Traverses the AST and rewrites imports/exports to `window.ms_globals.*` accesses, enabling runtime dependency sharing. +- **Types and checking**: The frontend `tsconfig.json` extends the root tsconfig and enables ESNext module types; `svelte-tsconfig.json` is used for Svelte type checking. + +```mermaid +flowchart TD +Start(["Enter Vite Config"]) --> Alias["Configure aliases
@utils/@globals/svelte-preprocess-react"] +Alias --> External{"Externalization enabled?"} +External --> |Yes| MarkExt["Mark external list"] +External --> |No| SkipExt["Skip externalization"] +MarkExt --> DefineEnv["Define production environment constants"] +SkipExt --> DefineEnv +DefineEnv --> Transform["AST traversal and transformation
import/export -> window.ms_globals.*"] +Transform --> End(["Configuration complete"]) +``` + +**Diagram sources** + +- [frontend/defineConfig.js:5-18](file://frontend/defineConfig.js#L5-L18) +- [frontend/plugin.js:41-76](file://frontend/plugin.js#L41-L76) +- [frontend/plugin.js:77-167](file://frontend/plugin.js#L77-L167) +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) +- [svelte-tsconfig.json:1-4](file://svelte-tsconfig.json#L1-L4) + +**Section sources** + +- [frontend/defineConfig.js:1-19](file://frontend/defineConfig.js#L1-L19) +- [frontend/plugin.js:1-168](file://frontend/plugin.js#L1-L168) +- [frontend/tsconfig.json:1-8](file://frontend/tsconfig.json#L1-L8) +- [svelte-tsconfig.json:1-4](file://svelte-tsconfig.json#L1-L4) + +### Svelte Component Compilation and React Bridging + +- **Component export**: Each frontend component package declares its Gradio entry (`Index.svelte`) via the `exports` field in its `package.json`. +- **Configuration inheritance**: The component-level `gradio.config.js` generates a unified configuration through `defineConfig`. +- **Component implementation**: + - **Svelte layer**: `Index.svelte` uses APIs from `svelte-preprocess-react` such as `getProps`, `processProps`, and `getSlots` to transform props and slots passed in by Gradio into forms usable by React components. + - **React layer**: `button.tsx` uses `sveltify` to wrap the Ant Design Button so it can be used by Svelte, supporting slots and children rendering. +- **Slots and props**: Complex child nodes and icon slots are rendered via `ReactSlot` and `useTargets`. + +```mermaid +sequenceDiagram +participant Gradio as "Gradio Runtime" +participant Svelte as "Index.svelte" +participant Bridge as "svelte-preprocess-react" +participant React as "button.tsx" +Gradio->>Svelte : Pass in props and slots +Svelte->>Bridge : getProps()/processProps()/getSlots() +Bridge-->>Svelte : Normalized props/slots +Svelte->>React : importComponent to load React component +React-->>Svelte : Render Ant Design Button +Svelte-->>Gradio : Output final DOM +``` + +**Diagram sources** + +- [frontend/antd/button/package.json:1-15](file://frontend/antd/button/package.json#L1-L15) +- [frontend/antd/button/gradio.config.js:1-4](file://frontend/antd/button/gradio.config.js#L1-L4) +- [frontend/antd/button/Index.svelte:10-55](file://frontend/antd/button/Index.svelte#L10-L55) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) + +**Section sources** + +- [frontend/antd/button/package.json:1-15](file://frontend/antd/button/package.json#L1-L15) +- [frontend/antd/button/gradio.config.js:1-4](file://frontend/antd/button/gradio.config.js#L1-L4) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) + +### Python Package Build and Publish + +- **Build backend**: `pyproject.toml` uses hatchling as the build backend, together with `hatch-requirements-txt` and `hatch-fancy-pypi-readme`. +- **Dependencies and metadata**: Declares Python version requirements, license, keywords, classifiers, and core dependencies (such as Gradio). +- **Packaging scope**: `tool.hatch.build.artifacts` explicitly lists numerous template directories to ensure frontend component templates are distributed with the package; wheel/sdist inclusion and exclusion rules are clearly defined. +- **Version synchronization**: The Python package version is kept in sync with the frontend version for unified publishing and tracking. +- **Publish script**: `scripts/publish-to-pypi.mts` handles installation, building, version checking, and twine upload in CI, preventing duplicate publishing. + +```mermaid +flowchart TD +A["Read root package.json version"] --> B["Install project in editable mode"] +B --> C["Run frontend build"] +C --> D{"dist exists?"} +D --> |No| E["Throw build failure error"] +D --> |Yes| F["Check if version already exists on PyPI"] +F --> |Exists| G["Skip publish"] +F --> |Not exists| H["twine upload dist/*"] +H --> I["Output published=true"] +``` + +**Diagram sources** + +- [pyproject.toml:1-44](file://pyproject.toml#L1-L44) +- [pyproject.toml:45-257](file://pyproject.toml#L45-L257) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [scripts/publish-to-pypi.mts:14-55](file://scripts/publish-to-pypi.mts#L14-L55) + +**Section sources** + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +## Dependency Analysis + +- **Workspace and package management**: `pnpm-workspace.yaml` declares the root, config, frontend, and sub-packages, ensuring cross-package reference and build consistency. +- **Frontend dependencies**: `frontend/package.json` specifies core dependencies such as React 19, Svelte 5, Ant Design 6, and Monaco Editor. +- **Externalization and aliases**: `ModelScopeStudioVitePlugin` maps React, ReactDOM, antd, antdx, etc. to `window.ms_globals.*`, reducing duplicate bundling. +- **Python dependencies**: `pyproject.toml` declares only the Gradio dependency; other frontend assets are bundled via artifacts and template directories. + +```mermaid +graph LR +WS["pnpm-workspace.yaml"] --> FE["frontend/package.json"] +FE --> React["react / react-dom"] +FE --> Svelte["svelte 5"] +FE --> Antd["antd 6"] +FE --> Monaco["monaco-editor"] +FE --> Gradio["@gradio/*"] +Py["pyproject.toml"] --> Hatch["hatchling"] +Py --> Artifacts["artifacts template collection"] +Py --> Wheel["wheel/sdist config"] +``` + +**Diagram sources** + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [frontend/package.json:8-40](file://frontend/package.json#L8-L40) +- [pyproject.toml:1-44](file://pyproject.toml#L1-L44) +- [pyproject.toml:45-257](file://pyproject.toml#L45-L257) + +**Section sources** + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) + +## Performance Considerations + +- **Externalization and shared dependencies**: Through `ModelScopeStudioVitePlugin`'s external configuration and global mappings, large packages such as React and antd are not bundled repeatedly, significantly reducing artifact size and build time. +- **AST transformation and lazy loading**: Rewriting imports/exports to global access at build time, combined with dynamic `import` (e.g., `importComponent`), enables lazy loading and improves initial load performance. +- **Module aliases**: Using `@utils`, `@globals`, and `svelte-preprocess-react` aliases appropriately reduces path resolution overhead. +- **Packaging granularity**: Precisely listing template directories in `artifacts` prevents unrelated files from entering the package, shortening packaging and publish time. +- **Type checking**: Enabling `svelte-check` and TypeScript type checking catches type issues early, reducing the cost of rollbacks caused by runtime errors. + +[This section provides general performance recommendations and does not directly reference specific files, so no "Section sources" are listed.] + +## Troubleshooting Guide + +- **Build failure (dist does not exist)** + - Symptom: The publish script reports "Build Failed". + - Investigation: Confirm that the frontend build command completed successfully; check whether `defineConfig` and plugin configuration are correctly applied. + - References: + - [scripts/publish-to-pypi.mts:22-30](file://scripts/publish-to-pypi.mts#L22-L30) + - [frontend/defineConfig.js:8-18](file://frontend/defineConfig.js#L8-L18) +- **Duplicate version publish** + - Symptom: The same version already exists on PyPI; the script skips publishing. + - Investigation: Confirm that the version number has not been changed, or manually clear the cache. + - References: + - [scripts/publish-to-pypi.mts:44-51](file://scripts/publish-to-pypi.mts#L44-L51) +- **Missing externalized dependency** + - Symptom: Runtime error — `window.ms_globals` is not defined. + - Investigation: Check the `external`/`excludes` configuration in `ModelScopeStudioVitePlugin` to confirm the global mapping covers all required dependencies. + - References: + - [frontend/plugin.js:41-76](file://frontend/plugin.js#L41-L76) + - [frontend/plugin.js:5-20](file://frontend/plugin.js#L5-L20) +- **Svelte/React slot rendering issue** + - Symptom: Slot content is not displayed, or icons/loading states do not work. + - Investigation: Confirm that `getProps`/`processProps`/`getSlots` in `Index.svelte` are used correctly, and that `ReactSlot` and `useTargets` in `button.tsx` behave as expected. + - References: + - [frontend/antd/button/Index.svelte:10-55](file://frontend/antd/button/Index.svelte#L10-L55) + - [frontend/antd/button/button.tsx:11-36](file://frontend/antd/button/button.tsx#L11-L36) +- **Python packaging missing templates** + - Symptom: Component templates are missing after installation. + - Investigation: Cross-check the `artifacts` list in `pyproject.toml` against the wheel/sdist inclusion paths. + - References: + - [pyproject.toml:45-257](file://pyproject.toml#L45-L257) + +**Section sources** + +- [scripts/publish-to-pypi.mts:22-51](file://scripts/publish-to-pypi.mts#L22-L51) +- [frontend/plugin.js:5-20](file://frontend/plugin.js#L5-L20) +- [frontend/antd/button/Index.svelte:10-55](file://frontend/antd/button/Index.svelte#L10-L55) +- [frontend/antd/button/button.tsx:11-36](file://frontend/antd/button/button.tsx#L11-L36) +- [pyproject.toml:45-257](file://pyproject.toml#L45-L257) + +## Conclusion + +The build system of this project revolves around a combination of "frontend Vite + Svelte + React bridging + Python packaging". Through externalized shared dependencies, AST transformation, and a precise template packaging strategy, it achieves efficient builds and stable runtime behavior. Following the configuration and troubleshooting recommendations in this document will effectively improve build stability and performance in both local and CI environments. + +[This section contains summary content and does not directly reference specific files, so no "Section sources" are listed.] + +## Appendix + +### Local Build Environment Setup + +- **Node.js** + - Version requirements: must satisfy the needs of frontend dependencies (React 19, Svelte 5, Ant Design 6). + - Package manager: use pnpm, consistent with the workspace configuration. + - References: + - [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) + - [frontend/package.json:8-40](file://frontend/package.json#L8-L40) +- **Python** + - Version requirements: must satisfy `requires-python` in `pyproject.toml`. + - Build tools: install hatchling and twine to ensure they are executable. + - References: + - [pyproject.toml:1-7](file://pyproject.toml#L1-L7) + - [pyproject.toml:42-43](file://pyproject.toml#L42-L43) +- **Frontend build** + - Run root scripts for building and development, ensuring that `defineConfig` and the plugin load correctly. + - References: + - [package.json:8-25](file://package.json#L8-L25) + - [frontend/defineConfig.js:5-18](file://frontend/defineConfig.js#L5-L18) + - [frontend/plugin.js:41-76](file://frontend/plugin.js#L41-L76) + +**Section sources** + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [pyproject.toml:1-44](file://pyproject.toml#L1-L44) +- [package.json:8-25](file://package.json#L8-L25) +- [frontend/defineConfig.js:1-19](file://frontend/defineConfig.js#L1-L19) +- [frontend/plugin.js:1-168](file://frontend/plugin.js#L1-L168) diff --git a/.wiki/en/Deployment Guide/CI CD.md b/.wiki/en/Deployment Guide/CI CD.md new file mode 100644 index 00000000..9cc946fa --- /dev/null +++ b/.wiki/en/Deployment Guide/CI CD.md @@ -0,0 +1,436 @@ +# CI/CD + + +**Files referenced in this document** +- [.github/workflows/lint.yaml](file://.github/workflows/lint.yaml) +- [.github/workflows/publish.yaml](file://.github/workflows/publish.yaml) +- [.changeset/config.json](file://.changeset/config.json) +- [.changeset/README.md](file://.changeset/README.md) +- [package.json](file://package.json) +- [pyproject.toml](file://pyproject.toml) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) +- [scripts/create-tag-n-release.mts](file://scripts/create-tag-n-release.mts) +- [eslint.config.mjs](file://eslint.config.mjs) +- [prettier.config.mjs](file://prettier.config.mjs) +- [.flake8](file://.flake8) +- [config/lint-config/eslint.mjs](file://config/lint-config/eslint.mjs) +- [.commitlintrc.js](file://.commitlintrc.js) +- [.lintstagedrc](file://.lintstagedrc) +- [.editorconfig](file://.editorconfig) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is intended for developers and operators who need to configure and maintain automated pipelines for ModelScope Studio. It systematically covers the following topics: + +- GitHub Actions workflows: configuration and execution logic for Lint and Publish +- Lint workflow integration: how ESLint, Prettier, Flake8, isort, yapf, and other tools are used in CI +- Publish workflow: version detection, build validation, PyPI publishing, tag and release creation +- Changesets usage: version updates, changelog generation, and release tag creation +- Custom workflows: how to extend and customize existing pipelines +- Troubleshooting and performance optimization recommendations + +## Project Structure + +The repository is a polyglot project: the frontend is built on Svelte/TypeScript, the backend is a Python package. Version and changelog management is unified through Changesets, and CI/CD is implemented with GitHub Actions. + +```mermaid +graph TB +subgraph "CI/CD Workflows" +LINT[".github/workflows/lint.yaml"] +PUBLISH[".github/workflows/publish.yaml"] +end +subgraph "Versioning & Changelog" +CHCFG[".changeset/config.json"] +CHREADM[".changeset/README.md"] +end +subgraph "Frontend & Scripts" +PKGJSON["package.json"] +ESLINTCFG["eslint.config.mjs"] +PRETTIERCFG["prettier.config.mjs"] +LINTSTAGED[".lintstagedrc"] +EDITOR[".editorconfig"] +SCRIPT_PUBLISH["scripts/publish-to-pypi.mts"] +SCRIPT_TAGREL["scripts/create-tag-n-release.mts"] +end +subgraph "Python Package" +PYPROJ["pyproject.toml"] +FLAKE8[".flake8"] +end +LINT --> PKGJSON +PUBLISH --> PKGJSON +PUBLISH --> SCRIPT_PUBLISH +PUBLISH --> SCRIPT_TAGREL +PKGJSON --> ESLINTCFG +PKGJSON --> PRETTIERCFG +PKGJSON --> LINTSTAGED +PKGJSON --> EDITOR +PKGJSON --> CHCFG +PKGJSON --> CHREADM +PKGJSON --> PYPROJ +PYPROJ --> FLAKE8 +``` + +Diagram sources + +- [.github/workflows/lint.yaml:1-34](file://.github/workflows/lint.yaml#L1-L34) +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/README.md:1-9](file://.changeset/README.md#L1-L9) +- [package.json:1-55](file://package.json#L1-L55) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) +- [eslint.config.mjs:1-9](file://eslint.config.mjs#L1-L9) +- [prettier.config.mjs:1-26](file://prettier.config.mjs#L1-L26) +- [.lintstagedrc:1-7](file://.lintstagedrc#L1-L7) +- [.editorconfig:1-17](file://.editorconfig#L1-L17) +- [.flake8:1-16](file://.flake8#L1-L16) + +Section sources + +- [.github/workflows/lint.yaml:1-34](file://.github/workflows/lint.yaml#L1-L34) +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [package.json:1-55](file://package.json#L1-L55) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) + +## Core Components + +- **Lint Workflow**: Triggered on push and pull requests. Installs Python and Node dependencies, then runs the unified lint script. +- **Publish Workflow**: Triggered on pushes to main/next branches. Determines whether to execute version updates and publishing based on the commit message, and ultimately creates a Git tag and GitHub Release. +- **Changesets**: Centralized version and changelog management. Works with scripts to write version numbers and fix changelogs. +- **Publish Script**: Checks whether the target version already exists on PyPI, builds artifacts, uploads to PyPI, and sets a published output flag for downstream steps. +- **Tag & Release Script**: Aggregates changelogs from all packages, creates a Git tag, and creates a GitHub Release. + +Section sources + +- [.github/workflows/lint.yaml:1-34](file://.github/workflows/lint.yaml#L1-L34) +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [package.json:8-25](file://package.json#L8-L25) +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) + +## Architecture Overview + +The diagram below shows the critical path and decision points from code commit to release. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant GH as "GitHub" +participant LINT as "Lint Workflow" +participant PUBLISH as "Publish Workflow" +participant PYPI as "PyPI" +participant TAGREL as "Tag & Release Script" +Dev->>GH : Push commit / open PR +GH->>LINT : Trigger Lint (push/pull_request) +LINT-->>GH : Lint result +Dev->>GH : Push to main/next +GH->>PUBLISH : Trigger Publish (push) +PUBLISH->>PUBLISH : Check if commit message is "update versions" +alt "update versions" commit +PUBLISH->>PYPI : Build and upload +PYPI-->>PUBLISH : Upload result +PUBLISH->>TAGREL : Create Tag and Release +TAGREL-->>GH : Release complete +else Not an "update versions" commit +PUBLISH-->>GH : Skip publish steps +end +``` + +Diagram sources + +- [.github/workflows/lint.yaml:1-34](file://.github/workflows/lint.yaml#L1-L34) +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +## Detailed Component Analysis + +### Lint Workflow Configuration and Execution + +- **Trigger conditions**: push and pull_request +- **Concurrency control**: Only one running instance is retained per workflow per branch +- **Step overview**: + - Check out code (full history) + - Install Python dependencies (flake8, isort, yapf) + - Install Node.js and pnpm + - Install Node dependencies + - Run the unified lint script (JS/TS linting and formatting run in parallel) + +```mermaid +flowchart TD +Start(["Start"]) --> Checkout["Check Out Code"] +Checkout --> PySetup["Set Up Python 3.9"] +PySetup --> PyDeps["Install Python Dependencies"] +PyDeps --> NodeSetup["Set Up Node.js 20"] +NodeSetup --> PNPM["Install pnpm"] +PNPM --> NPMInstall["Install Node Dependencies"] +NPMInstall --> RunLint["Run Unified Lint Script"] +RunLint --> End(["End"]) +``` + +Diagram sources + +- [.github/workflows/lint.yaml:1-34](file://.github/workflows/lint.yaml#L1-L34) + +Section sources + +- [.github/workflows/lint.yaml:1-34](file://.github/workflows/lint.yaml#L1-L34) +- [package.json:18-22](file://package.json#L18-L22) +- [.lintstagedrc:1-7](file://.lintstagedrc#L1-L7) +- [.editorconfig:1-17](file://.editorconfig#L1-L17) +- [.flake8:1-16](file://.flake8#L1-L16) + +### Publish Workflow Configuration and Execution + +- **Trigger conditions**: Push to main or next branch +- **Concurrency control**: Independent group to avoid concurrent conflicts +- **Key steps**: + - **Conditional execution**: Subsequent steps run only when the commit message is "update versions" + - **Build and publish**: Invokes the publish script with the PyPI token + - **Tag and release**: If publishing succeeds, invokes the tag and release script with the GitHub token, repository name, and owner + +```mermaid +flowchart TD +PS(["Start"]) --> CheckCommit["Check if commit message is 'update versions'"] +CheckCommit --> |No| Skip["Skip publish steps"] +CheckCommit --> |Yes| Build["Install Python/Node dependencies"] +Build --> Publish["Run publish script to upload to PyPI"] +Publish --> Published{"Publish successful?"} +Published --> |No| End(["End"]) +Published --> |Yes| TagRel["Create Git Tag and publish to GitHub"] +TagRel --> End +``` + +Diagram sources + +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +Section sources + +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) + +### Changesets Version and Changelog Management + +- **Configuration highlights**: + - Uses a custom changelog generator with the repository URL specified + - Base branch is `main` + - Internal dependency update strategy is patch +- **Common commands**: + - Version update and changelog fix: executed by the root script + - CLI interactive version selection and change recording + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant CS as "Changesets CLI" +participant Root as "Root Script" +participant Changelog as "Changelog Generator" +Dev->>CS : Add/edit changeset +Dev->>Root : Run version update script +Root->>CS : Execute version update +CS-->>Root : Generate version numbers and changelogs +Root->>Changelog : Fix/aggregate changelogs +Changelog-->>Dev : Output changelog files +``` + +Diagram sources + +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [package.json](file://package.json#L24) + +Section sources + +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/README.md:1-9](file://.changeset/README.md#L1-L9) +- [package.json:8-25](file://package.json#L8-L25) + +### Publish Script: Version Detection, Build, and Upload + +- **Functionality overview**: + - Checks whether the target version already exists on PyPI; skips if it does + - Installs editable-mode dependencies and runs the build + - Verifies that the dist directory exists + - Uploads to PyPI with twine, skipping already-existing files + - Sets a published-success output flag for subsequent steps + +```mermaid +flowchart TD +S(["Start"]) --> Exists["Check if version already exists on PyPI"] +Exists --> |Exists| Warn["Skip and output notice"] --> End(["End"]) +Exists --> |Not exists| Install["Install editable dependencies"] +Install --> Build["Run build"] +Build --> Dist{"dist directory exists?"} +Dist --> |No| Fail["Throw build failure error"] --> End +Dist --> |Yes| Upload["Upload with twine"] +Upload --> SetOut["Set published-success output flag"] +SetOut --> End +``` + +Diagram sources + +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +Section sources + +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +### Tag & Release Script: Aggregating Changelogs, Creating Tag and Release + +- **Functionality overview**: + - Reads the root changelog and per-package changelogs, aggregated by version + - Configures Git user information + - Creates a tag with a `v` prefix and pushes it to the remote + - Calls the GitHub API to create a Release; the pre-release flag is determined based on the version number + +```mermaid +sequenceDiagram +participant Script as "Tag & Release Script" +participant FS as "File System" +participant Git as "Git" +participant GH as "GitHub API" +Script->>FS : Read root and per-package changelogs +Script->>Script : Parse change entries by version +Script->>Git : Configure user name and email +Script->>Git : Create tag and push +Script->>GH : Create Release (with pre-release flag) +GH-->>Script : Return result +``` + +Diagram sources + +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +Section sources + +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +### Lint Toolchain and Configuration + +- **ESLint**: Imports the unified lint configuration set from the root config +- **Prettier**: Unified formatting rules and plugins, supporting Svelte and package.json +- **Flake8**: Python static analysis, ignoring specific rules and directories +- **isort/yapf**: Python import sorting and formatting +- **Stylelint**: Style file checking (invoked via script) +- **Commit convention**: commitlint based on Conventional Commits + +Section sources + +- [eslint.config.mjs:1-9](file://eslint.config.mjs#L1-L9) +- [config/lint-config/eslint.mjs:1-11](file://config/lint-config/eslint.mjs#L1-L11) +- [prettier.config.mjs:1-26](file://prettier.config.mjs#L1-L26) +- [.lintstagedrc:1-7](file://.lintstagedrc#L1-L7) +- [.flake8:1-16](file://.flake8#L1-L16) +- [.commitlintrc.js:1-30](file://.commitlintrc.js#L1-L30) +- [.editorconfig:1-17](file://.editorconfig#L1-L17) + +## Dependency Analysis + +- **Workflow dependency on scripts**: The publish workflow directly invokes the publish and tag scripts +- **Script dependency on tools**: The publish script depends on twine and the build toolchain; the tag script depends on the GitHub API and Git +- **Language ecosystem dependencies**: The frontend uses pnpm for dependency management; Python uses hatchling for building and twine for uploading +- **Version and changelog**: Changesets and root scripts jointly drive version number and changelog generation + +```mermaid +graph LR +LINTWF[".github/workflows/lint.yaml"] --> PKG["package.json scripts"] +PUBWF[".github/workflows/publish.yaml"] --> PUBLISH["scripts/publish-to-pypi.mts"] +PUBWF --> TAGREL["scripts/create-tag-n-release.mts"] +PUBLISH --> TWINE["twine upload"] +PUBLISH --> BUILD["Build artifacts"] +TAGREL --> GHAPI["GitHub API"] +TAGREL --> GIT["Git tags"] +PKG --> ESL["ESLint/Prettier/Stylelint"] +PKG --> PY["Python deps (flake8/isort/yapf)"] +PY --> PYPROJ["pyproject.toml"] +``` + +Diagram sources + +- [.github/workflows/lint.yaml:1-34](file://.github/workflows/lint.yaml#L1-L34) +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) +- [package.json:8-25](file://package.json#L8-L25) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) + +Section sources + +- [package.json:1-55](file://package.json#L1-L55) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) + +## Performance Considerations + +- **Caching and concurrency**: Make proper use of caching and concurrency control to avoid redundant installs and builds +- **Task splitting**: Separating Lint and build into independent steps facilitates parallelism and retries +- **Dependency minimization**: Install only the extra dependencies needed to reduce image size and wait time +- **Fail fast**: Exit early when a version already exists or a build fails to conserve resources + +## Troubleshooting Guide + +- **PyPI version already exists** + - Symptom: The publish script skips the upload and outputs a notice + - Resolution: Confirm whether the version number has been correctly updated, or clear the cache and retry +- **Missing build artifacts** + - Symptom: No `dist` directory generated after build, causing failure + - Resolution: Check whether the build script and dependency installation completed successfully +- **Upload failure (permissions / token)** + - Symptom: twine upload reports an error + - Resolution: Confirm that `PYPI_TOKEN` is configured and valid +- **Tag and Release failure** + - Symptom: GitHub API throws an exception or changelog is not found + - Resolution: Check whether changelog generation is working correctly and confirm the version number matches the tag +- **Lint failure** + - Symptom: ESLint / Prettier / Flake8 reports errors + - Resolution: Fix the code or adjust the rules according to the error messages; ensure local and CI use the same configuration + +Section sources + +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) +- [package.json:18-22](file://package.json#L18-L22) +- [.lintstagedrc:1-7](file://.lintstagedrc#L1-L7) +- [.flake8:1-16](file://.flake8#L1-L16) + +## Conclusion + +The CI/CD system in this repository is built around GitHub Actions, Changesets, and a set of Node/Python toolchains, implementing an end-to-end pipeline from code linting to version publishing. Through clear workflow separation, strict version and changelog management, and reusable publish and tag scripts, the team can deliver products efficiently and reliably. + +## Appendix + +### Custom Workflow Recommendations + +- **Adding lint rules**: Extend ESLint/Prettier rules in the root config and sync them to `.lintstagedrc` +- **Adding languages or tools**: Add scripts and dependencies in `package.json`, and add corresponding steps in the workflow +- **Publish strategy**: Adjust trigger branches and conditional checks as needed to ensure publishing only occurs on "update versions" commits +- **Security and secrets**: Strictly manage `PYPI_TOKEN` and `GITHUB_TOKEN`, restricting their scope and access + +### Reference File Index + +- Lint workflow: [lint.yaml:1-34](file://.github/workflows/lint.yaml#L1-L34) +- Publish workflow: [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- Changesets config: [config.json:1-15](file://.changeset/config.json#L1-L15) +- Root scripts and toolchain: [package.json:8-25](file://package.json#L8-L25) +- Python build and publish: [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- Publish script: [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- Tag and release script: [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) +- Lint configuration: [eslint.config.mjs:1-9](file://eslint.config.mjs#L1-L9), [prettier.config.mjs:1-26](file://prettier.config.mjs#L1-L26), [lint-staged config:1-7](file://.lintstagedrc#L1-L7), [flake8 config:1-16](file://.flake8#L1-L16) +- Commit convention: [commitlint config:1-30](file://.commitlintrc.js#L1-L30) +- Editor configuration: [EditorConfig:1-17](file://.editorconfig#L1-L17) diff --git a/.wiki/en/Deployment Guide/Deployment Guide.md b/.wiki/en/Deployment Guide/Deployment Guide.md new file mode 100644 index 00000000..cc1811de --- /dev/null +++ b/.wiki/en/Deployment Guide/Deployment Guide.md @@ -0,0 +1,333 @@ +# Deployment Guide + + +**Files Referenced in This Document** +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [.github/workflows/publish.yaml](file://.github/workflows/publish.yaml) +- [.github/workflows/lint.yaml](file://.github/workflows/lint.yaml) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) +- [scripts/create-tag-n-release.mts](file://scripts/create-tag-n-release.mts) +- [frontend/package.json](file://frontend/package.json) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [frontend/plugin.js](file://frontend/plugin.js) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) +- [README.md](file://README.md) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This guide is intended for operations personnel and developers, providing a systematic explanation of ModelScope Studio's build process, release strategy, and deployment practices, covering the following topics: + +- Frontend component build and packaging strategy +- Python package build and publishing to PyPI +- CI/CD pipeline configuration and usage +- Configuration methods for different deployment environments (local development, production, cloud platforms) +- Performance optimization and monitoring recommendations +- Common issue troubleshooting and solutions + +## Project Structure + +The project uses a multi-package workspace organization, with the root directory managing frontend sub-packages and configuration modules uniformly via pnpm workspaces. The backend Python package is in the `backend/modelscope_studio` directory and defines build and packaging rules via `pyproject.toml`. + +```mermaid +graph TB +Root["Repository Root"] --> Backend["Backend Python Package
backend/modelscope_studio"] +Root --> Frontend["Frontend Workspace
frontend/*"] +Root --> Config["Configuration Toolset
config/*"] +Root --> Scripts["Release Scripts
scripts/*"] +Root --> Workflows["CI/CD Pipelines
.github/workflows/*"] +Frontend --> Antd["Ant Design Component Library
frontend/antd/*"] +Frontend --> Antdx["Ant Design X Component Library
frontend/antdx/*"] +Frontend --> Pro["Pro Component Library
frontend/pro/*"] +Frontend --> Base["Base Component Library
frontend/base/*"] +``` + +Chart Sources + +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [frontend/package.json](file://frontend/package.json) +- [pyproject.toml](file://pyproject.toml) + +Section Sources + +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [frontend/package.json](file://frontend/package.json) +- [pyproject.toml](file://pyproject.toml) + +## Core Components + +- Build and Packaging + - Frontend: Based on Vite and custom plugins, implements React/Svelte mixed compilation and externalization strategies, outputting component assets usable by Gradio. + - Backend: Built using Hatchling, packaging templates and component assets into the Python package via toolchain. +- Release and Version Management + - Uses Changesets for version and changelog management; CI executes build, upload to PyPI, creation of Git Tag, and GitHub Release. +- Quality Assurance + - Lint pipeline runs on PRs and pushes to ensure consistent code style and static checks. + +Section Sources + +- [package.json](file://package.json) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [frontend/plugin.js](file://frontend/plugin.js) +- [pyproject.toml](file://pyproject.toml) +- [.github/workflows/lint.yaml](file://.github/workflows/lint.yaml) + +## Architecture Overview + +The diagram below shows the complete deployment path from local to cloud: Local development build → CI trigger → PyPI publishing → Tag and Release creation. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Local as "Local Build" +participant GH as "GitHub Actions" +participant PyPI as "PyPI" +participant Git as "Git Repository" +Dev->>Local : Execute build script +Local-->>Dev : Output dist/ frontend artifacts +Dev->>GH : Push branch / trigger pipeline +GH->>GH : Fetch code / install dependencies +GH->>GH : Build Python package and validate version +GH->>PyPI : Upload wheel and source package +PyPI-->>GH : Return publish result +GH->>Git : Create Tag and push +GH->>Git : Create GitHub Release +``` + +Chart Sources + +- [.github/workflows/publish.yaml](file://.github/workflows/publish.yaml) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) +- [scripts/create-tag-n-release.mts](file://scripts/create-tag-n-release.mts) + +## Detailed Component Analysis + +### Frontend Build and Packaging + +- Build Entry and Commands + - The build script in the root `package.json` calls the Gradio custom component CLI for building (using `--no-generate-docs` to disable automatic documentation generation for faster builds). + - Full command: `rimraf dist && gradio cc build --no-generate-docs` +- Vite Plugins and Aliases + - The custom Vite plugin is responsible for: + - Setting environment variables to production mode during the build phase + - Externalizing specified dependencies to reduce bundle size + - Transforming import/export statements via Babel AST to map modules to global objects, enabling on-demand loading in browser environments + - Alias mappings to utility and global component modules improve development experience and consistency. +- Externalization Strategy + - React, Ant Design, and their ecosystems are externalized to avoid duplicate bundling, reducing bundle size and improving cache hit rate. + +```mermaid +flowchart TD +Start(["Start Build"]) --> LoadCfg["Load Vite config and plugins"] +LoadCfg --> SetEnv["Set production environment variables"] +SetEnv --> Externalize["Configure externalized dependency list"] +Externalize --> Alias["Configure module aliases"] +Alias --> Transform["Babel AST transform imports/exports"] +Transform --> Bundle["Rollup bundle artifacts"] +Bundle --> End(["Done"]) +``` + +Chart Sources + +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [frontend/plugin.js](file://frontend/plugin.js) + +Section Sources + +- [package.json](file://package.json) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [frontend/plugin.js](file://frontend/plugin.js) + +### Python Package Build and Release + +- Build System and Metadata + - Uses Hatchling as the build backend, declares dependencies and optional dependencies, defines classifiers and keywords. +- Asset Packaging + - A large number of component templates and static assets are included in the packaging scope via toolchain, ensuring they are directly available at runtime. +- Version and Metadata + - Root `pyproject.toml` stays consistent with the backend version file, ensuring unified release version numbers. + +```mermaid +flowchart TD +A["Read pyproject.toml metadata"] --> B["Install build dependencies"] +B --> C["Execute build command to generate dist/"] +C --> D{"Does dist/ exist?"} +D --> |No| E["Throw build failure error"] +D --> |Yes| F["Check if version already exists on PyPI"] +F --> |Exists| G["Skip publishing"] +F --> |Not Exists| H["Use Twine to upload to PyPI"] +H --> I["Mark publish as successful"] +``` + +Chart Sources + +- [pyproject.toml](file://pyproject.toml) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) + +Section Sources + +- [pyproject.toml](file://pyproject.toml) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) + +### CI/CD Pipeline + +- Publish Pipeline + - Trigger: Push to `main` or `next` branch + - Steps: Install Python and Node.js, install pnpm, install dependencies, build frontend and backend, upload to PyPI, create Tag and Release +- Lint Pipeline + - Trigger: Push and Pull Requests + - Steps: Install Python and Node.js, install dependencies, run Lint tasks + +```mermaid +sequenceDiagram +participant Push as "Push Event" +participant PubWF as "Publish Pipeline" +participant LintWF as "Lint Pipeline" +participant PyPI as "PyPI" +participant GH as "GitHub" +Push->>PubWF : Trigger publish +PubWF->>PubWF : Install dependencies / build +PubWF->>PyPI : Upload package +PubWF->>GH : Create Tag and Release +Push->>LintWF : Trigger Lint +LintWF->>LintWF : Run code style and static checks +``` + +Chart Sources + +- [.github/workflows/publish.yaml](file://.github/workflows/publish.yaml) +- [.github/workflows/lint.yaml](file://.github/workflows/lint.yaml) + +Section Sources + +- [.github/workflows/publish.yaml](file://.github/workflows/publish.yaml) +- [.github/workflows/lint.yaml](file://.github/workflows/lint.yaml) + +### Version and Changelog Management + +- Changesets + - Uses Changesets for version bumping and changelog generation, combined with scripts to automatically execute version updates and fixes in CI. +- Tags and Releases + - After a successful release, scripts generate unified Release content from the root and sub-package changelogs, create a Git Tag, and push to remote. + +Section Sources + +- [package.json](file://package.json) +- [scripts/create-tag-n-release.mts](file://scripts/create-tag-n-release.mts) + +## Dependency Analysis + +- Frontend Dependencies + - React and Svelte ecosystems, Ant Design and Ant Design X, Monaco Editor, Mermaid, etc., form the core capabilities of the component library. +- Build Tools + - Vite, @vitejs/plugin-react-swc, Babel, Rollup (driven by Vite) +- Python Dependencies + - Gradio as the runtime framework, Hatchling for building, Twine for uploading + +```mermaid +graph LR +FE["Frontend Build"] --> Vite["Vite"] +FE --> Babel["Babel"] +FE --> Rollup["Rollup"] +BE["Backend Build"] --> Hatch["Hatchling"] +BE --> Gradio["Gradio"] +Pub["Release"] --> Twine["Twine"] +Pub --> PyPI["PyPI"] +``` + +Chart Sources + +- [frontend/package.json](file://frontend/package.json) +- [pyproject.toml](file://pyproject.toml) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) + +Section Sources + +- [frontend/package.json](file://frontend/package.json) +- [pyproject.toml](file://pyproject.toml) + +## Performance Considerations + +- Frontend Bundle Optimization + - Externalization strategy: Externalizes large dependencies such as React and Ant Design to reduce bundle size and duplicate bundling. + - AST transformation: The plugin transforms imports/exports to global access at build time, avoiding redundant runtime logic. + - On-demand loading: Combined with Gradio's loading mechanism, component assets are only loaded when needed. +- Build Efficiency + - Disabling the documentation generation build option can significantly reduce frontend build time. + - Using pnpm workspaces to unify dependencies reduces disk usage and installation time. +- Python Package Size + - Only package the necessary templates and assets to avoid unnecessary files entering the distribution package. + +Section Sources + +- [frontend/plugin.js](file://frontend/plugin.js) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [package.json](file://package.json) +- [pyproject.toml](file://pyproject.toml) + +## Troubleshooting Guide + +- Build Failure + - Symptom: `dist/` not generated or build errors + - Investigation: Confirm the frontend build script executed, verify Node.js and pnpm versions meet requirements, check dependency installation success + - Reference: Root `package.json` build scripts and frontend `defineConfig` configuration +- PyPI Upload Failure + - Symptom: Twine upload error or version already exists + - Investigation: Check whether `PYPI_TOKEN` is correctly configured, whether the version already exists on PyPI, and network connectivity + - Reference: Version check and upload logic in the publish script +- CI Pipeline Interruption + - Symptom: Lint or publish step fails + - Investigation: Check the corresponding workflow logs, confirm environment variables and permissions, verify trigger conditions + - Reference: `lint` and `publish` workflow configurations +- Documentation and Examples + - Reference: Root README installation and quick start instructions to ensure local development environment and dependency versions are consistent + +Section Sources + +- [package.json](file://package.json) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) +- [.github/workflows/publish.yaml](file://.github/workflows/publish.yaml) +- [.github/workflows/lint.yaml](file://.github/workflows/lint.yaml) +- [README.md](file://README.md) + +## Conclusion + +This guide provides an integrated deployment solution from local to cloud: optimizing bundle size via frontend Vite plugins and externalization strategies, achieving stable Python package publishing with Hatchling and Twine, and completing automated pipelines and version management with GitHub Actions. For production and cloud platform deployments, it is recommended to further optimize loading performance by combining externalization and caching strategies, and to continuously run Lint in CI to maintain quality. + +## Appendix + +### Configuration Methods for Different Deployment Environments + +- Local Development + - Install dependencies: use pnpm to install workspace dependencies + - Start development server: run the Gradio custom component development command + - Reference: Root README development instructions and `package.json` scripts +- Production Environment + - Build artifacts: execute the frontend build script to generate `dist/`, ensure externalized dependencies are available at runtime + - Python package: build with Hatchling, ensure templates and assets are packaged +- Cloud Platform Deployment + - Use CI to trigger the publish pipeline, automatically upload to PyPI and create Tag/Release + - Install the Python package on the target platform and start the application + +Section Sources + +- [README.md](file://README.md) +- [package.json](file://package.json) +- [pyproject.toml](file://pyproject.toml) +- [.github/workflows/publish.yaml](file://.github/workflows/publish.yaml) diff --git a/.wiki/en/Deployment Guide/Environment Configuration.md b/.wiki/en/Deployment Guide/Environment Configuration.md new file mode 100644 index 00000000..0fb2becd --- /dev/null +++ b/.wiki/en/Deployment Guide/Environment Configuration.md @@ -0,0 +1,315 @@ +# Environment Configuration + + +**Files Referenced in This Document** +- [README.md](file://README.md) +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [docs/app.py](file://docs/app.py) +- [frontend/package.json](file://frontend/package.json) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [backend/modelscope_studio/utils/dev/app_context.py](file://backend/modelscope_studio/utils/dev/app_context.py) +- [backend/modelscope_studio/utils/dev/process_links.py](file://backend/modelscope_studio/utils/dev/process_links.py) +- [backend/modelscope_studio/utils/dev/resolve_frontend_dir.py](file://backend/modelscope_studio/utils/dev/resolve_frontend_dir.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is intended for operations personnel and developers, providing environment configuration and deployment best practices for ModelScope Studio, covering configuration essentials for local development, testing, and production environments, including environment variables, dependency management, containerization (Docker/Kubernetes), performance monitoring, log configuration, environment migration and upgrade strategies, as well as deployment differences and considerations across different platforms. + +## Project Structure + +The repository uses a multi-package workspace organization. The backend is published as a Python package, the frontend is built with Svelte + Vite, and the documentation site is started via Gradio CC. Key directories and responsibilities: + +- `backend/modelscope_studio`: Python backend components and utilities +- `frontend`: Frontend components and build configuration +- `docs`: Documentation site and example application +- `config`: Shared Lint and changelog configuration +- Root-level configuration: `pyproject.toml` (Python packaging), `package.json` (Node workspace scripts), `pnpm-workspace.yaml` (workspace definition) + +```mermaid +graph TB +A["Root Directory"] --> B["backend/modelscope_studio
Python Package and Components"] +A --> C["frontend
Svelte/Vite Frontend"] +A --> D["docs
Gradio CC Documentation Site"] +A --> E["config
Shared Configuration"] +A --> F["pyproject.toml
Python Packaging and Metadata"] +A --> G["package.json
Node Workspace Scripts"] +A --> H["pnpm-workspace.yaml
Workspace and Build-only Dependencies"] +``` + +**Chart Sources** + +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) + +**Section Sources** + +- [README.md](file://README.md) +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) + +## Core Components + +- Python Packaging and Distribution: Built using Hatchling, including a backend component template manifest and packaging targets +- Node Workspace: Unified scripts and dependency management, supporting parallel development across multiple sub-packages +- Documentation Site: `docs/app.py` based on Gradio CC, providing visual documentation for components and layout templates +- Frontend Build: Vite + React SWC plugin, combined with custom plugins and Svelte preprocessing + +**Section Sources** + +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [docs/app.py](file://docs/app.py) +- [frontend/package.json](file://frontend/package.json) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) + +## Architecture Overview + +The diagram below shows the key path from development to runtime: local development starts `docs/app.py` via Gradio CC; the build phase is completed jointly by frontend Vite and backend packaging; at runtime, the Python backend and frontend static assets collaborate to serve the application. + +```mermaid +graph TB +Dev["Developer"] --> CC["Gradio CC Development Server
docs/app.py"] +CC --> FE["Frontend Build
Vite + Plugins"] +FE --> Dist["Static Asset Artifacts"] +CC --> Py["Python Backend Components
modelscope_studio"] +Py --> Serve["Service Startup and Page Rendering"] +Dist --> Serve +``` + +**Chart Sources** + +- [docs/app.py](file://docs/app.py) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [frontend/package.json](file://frontend/package.json) +- [pyproject.toml](file://pyproject.toml) + +## Detailed Component Analysis + +### Environment Variables and Runtime Parameters + +- The documentation site's default concurrency and thread count are set at the entry point and can be adjusted to fit the throughput and resource limits of different environments +- Development mode is triggered via environment variables to enable Gradio Watch Module for hot reloading and debugging + +Recommended environment variables and purposes (examples, not fixed values): + +- `GRADIO_WATCH_MODULE_NAME`: Used to enable development listening +- `PYTHONPATH` or workspace path: Ensures Python can import backend packages +- `NODE_ENV`: Controls frontend build mode (development/production) +- `PORT`/`APP_HOST`: Service listening address and port (if customization is needed) + +**Section Sources** + +- [docs/app.py](file://docs/app.py) +- [package.json](file://package.json) + +### Dependency Management Strategy + +- Python Dependencies + - Core dependency: Gradio version range constraints + - Packaging and distribution: Hatchling + hatch-requirements-txt + - Template manifest: The build phase includes a large number of frontend template directories to ensure complete artifacts +- Node.js Dependencies + - Workspace: pnpm workspace + build-only dependency declarations + - Scripts: Unified commands for building, developing, formatting, checking, etc. + - Frontend dependencies: React, Svelte, Ant Design, Monaco Editor, etc. +- Workspace Configuration + - `pnpm-workspace.yaml` defines `packages` and `onlyBuiltDependencies`, reducing unnecessary build overhead + +**Section Sources** + +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [frontend/package.json](file://frontend/package.json) + +### Containerized Deployment (Docker and Kubernetes) + +The following are general practice steps; specific images and orchestration need to be customized according to the actual environment: + +- Docker Build Process + - Base image: Select a base image containing Python and Node + - Install dependencies: Install system dependencies first, then Python and Node dependencies + - Build backend: Install the backend package with pip or in editable mode + - Build frontend: Execute the frontend build script to generate static assets + - Run: Start the Python service and serve static assets +- Kubernetes Deployment + - Use Deployments to manage Pod replicas + - Use Services to expose the service + - Use ConfigMap/Secret to manage environment variables and sensitive information + - Use PersistentVolume/PVC to store logs and temporary files (if needed) + - Health checks: Configure liveness/readiness probes + - Resource limits: Set CPU/memory requests and limits based on concurrency and thread configuration + +[This section provides general practice guidance and does not analyze specific files, so there are no "Section Sources"] + +### Performance Monitoring and Log Configuration + +- Performance Monitoring + - At the Python level: Record request latency, queue length, concurrency limits, and other metrics + - At the frontend level: Monitor first contentful paint time, resource load time, error rate + - At the container level: Collect CPU/memory/network metrics, combined with logs for correlation analysis +- Log Configuration + - Python: Use the standard logging module, output to stdout/stderr based on environment, combined with container log collection + - Frontend: Avoid outputting excessive debug logs in production; use conditional logging when necessary + - Documentation site: Note the impact of concurrency and thread configuration on resource usage + +[This section provides general practice guidance and does not analyze specific files, so there are no "Section Sources"] + +### Environment Migration and Upgrade + +- Python Upgrade + - Update Python version requirements and dependency version ranges to ensure compatibility + - Repackage and verify build artifact completeness +- Node Upgrade + - Update Node version and dependencies, run lint and type checks + - Rebuild frontend and verify static asset availability +- Documentation Site Upgrade + - Update Gradio CC version and related dependencies + - Verify rendering consistency of each component and layout template +- Migration Strategy + - Small steps: Gradually replace old components and templates + - Rollback plan: Keep the previous version's image and configuration to ensure fast rollback + - Data and configuration: Ensure backward compatibility of environment variables and configuration files + +[This section provides general practice guidance and does not analyze specific files, so there are no "Section Sources"] + +### Deployment Differences and Considerations Across Platforms + +- Local Development + - Use Gradio CC's development server with hot reloading enabled + - Pay attention to cross-platform path and permission issues +- Testing Environment + - Independent services and storage isolated from production + - Strictly control concurrency and thread count to simulate real load +- Production Environment + - Use stable versions and long-term support base images + - Configure health checks and auto-scaling + - Strict logging and monitoring strategies + +[This section provides general practice guidance and does not analyze specific files, so there are no "Section Sources"] + +## Dependency Analysis + +- Python Side + - Dependencies: Gradio version range constraints + - Packaging: Hatchling build, `artifacts` list contains a large number of frontend template directories +- Node Side + - Workspace: `packages` and `onlyBuiltDependencies` + - Scripts: Unified build, development, formatting, and check commands + - Frontend dependencies: React, Svelte, Ant Design, Monaco Editor, etc. + +```mermaid +graph LR +P["pyproject.toml
Python Dependencies and Packaging"] --> B["Backend Components
modelscope_studio"] +N["package.json
Node Scripts and Dependencies"] --> F["Frontend Build
Vite + Plugins"] +W["pnpm-workspace.yaml
Workspace and Build-only Dependencies"] --> N +F --> R["Static Asset Artifacts"] +B --> R +``` + +**Chart Sources** + +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) + +**Section Sources** + +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [frontend/package.json](file://frontend/package.json) + +## Performance Considerations + +- Concurrency and Threads + - The documentation site entry point sets default concurrency and maximum thread count; these should be tuned based on hardware and business load +- Build Optimization + - Use pnpm and `onlyBuiltDependencies` to reduce unnecessary dependency builds + - Set the frontend build target to `modules` for improved compatibility and loading efficiency +- Resources and Caching + - Place static assets on CDN or reverse proxy caching + - Control template and asset size to avoid redundant files in artifacts + +**Section Sources** + +- [docs/app.py](file://docs/app.py) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) + +## Troubleshooting Guide + +- Documentation Site Cannot Start or Page is Blank + - Check whether `GRADIO_WATCH_MODULE_NAME` is correctly set to enable development listening + - Confirm the backend package is correctly installed and can be imported +- Frontend Build Failure + - Check whether Node version and dependencies meet requirements + - Clear `node_modules` and build cache, then retry +- Link and Resource 404 + - Confirm static asset paths are consistent with service routes + - Check link transformation logic and resource cache path mapping +- Development Context Missing Warning + - Ensure the `Application` component is used at the top level to avoid empty runtime context + +```mermaid +flowchart TD +Start(["Start Troubleshooting"]) --> CheckEnv["Check environment variables and dependency versions"] +CheckEnv --> BuildFE["Execute frontend build and view errors"] +BuildFE --> FixFE["Fix frontend dependencies or build config"] +CheckEnv --> RunDocs["Start documentation site and observe behavior"] +RunDocs --> FixDocs["Fix runtime parameters and concurrency settings"] +FixFE --> Verify["Verify static asset availability"] +FixDocs --> Verify +Verify --> End(["End"]) +``` + +**Chart Sources** + +- [docs/app.py](file://docs/app.py) +- [package.json](file://package.json) +- [backend/modelscope_studio/utils/dev/process_links.py](file://backend/modelscope_studio/utils/dev/process_links.py) +- [backend/modelscope_studio/utils/dev/app_context.py](file://backend/modelscope_studio/utils/dev/app_context.py) + +**Section Sources** + +- [docs/app.py](file://docs/app.py) +- [backend/modelscope_studio/utils/dev/process_links.py](file://backend/modelscope_studio/utils/dev/process_links.py) +- [backend/modelscope_studio/utils/dev/app_context.py](file://backend/modelscope_studio/utils/dev/app_context.py) + +## Conclusion + +With clear environment variables and runtime parameters, standardized dependency management and workspace configuration, scalable containerization and monitoring strategies, and rigorous migration and upgrade processes, ModelScope Studio can run stably in different environments. It is recommended to prioritize controlled versions and a comprehensive observability system in production environments, and to continuously optimize build and runtime performance. + +## Appendix + +- Quick Start and Development + - Install backend and frontend dependencies and execute the build + - Use Gradio CC to start the documentation site for development and debugging +- Reference Commands + - Backend installation and build: See root-level README installation and development instructions + - Frontend installation and build: See scripts in `package.json` and dependencies in `frontend/package.json` + +**Section Sources** + +- [README.md](file://README.md) +- [package.json](file://package.json) +- [frontend/package.json](file://frontend/package.json) diff --git a/.wiki/en/Deployment Guide/Release Process.md b/.wiki/en/Deployment Guide/Release Process.md new file mode 100644 index 00000000..9aae0662 --- /dev/null +++ b/.wiki/en/Deployment Guide/Release Process.md @@ -0,0 +1,441 @@ +# Release Process + + +**Files Referenced in This Document** +- [publish.yaml](file://.github/workflows/publish.yaml) +- [lint.yaml](file://.github/workflows/lint.yaml) +- [pyproject.toml](file://pyproject.toml) +- [package.json](file://package.json) +- [publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) +- [create-tag-n-release.mts](file://scripts/create-tag-n-release.mts) +- [.changeset/config.json](file://.changeset/config.json) +- [.changeset/pre.json](file://.changeset/pre.json) +- [version.py](file://backend/modelscope_studio/version.py) +- [CHANGELOG.md](file://CHANGELOG.md) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [index.ts](file://config/changelog/src/index.ts) +- [package.json](file://config/changelog/package.json) +- [frontend/package.json](file://frontend/package.json) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This document is intended for maintainers and senior developers who need to manage the release of the ModelScope Studio project. It systematically explains the complete process from local development to official PyPI release (including pre-releases and hotfixes), covering version management, changelog generation, automated pipelines, quality assurance, and rollback strategies. The content is based on existing release scripts, GitHub Actions workflows, and changeset configurations within the repository, ensuring it is actionable, traceable, and reproducible. + +## Project Structure + +ModelScope Studio uses a multi-package workspace (pnpm workspace) organization, with the root directory containing Python package metadata and frontend component source code. Key locations related to releases: + +- Root-level package metadata and build configuration: `pyproject.toml` +- Release scripts and workflows: `scripts/` and `.github/workflows/` +- Changeset and changelog generator: `.changeset/` and `config/changelog/` +- Version number sources: `backend/modelscope_studio/version.py` and each package's `package.json` +- Workspace definition: `pnpm-workspace.yaml` + +```mermaid +graph TB +A["Root Workspace
pnpm-workspace.yaml"] --> B["Python Package
pyproject.toml"] +A --> C["Frontend Package
frontend/package.json"] +A --> D["Changelog Generator
config/changelog/"] +A --> E["Release Scripts
scripts/"] +A --> F["GitHub Actions
.github/workflows/"] +B --> G["Version Source
backend/modelscope_studio/version.py"] +D --> H["Changeset Config
.changeset/config.json"] +D --> I[".changeset/pre.json"] +``` + +Chart Sources + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +Section Sources + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +## Core Components + +- Version and Metadata + - Python package version and metadata are provided by `pyproject.toml`; the Python module version is also maintained synchronously in `backend/modelscope_studio/version.py`. + - Frontend package and sub-package versions are declared in their respective `package.json` files. +- Changesets and Changelogs + - Uses Changesets to manage cross-package versions and change summaries, classifying changes and writing them to each package's `CHANGELOG.md` via a custom changelog generator. +- Automated Release Pipeline + - GitHub Actions triggers when a "version update" commit is detected on the main or next branch, executes build and release, and upon success, creates a tag and GitHub Release. +- Release Scripts + - `scripts/publish-to-pypi.mts` checks whether the version already exists, builds artifacts, and uploads to PyPI. + - `scripts/create-tag-n-release.mts` generates merged changelogs, creates a tag, and creates a Release. + +Section Sources + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +## Architecture Overview + +The diagram below shows the overall flow from code commit to PyPI publishing and GitHub Release, including version checking, building, uploading, tagging, and releasing. + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Repo as "Repository (main/next)" +participant GH as "GitHub Actions" +participant Script as "Release Script
publish-to-pypi.mts" +participant PyPI as "PyPI" +participant Tag as "Tag and Release
create-tag-n-release.mts" +Dev->>Repo : Push commit with "version update" +Repo-->>GH : Trigger publish workflow +GH->>Script : Execute build and release +Script->>PyPI : Check version and upload +PyPI-->>Script : Return publish result +Script-->>GH : Output published marker +GH->>Tag : If published, create tag and Release +Tag-->>Repo : Push tag and release notes +``` + +Chart Sources + +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +Section Sources + +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +## Detailed Component Analysis + +### Component 1: Version and Metadata Management + +- Python Package Version and Metadata + - `pyproject.toml` defines the package name, version, license, dependencies, and build targets, with clearly defined wheel and sdist packaging scope. + - `backend/modelscope_studio/version.py` serves as the Python module version entry point and must stay consistent with the `pyproject.toml` version. +- Frontend and Sub-package Versions + - Each package's `package.json` (such as `frontend/package.json`) declares an independent version, facilitating coordinated multi-package releases. +- Workspace and Multi-package + - `pnpm-workspace.yaml` explicitly includes root, `config/*`, `frontend`, and its sub-packages, ensuring release scripts can correctly resolve package metadata. + +```mermaid +flowchart TD +Start(["Start"]) --> ReadMeta["Read package metadata
pyproject.toml / package.json"] +ReadMeta --> CompareVer{"Version consistency check"} +CompareVer --> |Inconsistent| FixVer["Synchronize versions"] +CompareVer --> |Consistent| Next["Enter changeset flow"] +FixVer --> Next +Next --> End(["End"]) +``` + +Chart Sources + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) + +Section Sources + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) + +### Component 2: Changesets and Changelog Generation + +- Changesets Configuration + - `.changeset/config.json` specifies using a custom changelog generator and repository information, disables commit recording, and sets the base branch to `main`. + - `.changeset/pre.json` defines the pre-release mode and initial version mapping, supporting pre-releases with the `beta` tag. +- Custom Changelog Generator + - `index.ts` implements `getReleaseLine` and `getDependencyReleaseLine`, classifying changes by `feat`/`fix`/`chore`, extracting PR/Commit/User information, and writing to each package's `CHANGELOG.md`. +- Generation Flow + - The `version` script in `package.json` calls `changeset version` and fixes changelogs, then builds the changelog package. + +```mermaid +flowchart TD +CS["Changeset Summary"] --> Parse["Parse summary
PR/Commit/User/Type"] +Parse --> Classify{"Classify feat/fix/chore"} +Classify --> Write["Write to each package's CHANGELOG.md"] +Write --> Done["Done"] +``` + +Chart Sources + +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [package.json:1-55](file://package.json#L1-L55) +- [config/changelog/package.json:1-32](file://config/changelog/package.json#L1-L32) + +Section Sources + +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [package.json:1-55](file://package.json#L1-L55) +- [config/changelog/package.json:1-32](file://config/changelog/package.json#L1-L32) + +### Component 3: PyPI Release Script + +- Functional Responsibilities + - `publish-to-pypi.mts` checks whether the same version already exists on PyPI before releasing, to avoid duplicate uploads; then executes installation and build, and finally uploads via `twine`. +- Key Logic + - Uses `@manypkg/get-packages` to obtain workspace package metadata and read the root package version. + - Queries the PyPI JSON API to check whether the version exists; if it does, skips. + - Checks the existence of the `dist` directory after building before uploading. + - Sets the GitHub Actions output variable `published=true` for subsequent steps to use. + +```mermaid +flowchart TD +S(["Start"]) --> Check["Query PyPI for existing version"] +Check --> Exists{"Exists?"} +Exists --> |Yes| Skip["Skip publish and output marker"] +Exists --> |No| Build["Install and build"] +Build --> Dist{"dist exists?"} +Dist --> |No| Fail["Throw build failure error"] +Dist --> |Yes| Upload["twine upload"] +Upload --> SetOut["Set published=true"] +Skip --> End(["End"]) +SetOut --> End +Fail --> End +``` + +Chart Sources + +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +Section Sources + +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +### Component 4: Tag and Release Creation + +- Functional Responsibilities + - `create-tag-n-release.mts` aggregates change descriptions for the current version from the root and sub-package `CHANGELOG.md` files, creates a Git tag and pushes it, then calls the GitHub API to create a Release. +- Key Logic + - Parses `CHANGELOG.md`, extracts the entry for the corresponding version number, and concatenates it into the Release Body. + - Uses the GitHub Token to call `createRelease`; decides whether to mark as pre-release based on whether the version number contains a hyphen. + - Configures Git username and email to ensure tags are pushed to the remote. + +```mermaid +flowchart TD +R(["Start"]) --> ReadCL["Read root and sub-package CHANGELOG.md"] +ReadCL --> Merge["Aggregate into Release Body"] +Merge --> Tag["Create v tag and push"] +Tag --> Release["Call GitHub API to create Release"] +Release --> DoneR(["End"]) +``` + +Chart Sources + +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) +- [CHANGELOG.md:1-200](file://CHANGELOG.md#L1-L200) + +Section Sources + +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) +- [CHANGELOG.md:1-200](file://CHANGELOG.md#L1-L200) + +### Component 5: GitHub Actions Publish Pipeline + +- Trigger Conditions + - Triggers on push to `main` or `next` branch with a commit message matching "version update". +- Step Description + - Install Python and Node.js dependencies; pnpm installs frontend dependencies. + - Execute the publish script `pnpm run ci:publish`, passing in `PYPI_TOKEN`. + - If publish succeeds, execute `pnpm run ci:create-tag-n-release`, passing in `GITHUB_TOKEN`, `REPO`, and `OWNER`. + +```mermaid +sequenceDiagram +participant Push as "Push (main/next)" +participant WF as "publish workflow" +participant Steps as "Steps" +participant Pub as "ci:publish" +participant Tag as "ci:create-tag-n-release" +Push->>WF : Trigger +WF->>Steps : Checkout code / set up environment +Steps->>Pub : Execute publish +Pub-->>Steps : Output published=true +Steps->>Tag : Create tag and Release +``` + +Chart Sources + +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) + +Section Sources + +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) + +## Dependency Analysis + +- Package Version Sources and Consistency + - Root package version is jointly constrained by `pyproject.toml` and `backend/modelscope_studio/version.py`; frontend and sub-package versions are constrained by their respective `package.json`. +- Release Script Dependencies on Workspace + - Both `publish-to-pypi.mts` and `create-tag-n-release.mts` read workspace package information via `@manypkg/get-packages`, ensuring unified multi-package versions and changelogs. +- Changelog Generator Dependencies on Changesets + - `index.ts` depends on `@changesets/get-github-info` and `@manypkg/get-packages` to transform changesets into `CHANGELOG.md`. + +```mermaid +graph LR +P["pyproject.toml"] --> V["backend/modelscope_studio/version.py"] +P --> S1["scripts/publish-to-pypi.mts"] +F["frontend/package.json"] --> S1 +Cfg["config/changelog/src/index.ts"] --> CL["CHANGELOG.md"] +Pre["changeset/pre.json"] --> CL +W["pnpm-workspace.yaml"] --> S1 +W --> S2["scripts/create-tag-n-release.mts"] +``` + +Chart Sources + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +Section Sources + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +## Performance Considerations + +- Publish Pipeline Concurrency and Timeout + - The workflow enables concurrency groups and cancellation strategies to avoid multiple releases on the same branch interfering with each other; single job timeout is generous to accommodate large build needs. +- Build and Upload Efficiency + - The release script checks whether the version exists before uploading to avoid duplicate uploads; the build phase only continues when `dist` exists, reducing invalid I/O. +- Multi-package Workspace + - Reads all package metadata at once via `@manypkg/get-packages`, reducing multiple I/O overhead. + +Section Sources + +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) + +## Troubleshooting Guide + +- Publish Skipped + - Symptom: Log shows version already exists on PyPI, publish skipped. + - Investigation: Confirm whether the version number was correctly incremented; check whether `PYPI_TOKEN` is valid. + - Reference: Version check logic in the publish script. +- Build Failure + - Symptom: `dist` directory does not exist, causing build failure. + - Investigation: Check the build command and dependency installation; confirm Node.js and pnpm versions meet requirements. + - Reference: Build and validation steps in the publish script. +- Tag and Release Creation Failure + - Symptom: Cannot create Release or tag was not pushed. + - Investigation: Confirm `GITHUB_TOKEN` permissions; check whether `CHANGELOG.md` contains the corresponding version entry; confirm branch protection rules allow tag pushes. + - Reference: Tag and Release creation script. +- Changelog Missing + - Symptom: Release Body is empty or some packages are not included in the change. + - Investigation: Confirm changeset summary format is standardized; check initial version mapping in `pre.json`; verify the changelog generator correctly writes to each package's `CHANGELOG.md`. +- Pre-release vs Official Release + - Symptom: Release not marked as pre-release. + - Investigation: Confirm the version number contains a hyphen; check the `tag` configuration and initial version mapping in `pre.json`. + +Section Sources + +- [publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) + +## Conclusion + +This release system uses Changesets as the core to coordinate multi-package versions and changelogs, combined with GitHub Actions to automate building, uploading, and releasing. Through version checks, tag, and Release creation scripts, the release process is traceable and reversible. It is recommended to strictly follow version management and changelog specifications before each release to maintain high-quality delivery. + +## Appendix + +### A. Version Control and Semantic Versioning Best Practices + +- Semantic Versioning + - Major version: Breaking changes + - Minor version: Backwards-compatible feature additions + - Patch version: Backwards-compatible bug fixes +- Pre-release + - Use the `beta` tag in `pre.json` for pre-releases; versions containing hyphens are automatically marked as pre-releases. +- Hotfix + - Fix directly on the `main` branch and create a patch version; if prior validation is needed, pre-release on the `next` branch first. + +Section Sources + +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +### B. Pre-release Checklist + +- Version Consistency + - `pyproject.toml` and `backend/modelscope_studio/version.py` versions are consistent; each package's `package.json` versions are consistent. +- Changelog + - Changeset has been run and corresponding summaries have been generated; each package's `CHANGELOG.md` contains the current version entry. +- Local Build + - Build executed locally and basic functional tests passed. +- Secrets and Permissions + - `PYPI_TOKEN` and `GITHUB_TOKEN` are valid with correct permissions. +- Branch and Commit + - Push branch is `main` or `next`; commit message contains "version update". + +Section Sources + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) + +### C. Configuration for Different Release Scenarios + +- Official Release + - Push a "version update" commit on the `main` branch to trigger the release pipeline; version number does not contain a hyphen, Release is marked as official. +- Pre-release + - Use the `beta` tag in `pre.json`; version number contains a hyphen, Release is marked as pre-release. +- Hotfix + - Create a patch version directly on the `main` branch; if prior validation is needed, pre-release on the `next` branch first, then merge. + +Section Sources + +- [publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) diff --git a/.wiki/en/Development Guide/Build and Deploy.md b/.wiki/en/Development Guide/Build and Deploy.md new file mode 100644 index 00000000..d6ebc8d1 --- /dev/null +++ b/.wiki/en/Development Guide/Build and Deploy.md @@ -0,0 +1,370 @@ +# Build and Deploy + + +**Files referenced in this document** +- [package.json](file://package.json) +- [pyproject.toml](file://pyproject.toml) +- [pnpm-workspace.yaml](file://pnpm-workspace.yaml) +- [frontend/package.json](file://frontend/package.json) +- [frontend/defineConfig.js](file://frontend/defineConfig.js) +- [frontend/plugin.js](file://frontend/plugin.js) +- [.github/workflows/publish.yaml](file://.github/workflows/publish.yaml) +- [scripts/publish-to-pypi.mts](file://scripts/publish-to-pypi.mts) +- [scripts/create-tag-n-release.mts](file://scripts/create-tag-n-release.mts) +- [backend/modelscope_studio/version.py](file://backend/modelscope_studio/version.py) +- [config/changelog/src/index.ts](file://config/changelog/src/index.ts) +- [config/changelog/tsup.config.ts](file://config/changelog/tsup.config.ts) +- [.changeset/config.json](file://.changeset/config.json) +- [.changeset/pre.json](file://.changeset/pre.json) +- [README.md](file://README.md) +- [docs/requirements.txt](file://docs/requirements.txt) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This guide covers the build and release process for ModelScope Studio, including the following topics: + +- Frontend build configuration and bundling strategy (Vite plugins, externalization and aliases) +- Python package build and distribution (Hatch configuration, wheel/sdist artifact manifest) +- Version management and changesets (Changesets, pre-release tags, automated changelog generation) +- Automated release pipeline (PyPI release, GitHub tags and Release creation) +- Deployment best practices and considerations +- Dependency update and compatibility handling recommendations + +## Project Structure + +The repository uses a multi-package workspace organization, containing root-level packages, frontend sub-packages, and configuration packages: + +- Root package: Provides build scripts, changeset configuration, and release scripts +- Frontend workspace: Contains component packages such as antd, antdx, base, pro +- Configuration packages: Changelog generator and Lint configuration +- Backend Python package: Built via Hatch and packaged as wheel/sdist + +```mermaid +graph TB +Root["Root Package
package.json, pyproject.toml"] --> Frontend["Frontend Workspace
frontend/*"] +Root --> Config["Config Packages
config/changelog"] +Root --> Scripts["Release Scripts
scripts/*"] +Frontend --> Antd["antd component package"] +Frontend --> Antdx["antdx component package"] +Frontend --> Base["base component package"] +Frontend --> Pro["pro component package"] +Root --> Backend["Backend Python Package
backend/modelscope_studio"] +``` + +**Diagram Sources** + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [package.json:1-55](file://package.json#L1-L55) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) + +**Section Sources** + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [package.json:1-55](file://package.json#L1-L55) +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) + +## Core Components + +- Frontend Vite build plugin: Handles React/Svelte preprocessing, global variable injection, and externalization strategy +- Python package build system: Based on Hatch, defining artifacts, wheel/sdist packaging scope, and optional dependencies +- Changesets and changelog: Changesets-driven version and log generation, supporting multi-package unified management +- Automated release pipeline: GitHub Actions triggers builds, PyPI releases, and GitHub Release creation + +**Section Sources** + +- [frontend/plugin.js:1-168](file://frontend/plugin.js#L1-L168) +- [frontend/defineConfig.js:1-19](file://frontend/defineConfig.js#L1-L19) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [config/changelog/src/index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) + +## Architecture Overview + +The diagram below shows the overall process from local development to automated release: + +```mermaid +sequenceDiagram +participant Dev as "Developer" +participant Root as "Root Package Scripts
package.json" +participant FE as "Frontend Build
Vite Plugin" +participant PY as "Python Build
Hatch" +participant TW as "Twine Release" +participant GH as "GitHub Actions" +participant Repo as "PyPI Repository" +Dev->>Root : Run build/version commands +Root->>FE : pnpm run build +FE-->>Root : Output dist/ frontend assets +Root->>PY : pnpm run build (backend) +PY-->>Root : Output wheel/sdist +Root->>TW : pnpm run ci:publish +TW->>Repo : Upload wheel/sdist +GH->>Root : Trigger release pipeline +Root->>GH : Create tags and Release +``` + +**Diagram Sources** + +- [package.json:8-25](file://package.json#L8-L25) +- [frontend/defineConfig.js:1-19](file://frontend/defineConfig.js#L1-L19) +- [frontend/plugin.js:41-76](file://frontend/plugin.js#L41-L76) +- [pyproject.toml:45-257](file://pyproject.toml#L45-L257) +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [scripts/publish-to-pypi.mts:22-55](file://scripts/publish-to-pypi.mts#L22-L55) + +## Detailed Component Analysis + +### Frontend Build and Bundling + +- Build entry and plugin chain + - Uses Vite plugin combination: React SWC and custom ModelScopeStudioVitePlugin + - Defines global variable mappings, externalizing common dependencies to host environment (e.g., `window.ms_globals.React`) + - Supports excluding certain externalized items on-demand, for inlining in specific scenarios +- Aliases and preprocessing + - Points to `utils/globals` directory via aliases to simplify import paths + - Disables Svelte preprocessing to avoid conflicts with existing solutions +- Production environment optimization + - Sets `NODE_ENV` to `production` during the build stage + - Performs AST transformation on exported modules, rewriting imports/exports to global object access to reduce bundle size + +```mermaid +flowchart TD +Start(["Start"]) --> DefineCfg["Load defineConfig options"] +DefineCfg --> UsePlugins["Enable React + ModelScopeStudioVitePlugin"] +UsePlugins --> ResolveAlias["@utils/@globals alias resolution"] +ResolveAlias --> Externalize{"Externalization enabled?"} +Externalize --> |Yes| RollupExt["Rollup externalize global mappings"] +Externalize --> |No| SkipExt["Skip externalization"] +RollupExt --> Transform["AST transformation: map imports/exports to globals"] +SkipExt --> Transform +Transform --> BuildOut["Output production build artifacts"] +BuildOut --> End(["End"]) +``` + +**Diagram Sources** + +- [frontend/defineConfig.js:8-18](file://frontend/defineConfig.js#L8-L18) +- [frontend/plugin.js:41-76](file://frontend/plugin.js#L41-L76) +- [frontend/plugin.js:77-165](file://frontend/plugin.js#L77-L165) + +**Section Sources** + +- [frontend/defineConfig.js:1-19](file://frontend/defineConfig.js#L1-L19) +- [frontend/plugin.js:1-168](file://frontend/plugin.js#L1-L168) + +### Python Package Build and Distribution + +- Build backend Python package + - Uses Hatchling as build backend, reading metadata and dependencies from `pyproject.toml` + - Specifies `artifacts` list to ensure templates and static assets are included in the wheel + - Target directories and exclusion rules for wheel/sdist are clearly defined to avoid redundant files in release packages +- Dependencies and compatibility + - Manages dependencies and README rendering via `hatch-requirements-txt` and `hatch-fancy-pypi-readme` + - Python version requirements and classifier declarations are clear, facilitating PyPI display and installer recognition +- Version consistency + - Root package and backend versions are kept in sync to avoid mismatches during release + +```mermaid +flowchart TD +A["Read pyproject.toml"] --> B["Hatchling Build"] +B --> C{"Target type?"} +C --> |wheel| D["Package as wheel
including artifacts"] +C --> |sdist| E["Package as sdist
including backend/modelscope_studio"] +D --> F["Verify artifact integrity"] +E --> F +F --> G["Upload to PyPI via Twine"] +``` + +**Diagram Sources** + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) + +**Section Sources** + +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) +- [backend/modelscope_studio/version.py:1-2](file://backend/modelscope_studio/version.py#L1-L2) + +### Version Management and Changelog + +- Changesets configuration + - Uses custom changelog generator, supporting PR/Commit/user link parsing + - Unified version baseline and pre-release tags (beta), facilitating preview and rollback +- Changelog generation + - Compiles configuration package via tsup, outputting both esm/cjs formats + - Changelog generator aggregates CHANGELOGs from each package and writes to a temporary state file, ultimately driven by the root package to generate unified release content +- Pre-release mode + - `pre.json` specifies pre-release tags and initial version, working with Changesets workflow for canary releases + +```mermaid +flowchart TD +CS["Changesets commit"] --> Gen["Run version script"] +Gen --> Changelog["Generate/update changelog"] +Changelog --> Pre["Pre-release tag (beta)"] +Pre --> Release["Trigger release pipeline"] +``` + +**Diagram Sources** + +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [config/changelog/src/index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [config/changelog/tsup.config.ts:1-21](file://config/changelog/tsup.config.ts#L1-L21) + +**Section Sources** + +- [.changeset/config.json:1-15](file://.changeset/config.json#L1-L15) +- [.changeset/pre.json:1-16](file://.changeset/pre.json#L1-L16) +- [config/changelog/src/index.ts:1-222](file://config/changelog/src/index.ts#L1-L222) +- [config/changelog/tsup.config.ts:1-21](file://config/changelog/tsup.config.ts#L1-L21) + +### Automated Release Pipeline + +- Trigger conditions + - Push to `main`/`next` branch with commit message "chore: update versions" +- Step breakdown + - Install Python and Node dependencies, prepare build environment + - Execute build: pip editable mode install, pnpm run build + - Check if `dist` exists to prevent continuing release after build failure + - Use Twine to upload all artifacts in `dist` to PyPI (with skip-existing) + - If release succeeds, call script to create Git tag and push, then create Release on GitHub with content from changelog + +```mermaid +sequenceDiagram +participant WF as "GitHub Actions" +participant Build as "Build Step" +participant Check as "Version Check" +participant Upload as "Twine Upload" +participant Tag as "Create Tag and Release" +WF->>Build : Install dependencies and build +Build-->>WF : Output dist/ +WF->>Check : Check if version already exists on PyPI +alt Already exists +Check-->>WF : Skip release +else Does not exist +WF->>Upload : Upload dist/* to PyPI +Upload-->>WF : Release complete +WF->>Tag : Create v tag and release +end +``` + +**Diagram Sources** + +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [scripts/publish-to-pypi.mts:14-55](file://scripts/publish-to-pypi.mts#L14-L55) +- [scripts/create-tag-n-release.mts:80-125](file://scripts/create-tag-n-release.mts#L80-L125) + +**Section Sources** + +- [.github/workflows/publish.yaml:1-74](file://.github/workflows/publish.yaml#L1-L74) +- [scripts/publish-to-pypi.mts:1-60](file://scripts/publish-to-pypi.mts#L1-L60) +- [scripts/create-tag-n-release.mts:1-131](file://scripts/create-tag-n-release.mts#L1-L131) + +## Dependency Analysis + +- Workspace and package relationships + - pnpm-workspace defines the root package and multiple frontend sub-packages, ensuring inter-package sharing and build order + - Root package `package.json` provides unified scripts and dependencies, centralizing build and release tasks +- Frontend dependency externalization strategy + - Maps React, Ant Design, Monaco Editor, etc. to globals via Vite plugin to reduce bundle size + - Supports on-demand exclusion from externalization list to meet different host environment needs +- Python dependencies and compatibility + - Manages dependencies and README rendering via `hatch-requirements-txt` and `hatch-fancy-pypi-readme` + - Constrains Gradio version range to ensure coordination with frontend components + +```mermaid +graph LR +RootPkg["Root package.json"] --> FEWS["pnpm-workspace.yaml"] +FEWS --> FEAntd["@modelscope-studio/antd"] +FEWS --> FEAntdx["@modelscope-studio/antdx"] +FEWS --> FEBase["@modelscope-studio/base"] +FEWS --> FEPro["@modelscope-studio/pro"] +RootPkg --> PyProj["pyproject.toml"] +PyProj --> Artifacts["artifacts list"] +``` + +**Diagram Sources** + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [package.json:1-55](file://package.json#L1-L55) +- [pyproject.toml:45-245](file://pyproject.toml#L45-L245) + +**Section Sources** + +- [pnpm-workspace.yaml:1-12](file://pnpm-workspace.yaml#L1-L12) +- [package.json:1-55](file://package.json#L1-L55) +- [pyproject.toml:1-257](file://pyproject.toml#L1-L257) + +## Performance Considerations + +- Frontend build optimization + - Enable externalization strategy to reduce repeated bundling and size bloat + - AST transformation only applies to export/import statements, avoiding impact on runtime performance + - Force-set `NODE_ENV` in production to ensure minification and Tree-shaking take effect +- Python package size control + - Explicitly define artifacts whitelist to avoid packaging test or source cache files + - Use dual sdist/wheel release for both installer and cache efficiency +- Release process stability + - Check if same version exists on PyPI first to avoid repeated uploads and failed retries + - Use "skip-existing" parameter to reduce network and time overhead + +## Troubleshooting Guide + +- Build failure + - Check if `dist` directory exists; if missing, confirm frontend build scripts and Vite plugin configuration are correct + - Confirm Node and Python environment versions meet requirements +- PyPI release failure + - Verify `PYPI_TOKEN` is configured and network connectivity is normal + - If prompted that version already exists, confirm whether version upgrade or cache clearing is needed +- GitHub Release creation failure + - Check `GITHUB_TOKEN` permissions and REPO/OWNER parameters + - Confirm changelog generation succeeded to avoid empty content causing creation failure +- Dependency conflicts + - Update Gradio version range and frontend dependencies to ensure compatibility + - Use `docs/requirements.txt` to pin example dependency versions for easier reproduction and debugging + +**Section Sources** + +- [scripts/publish-to-pypi.mts:22-55](file://scripts/publish-to-pypi.mts#L22-L55) +- [scripts/create-tag-n-release.mts:88-125](file://scripts/create-tag-n-release.mts#L88-L125) +- [docs/requirements.txt:1-4](file://docs/requirements.txt#L1-L4) + +## Conclusion + +This guide provides a complete path from local development to automated release: the frontend implements externalization and alias optimization through the Vite plugin, the Python package uses Hatch for precise packaging and distribution, versions and changelogs are driven by Changesets, and GitHub Actions completes PyPI releases and GitHub Release creation. Following the steps and best practices in this document can significantly improve build efficiency and release reliability. + +## Appendix + +### Common Build and Release Commands + +- Local development and build + - Run root package build script to generate frontend and backend artifacts + - Documentation site can be started by specifying an entry point +- Version and changelog + - Use Changesets to update version and generate changelog + - Regenerate after fixing changelog format +- Publish to PyPI + - Use CI script to check if version already exists; skip if it does, otherwise build and upload +- Create tags and Releases + - Generate content from changelog, create Git tags and push, then create Release on GitHub + +**Section Sources** + +- [package.json:8-25](file://package.json#L8-L25) +- [README.md:80-101](file://README.md#L80-L101) +- [scripts/publish-to-pypi.mts:44-55](file://scripts/publish-to-pypi.mts#L44-L55) +- [scripts/create-tag-n-release.mts:117-125](file://scripts/create-tag-n-release.mts#L117-L125) diff --git a/.wiki/en/Development Guide/Component Development/Backend Component Development.md b/.wiki/en/Development Guide/Component Development/Backend Component Development.md new file mode 100644 index 00000000..ecfbec16 --- /dev/null +++ b/.wiki/en/Development Guide/Component Development/Backend Component Development.md @@ -0,0 +1,363 @@ +# Backend Component Development + + +**Files Referenced in This Document** +- [backend/modelscope_studio/components/__init__.py](file://backend/modelscope_studio/components/__init__.py) +- [backend/modelscope_studio/components/antd/components.py](file://backend/modelscope_studio/components/antd/components.py) +- [backend/modelscope_studio/components/antdx/components.py](file://backend/modelscope_studio/components/antdx/components.py) +- [backend/modelscope_studio/components/pro/components.py](file://backend/modelscope_studio/components/pro/components.py) +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [backend/modelscope_studio/utils/dev/__init__.py](file://backend/modelscope_studio/utils/dev/__init__.py) +- [backend/modelscope_studio/components/antd/button/__init__.py](file://backend/modelscope_studio/components/antd/button/__init__.py) +- [backend/modelscope_studio/components/antd/form/__init__.py](file://backend/modelscope_studio/components/antd/form/__init__.py) +- [backend/modelscope_studio/components/base/text/__init__.py](file://backend/modelscope_studio/components/base/text/__init__.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This guide is intended for backend component developers and provides a systematic explanation of how to implement Python components under the `backend/modelscope_studio/components/` directory, covering the component class inheritance hierarchy, property definition and validation, events and callbacks, lifecycle hooks, integration with frontend Svelte components, and the data transformation flow from Python to JavaScript. The document also explains how to use the component registration mechanism (`__init__.py` and `components.py`), with concrete implementation steps guided by real file paths. + +## Project Structure + +ModelScope Studio's backend components are organized in a layered and categorized manner: component families include `antd`, `antdx`, `base`, and `pro`; within each family, concrete components are organized in modular directories; centralized exports are handled by each family's `components.py`, which are then aggregated into the top-level namespace by `components/__init__.py` for unified import and use. + +```mermaid +graph TB +subgraph "Component Package" +A["backend/modelscope_studio/components/"] +A1["antd/"] +A2["antdx/"] +A3["base/"] +A4["pro/"] +end +subgraph "Registration Entry" +R1["antd/components.py"] +R2["antdx/components.py"] +R3["pro/components.py"] +R4["base/__init__.py"] +R0["components/__init__.py"] +end +A --> A1 +A --> A2 +A --> A3 +A --> A4 +A1 --> R1 +A2 --> R2 +A3 --> R4 +A4 --> R3 +R0 --> R1 +R0 --> R2 +R0 --> R3 +R0 --> R4 +``` + +Diagram Sources + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +Section Sources + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) + +## Core Components + +The base classes and metaclasses for backend components are provided by the development utility module, which standardizes component lifecycle, event binding, layout and render control, and the ability to map to frontend directory paths. + +- Base Classes and Metaclasses + - `ModelScopeComponent`: General-purpose component base class, supporting standard properties such as `value`, `visible`, `elem_*`, `render`, as well as advanced configuration like `load_fn`, `inputs`, `key`, and `every`. + - `ModelScopeLayoutComponent`: Used for layout or container-type components, emphasizing layout updates and context exit behavior. + - `ModelScopeDataLayoutComponent`: Data-driven layout component that integrates Gradio's `BlockContext` capabilities, supporting features like `preserved_by_key`. +- Key Conventions + - `EVENTS`: The list of events supported by the component, typically defined via `EventListener`; callbacks update the binding flags in `_internal` so the frontend can listen. + - `SLOTS`: The set of slot names supported by the component, used for slot injection during frontend rendering. + - `FRONTEND_DIR`: Resolved via `resolve_frontend_dir` to the corresponding frontend Svelte component directory, ensuring frontend-backend consistency. + - `skip_api`: Determines whether the component exposes an API interface (e.g., some purely display components can skip the API). + - `preprocess`/`postprocess`/`example_payload`/`example_value`: Standardize data conversion and sample values, ensuring consistent data contracts between frontend and backend. + +Section Sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/utils/dev/**init**.py:9-13](file://backend/modelscope_studio/utils/dev/__init__.py#L9-L13) + +## Architecture Overview + +Backend components interface with frontend Svelte components through a unified directory mapping and event binding mechanism. During initialization, the component class sets `FRONTEND_DIR` so the frontend can locate the corresponding Svelte implementation; events are registered via the `EVENTS` list and callbacks update `_internal` flags, which the frontend uses to bind the corresponding behaviors; data flow is normalized through `preprocess`/`postprocess`, ensuring consistent data shapes between the Python and JS layers. + +```mermaid +sequenceDiagram +participant Py as "Python Component Class" +participant Meta as "Event Metaclass/Context" +participant FE as "Frontend Svelte Component" +Py->>Py : Initialize component
Set value/props/SLOTS/EVENTS/FrontendDir +Py->>Meta : Register event callbacks
Update _internal flags +Meta-->>FE : Frontend listens and binds events +FE-->>Py : User interaction triggers event +Py->>Py : preprocess(payload)
Normalize input +Py->>Py : postprocess(value)
Normalize output +Py-->>FE : Render result/state change +``` + +Diagram Sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [backend/modelscope_studio/components/antd/button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46) +- [backend/modelscope_studio/components/antd/form/**init**.py:23-36](file://backend/modelscope_studio/components/antd/form/__init__.py#L23-L36) + +## Detailed Component Analysis + +### Component Class Inheritance Hierarchy and Responsibilities + +- `ModelScopeComponent`: General-purpose component, suitable for data-type components (e.g., text, input, select), supporting `value` and standard UI properties. +- `ModelScopeLayoutComponent`: Layout-type components (e.g., button, card, grid), emphasizing layout updates and context exit. +- `ModelScopeDataLayoutComponent`: Data-driven layout components (e.g., form, table), with `BlockContext` capability, suitable for complex interactions and state persistence. + +```mermaid +classDiagram +class ModelScopeComponent { ++EVENTS ++SLOTS ++FRONTEND_DIR ++skip_api ++preprocess(payload) ++postprocess(value) ++example_payload() ++example_value() +} +class ModelScopeLayoutComponent { ++__exit__() +} +class ModelScopeDataLayoutComponent { ++__exit__() +} +ModelScopeLayoutComponent --|> ModelScopeComponent +ModelScopeDataLayoutComponent --|> ModelScopeComponent +ModelScopeDataLayoutComponent --|> BlockContext +``` + +Diagram Sources + +- [backend/modelscope_studio/utils/dev/component.py:54-169](file://backend/modelscope_studio/utils/dev/component.py#L54-L169) + +Section Sources + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +### Event Handling and Callback Mechanism + +- Event Definition: Declare events supported by the component via the `EVENTS` list, such as click, field change, submit completion, etc. +- Callback Logic: Event callbacks update the binding flags in `_internal`, notifying the frontend to bind events. +- Typical Usage: Click event of `AntdButton`; `fields_change`/`finish`/`values_change` of `AntdForm`, etc. + +```mermaid +sequenceDiagram +participant Btn as "AntdButton" +participant Form as "AntdForm" +participant FE as "Frontend" +Btn->>Btn : Define EVENTS["click"] +Btn->>Btn : Callback updates _internal.bind_click_event +FE-->>Btn : Listen for click event and execute callback +Form->>Form : Define EVENTS["fields_change","finish","finish_failed","values_change"] +Form->>Form : Callback updates _internal binding flags +FE-->>Form : Listen for form events and sync state +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46) +- [backend/modelscope_studio/components/antd/form/**init**.py:23-36](file://backend/modelscope_studio/components/antd/form/__init__.py#L23-L36) + +Section Sources + +- [backend/modelscope_studio/components/antd/button/**init**.py:41-46](file://backend/modelscope_studio/components/antd/button/__init__.py#L41-L46) +- [backend/modelscope_studio/components/antd/form/**init**.py:23-36](file://backend/modelscope_studio/components/antd/form/__init__.py#L23-L36) + +### Property Definition and Validation Mechanism + +- Property Declaration: Components receive `value`, `additional_props`, and numerous UI-related parameters (e.g., size, shape, color, style) in `__init__`, saved as instance properties. +- Data Model: Some components provide custom data models (e.g., `AntdFormData`) to normalize complex data structures. +- Validation and Conversion: `preprocess`/`postprocess` explicitly define input/output shapes, preventing data inconsistencies between frontend and backend. + +```mermaid +flowchart TD +Start(["Enter Component"]) --> Init["Receive parameters and assign to instance properties"] +Init --> DataModel{"Data model defined?"} +DataModel --> |Yes| UseDM["Use data model to normalize input"] +DataModel --> |No| SkipDM["Skip data model"] +UseDM --> Pre["preprocess(payload) normalize input"] +SkipDM --> Pre +Pre --> Process["Business logic/state update"] +Process --> Post["postprocess(value) normalize output"] +Post --> End(["Return to frontend"]) +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/form/**init**.py:13-15](file://backend/modelscope_studio/components/antd/form/__init__.py#L13-L15) +- [backend/modelscope_studio/components/antd/form/**init**.py:120-126](file://backend/modelscope_studio/components/antd/form/__init__.py#L120-L126) + +Section Sources + +- [backend/modelscope_studio/components/antd/button/**init**.py:51-137](file://backend/modelscope_studio/components/antd/button/__init__.py#L51-L137) +- [backend/modelscope_studio/components/antd/form/**init**.py:13-15](file://backend/modelscope_studio/components/antd/form/__init__.py#L13-L15) +- [backend/modelscope_studio/components/antd/form/**init**.py:120-126](file://backend/modelscope_studio/components/antd/form/__init__.py#L120-L126) + +### Lifecycle Hooks and Render Control + +- Initialization: Sets base properties such as `visible`, `elem_id`, `elem_classes`, `elem_style`, `render`, `as_item`, and `_internal`. +- Context Exit: Layout-type components update `layout=True` in `__exit__` to ensure the frontend recalculates the layout. +- Rendering Strategy: `skip_api` controls whether to expose an API; `render` controls whether to render; `preserved_by_key` controls the data retention strategy (effective in data layout components). + +Section Sources + +- [backend/modelscope_studio/utils/dev/component.py:24-26](file://backend/modelscope_studio/utils/dev/component.py#L24-L26) +- [backend/modelscope_studio/utils/dev/component.py:125-127](file://backend/modelscope_studio/utils/dev/component.py#L125-L127) +- [backend/modelscope_studio/utils/dev/component.py:161-168](file://backend/modelscope_studio/utils/dev/component.py#L161-L168) + +### Integration with Frontend Svelte Components + +- Directory Mapping: Component classes point to the frontend Svelte component directory via `FRONTEND_DIR`, ensuring one-to-one correspondence between frontend and backend. +- Slots and Events: `SLOTS` defines slot names; `EVENTS` defines events; the frontend renders and binds accordingly. +- Data Conversion: `preprocess`/`postprocess` ensures consistent data shapes between Python and JS layers. + +Section Sources + +- [backend/modelscope_studio/components/antd/button/**init**.py:139-156](file://backend/modelscope_studio/components/antd/button/__init__.py#L139-L156) +- [backend/modelscope_studio/components/antd/form/**init**.py:114-132](file://backend/modelscope_studio/components/antd/form/__init__.py#L114-L132) +- [backend/modelscope_studio/components/base/text/**init**.py:39-56](file://backend/modelscope_studio/components/base/text/__init__.py#L39-L56) + +### Steps and Standards for Creating a New Component + +- Choose a Family and Directory + - Select the appropriate family from `antd`, `antdx`, `base`, or `pro`, and create a new component subdirectory under the corresponding directory. +- Write the Component Class + - Inherit from the appropriate base class (general / layout / data layout). + - Define `EVENTS`, `SLOTS`, and `FRONTEND_DIR`. + - Implement `preprocess`/`postprocess`/`example_payload`/`example_value`. + - Receive and store all external parameters in `__init__`. +- Register the Component + - Import and export the component class in the family-level `components.py`. + - If adding a new family, add the export to `components/__init__.py`. +- Reference Examples + - Text component (`base/text`): Minimal component example, demonstrating minimal properties and methods. + - Button component (`antd/button`): Layout-type component with events and slots. + - Form component (`antd/form`): Data layout component with a data model and multiple events. + +Section Sources + +- [backend/modelscope_studio/components/antd/button/**init**.py:15-157](file://backend/modelscope_studio/components/antd/button/__init__.py#L15-L157) +- [backend/modelscope_studio/components/antd/form/**init**.py:17-133](file://backend/modelscope_studio/components/antd/form/__init__.py#L17-L133) +- [backend/modelscope_studio/components/base/text/**init**.py:8-57](file://backend/modelscope_studio/components/base/text/__init__.py#L8-L57) +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) + +## Dependency Analysis + +- Component Family Exports + - `antd/components.py` imports and exports numerous component classes, forming a complete ecosystem. + - `antdx/components.py` exports the extended component family. + - `pro/components.py` exports the professional component family. + - `base/__init__.py` exports the base component family. + - `components/__init__.py` aggregates the above family exports as a unified entry point. +- Component Class Dependencies + - All components depend on base classes and utility functions (e.g., `resolve_frontend_dir`) under `utils/dev`. +- Events and Context + - Events are defined via `gradio.events.EventListener`; callbacks update `_internal` flags, which the frontend uses to bind. + +```mermaid +graph LR +subgraph "Component Families" +ANTDA["antd/components.py"] +ANTDXA["antdx/components.py"] +PROA["pro/components.py"] +BASEA["base/__init__.py"] +end +subgraph "Aggregation" +ROOTI["components/__init__.py"] +end +ANTDA --> ROOTI +ANTDXA --> ROOTI +PROA --> ROOTI +BASEA --> ROOTI +``` + +Diagram Sources + +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) + +Section Sources + +- [backend/modelscope_studio/components/antd/components.py:1-145](file://backend/modelscope_studio/components/antd/components.py#L1-L145) +- [backend/modelscope_studio/components/antdx/components.py:1-40](file://backend/modelscope_studio/components/antdx/components.py#L1-L40) +- [backend/modelscope_studio/components/pro/components.py:1-8](file://backend/modelscope_studio/components/pro/components.py#L1-L8) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) + +## Performance Considerations + +- Minimize Event Binding: Only enable event binding when necessary to avoid frequent `_internal` updates causing frontend re-renders. +- Lightweight Data Conversion: `preprocess`/`postprocess` should remain simple and efficient, avoiding deep copying and complex calculations. +- Render Control: Use `render` and `skip_api` appropriately to reduce unnecessary API exposure and rendering overhead. +- Layout Component Optimization: Layout components update `layout=True` in `__exit__`; avoid triggering this repeatedly in high-frequency events. + +## Troubleshooting Guide + +- Event Not Taking Effect + - Check that `EVENTS` is correctly declared and that callbacks update the corresponding `_internal` flags. + - Confirm that the frontend has bound events based on `_internal` flags. +- Frontend Cannot Find Component + - Check that `FRONTEND_DIR` points to the correct Svelte directory. + - Confirm that the component class is exported in `components.py` and aggregated in `components/__init__.py`. +- Data Inconsistency + - Check that `preprocess`/`postprocess` aligns with the data shapes on both frontend and backend. + - For complex data, confirm that a custom data model is used and correctly parsed/serialized. +- Rendering Anomaly + - Check that `skip_api` and `render` settings match expectations. + - For layout components, pay attention to the timing of layout updates in `__exit__`. + +Section Sources + +- [backend/modelscope_studio/utils/dev/component.py:15-26](file://backend/modelscope_studio/utils/dev/component.py#L15-L26) +- [backend/modelscope_studio/utils/dev/component.py:125-127](file://backend/modelscope_studio/utils/dev/component.py#L125-L127) +- [backend/modelscope_studio/components/antd/button/**init**.py:139-156](file://backend/modelscope_studio/components/antd/button/__init__.py#L139-L156) +- [backend/modelscope_studio/components/antd/form/**init**.py:114-132](file://backend/modelscope_studio/components/antd/form/__init__.py#L114-L132) + +## Conclusion + +Through a unified base class hierarchy, clear event and slot conventions, strict frontend-backend directory mapping, and data conversion standards, ModelScope Studio's backend component development achieves a highly cohesive, loosely coupled, and easily extensible architecture. By following the structural conventions and implementation steps in this document, you can quickly create high-quality components that integrate seamlessly with the frontend Svelte ecosystem. + +## Appendix + +- Quick Reference + - Component Base Classes: `ModelScopeComponent` / `ModelScopeLayoutComponent` / `ModelScopeDataLayoutComponent` + - Key Properties: `EVENTS`, `SLOTS`, `FRONTEND_DIR`, `skip_api`, `preprocess`/`postprocess`, `example_payload`/`example_value` + - Registration Path: Family-level `components.py` → `components/__init__.py` + - Example Components: `antd/button`, `antd/form`, `base/text` diff --git a/.wiki/en/Development Guide/Component Development/Component Development Best Practices.md b/.wiki/en/Development Guide/Component Development/Component Development Best Practices.md new file mode 100644 index 00000000..37bfbb9f --- /dev/null +++ b/.wiki/en/Development Guide/Component Development/Component Development Best Practices.md @@ -0,0 +1,407 @@ +# Component Development Best Practices + + +**Files Referenced in This Document** +- [frontend/package.json](file://frontend/package.json) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [frontend/antd/form/form.tsx](file://frontend/antd/form/form.tsx) +- [frontend/base/text/text.tsx](file://frontend/base/text/text.tsx) +- [frontend/antd/layout/layout.base.tsx](file://frontend/antd/layout/layout.base.tsx) +- [frontend/antd/grid/context.ts](file://frontend/antd/grid/context.ts) +- [frontend/antd/config-provider/config-provider.tsx](file://frontend/antd/config-provider/config-provider.tsx) +- [frontend/antd/form/context.ts](file://frontend/antd/form/context.ts) +- [frontend/utils/hooks/useFunction.ts](file://frontend/utils/hooks/useFunction.ts) +- [frontend/utils/hooks/useMemoizedFn.ts](file://frontend/utils/hooks/useMemoizedFn.ts) +- [frontend/utils/createFunction.ts](file://frontend/utils/createFunction.ts) +- [frontend/utils/createItemsContext.tsx](file://frontend/utils/createItemsContext.tsx) +- [frontend/antd/table/table.tsx](file://frontend/antd/table/table.tsx) +- [frontend/antd/modal/modal.tsx](file://frontend/antd/modal/modal.tsx) +- [eslint.config.mjs](file://eslint.config.mjs) +- [prettier.config.mjs](file://prettier.config.mjs) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This guide is intended for engineers developing components within the ModelScope Studio frontend ecosystem. It systematically summarizes design principles and coding conventions, covering naming conventions, file organization, code style, performance optimization, reusability design, error handling and edge cases, internationalization and accessibility, and cross-browser compatibility — with refactoring recommendations and best practices drawn from real component implementations in the repository. + +## Project Structure + +This project uses a multi-package workspace (pnpm workspace) structure, with the frontend centered on the Svelte 5 + React ecosystem, bridging the Ant Design component library through a preprocessing layer to form a unified component system. Components are layered by domain: modules such as `antd`, `antdx`, `base`, and `pro`, where each component typically consists of a Svelte entry file and a corresponding React wrapper, with utility functions and context for high cohesion and low coupling. + +```mermaid +graph TB +subgraph "Frontend Package" +Pkg["package.json
Dependency Declaration"] +end +subgraph "Component Layer" +AntD["antd/* Components"] +AntDX["antdx/* Components"] +Base["base/* Base Components"] +Pro["pro/* Pro Components"] +end +subgraph "Utilities and Context" +Utils["utils/* Utility Functions"] +Ctx["createItemsContext.tsx
Generic Items Context"] +end +Pkg --> AntD +Pkg --> AntDX +Pkg --> Base +Pkg --> Pro +AntD --> Utils +AntDX --> Utils +Base --> Utils +Pro --> Utils +Utils --> Ctx +``` + +Diagram Sources + +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) + +Section Sources + +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) + +## Core Components + +This section focuses on key patterns and conventions for component development, including: + +- Unified entry and wrapping: The Svelte entry handles prop forwarding, lazy loading, and slot rendering; the React wrapper handles lifecycle and state management. +- Configurable internationalization and theming: Use `ConfigProvider` to manage language, theme algorithm, and container strategy. +- Highly cohesive context: `createItemsContext` abstracts "item collections" and "sub-item handlers", supporting complex component scenarios such as dynamic columns, row selection, and expand. +- Functional capabilities: `useFunction`, `useMemoizedFn`, and `createFunction` safely convert string or functional configurations into runtime functions. + +Section Sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/utils/hooks/useFunction.ts:1-13](file://frontend/utils/hooks/useFunction.ts#L1-L13) +- [frontend/utils/hooks/useMemoizedFn.ts:1-11](file://frontend/utils/hooks/useMemoizedFn.ts#L1-L11) +- [frontend/utils/createFunction.ts:1-38](file://frontend/utils/createFunction.ts#L1-L38) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +## Architecture Overview + +The diagram below shows the critical path from entry to rendering, as well as the relationships with utility functions and context. + +```mermaid +sequenceDiagram +participant Svelte as "Svelte Entry (Index.svelte)" +participant Preprocess as "Preprocess Bridge" +participant ReactComp as "React Wrapper (.tsx)" +participant Util as "Utility Functions (useFunction/createFunction)" +participant Ctx as "Context (createItemsContext)" +Svelte->>Preprocess : "importComponent lazy load" +Preprocess-->>Svelte : "Awaited component" +Svelte->>ReactComp : "processProps forward props/slots" +ReactComp->>Util : "useFunction/createFunction safe execution" +ReactComp->>Ctx : "withItemsContextProvider/ItemHandler" +ReactComp-->>Svelte : "Render final UI" +``` + +Diagram Sources + +- [frontend/antd/button/Index.svelte:10-73](file://frontend/antd/button/Index.svelte#L10-L73) +- [frontend/antd/form/form.tsx:15-76](file://frontend/antd/form/form.tsx#L15-L76) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [frontend/utils/createFunction.ts:10-37](file://frontend/utils/createFunction.ts#L10-L37) +- [frontend/utils/createItemsContext.tsx:171-184](file://frontend/utils/createItemsContext.tsx#L171-L184) + +## Detailed Component Analysis + +### Component Naming and File Organization + +- Naming Conventions + - Component directories and file names use lowerCamelCase or kebab-case, e.g., `button`, `date-picker`, `config-provider`. + - Svelte entries are uniformly named `Index.svelte`; the corresponding component source file is named `componentName.tsx` or `componentName.svelte`. +- File Organization + - Each component contains: an entry file (`Index.svelte`), component implementation (`*.tsx`), styles (`*.less`), and configuration (`package.json`, `gradio.config.js`). + - Complex components are split into sub-modules (e.g., `column`, `row-selection`, `expandable` for `table`), aggregated via context. + +Section Sources + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) +- [frontend/antd/table/table.tsx:1-200](file://frontend/antd/table/table.tsx#L1-L200) + +### Prop Forwarding and Lazy Loading + +- Lazy Loading: Use `importComponent` for on-demand loading, preventing initial bundle bloat. +- Prop Forwarding: `processProps` filters internal fields and retains external-facing props such as visibility, style, class names, and IDs. +- Slot Rendering: `getSlots` retrieves default slots and renders custom nodes in conjunction with `ReactSlot`. + +```mermaid +flowchart TD +Start(["Enter Component"]) --> Load["Lazy load React component"] +Load --> Props["processProps filter/merge props"] +Props --> Slots["getSlots parse slots"] +Slots --> Visible{"visible is true?"} +Visible --> |Yes| Render["Render component with props/slots"] +Visible --> |No| Hide["Do not render"] +Render --> End(["Complete"]) +Hide --> End +``` + +Diagram Sources + +- [frontend/antd/button/Index.svelte:12-56](file://frontend/antd/button/Index.svelte#L12-L56) + +Section Sources + +- [frontend/antd/button/Index.svelte:12-74](file://frontend/antd/button/Index.svelte#L12-L74) + +### Form Component: State Synchronization and Action Dispatch + +- Action Dispatch: Triggers the corresponding behavior based on `formAction` (reset/submit/validate), then resets the action flag upon completion. +- Value Synchronization: Sets form values when `value` changes; resets fields when not provided. +- Slots and Callbacks: `requiredMark` and `feedbackIcons` prefer slots; otherwise fall back to functions or static values; `onValuesChange` syncs external state. + +```mermaid +sequenceDiagram +participant UI as "Caller" +participant Form as "Form Component" +participant AntD as "Antd Form" +UI->>Form : "Pass value / formAction" +Form->>AntD : "Initialize Form instance" +alt formAction = reset +Form->>AntD : "resetFields()" +else formAction = submit +Form->>AntD : "submit()" +else formAction = validate +Form->>AntD : "validateFields()" +end +Form->>UI : "onResetFormAction()" +UI->>Form : "value change" +Form->>AntD : "setFieldsValue(value)" +``` + +Diagram Sources + +- [frontend/antd/form/form.tsx:32-53](file://frontend/antd/form/form.tsx#L32-L53) +- [frontend/antd/form/form.tsx:15-76](file://frontend/antd/form/form.tsx#L15-L76) + +Section Sources + +- [frontend/antd/form/form.tsx:1-79](file://frontend/antd/form/form.tsx#L1-L79) + +### Layout Base Component: Dynamic Selector + +- The Base component dynamically selects Header/Footer/Content/Layout based on the `component` parameter and uniformly injects a class prefix for style isolation. + +Section Sources + +- [frontend/antd/layout/layout.base.tsx:1-40](file://frontend/antd/layout/layout.base.tsx#L1-L40) + +### Internationalization and Theming: ConfigProvider + +- Theme Algorithm: Supports dark and compact algorithm combinations, switching based on `themeMode`. +- Language Switching: Formats the `navigator` language as an available locale code and dynamically loads `antd` and `dayjs` localization resources. +- Container Strategy: `getPopupContainer`/`getTargetContainer` supports strings or functions; functions are safely executed via `useFunction`. +- Slot Injection: Supports converting slots like `renderEmpty` to React nodes. + +```mermaid +flowchart TD +Init["Initialize ConfigProvider"] --> Locale["Parse locale code"] +Locale --> LoadRes["Async load language resources"] +LoadRes --> ApplyTheme["Compute algorithm array"] +ApplyTheme --> Render["Render subtree"] +``` + +Diagram Sources + +- [frontend/antd/config-provider/config-provider.tsx:85-105](file://frontend/antd/config-provider/config-provider.tsx#L85-L105) +- [frontend/antd/config-provider/config-provider.tsx:127-143](file://frontend/antd/config-provider/config-provider.tsx#L127-L143) + +Section Sources + +- [frontend/antd/config-provider/config-provider.tsx:1-154](file://frontend/antd/config-provider/config-provider.tsx#L1-L154) + +### Context and Item Collections: createItemsContext + +- Purpose: Provides a collection and passing mechanism for "item collections" in complex components (e.g., tables, form item rules). +- Key Capabilities + - `withItemsContextProvider`: Wraps the subtree to establish context. + - `ItemHandler`: Writes child items (props/slots/children) to the context, supporting memoization and deduplication. + - `useItems`: Reads the current item collection and triggers the `onChange` callback. +- Use Cases: Table columns, expandable items, row selection, form item rules, etc. + +```mermaid +classDiagram +class ItemsContextProvider { ++allowedSlots ++onChange(items) ++setItem(slotKey, index, item) +} +class ItemHandler { ++itemIndex ++itemSlotKey ++itemProps(props, items) ++itemChildren(items) ++slots +} +class useItems { ++items ++initial ++setItem(...) +} +ItemsContextProvider --> useItems : "Provides" +ItemHandler --> ItemsContextProvider : "Write item" +useItems --> ItemsContextProvider : "Read item" +``` + +Diagram Sources + +- [frontend/utils/createItemsContext.tsx:108-170](file://frontend/utils/createItemsContext.tsx#L108-L170) +- [frontend/utils/createItemsContext.tsx:190-261](file://frontend/utils/createItemsContext.tsx#L190-L261) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) + +Section Sources + +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) +- [frontend/antd/grid/context.ts:1-7](file://frontend/antd/grid/context.ts#L1-L7) +- [frontend/antd/form/context.ts:1-10](file://frontend/antd/form/context.ts#L1-L10) + +### Table Component: Columns, Expand, Row Selection, and Function Configuration + +- Columns and Expand: Aggregates column and expand configurations via context, supporting default columns and built-in placeholders (`EXPAND_COLUMN`, `SELECTION_COLUMN`). +- Function Configuration: `getPopupContainer`, `rowKey`, `rowClassName`, `sticky`, `showSorterTooltip`, `summary`/`footer`, etc. all support strings or functions, executed safely via `createFunction`/`useFunction`. +- Slots: `loading`, `pagination`, `tooltip`, `summary`, etc. support parameterized slot rendering. + +Section Sources + +- [frontend/antd/table/table.tsx:41-200](file://frontend/antd/table/table.tsx#L41-L200) + +### Modal Component: Slots and Functional Configuration + +- Slot Priority: `okText`, `cancelText`, `footer`, `title`, `closeIcon`, `okButtonProps.icon`, `cancelButtonProps.icon`, `closable.closeIcon`, `modalRender`, etc. prefer slots. +- Function Fallback: When slots are unavailable, `useFunction` converts strings or functions into executable functions. +- Container Strategy: `getContainer` supports string selectors or functions. + +Section Sources + +- [frontend/antd/modal/modal.tsx:1-107](file://frontend/antd/modal/modal.tsx#L1-L107) + +### Base Text Component: Minimal Implementation + +- Receives only `value` and renders it; inserts an empty placeholder element if empty, ensuring stable DOM structure. + +Section Sources + +- [frontend/base/text/text.tsx:1-11](file://frontend/base/text/text.tsx#L1-L11) + +## Dependency Analysis + +- Dependency Sources: `package.json` centrally declares dependencies related to Ant Design, React, Svelte, internationalization, and multimedia. +- Inter-Component Coupling: Coupling is reduced through the preprocessing bridge and utility functions; complex components are decoupled via context. +- External Integration: `ConfigProvider` works with `dayjs` for language switching; `StyleProvider` controls style hash priority. + +```mermaid +graph LR +AntD["antd"] --> Comp["Component Implementation (.tsx)"] +React["react + react-dom"] --> Comp +Svelte["svelte"] --> Entry["Entry (Index.svelte)"] +Entry --> Comp +Utils["Utility Functions"] --> Comp +Ctx["createItemsContext"] --> Comp +``` + +Diagram Sources + +- [frontend/package.json:8-40](file://frontend/package.json#L8-L40) +- [frontend/antd/button/Index.svelte:6-10](file://frontend/antd/button/Index.svelte#L6-L10) +- [frontend/utils/createItemsContext.tsx:1-274](file://frontend/utils/createItemsContext.tsx#L1-L274) + +Section Sources + +- [frontend/package.json:1-59](file://frontend/package.json#L1-L59) + +## Performance Considerations + +- Lazy Loading and On-Demand Rendering + - Use `importComponent` for on-demand loading, avoiding initial blocking from importing too many components at once. + - Svelte conditional rendering with the `visible` field reduces mounting of invalid nodes. +- Function and Object Stability + - `useFunction`/`useMemoizedFn`/`createFunction` convert string or functional configurations into stable functions, avoiding repeated closure creation. + - `useMemo`/`useMemoizedEqualValue` cache expensive calculations and equality comparisons in context. +- Slots and Hidden Rendering + - Complex components often render actual content in a hidden state, only exposing placeholders, to reduce initial layout jitter. +- Theming and Styles + - `StyleProvider` configures hash priority to prevent repaints caused by style conflicts. +- Events and Callbacks + - Use `useMemoizedFn` to cache references for high-frequency callbacks, reducing the probability of child component re-renders. + +Section Sources + +- [frontend/antd/button/Index.svelte:59-73](file://frontend/antd/button/Index.svelte#L59-L73) +- [frontend/antd/form/form.tsx:28-30](file://frontend/antd/form/form.tsx#L28-L30) +- [frontend/utils/hooks/useFunction.ts:5-12](file://frontend/utils/hooks/useFunction.ts#L5-L12) +- [frontend/utils/hooks/useMemoizedFn.ts:3-10](file://frontend/utils/hooks/useMemoizedFn.ts#L3-L10) +- [frontend/utils/createFunction.ts:10-37](file://frontend/utils/createFunction.ts#L10-L37) +- [frontend/antd/config-provider/config-provider.tsx:110-110](file://frontend/antd/config-provider/config-provider.tsx#L110-L110) + +## Troubleshooting Guide + +- Slot Not Taking Effect + - Check that the slot key is correct (e.g., `footer`, `title`, `okText`); confirm that it is wrapped with `ReactSlot`. + - For slots requiring parameters, use `renderParamsSlot` for rendering. +- Function Configuration Anomaly + - If a string function is passed, ensure the format is valid; use `createFunction`/`useFunction` for safe execution. +- Theme or Language Not Taking Effect + - Confirm the `themeMode` and `locale` settings; check that language resource loading succeeded. +- Context Items Not Updating + - Ensure `ItemHandler`'s `itemIndex` and `itemSlotKey` are correct; check that `setItem` is being called. +- Performance Issues + - Check for unnecessary prop changes; use `useMemoizedFn` for callbacks; avoid creating new functions inside `render`. + +Section Sources + +- [frontend/antd/modal/modal.tsx:40-95](file://frontend/antd/modal/modal.tsx#L40-L95) +- [frontend/antd/config-provider/config-provider.tsx:96-105](file://frontend/antd/config-provider/config-provider.tsx#L96-L105) +- [frontend/utils/createFunction.ts:10-37](file://frontend/utils/createFunction.ts#L10-L37) +- [frontend/utils/createItemsContext.tsx:234-254](file://frontend/utils/createItemsContext.tsx#L234-L254) + +## Conclusion + +Based on existing component implementations in the repository, this guide summarizes the design principles and engineering practices for component development: using the Svelte entry + React wrapper bridging pattern for a unified ecosystem; achieving high cohesion and low coupling through context and utility functions; improving performance and extensibility through lazy loading, function stabilization, and the slot mechanism. Following these best practices will enhance component quality and maintainability while ensuring consistency. + +## Appendix + +### Design Principles and Coding Standards + +- Naming and Organization + - Component directories and file names use lowerCamelCase or kebab-case; entries are uniformly `Index.svelte`; implementations are `*.tsx`. + - Complex components are split into sub-modules and aggregated via context. +- Props and Slots + - Clearly distinguish between external and internal props; forward external props via `processProps`; slots take priority over static values. +- Functions and Callbacks + - All string functions are executed safely via `createFunction`/`useFunction`; high-frequency callbacks are cached with `useMemoizedFn`. +- Internationalization and Theming + - Use `ConfigProvider` to manage language and theme; load language resources on demand; container strategy supports both strings and functions. +- Styles and Theming + - Use `StyleProvider` to control style hash priority; inject unified prefix class names for different component types. +- Error Handling and Edge Cases + - Return `undefined` and degrade gracefully for unrecognized function strings; provide reasonable default values when slots are missing. +- Accessibility and Compatibility + - Maintain semantic tags and accessible attributes; avoid relying solely on color to convey information; test on mainstream browsers and mobile devices. + +Section Sources + +- [frontend/antd/button/Index.svelte:24-52](file://frontend/antd/button/Index.svelte#L24-L52) +- [frontend/antd/config-provider/config-provider.tsx:110-149](file://frontend/antd/config-provider/config-provider.tsx#L110-L149) +- [frontend/utils/createFunction.ts:10-37](file://frontend/utils/createFunction.ts#L10-L37) +- [eslint.config.mjs:1-9](file://eslint.config.mjs#L1-L9) +- [prettier.config.mjs:1-26](file://prettier.config.mjs#L1-L26) diff --git a/.wiki/en/Development Guide/Component Development/Component Development.md b/.wiki/en/Development Guide/Component Development/Component Development.md new file mode 100644 index 00000000..6aa46510 --- /dev/null +++ b/.wiki/en/Development Guide/Component Development/Component Development.md @@ -0,0 +1,366 @@ +# Component Development + + +**Files referenced in this document** +- [backend/modelscope_studio/components/__init__.py](file://backend/modelscope_studio/components/__init__.py) +- [backend/modelscope_studio/components/base/__init__.py](file://backend/modelscope_studio/components/base/__init__.py) +- [backend/modelscope_studio/components/antd/__init__.py](file://backend/modelscope_studio/components/antd/__init__.py) +- [backend/modelscope_studio/components/pro/__init__.py](file://backend/modelscope_studio/components/pro/__init__.py) +- [backend/modelscope_studio/utils/dev/component.py](file://backend/modelscope_studio/utils/dev/component.py) +- [frontend/svelte-preprocess-react/index.ts](file://frontend/svelte-preprocess-react/index.ts) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts](file://frontend/svelte-preprocess-react/sveltify.svelte.ts) +- [frontend/svelte-preprocess-react/react-slot.tsx](file://frontend/svelte-preprocess-react/react-slot.tsx) +- [frontend/utils/renderSlot.tsx](file://frontend/utils/renderSlot.tsx) +- [frontend/utils/patchProps.tsx](file://frontend/utils/patchProps.tsx) +- [frontend/antd/button/Index.svelte](file://frontend/antd/button/Index.svelte) +- [frontend/antd/form/Index.svelte](file://frontend/antd/form/Index.svelte) +- [frontend/antd/button/button.tsx](file://frontend/antd/button/button.tsx) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This guide is intended for engineers and product teams developing components in ModelScope Studio. It covers backend Python component implementation, frontend Svelte component development, React component bridging and slot system usage, as well as component structure conventions, property definitions, event handling, testing, and documentation best practices. By analyzing the backend component base classes and frontend bridging mechanisms in parallel, this guide helps you quickly extend existing components or create entirely new component types. + +## Project Structure + +The ModelScope Studio component system consists of three layers: + +- Backend Python component layer: Uniformly inherits from Gradio's component metaclass, providing common lifecycle, events, and slot capabilities. +- Frontend Svelte layer: Each component loads its corresponding React implementation as a Svelte wrapper, responsible for prop passing, event bridging, and slot rendering. +- React bridging layer: Bridges Ant Design and other React components to be usable as Svelte components via `sveltify`, supporting slot and style passing. + +```mermaid +graph TB +subgraph "Backend Python" +PY_BASE["ModelScopeComponent
ModelScopeLayoutComponent
ModelScopeDataLayoutComponent"] +end +subgraph "Frontend Svelte" +SV_WRAPPER["Svelte Wrapper
Index.svelte"] +SV_SLOT["Slot Rendering Utility
renderSlot.tsx"] +end +subgraph "React Bridge" +REACT_SVELTIFY["sveltify Bridge
sveltify.svelte.ts"] +REACT_SLOT["ReactSlot Bridge
react-slot.tsx"] +PATCH_PROPS["Props Patch Utility
patchProps.tsx"] +end +PY_BASE --> SV_WRAPPER +SV_WRAPPER --> REACT_SVELTIFY +SV_WRAPPER --> SV_SLOT +SV_SLOT --> REACT_SLOT +REACT_SVELTIFY --> PATCH_PROPS +``` + +**Diagram Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) + +**Section Sources** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) + +## Core Components + +- Backend component base classes + - ModelScopeComponent: For data components, supports common props like `visible`, `elem_id`, `elem_classes`, `elem_style`, `value`, `key`, `inputs`, `load_fn`, etc.; exposes API by default. + - ModelScopeLayoutComponent: For layout components, supports `as_item`, `visible`, `elem_id`, `elem_classes`, `elem_style`, `render`, etc.; skips API export by default. + - ModelScopeDataLayoutComponent: Data + layout hybrid component, has BlockContext capability and layout marker to avoid duplicate rendering. +- Frontend bridging and slots + - sveltify: Wraps React components as Svelte components, supporting slots parameter declaration and slot tree construction. + - ReactSlot: Clones and mounts Svelte slot content into React subtrees, supporting prop and event passing, and MutationObserver observation. + - renderSlot: Convenient entry point for context-wrapped rendering based on whether forced cloning or parameterized rendering is needed. + - patchProps/applyPatchToProps: Compatibility conversion of internal fields like `key`, ensuring stable React rendering. + +**Section Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) + +## Architecture Overview + +The diagram below shows the call chain from backend component to frontend Svelte wrapper to React component, and how the slot system reuses Svelte slot content in React subtrees. + +```mermaid +sequenceDiagram +participant PY as "Backend Component
ModelScopeComponent" +participant SV as "Svelte Wrapper
Index.svelte" +participant BR as "Bridge
sveltify.svelte.ts" +participant RX as "React Component
button.tsx" +participant RS as "Slot Bridge
ReactSlot" +PY->>SV : Initialize and inject props/values +SV->>BR : importComponent loads React implementation +BR->>RX : Create Svelte node tree and mount +RX->>RS : Render slots using slots and ReactSlot +RS-->>RX : Clone and mount slot DOM (with events) +RX-->>SV : Event callback triggers updateProps +SV-->>PY : Update backend state (e.g., value, form_action) +``` + +**Diagram Sources** + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) + +## Detailed Component Analysis + +### Backend Component Base Classes and Lifecycle + +- Inheritance relationships + - ModelScopeComponent: Base data component, supports `value`, `visible`, `elem_*`, `key`, `inputs`, `load_fn`, etc. + - ModelScopeLayoutComponent: Layout component, supports `as_item`, `visible`, `elem_*`, `render`. + - ModelScopeDataLayoutComponent: Combines data and layout characteristics, marks layout on enter/exit to avoid duplicate rendering. +- Key behaviors + - Automatically records parent component child node indexes for positioning and updates. + - Supports skipping API export (`skip_api`), used for layout components. + - Works with AppContext to ensure application context exists. + +```mermaid +classDiagram +class ModelScopeComponent { ++EVENTS ++skip_api ++__init__(...) +} +class ModelScopeLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__exit__(...) +} +class ModelScopeDataLayoutComponent { ++EVENTS ++SLOTS ++skip_api ++__exit__(...) +} +ModelScopeLayoutComponent --|> ModelScopeComponent +ModelScopeDataLayoutComponent --|> ModelScopeComponent +``` + +**Diagram Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +**Section Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) + +### Frontend Svelte Wrapper and Prop Handling + +- Typical flow + - Asynchronously load the corresponding React component via `importComponent`. + - Extract and transform props using `getProps`/`processProps`, mapping names (e.g., `fields_change` → `fieldsChange`). + - Retrieve the slot collection via `getSlots` and pass to the React component. + - Render with visibility control, passing `children` as the default slot. +- Event bridging + - For mutable value components (e.g., Form), listen to `onValueChange` and call `updateProps` to update backend state. + +```mermaid +flowchart TD +Start(["Enter Svelte Wrapper"]) --> Load["importComponent loads React component"] +Load --> Extract["getProps/processProps extract and transform props"] +Extract --> Slots["getSlots retrieves slot collection"] +Slots --> Visible{"visible is true?"} +Visible --> |Yes| Render["Render React component with slots/value/events"] +Visible --> |No| Skip["Skip rendering"] +Render --> Events["Bind event callbacks (e.g., onValueChange)"] +Events --> Update["updateProps updates backend state"] +Update --> End(["Complete"]) +Skip --> End +``` + +**Diagram Sources** + +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + +**Section Sources** + +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + +### React Component Bridging and Slot System + +- sveltify + - Accepts React component and optional slots declarations, returns a Sveltified component. + - Internally maintains shared root nodes and Portals, creating Bridge render trees on demand. + - Supports ignoring certain nodes for complex scenario optimization. +- ReactSlot + - Clones Svelte slots into React subtrees, preserving event listeners and child nodes. + - Supports force cloning (`forceClone`), parameterized rendering (`params`), and attribute observation (`observeAttributes`). + - Uses ContextPropsProvider and patchProps utilities to ensure internal fields like `key` are correctly passed. +- Slot rendering pipeline + - `renderSlot` decides whether to wrap with ContextPropsProvider based on options. + - `patchProps`/`applyPatchToProps` corrects the `key` field before and after bridging to avoid React warnings. + +```mermaid +sequenceDiagram +participant SV as "Svelte Component" +participant BR as "sveltify" +participant RD as "Bridge/ReactDOM" +participant RS as "ReactSlot" +participant RX as "Antd Component" +SV->>BR : sveltify(ReactComp, { slots }) +BR->>RD : Create shared root node and Portal +RD-->>BR : Initialization complete +BR-->>SV : Return renderable Sveltified component +SV->>RS : Pass slots and props +RS->>RS : Clone slot DOM (with events) +RS-->>RX : Render slot content +``` + +**Diagram Sources** + +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) + +**Section Sources** + +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) +- [frontend/svelte-preprocess-react/react-slot.tsx:1-224](file://frontend/svelte-preprocess-react/react-slot.tsx#L1-L224) +- [frontend/utils/renderSlot.tsx:1-29](file://frontend/utils/renderSlot.tsx#L1-L29) +- [frontend/utils/patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) + +### Component Structure Conventions and Prop Definitions + +- Structure conventions + - Each component directory contains: `Index.svelte` (wrapper), corresponding React implementation (e.g., `button.tsx`), `package.json`, and `gradio.config.js`. + - Wrappers handle prop extraction, event bridging, and slot passing. +- Prop definitions + - Common props: `visible`, `elem_id`, `elem_classes`, `elem_style`, `as_item`, `_internal.layout`, etc. + - Business props: e.g., Form's `formAction`, `name`, Button's `target`, `loading.icon`, etc. + - Mapping rules: `processProps` supports name mapping (e.g., `fields_change` → `fieldsChange`). +- Event handling + - Data components write back to backend via `onValueChange`/`updateProps`. + - Behavior components trigger backend actions via native events like `onClick`/`onSubmit`. +- Slot system + - Named slots like `slots.icon`, `slots['loading.icon']` inject ReactSlot. + - Supports `children` default slot and parameterized slots (`params`). + +**Section Sources** + +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) + +### Extending Existing Components and Creating New Component Types + +- Extending existing components + - Backend: Based on `ModelScopeComponent`/`ModelScopeLayoutComponent`, add props and events, rewrite `__exit__`/`__enter__` as needed. + - Frontend: Extend `getProps`/`processProps` mappings in the Svelte wrapper, add event callbacks and slots. + - React: Use sveltify to add slot declarations, render slots with ReactSlot. +- Creating new component types + - Backend: Choose appropriate base class, define `EVENTS`/`SLOTS`, set `skip_api`. + - Frontend: Create new `Index.svelte`, import `importComponent` and `getSlots`, configure `processProps`. + - React: Implement sveltify wrapping, handle slots and styles, export default component. + +**Section Sources** + +- [backend/modelscope_studio/utils/dev/component.py:11-169](file://backend/modelscope_studio/utils/dev/component.py#L11-L169) +- [frontend/svelte-preprocess-react/sveltify.svelte.ts:1-119](file://frontend/svelte-preprocess-react/sveltify.svelte.ts#L1-L119) +- [frontend/antd/button/Index.svelte:1-74](file://frontend/antd/button/Index.svelte#L1-L74) + +## Dependency Analysis + +- Component classification entry points + - Backend `components/__init__.py` aggregates components from antd, antdx, base, and pro modules. + - `antd/__init__.py` lists numerous Ant Design component aliases for unified importing. + - `base/__init__.py` aggregates base layout and text components. + - `pro/__init__.py` aggregates professional components (e.g., Chatbot, Monaco Editor). +- Frontend bridging entry point + - `svelte-preprocess-react/index.ts` exposes sveltify and internal types for use in component wrappers. + +```mermaid +graph TB +A["backend/modelscope_studio/components/__init__.py"] --> B["antd/__init__.py"] +A --> C["antdx/__init__.py"] +A --> D["base/__init__.py"] +A --> E["pro/__init__.py"] +F["frontend/svelte-preprocess-react/index.ts"] --> G["sveltify.svelte.ts"] +F --> H["react-slot.tsx"] +``` + +**Diagram Sources** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [backend/modelscope_studio/components/antd/**init**.py:1-150](file://backend/modelscope_studio/components/antd/__init__.py#L1-L150) +- [backend/modelscope_studio/components/base/**init**.py:1-11](file://backend/modelscope_studio/components/base/__init__.py#L1-L11) +- [backend/modelscope_studio/components/pro/**init**.py:1-7](file://backend/modelscope_studio/components/pro/__init__.py#L1-L7) +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) + +**Section Sources** + +- [backend/modelscope_studio/components/**init**.py:1-5](file://backend/modelscope_studio/components/__init__.py#L1-L5) +- [frontend/svelte-preprocess-react/index.ts:1-8](file://frontend/svelte-preprocess-react/index.ts#L1-L8) + +## Performance Considerations + +- Avoid duplicate rendering + - Use the `layout` marker of `ModelScopeDataLayoutComponent` to reduce duplicate BlockContext rendering. +- Slot cloning strategy + - ReactSlot supports force cloning (`clone`/`forceClone`) to maintain event and structure consistency during complex DOM changes. + - Uses MutationObserver to observe slot changes and redraw on demand, reducing full update costs. +- Prop passing optimization + - Only transform fields like `key` via `patchProps`/`applyPatchToProps` when necessary to reduce React diff overhead. +- Async loading + - Svelte wrappers use `importComponent` to asynchronously load React components to avoid first-screen blocking. + +## Troubleshooting Guide + +- Slots not working + - Check whether the Svelte wrapper correctly calls `getSlots` and passes them to the React component's slots. + - Confirm whether the ReactSlot's `slot` parameter points to the correct DOM node. +- Events not being passed back + - Confirm whether the component listens to `onValueChange` or other callbacks and calls `updateProps` to update backend state. + - For form components, check whether `formAction` has been cleared or reset. +- Style and class name abnormalities + - Check whether `elem_id`, `elem_classes`, `elem_style` are correctly passed to the React component. + - Confirm whether ReactSlot correctly applies `className` and inline styles. +- Key conflicts or warnings + - Use `patchProps`/`applyPatchToProps` to handle internal `key` fields to avoid React errors. + +**Section Sources** + +- [frontend/antd/form/Index.svelte:1-99](file://frontend/antd/form/Index.svelte#L1-L99) +- [frontend/antd/button/button.tsx:1-39](file://frontend/antd/button/button.tsx#L1-L39) +- [frontend/utils/patchProps.tsx:1-39](file://frontend/utils/patchProps.tsx#L1-L39) + +## Conclusion + +Through the coordination of backend component base classes and frontend bridging mechanisms, ModelScope Studio implements a complete component chain from Python to Svelte to React. By following this guide's structure conventions, prop definitions, and event handling practices, you can efficiently extend existing components or create entirely new component types, and use the slot system to achieve flexible content reuse and style passing. + +## Appendix + +- Component Development Checklist + - Backend: Choose appropriate base class, define EVENTS/SLOTS, set skip_api, rewrite lifecycle as needed. + - Frontend: Write Index.svelte, configure getProps/processProps and getSlots, handle event callbacks. + - React: Use sveltify wrapping, declare slots, render slots via ReactSlot, apply styles and props. + - Testing: Cover prop mapping, event passing, slot rendering, and error boundaries. + - Documentation: Write following each component README template under docs/components, provide minimal usable examples and parameter descriptions. diff --git a/.wiki/en/Development Guide/Component Development/Component Documentation Writing.md b/.wiki/en/Development Guide/Component Development/Component Documentation Writing.md new file mode 100644 index 00000000..3873098b --- /dev/null +++ b/.wiki/en/Development Guide/Component Development/Component Documentation Writing.md @@ -0,0 +1,345 @@ +# Component Documentation Writing + + +**Files Referenced in This Document** +- [Docs.py](file://docs/helper/Docs.py) +- [Site.py](file://docs/helper/Site.py) +- [app.py](file://docs/app.py) +- [README.md](file://docs/README.md) +- [FAQ.md](file://docs/FAQ.md) +- [parse_markdown.py](file://docs/helper/parse_markdown.py) +- [button/README.md](file://docs/components/antd/button/README.md) +- [button/app.py](file://docs/components/antd/button/app.py) +- [chatbot/README.md](file://docs/layout_templates/chatbot/README.md) +- [chatbot/app.py](file://docs/layout_templates/chatbot/app.py) +- [example.py](file://docs/demos/example.py) +- [basic.py (button example)](file://docs/components/antd/button/demos/basic.py) +- [basic.py (chatbot template example)](file://docs/layout_templates/chatbot/demos/basic.py) + + +## Table of Contents + +1. [Introduction](#introduction) +2. [Project Structure](#project-structure) +3. [Core Components](#core-components) +4. [Architecture Overview](#architecture-overview) +5. [Detailed Component Analysis](#detailed-component-analysis) +6. [Dependency Analysis](#dependency-analysis) +7. [Performance Considerations](#performance-considerations) +8. [Troubleshooting Guide](#troubleshooting-guide) +9. [Conclusion](#conclusion) +10. [Appendix](#appendix) + +## Introduction + +This guide is intended for developers writing complete documentation for ModelScope Studio components, covering the following topics: + +- Writing conventions and metadata configuration for README.md +- Organization structure of the `demos` directory and naming conventions for example files +- Configuration methods for `app.py` and site navigation construction +- Features and usage of the documentation generation tools `Docs.py` and `Site.py` +- Layered conventions for example code: basic usage, advanced configuration, and FAQs +- How to organize component categories and navigation structures +- Template and example path references to help you get started quickly + +## Project Structure + +The documentation system consists of three parts: "component documentation," "layout templates," and "helper utilities," with a unified entry point `app.py` that builds site navigation and content rendering. + +```mermaid +graph TB +A["docs/app.py
Site Entry & Navigation"] --> B["docs/components//
Component Documentation Directory"] +A --> C["docs/layout_templates/