Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(web): drop headless-ui, migrate overlay to dify-ui (#35963)

Coding On Star8581a6817464
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 683e6b09fed..f7ff4f8d6da 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -159,21 +159,11 @@
"count": 5
}
},
- "web/app/account/(commonLayout)/delete-account/components/feed-back.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/account/(commonLayout)/delete-account/components/verify-email.tsx": {
"react/set-state-in-effect": {
"count": 1
}
},
- "web/app/account/(commonLayout)/delete-account/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/account/oauth/authorize/layout.tsx": {
"ts/no-explicit-any": {
"count": 1
@@ -211,9 +201,6 @@
"erasable-syntax-only/enums": {
"count": 1
},
- "no-restricted-imports": {
- "count": 1
- },
"react-refresh/only-export-components": {
"count": 1
},
@@ -272,16 +259,16 @@
"count": 1
}
},
+ "web/app/components/app/app-access-control/add-member-or-group-pop.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
"web/app/components/app/app-publisher/features-wrapper.tsx": {
"ts/no-explicit-any": {
"count": 4
}
},
- "web/app/components/app/app-publisher/version-info-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/app/configuration/base/var-highlight/index.tsx": {
"react-refresh/only-export-components": {
"count": 1
@@ -293,9 +280,6 @@
}
},
"web/app/components/app/configuration/config-prompt/conversation-history/edit-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"ts/no-explicit-any": {
"count": 1
}
@@ -311,9 +295,6 @@
}
},
"web/app/components/app/configuration/config-var/config-modal/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"ts/no-explicit-any": {
"count": 4
}
@@ -356,9 +337,6 @@
}
},
"web/app/components/app/configuration/config/automatic/get-automatic-res.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"react/set-state-in-effect": {
"count": 4
},
@@ -387,9 +365,6 @@
}
},
"web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"react/set-state-in-effect": {
"count": 4
},
@@ -418,9 +393,6 @@
}
},
"web/app/components/app/configuration/dataset-config/params-config/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"react/set-state-in-effect": {
"count": 1
}
@@ -494,26 +466,10 @@
"count": 1
}
},
- "web/app/components/app/create-app-modal/index.tsx": {
- "react/set-state-in-effect": {
- "count": 1
- },
- "ts/no-explicit-any": {
- "count": 1
- }
- },
- "web/app/components/app/create-from-dsl-modal/dsl-confirm-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/app/create-from-dsl-modal/index.tsx": {
"erasable-syntax-only/enums": {
"count": 1
},
- "no-restricted-imports": {
- "count": 1
- },
"react-refresh/only-export-components": {
"count": 1
},
@@ -521,11 +477,6 @@
"count": 2
}
},
- "web/app/components/app/duplicate-modal/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/app/log/filter.tsx": {
"react-refresh/only-export-components": {
"count": 1
@@ -561,9 +512,6 @@
}
},
"web/app/components/app/switch-app-modal/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"react/set-state-in-effect": {
"count": 1
}
@@ -881,11 +829,6 @@
"count": 3
}
},
- "web/app/components/base/content-dialog/index.stories.tsx": {
- "react/set-state-in-effect": {
- "count": 1
- }
- },
"web/app/components/base/date-and-time-picker/hooks.ts": {
"react/no-unnecessary-use-prefix": {
"count": 2
@@ -901,11 +844,6 @@
"count": 1
}
},
- "web/app/components/base/dialog/index.stories.tsx": {
- "react/set-state-in-effect": {
- "count": 1
- }
- },
"web/app/components/base/drawer-plus/index.stories.tsx": {
"react/component-hook-factories": {
"count": 1
@@ -916,11 +854,6 @@
"count": 1
}
},
- "web/app/components/base/emoji-picker/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/base/error-boundary/index.tsx": {
"react-refresh/only-export-components": {
"count": 3
@@ -942,11 +875,6 @@
"count": 1
}
},
- "web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/base/features/new-feature-panel/annotation-reply/index.tsx": {
"ts/no-explicit-any": {
"count": 3
@@ -973,9 +901,6 @@
}
},
"web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"ts/no-explicit-any": {
"count": 2
}
@@ -1544,16 +1469,6 @@
"count": 1
}
},
- "web/app/components/base/modal-like-wrap/index.stories.tsx": {
- "no-console": {
- "count": 3
- }
- },
- "web/app/components/base/modal/index.stories.tsx": {
- "react/set-state-in-effect": {
- "count": 1
- }
- },
"web/app/components/base/new-audio-button/index.tsx": {
"ts/no-explicit-any": {
"count": 1
@@ -1600,6 +1515,11 @@
"count": 4
}
},
+ "web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
"web/app/components/base/prompt-editor/plugins/component-picker-block/menu.tsx": {
"erasable-syntax-only/parameter-properties": {
"count": 1
@@ -1685,8 +1605,8 @@
}
},
"web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx": {
- "ts/no-explicit-any": {
- "count": 2
+ "no-restricted-imports": {
+ "count": 1
}
},
"web/app/components/base/prompt-editor/plugins/update-block.tsx": {
@@ -1840,11 +1760,6 @@
"count": 4
}
},
- "web/app/components/billing/annotation-full/modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/billing/billing-page/__tests__/index.spec.tsx": {
"ts/no-explicit-any": {
"count": 4
@@ -1908,11 +1823,6 @@
"count": 1
}
},
- "web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/dsl-confirm-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts": {
"erasable-syntax-only/enums": {
"count": 1
@@ -1921,9 +1831,6 @@
"web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/index.tsx": {
"no-barrel-files/no-barrel-files": {
"count": 1
- },
- "no-restricted-imports": {
- "count": 1
}
},
"web/app/components/datasets/create-from-pipeline/list/template-card/details/types.ts": {
@@ -1931,16 +1838,6 @@
"count": 1
}
},
- "web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/datasets/create/file-preview/index.tsx": {
"react/set-state-in-effect": {
"count": 1
@@ -1995,11 +1892,6 @@
"count": 1
}
},
- "web/app/components/datasets/create/stop-embedding-modal/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/datasets/create/website/firecrawl/index.tsx": {
"no-console": {
"count": 1
@@ -2058,11 +1950,6 @@
"count": 4
}
},
- "web/app/components/datasets/documents/components/rename-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/datasets/documents/create-from-pipeline/data-source/base/credential-selector/__tests__/index.spec.tsx": {
"erasable-syntax-only/enums": {
"count": 1
@@ -2133,11 +2020,6 @@
"count": 1
}
},
- "web/app/components/datasets/documents/detail/completed/common/regeneration-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/datasets/documents/detail/completed/components/segment-list-content.tsx": {
"ts/no-non-null-asserted-optional-chain": {
"count": 1
@@ -2212,18 +2094,18 @@
"count": 1
}
},
- "web/app/components/datasets/formatted-text/flavours/type.ts": {
- "ts/no-empty-object-type": {
- "count": 1
+ "web/app/components/datasets/formatted-text/flavours/edit-slice.tsx": {
+ "no-restricted-imports": {
+ "count": 2
}
},
- "web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx": {
+ "web/app/components/datasets/formatted-text/flavours/preview-slice.tsx": {
"no-restricted-imports": {
"count": 1
}
},
- "web/app/components/datasets/hit-testing/components/result-item-external.tsx": {
- "no-restricted-imports": {
+ "web/app/components/datasets/formatted-text/flavours/type.ts": {
+ "ts/no-empty-object-type": {
"count": 1
}
},
@@ -2245,11 +2127,6 @@
"count": 2
}
},
- "web/app/components/datasets/metadata/edit-metadata-batch/modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/datasets/metadata/hooks/use-edit-dataset-metadata.ts": {
"react/set-state-in-effect": {
"count": 1
@@ -2263,36 +2140,11 @@
"count": 2
}
},
- "web/app/components/datasets/metadata/metadata-dataset/create-content.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
- "web/app/components/datasets/metadata/metadata-dataset/create-metadata-modal.tsx": {
- "ts/no-explicit-any": {
- "count": 1
- }
- },
- "web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx": {
- "no-restricted-imports": {
- "count": 2
- }
- },
- "web/app/components/datasets/metadata/metadata-dataset/select-metadata-modal.tsx": {
- "erasable-syntax-only/enums": {
- "count": 1
- }
- },
"web/app/components/datasets/metadata/types.ts": {
"erasable-syntax-only/enums": {
"count": 2
}
},
- "web/app/components/datasets/rename-modal/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/datasets/settings/chunk-structure/types.ts": {
"erasable-syntax-only/enums": {
"count": 1
@@ -2311,16 +2163,6 @@
"count": 2
}
},
- "web/app/components/develop/secret-key/secret-key-generate.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "web/app/components/develop/secret-key/secret-key-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/explore/banner/banner-item.tsx": {
"react-hooks-extra/no-direct-set-state-in-use-effect": {
"count": 1
@@ -2342,11 +2184,6 @@
"count": 1
}
},
- "web/app/components/explore/try-app/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/explore/try-app/tab.tsx": {
"erasable-syntax-only/enums": {
"count": 1
@@ -2426,16 +2263,6 @@
"count": 1
}
},
- "web/app/components/header/account-about/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "web/app/components/header/account-setting/api-based-extension-page/modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/header/account-setting/data-source-page-new/card.tsx": {
"ts/no-explicit-any": {
"count": 2
@@ -2505,6 +2332,11 @@
"count": 4
}
},
+ "web/app/components/header/account-setting/model-provider-page/model-auth/authorized/index.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
"web/app/components/header/account-setting/model-provider-page/model-auth/hooks/index.ts": {
"no-barrel-files/no-barrel-files": {
"count": 6
@@ -2576,9 +2408,6 @@
}
},
"web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"react/set-state-in-effect": {
"count": 1
},
@@ -2620,9 +2449,6 @@
"erasable-syntax-only/enums": {
"count": 1
},
- "no-restricted-imports": {
- "count": 1
- },
"react-refresh/only-export-components": {
"count": 1
}
@@ -2638,9 +2464,6 @@
}
},
"web/app/components/plugins/install-plugin/install-from-github/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"ts/no-explicit-any": {
"count": 3
}
@@ -2650,21 +2473,6 @@
"count": 1
}
},
- "web/app/components/plugins/install-plugin/install-from-local-package/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx": {
- "ts/no-explicit-any": {
- "count": 2
- }
- },
- "web/app/components/plugins/install-plugin/install-from-marketplace/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/plugins/marketplace/hooks.ts": {
"@tanstack/query/exhaustive-deps": {
"count": 1
@@ -2675,6 +2483,11 @@
"count": 1
}
},
+ "web/app/components/plugins/plugin-auth/authorized/index.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
"web/app/components/plugins/plugin-auth/authorized/item.tsx": {
"ts/no-explicit-any": {
"count": 1
@@ -2828,11 +2641,21 @@
"count": 7
}
},
+ "web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-base-form.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
"web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/index.ts": {
"no-barrel-files/no-barrel-files": {
"count": 2
}
},
+ "web/app/components/plugins/plugin-detail-panel/tool-selector/index.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
"web/app/components/plugins/plugin-detail-panel/trigger/event-detail-drawer.tsx": {
"no-restricted-imports": {
"count": 1
@@ -2846,11 +2669,6 @@
"count": 1
}
},
- "web/app/components/plugins/plugin-mutation-model/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/plugins/plugin-page/context.ts": {
"ts/no-explicit-any": {
"count": 1
@@ -2866,21 +2684,11 @@
"count": 2
}
},
- "web/app/components/plugins/plugin-page/plugin-info.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/plugins/reference-setting-modal/auto-update-setting/types.ts": {
"erasable-syntax-only/enums": {
"count": 2
}
},
- "web/app/components/plugins/reference-setting-modal/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/plugins/types.ts": {
"erasable-syntax-only/enums": {
"count": 7
@@ -2963,11 +2771,6 @@
"count": 4
}
},
- "web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/rag-pipeline/components/rag-pipeline-children.tsx": {
"ts/no-explicit-any": {
"count": 1
@@ -2983,16 +2786,6 @@
"count": 2
}
},
- "web/app/components/rag-pipeline/components/update-dsl-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "web/app/components/rag-pipeline/components/version-mismatch-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/rag-pipeline/hooks/index.ts": {
"no-barrel-files/no-barrel-files": {
"count": 9
@@ -3048,11 +2841,6 @@
"count": 1
}
},
- "web/app/components/share/text-generation/info-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/share/text-generation/menu-dropdown.tsx": {
"react/set-state-in-effect": {
"count": 1
@@ -3130,24 +2918,11 @@
"count": 1
}
},
- "web/app/components/tools/mcp/mcp-server-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
- "ts/no-explicit-any": {
- "count": 5
- }
- },
"web/app/components/tools/mcp/mcp-server-param-item.tsx": {
"ts/no-explicit-any": {
"count": 1
}
},
- "web/app/components/tools/mcp/modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/tools/mcp/provider-card.tsx": {
"ts/no-explicit-any": {
"count": 3
@@ -3265,6 +3040,11 @@
"count": 1
}
},
+ "web/app/components/workflow/block-selector/main.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
"web/app/components/workflow/block-selector/market-place-plugin/action.tsx": {
"react/set-state-in-effect": {
"count": 1
@@ -3280,6 +3060,11 @@
"count": 1
}
},
+ "web/app/components/workflow/block-selector/tool-picker.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ }
+ },
"web/app/components/workflow/block-selector/tool/tool-list-flat-view/list.tsx": {
"ts/no-explicit-any": {
"count": 1
@@ -3843,16 +3628,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/http/components/authorization/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "web/app/components/workflow/nodes/http/components/curl-panel.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/http/components/key-value/key-value-edit/index.tsx": {
"ts/no-explicit-any": {
"count": 2
@@ -4034,11 +3809,6 @@
"count": 1
}
},
- "web/app/components/workflow/nodes/llm/components/json-schema-config-modal/index.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/llm/components/json-schema-config-modal/json-importer.tsx": {
"ts/no-explicit-any": {
"count": 3
@@ -4159,9 +3929,6 @@
}
},
"web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"ts/no-explicit-any": {
"count": 1
}
@@ -4395,6 +4162,9 @@
}
},
"web/app/components/workflow/note-node/note-editor/plugins/link-editor-plugin/component.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ },
"react/set-state-in-effect": {
"count": 1
}
@@ -4405,6 +4175,9 @@
}
},
"web/app/components/workflow/operator/add-block.tsx": {
+ "no-restricted-imports": {
+ "count": 1
+ },
"ts/no-explicit-any": {
"count": 1
}
@@ -4466,9 +4239,6 @@
}
},
"web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"ts/no-explicit-any": {
"count": 2
}
@@ -4496,16 +4266,6 @@
"count": 4
}
},
- "web/app/components/workflow/panel/version-history-panel/delete-confirm-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "web/app/components/workflow/panel/version-history-panel/restore-confirm-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/components/workflow/panel/workflow-preview.tsx": {
"ts/no-explicit-any": {
"count": 2
@@ -4641,9 +4401,6 @@
}
},
"web/app/components/workflow/update-dsl-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- },
"ts/no-explicit-any": {
"count": 1
}
@@ -4757,11 +4514,6 @@
"count": 1
}
},
- "web/app/education-apply/expire-notice-modal.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/app/education-apply/hooks.ts": {
"react/set-state-in-effect": {
"count": 5
diff --git a/packages/dify-ui/src/dialog/index.tsx b/packages/dify-ui/src/dialog/index.tsx
index 24c5bcc463d..dbb2448ff6c 100644
--- a/packages/dify-ui/src/dialog/index.tsx
+++ b/packages/dify-ui/src/dialog/index.tsx
@@ -63,7 +63,7 @@ export function DialogContent({
/>
<BaseDialog.Popup
className={cn(
- 'fixed top-1/2 left-1/2 z-1002 max-h-[80dvh] w-[480px] max-w-[calc(100vw-2rem)] -translate-x-1/2 -translate-y-1/2 overflow-y-auto overscroll-contain rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-6 shadow-xl',
+ 'fixed top-1/2 left-1/2 z-1002 max-h-[80dvh] w-120 max-w-[calc(100vw-2rem)] -translate-x-1/2 -translate-y-1/2 overflow-y-auto overscroll-contain rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-6 shadow-xl',
'transition-[transform,scale,opacity] duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0 motion-reduce:transition-none',
className,
)}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 88e9eab4a04..64e49c6777d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -42,9 +42,6 @@ catalogs:
'@formatjs/intl-localematcher':
specifier: 0.8.6
version: 0.8.6
- '@headlessui/react':
- specifier: 2.2.10
- version: 2.2.10
'@heroicons/react':
specifier: 2.2.0
version: 2.2.0
@@ -901,9 +898,6 @@ importers:
'@formatjs/intl-localematcher':
specifier: 'catalog:'
version: 0.8.6
- '@headlessui/react':
- specifier: 'catalog:'
'@heroicons/react':
specifier: 'catalog:'
version: 2.2.0([email protected])
@@ -2108,12 +2102,6 @@ packages:
react: '>=16.8.0'
react-dom: '>=16.8.0'
- '@floating-ui/[email protected]':
- resolution: {integrity: sha512-yORQuuAtVpiRjpMhdc0wJj06b9JFjrYF4qp96j++v2NBpbi6SEGF7donUJ3TMieerQ6qVkAv1tgr7L4r5roTqw==}
- peerDependencies:
- react: '>=16.8.0'
- react-dom: '>=16.8.0'
-
'@floating-ui/[email protected]':
resolution: {integrity: sha512-31B8h5mm8YxotlE7/AU/PhNAl8eWxAmjL/v2QOxroDNkTFLk3Uu82u63N3b6TXa4EGJeeZLVcd/9AlNlVqzeog==}
peerDependencies:
@@ -2129,13 +2117,6 @@ packages:
'@formatjs/[email protected]':
resolution: {integrity: sha512-AZRgUxj0q93lyF7Z5lFS85bLINXuBLX4R3tCKicO6fSWo6cvh9GQfoR3B1WlsqQwefZ1QORTivhInx7gM6HUzQ==}
- '@headlessui/[email protected]':
- resolution: {integrity: sha512-5pVLNK9wlpxTUTy9GpgbX/SdcRh+HBnPktjM2wbiLTH4p+2EPHBO1aoSryUCuKUIItdDWO9ITlhUL8UnUN/oIA==}
- engines: {node: '>=10'}
- peerDependencies:
- react: ^18 || ^19 || ^19.0.0-rc
- react-dom: ^18 || ^19 || ^19.0.0-rc
-
'@heroicons/[email protected]':
resolution: {integrity: sha512-LMcepvRaS9LYHJGsF0zzmgKCUim/X3N/DQKc4jepAXJ7l8QxJ1PmxJzqplF2Z3FE4PqBAIGyJAQ/w4B5dsqbtQ==}
peerDependencies:
@@ -3373,43 +3354,6 @@ packages:
'@types/react':
optional: true
- '@react-aria/[email protected]':
- resolution: {integrity: sha512-V18fwCyf8zqgJdpLQeDU5ZRNd9TeOfBbhLgmX77Zr5ae9XwaoJ1R3SFJG1wCJX60t34AW+aLZSEEK+saQElf3Q==}
- peerDependencies:
- react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
- react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
-
- '@react-aria/[email protected]':
- resolution: {integrity: sha512-M3wLpTTmDflI0QGNK0PJNUaBXXfeBXue8ZxLMngfc1piHNiH4G5lUvWd9W14XVbqrSCVY8i8DfGrNYpyyZu0tw==}
- peerDependencies:
- react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
- react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
-
- '@react-aria/[email protected]':
- resolution: {integrity: sha512-hvTm77Pf+pMBhuBm760Li0BVIO38jv1IBws1xFm1NoL26PU+fe+FMW5+VZWyANR6nYL65joaJKZqOdTQMkO9IQ==}
- engines: {node: '>= 12'}
- peerDependencies:
- react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
-
- '@react-aria/[email protected]':
- resolution: {integrity: sha512-kIx1Sj6bbAT0pdqCegHuPanR9zrLn5zMRiM7LN12rgRf55S19ptd9g3ncahArifYTRkfEU9VIn+q0HjfMqS9/w==}
- peerDependencies:
- react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
- react-dom: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
-
- '@react-stately/[email protected]':
- resolution: {integrity: sha512-2HjFcZx1MyQXoPqcBGALwWWmgFVUk2TuKVIQxCbRq7fPyWXIl6VHcakCLurdtYC2Iks7zizvz0Idv48MQ38DWg==}
-
- '@react-stately/[email protected]':
- resolution: {integrity: sha512-8LZpYowJ9eZmmYLpudbo/eclIRnbhWIJZ994ncmlKlouNzKohtM8qTC6B1w1pwUbiwGdUoyzLuQbeaIor5Dvcw==}
- peerDependencies:
- react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
-
- '@react-types/[email protected]':
- resolution: {integrity: sha512-oJHtjvLG43VjwemQDadlR5g/8VepK56B/xKO2XORPHt9zlW6IZs3tZrYlvH29BMvoqC7RtE7E5UjgbnbFtDGag==}
- peerDependencies:
- react: ^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1
-
'@reactflow/[email protected]':
resolution: {integrity: sha512-Gewd7blEVT5Lh6jqrvOgd4G6Qk17eGKQfsDXgyRSqM+CTwDqRldG2LsWN4sNeno6sbqVIC2fZ+rAUBFA9ZEUDA==}
peerDependencies:
@@ -3705,9 +3649,6 @@ packages:
resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}
- resolution: {integrity: sha512-2egEBHUMasdypIzrprsu8g+OEVd7Vp2MM3a2eVlM/cyFYto0nGz5BX5BTgh/ShZZI9ed+ozEq+Ngt+rgmUs8tw==}
-
'@t3-oss/[email protected]':
resolution: {integrity: sha512-sM7GYY+KL7H/Hl0BE0inWfk3nRHZOLhmVn7sHGxaZt9FAR6KqREXAE+6TqKfiavfXmpRxO/OZ2QgKRd+oiBYRQ==}
peerDependencies:
@@ -9410,14 +9351,6 @@ snapshots:
react: 19.2.6
react-dom: 19.2.6([email protected])
- dependencies:
- '@floating-ui/react-dom': 2.1.8([email protected]([email protected]))([email protected])
- '@floating-ui/utils': 0.2.11
- react: 19.2.6
- react-dom: 19.2.6([email protected])
- tabbable: 6.4.0
-
dependencies:
'@floating-ui/react-dom': 2.1.8([email protected]([email protected]))([email protected])
@@ -9434,16 +9367,6 @@ snapshots:
dependencies:
'@formatjs/fast-memoize': 3.1.4
- dependencies:
- '@floating-ui/react': 0.26.28([email protected]([email protected]))([email protected])
- '@react-aria/interactions': 3.27.1([email protected]([email protected]))([email protected])
- '@tanstack/react-virtual': 3.13.24([email protected]([email protected]))([email protected])
- react: 19.2.6
- react-dom: 19.2.6([email protected])
- use-sync-external-store: 1.6.0([email protected])
-
dependencies:
react: 19.2.6
@@ -10469,55 +10392,6 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.14
- dependencies:
- '@react-aria/interactions': 3.27.1([email protected]([email protected]))([email protected])
- '@react-types/shared': 3.33.1([email protected])
- '@swc/helpers': 0.5.20
- clsx: 2.1.1
- react: 19.2.6
- react-dom: 19.2.6([email protected])
-
- dependencies:
- '@react-aria/ssr': 3.9.10([email protected])
- '@react-stately/flags': 3.1.2
- '@react-types/shared': 3.33.1([email protected])
- '@swc/helpers': 0.5.20
- react: 19.2.6
- react-dom: 19.2.6([email protected])
-
- dependencies:
- '@swc/helpers': 0.5.20
- react: 19.2.6
-
- dependencies:
- '@react-aria/ssr': 3.9.10([email protected])
- '@react-stately/flags': 3.1.2
- '@react-stately/utils': 3.11.0([email protected])
- '@react-types/shared': 3.33.1([email protected])
- '@swc/helpers': 0.5.20
- clsx: 2.1.1
- react: 19.2.6
- react-dom: 19.2.6([email protected])
-
- '@react-stately/[email protected]':
- dependencies:
- '@swc/helpers': 0.5.20
-
- dependencies:
- '@swc/helpers': 0.5.20
- react: 19.2.6
-
- dependencies:
- react: 19.2.6
-
dependencies:
@@ -10888,10 +10762,6 @@ snapshots:
dependencies:
tslib: 2.8.1
- dependencies:
- tslib: 2.8.1
-
optionalDependencies:
typescript: 6.0.3
@@ -16514,7 +16384,6 @@ time:
'@eslint/[email protected]': '2026-02-06T22:34:56.290Z'
'@floating-ui/[email protected]': '2026-03-03T03:02:09.664Z'
'@formatjs/[email protected]': '2026-05-05T17:39:39.364Z'
- '@headlessui/[email protected]': '2026-04-07T17:12:43.551Z'
'@heroicons/[email protected]': '2024-11-18T15:33:27.317Z'
'@hey-api/[email protected]': '2026-05-04T00:37:14.271Z'
'@hono/[email protected]': '2026-04-30T08:51:26.973Z'
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 2a8be979694..1373efd21ee 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -66,7 +66,6 @@ catalog:
'@eslint/js': 10.0.1
'@floating-ui/react': 0.27.19
'@formatjs/intl-localematcher': 0.8.6
- '@headlessui/react': 2.2.10
'@heroicons/react': 2.2.0
'@hey-api/openapi-ts': 0.97.1
'@hono/node-server': 2.0.1
diff --git a/web/__tests__/apps/app-card-operations-flow.test.tsx b/web/__tests__/apps/app-card-operations-flow.test.tsx
index ef3bee51673..8162f12dadd 100644
--- a/web/__tests__/apps/app-card-operations-flow.test.tsx
+++ b/web/__tests__/apps/app-card-operations-flow.test.tsx
@@ -63,28 +63,6 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {
}
})
-// Mock headless UI Popover so it renders content without transition
-vi.mock('@headlessui/react', async () => {
- const actual = await vi.importActual<typeof import('@headlessui/react')>('@headlessui/react')
- return {
- ...actual,
- Popover: ({ children, className }: { children: ((bag: { open: boolean }) => React.ReactNode) | React.ReactNode, className?: string }) => (
- <div className={className} data-testid="popover-wrapper">
- {typeof children === 'function' ? children({ open: true }) : children}
- </div>
- ),
- PopoverButton: ({ children, className, ref: _ref, ...rest }: Record<string, unknown>) => (
- <button className={className as string} {...rest}>{children as React.ReactNode}</button>
- ),
- PopoverPanel: ({ children, className }: { children: ((bag: { close: () => void }) => React.ReactNode) | React.ReactNode, className?: string }) => (
- <div className={className}>
- {typeof children === 'function' ? children({ close: vi.fn() }) : children}
- </div>
- ),
- Transition: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- }
-})
-
vi.mock('@/next/dynamic', () => ({
default: (loader: () => Promise<{ default: React.ComponentType }>) => {
let Component: React.ComponentType<Record<string, unknown>> | null = null
diff --git a/web/__tests__/develop/api-key-management-flow.test.tsx b/web/__tests__/develop/api-key-management-flow.test.tsx
index 188b8e63040..233e152f8fa 100644
--- a/web/__tests__/develop/api-key-management-flow.test.tsx
+++ b/web/__tests__/develop/api-key-management-flow.test.tsx
@@ -13,7 +13,7 @@ import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import ApiServer from '@/app/components/develop/ApiServer'
-// ---------- fake timers (HeadlessUI Dialog transitions) ----------
+// ---------- fake timers (modal transitions) ----------
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
})
@@ -100,7 +100,7 @@ describe('API Key management flow', () => {
})
await flushUI()
- // SecretKeyModal should render with real HeadlessUI Dialog
+ // SecretKeyModal should render with real modal content
await waitFor(() => {
expect(screen.getByText('appApi.apiKeyModal.apiSecretKey')).toBeInTheDocument()
expect(screen.getByText('appApi.apiKeyModal.apiSecretKeyTips')).toBeInTheDocument()
diff --git a/web/__tests__/header/account-dropdown-flow.test.tsx b/web/__tests__/header/account-dropdown-flow.test.tsx
index b4a3befea06..eb128924c01 100644
--- a/web/__tests__/header/account-dropdown-flow.test.tsx
+++ b/web/__tests__/header/account-dropdown-flow.test.tsx
@@ -131,6 +131,7 @@ describe('Header Account Dropdown Flow', () => {
payload: ACCOUNT_SETTING_TAB.MEMBERS,
})
+ fireEvent.click(screen.getByRole('button', { name: 'common.account.account' }))
fireEvent.click(screen.getByText('common.userProfile.about'))
await waitFor(() => {
diff --git a/web/__tests__/header/nav-flow.test.tsx b/web/__tests__/header/nav-flow.test.tsx
index 58c95f0a010..dba7b4bf4af 100644
--- a/web/__tests__/header/nav-flow.test.tsx
+++ b/web/__tests__/header/nav-flow.test.tsx
@@ -13,83 +13,6 @@ const mockOnLoadMore = vi.fn()
let mockSelectedSegment = 'app'
let mockIsCurrentWorkspaceEditor = true
-vi.mock('@headlessui/react', () => {
- type MenuContextValue = {
- open: boolean
- setOpen: React.Dispatch<React.SetStateAction<boolean>>
- }
- const MenuContext = React.createContext<MenuContextValue | null>(null)
-
- const Menu = ({
- children,
- }: {
- children: React.ReactNode | ((props: { open: boolean }) => React.ReactNode)
- }) => {
- const [open, setOpen] = React.useState(false)
- const value = React.useMemo(() => ({ open, setOpen }), [open])
-
- return (
- <MenuContext.Provider value={value}>
- {typeof children === 'function' ? children({ open }) : children}
- </MenuContext.Provider>
- )
- }
-
- const MenuButton = ({
- children,
- onClick,
- ...props
- }: React.ButtonHTMLAttributes<HTMLButtonElement>) => {
- const context = React.useContext(MenuContext)
-
- return (
- <button
- type="button"
- aria-expanded={context?.open ?? false}
- onClick={(event) => {
- context?.setOpen(v => !v)
- onClick?.(event)
- }}
- {...props}
- >
- {children}
- </button>
- )
- }
-
- const MenuItems = ({
- as: Component = 'div',
- children,
- ...props
- }: {
- as?: React.ElementType
- children: React.ReactNode
- } & Record<string, unknown>) => {
- const context = React.useContext(MenuContext)
- if (!context?.open)
- return null
-
- return <Component {...props}>{children}</Component>
- }
-
- const MenuItem = ({
- as: Component = 'div',
- children,
- ...props
- }: {
- as?: React.ElementType
- children: React.ReactNode
- } & Record<string, unknown>) => <Component {...props}>{children}</Component>
-
- return {
- Menu,
- MenuButton,
- MenuItems,
- MenuItem,
- Transition: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- }
-})
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => key,
diff --git a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
index 46d7f7833e7..1e001a5ca4a 100644
--- a/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
+++ b/web/app/(commonLayout)/app/(appDetailLayout)/[appId]/layout-main.tsx
@@ -19,6 +19,8 @@ import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useShallow } from 'zustand/react/shallow'
import AppSideBar from '@/app/components/app-sidebar'
+import { AppInfoDetailLayer } from '@/app/components/app-sidebar/app-info'
+import { useAppInfoActions } from '@/app/components/app-sidebar/app-info/use-app-info-actions'
import { useStore } from '@/app/components/app/store'
import Loading from '@/app/components/base/loading'
import { useAppContext } from '@/context/app-context'
@@ -45,6 +47,7 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {
const media = useBreakpoints()
const isMobile = media === MediaType.mobile
const { isCurrentWorkspaceEditor, isLoadingCurrentWorkspace, currentWorkspace } = useAppContext()
+ const appInfoActions = useAppInfoActions({ resetKey: appId })
const { appDetail, setAppDetail, setAppSidebarExpand } = useStore(useShallow(state => ({
appDetail: state.appDetail,
setAppDetail: state.setAppDetail,
@@ -162,11 +165,13 @@ const AppDetailLayout: FC<IAppDetailLayoutProps> = (props) => {
{appDetail && (
<AppSideBar
navigation={navigation}
+ appInfoActions={appInfoActions}
/>
)}
<div className="grow overflow-hidden bg-components-panel-bg">
{children}
</div>
+ <AppInfoDetailLayer actions={appInfoActions} />
</div>
)
}
diff --git a/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx b/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx
index ee1e72e6e72..5b68290dd06 100644
--- a/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx
+++ b/web/app/account/(commonLayout)/delete-account/components/feed-back.tsx
@@ -1,9 +1,9 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import CustomDialog from '@/app/components/base/dialog'
import Textarea from '@/app/components/base/textarea'
import { useAppContext } from '@/context/app-context'
import { useRouter } from '@/next/navigation'
@@ -47,26 +47,34 @@ export default function FeedBack(props: DeleteAccountProps) {
handleSuccess()
}, [handleSuccess, props])
return (
- <CustomDialog
- show={true}
- onClose={props.onCancel}
- title={t('account.feedbackTitle', { ns: 'common' })}
- className="max-w-[480px]"
- footer={false}
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ props.onCancel()
+ }}
>
- <label className="mt-3 mb-1 flex items-center system-sm-semibold text-text-secondary">{t('account.feedbackLabel', { ns: 'common' })}</label>
- <Textarea
- rows={6}
- value={userFeedback}
- placeholder={t('account.feedbackPlaceholder', { ns: 'common' }) as string}
- onChange={(e) => {
- setUserFeedback(e.target.value)
- }}
- />
- <div className="mt-3 flex w-full flex-col gap-2">
- <Button className="w-full" loading={isPending} variant="primary" onClick={handleSubmit}>{t('operation.submit', { ns: 'common' })}</Button>
- <Button className="w-full" onClick={handleSkip}>{t('operation.skip', { ns: 'common' })}</Button>
- </div>
- </CustomDialog>
+ <DialogContent
+ className="max-w-[480px] overflow-hidden!"
+ backdropClassName="bg-background-overlay-backdrop backdrop-blur-[6px]"
+ >
+ <DialogTitle className="pr-8 pb-3 title-2xl-semi-bold text-text-primary">
+ {t('account.feedbackTitle', { ns: 'common' })}
+ </DialogTitle>
+ <label className="mt-3 mb-1 flex items-center system-sm-semibold text-text-secondary">{t('account.feedbackLabel', { ns: 'common' })}</label>
+ <Textarea
+ rows={6}
+ value={userFeedback}
+ placeholder={t('account.feedbackPlaceholder', { ns: 'common' }) as string}
+ onChange={(e) => {
+ setUserFeedback(e.target.value)
+ }}
+ />
+ <div className="mt-3 flex w-full flex-col gap-2">
+ <Button className="w-full" loading={isPending} variant="primary" onClick={handleSubmit}>{t('operation.submit', { ns: 'common' })}</Button>
+ <Button className="w-full" onClick={handleSkip}>{t('operation.skip', { ns: 'common' })}</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/account/(commonLayout)/delete-account/index.tsx b/web/app/account/(commonLayout)/delete-account/index.tsx
index 416f680a60a..e4af24e8bfc 100644
--- a/web/app/account/(commonLayout)/delete-account/index.tsx
+++ b/web/app/account/(commonLayout)/delete-account/index.tsx
@@ -1,7 +1,7 @@
'use client'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import CustomDialog from '@/app/components/base/dialog'
import { COUNT_DOWN_KEY, COUNT_DOWN_TIME_MS } from '@/app/components/signin/countdown'
import CheckEmail from './components/check-email'
import FeedBack from './components/feed-back'
@@ -30,22 +30,30 @@ export default function DeleteAccount(props: DeleteAccountProps) {
return <FeedBack onCancel={props.onCancel} onConfirm={props.onConfirm} />
return (
- <CustomDialog
- show={true}
- onClose={props.onCancel}
- title={t('account.delete', { ns: 'common' })}
- className="max-w-[480px]"
- footer={false}
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ props.onCancel()
+ }}
>
- {!showVerifyEmail && <CheckEmail onCancel={props.onCancel} onConfirm={handleEmailCheckSuccess} />}
- {showVerifyEmail && (
- <VerifyEmail
- onCancel={props.onCancel}
- onConfirm={() => {
- setShowFeedbackDialog(true)
- }}
- />
- )}
- </CustomDialog>
+ <DialogContent
+ className="max-w-[480px] overflow-hidden!"
+ backdropClassName="bg-background-overlay-backdrop backdrop-blur-[6px]"
+ >
+ <DialogTitle className="pr-8 pb-3 title-2xl-semi-bold text-text-primary">
+ {t('account.delete', { ns: 'common' })}
+ </DialogTitle>
+ {!showVerifyEmail && <CheckEmail onCancel={props.onCancel} onConfirm={handleEmailCheckSuccess} />}
+ {showVerifyEmail && (
+ <VerifyEmail
+ onCancel={props.onCancel}
+ onConfirm={() => {
+ setShowFeedbackDialog(true)
+ }}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/app-sidebar/__tests__/index.spec.tsx b/web/app/components/app-sidebar/__tests__/index.spec.tsx
index b2e1e92bbb3..5c00ced6cce 100644
--- a/web/app/components/app-sidebar/__tests__/index.spec.tsx
+++ b/web/app/components/app-sidebar/__tests__/index.spec.tsx
@@ -60,6 +60,9 @@ vi.mock('../app-info', () => ({
default: ({ expand }: { expand: boolean }) => (
<div data-testid="app-info" data-expand={expand} />
),
+ AppInfoView: ({ expand }: { expand: boolean }) => (
+ <div data-testid="app-info" data-expand={expand} />
+ ),
}))
vi.mock('../app-sidebar-dropdown', () => ({
diff --git a/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx b/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx
index 9af90359f0b..8017201e6e2 100644
--- a/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx
+++ b/web/app/components/app-sidebar/app-info/__tests__/app-info-detail-panel.spec.tsx
@@ -11,17 +11,16 @@ vi.mock('../../../base/app-icon', () => ({
),
}))
-vi.mock('@/app/components/base/content-dialog', () => ({
- default: ({ show, onClose, children, className }: {
- show: boolean
+vi.mock('../app-info-detail-drawer', () => ({
+ AppInfoDetailDrawer: ({ open, onClose, children }: {
+ open: boolean
onClose: () => void
children: React.ReactNode
- className?: string
}) => (
- show
+ open
? (
- <div data-testid="content-dialog" className={className}>
- <button type="button" data-testid="dialog-close" onClick={onClose}>Close</button>
+ <div data-testid="app-info-detail-drawer">
+ <button type="button" data-testid="drawer-close" onClick={onClose}>Close</button>
{children}
</div>
)
@@ -96,12 +95,12 @@ describe('AppInfoDetailPanel', () => {
describe('Rendering', () => {
it('should not render when show is false', () => {
render(<AppInfoDetailPanel {...defaultProps} show={false} />)
- expect(screen.queryByTestId('content-dialog')).not.toBeInTheDocument()
+ expect(screen.queryByTestId('app-info-detail-drawer')).not.toBeInTheDocument()
})
- it('should render dialog when show is true', () => {
+ it('should render drawer when show is true', () => {
render(<AppInfoDetailPanel {...defaultProps} />)
- expect(screen.getByTestId('content-dialog')).toBeInTheDocument()
+ expect(screen.getByTestId('app-info-detail-drawer')).toBeInTheDocument()
})
it('should display app name', () => {
@@ -285,12 +284,12 @@ describe('AppInfoDetailPanel', () => {
})
})
- describe('Dialog interactions', () => {
- it('should call onClose when dialog close button is clicked', async () => {
+ describe('Drawer interactions', () => {
+ it('should call onClose when drawer close button is clicked', async () => {
const user = userEvent.setup()
render(<AppInfoDetailPanel {...defaultProps} />)
- await user.click(screen.getByTestId('dialog-close'))
+ await user.click(screen.getByTestId('drawer-close'))
expect(defaultProps.onClose).toHaveBeenCalledTimes(1)
})
diff --git a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts
index 23e5e519491..fe5fa03f679 100644
--- a/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts
+++ b/web/app/components/app-sidebar/app-info/__tests__/use-app-info-actions.spec.ts
@@ -153,6 +153,27 @@ describe('useAppInfoActions', () => {
expect(result.current.panelOpen).toBe(false)
expect(onDetailExpand).toHaveBeenCalledWith(false)
})
+
+ it('should reset app-scoped state when resetKey changes', () => {
+ const { result, rerender } = renderHook(
+ ({ resetKey }) => useAppInfoActions({ resetKey }),
+ { initialProps: { resetKey: 'app-1' } },
+ )
+
+ act(() => {
+ result.current.openModal('delete')
+ result.current.setPanelOpen(true)
+ })
+
+ expect(result.current.panelOpen).toBe(true)
+ expect(result.current.activeModal).toBe('delete')
+
+ rerender({ resetKey: 'app-2' })
+
+ expect(result.current.panelOpen).toBe(false)
+ expect(result.current.activeModal).toBeNull()
+ expect(result.current.secretEnvList).toEqual([])
+ })
})
describe('Modal management', () => {
diff --git a/web/app/components/app-sidebar/app-info/app-info-detail-drawer.tsx b/web/app/components/app-sidebar/app-info/app-info-detail-drawer.tsx
new file mode 100644
index 00000000000..e9217df03c6
--- /dev/null
+++ b/web/app/components/app-sidebar/app-info/app-info-detail-drawer.tsx
@@ -0,0 +1,34 @@
+import type { ReactNode } from 'react'
+
+type AppInfoDetailDrawerProps = {
+ open: boolean
+ onClose: () => void
+ children: ReactNode
+}
+
+export function AppInfoDetailDrawer({
+ open,
+ onClose,
+ children,
+}: AppInfoDetailDrawerProps) {
+ if (!open)
+ return null
+
+ return (
+ <div className="absolute inset-0 z-50">
+ <button
+ type="button"
+ aria-label="Close app info"
+ className="absolute inset-0 cursor-default bg-app-detail-overlay-bg"
+ onClick={onClose}
+ />
+ <section
+ role="dialog"
+ aria-modal="false"
+ className="absolute top-2 bottom-2 left-2 flex w-[452px] max-w-[calc(100vw-1rem)] flex-col overflow-hidden rounded-2xl border-r border-divider-burn bg-app-detail-bg"
+ >
+ {children}
+ </section>
+ </div>
+ )
+}
diff --git a/web/app/components/app-sidebar/app-info/app-info-detail-panel.tsx b/web/app/components/app-sidebar/app-info/app-info-detail-panel.tsx
index 3dabb2a91e5..13a55f8984d 100644
--- a/web/app/components/app-sidebar/app-info/app-info-detail-panel.tsx
+++ b/web/app/components/app-sidebar/app-info/app-info-detail-panel.tsx
@@ -14,9 +14,9 @@ import * as React from 'react'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import CardView from '@/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/card-view'
-import ContentDialog from '@/app/components/base/content-dialog'
import { AppModeEnum } from '@/types/app'
import AppIcon from '../../base/app-icon'
+import { AppInfoDetailDrawer } from './app-info-detail-drawer'
import { getAppModeLabel } from './app-mode-labels'
import AppOperations from './app-operations'
@@ -94,10 +94,9 @@ const AppInfoDetailPanel = ({
}, [appDetail.mode, t, openModal])
return (
- <ContentDialog
- show={show}
+ <AppInfoDetailDrawer
+ open={show}
onClose={onClose}
- className="absolute top-2 bottom-2 left-2 flex w-[452px] max-w-[calc(100vw-1rem)] flex-col rounded-2xl p-0!"
>
<div className="flex shrink-0 flex-col items-start justify-center gap-3 self-stretch p-4">
<div className="flex items-center gap-3 self-stretch">
@@ -109,16 +108,16 @@ const AppInfoDetailPanel = ({
imageUrl={appDetail.icon_url}
/>
<div className="flex flex-1 flex-col items-start justify-center overflow-hidden">
- <div className="w-full truncate system-md-semibold text-text-secondary">{appDetail.name}</div>
+ <h2 className="w-full truncate system-md-semibold text-text-secondary">{appDetail.name}</h2>
<div className="system-2xs-medium-uppercase text-text-tertiary">
{getAppModeLabel(appDetail.mode, t)}
</div>
</div>
</div>
{appDetail.description && (
- <div className="overflow-wrap-anywhere max-h-[105px] w-full max-w-full overflow-y-auto system-xs-regular wrap-break-word whitespace-normal text-text-tertiary">
+ <p className="overflow-wrap-anywhere max-h-[105px] w-full max-w-full overflow-y-auto system-xs-regular wrap-break-word whitespace-normal text-text-tertiary">
{appDetail.description}
- </div>
+ </p>
)}
<AppOperations
gap={4}
@@ -144,7 +143,7 @@ const AppInfoDetailPanel = ({
</Button>
</div>
)}
- </ContentDialog>
+ </AppInfoDetailDrawer>
)
}
diff --git a/web/app/components/app-sidebar/app-info/index.tsx b/web/app/components/app-sidebar/app-info/index.tsx
index a0628ec7861..14a2defc1e7 100644
--- a/web/app/components/app-sidebar/app-info/index.tsx
+++ b/web/app/components/app-sidebar/app-info/index.tsx
@@ -1,3 +1,4 @@
+import type { AppInfoActions } from './use-app-info-actions'
import * as React from 'react'
import { useAppContext } from '@/context/app-context'
import AppInfoDetailPanel from './app-info-detail-panel'
@@ -12,13 +13,22 @@ type IAppInfoProps = {
onDetailExpand?: (expand: boolean) => void
}
-const AppInfo = ({ expand, onlyShowDetail = false, openState = false, onDetailExpand }: IAppInfoProps) => {
- const { isCurrentWorkspaceEditor } = useAppContext()
+type AppInfoViewProps = Omit<IAppInfoProps, 'onDetailExpand'> & {
+ actions: AppInfoActions
+ renderDetail?: boolean
+}
+
+type AppInfoDetailLayerProps = {
+ actions: AppInfoActions
+ open?: boolean
+}
+export const AppInfoDetailLayer = ({
+ actions,
+ open = actions.panelOpen,
+}: AppInfoDetailLayerProps) => {
const {
appDetail,
- panelOpen,
- setPanelOpen,
closePanel,
activeModal,
openModal,
@@ -31,26 +41,16 @@ const AppInfo = ({ expand, onlyShowDetail = false, openState = false, onDetailEx
exportCheck,
handleConfirmExport,
onConfirmDelete,
- } = useAppInfoActions({ onDetailExpand })
+ } = actions
if (!appDetail)
return null
return (
- <div>
- {!onlyShowDetail && (
- <AppInfoTrigger
- appDetail={appDetail}
- expand={expand}
- onClick={() => {
- if (isCurrentWorkspaceEditor)
- setPanelOpen(v => !v)
- }}
- />
- )}
+ <>
<AppInfoDetailPanel
appDetail={appDetail}
- show={onlyShowDetail ? openState : panelOpen}
+ show={open}
onClose={closePanel}
openModal={openModal}
exportCheck={exportCheck}
@@ -68,8 +68,58 @@ const AppInfo = ({ expand, onlyShowDetail = false, openState = false, onDetailEx
handleConfirmExport={handleConfirmExport}
onConfirmDelete={onConfirmDelete}
/>
+ </>
+ )
+}
+
+export const AppInfoView = ({
+ expand,
+ onlyShowDetail = false,
+ openState = false,
+ actions,
+ renderDetail = true,
+}: AppInfoViewProps) => {
+ const { isCurrentWorkspaceEditor } = useAppContext()
+ const {
+ appDetail,
+ panelOpen,
+ setPanelOpen,
+ } = actions
+
+ if (!appDetail)
+ return null
+
+ return (
+ <div>
+ {!onlyShowDetail && (
+ <AppInfoTrigger
+ appDetail={appDetail}
+ expand={expand}
+ onClick={() => {
+ if (isCurrentWorkspaceEditor)
+ setPanelOpen(v => !v)
+ }}
+ />
+ )}
+ {renderDetail && (
+ <AppInfoDetailLayer
+ actions={actions}
+ open={onlyShowDetail ? openState : panelOpen}
+ />
+ )}
</div>
)
}
+const AppInfo = ({ onDetailExpand, ...props }: IAppInfoProps) => {
+ const actions = useAppInfoActions({ onDetailExpand })
+
+ return (
+ <AppInfoView
+ {...props}
+ actions={actions}
+ />
+ )
+}
+
export default React.memo(AppInfo)
diff --git a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts
index 262a8c7db00..134726a50c3 100644
--- a/web/app/components/app-sidebar/app-info/use-app-info-actions.ts
+++ b/web/app/components/app-sidebar/app-info/use-app-info-actions.ts
@@ -1,3 +1,4 @@
+import type { Dispatch, SetStateAction } from 'react'
import type { DuplicateAppModalProps } from '@/app/components/app/duplicate-modal'
import type { CreateAppModalProps } from '@/app/components/explore/create-app-modal'
import type { EnvironmentVariable } from '@/app/components/workflow/types'
@@ -19,9 +20,36 @@ export type AppInfoModalType = 'edit' | 'duplicate' | 'delete' | 'switch' | 'imp
type UseAppInfoActionsParams = {
onDetailExpand?: (expand: boolean) => void
+ resetKey?: string
}
-export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {
+type AppInfoUiState = {
+ resetKey?: string
+ panelOpen: boolean
+ activeModal: AppInfoModalType
+ secretEnvList: EnvironmentVariable[]
+}
+
+const emptySecretEnvList: EnvironmentVariable[] = []
+
+const createInitialUiState = (resetKey?: string): AppInfoUiState => ({
+ resetKey,
+ panelOpen: false,
+ activeModal: null,
+ secretEnvList: [],
+})
+
+const resolveStateAction = <T>(value: SetStateAction<T>, previous: T) => {
+ return typeof value === 'function'
+ ? (value as (previous: T) => T)(previous)
+ : value
+}
+
+const getCurrentUiState = (state: AppInfoUiState, resetKey?: string) => {
+ return state.resetKey === resetKey ? state : createInitialUiState(resetKey)
+}
+
+export function useAppInfoActions({ onDetailExpand, resetKey }: UseAppInfoActionsParams) {
const { t } = useTranslation()
const { replace } = useRouter()
const { onPlanInfoChanged } = useProviderContext()
@@ -29,23 +57,55 @@ export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {
const setAppDetail = useAppStore(state => state.setAppDetail)
const invalidateAppList = useInvalidateAppList()
- const [panelOpen, setPanelOpen] = useState(false)
- const [activeModal, setActiveModal] = useState<AppInfoModalType>(null)
- const [secretEnvList, setSecretEnvList] = useState<EnvironmentVariable[]>([])
+ const [uiState, setUiState] = useState(() => createInitialUiState(resetKey))
+ const uiStateMatchesResetKey = uiState.resetKey === resetKey
+ const panelOpen = uiStateMatchesResetKey ? uiState.panelOpen : false
+ const activeModal = uiStateMatchesResetKey ? uiState.activeModal : null
+ const secretEnvList = uiStateMatchesResetKey ? uiState.secretEnvList : emptySecretEnvList
+
+ const setPanelOpen = useCallback<Dispatch<SetStateAction<boolean>>>((value) => {
+ setUiState((state) => {
+ const current = getCurrentUiState(state, resetKey)
+ return {
+ ...current,
+ panelOpen: resolveStateAction(value, current.panelOpen),
+ }
+ })
+ }, [resetKey])
+
+ const setActiveModal = useCallback<Dispatch<SetStateAction<AppInfoModalType>>>((value) => {
+ setUiState((state) => {
+ const current = getCurrentUiState(state, resetKey)
+ return {
+ ...current,
+ activeModal: resolveStateAction(value, current.activeModal),
+ }
+ })
+ }, [resetKey])
+
+ const setSecretEnvList = useCallback<Dispatch<SetStateAction<EnvironmentVariable[]>>>((value) => {
+ setUiState((state) => {
+ const current = getCurrentUiState(state, resetKey)
+ return {
+ ...current,
+ secretEnvList: resolveStateAction(value, current.secretEnvList),
+ }
+ })
+ }, [resetKey])
const closePanel = useCallback(() => {
setPanelOpen(false)
onDetailExpand?.(false)
- }, [onDetailExpand])
+ }, [onDetailExpand, setPanelOpen])
const openModal = useCallback((modal: Exclude<AppInfoModalType, null>) => {
closePanel()
setActiveModal(modal)
- }, [closePanel])
+ }, [closePanel, setActiveModal])
const closeModal = useCallback(() => {
setActiveModal(null)
- }, [])
+ }, [setActiveModal])
const emitAppMetaUpdate = useCallback(() => {
if (!appDetail?.id)
@@ -178,7 +238,7 @@ export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {
return
}
setActiveModal('exportWarning')
- }, [appDetail, onExport])
+ }, [appDetail, onExport, setActiveModal])
const handleConfirmExport = useCallback(async () => {
if (!appDetail)
@@ -198,7 +258,7 @@ export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {
finally {
closeModal()
}
- }, [appDetail, closeModal, onExport, t])
+ }, [appDetail, closeModal, onExport, setSecretEnvList, t])
const onConfirmDelete = useCallback(async () => {
if (!appDetail)
@@ -235,3 +295,5 @@ export function useAppInfoActions({ onDetailExpand }: UseAppInfoActionsParams) {
onConfirmDelete,
}
}
+
+export type AppInfoActions = ReturnType<typeof useAppInfoActions>
diff --git a/web/app/components/app-sidebar/app-sidebar-dropdown.tsx b/web/app/components/app-sidebar/app-sidebar-dropdown.tsx
index 0b5f13d9188..e0661b9c528 100644
--- a/web/app/components/app-sidebar/app-sidebar-dropdown.tsx
+++ b/web/app/components/app-sidebar/app-sidebar-dropdown.tsx
@@ -1,3 +1,4 @@
+import type { AppInfoActions } from './app-info/use-app-info-actions'
import type { NavIcon } from './nav-link'
import { cn } from '@langgenius/dify-ui/cn'
import {
@@ -27,9 +28,10 @@ type Props = {
icon: NavIcon
selectedIcon: NavIcon
}>
+ appInfoActions?: AppInfoActions
}
-const AppSidebarDropdown = ({ navigation }: Props) => {
+const AppSidebarDropdown = ({ navigation, appInfoActions }: Props) => {
const { t } = useTranslation()
const { isCurrentWorkspaceEditor } = useAppContext()
const appDetail = useAppStore(state => state.appDetail)
@@ -69,7 +71,10 @@ const AppSidebarDropdown = ({ navigation }: Props) => {
<div
className={cn('flex flex-col gap-2 rounded-lg p-2 pb-2.5', isCurrentWorkspaceEditor && 'cursor-pointer hover:bg-state-base-hover')}
onClick={() => {
- setDetailExpand(true)
+ if (appInfoActions)
+ appInfoActions.setPanelOpen(true)
+ else
+ setDetailExpand(true)
setOpen(false)
}}
>
@@ -109,9 +114,11 @@ const AppSidebarDropdown = ({ navigation }: Props) => {
</DropdownMenuContent>
</DropdownMenu>
</div>
- <div className="z-20">
- <AppInfo expand onlyShowDetail openState={detailExpand} onDetailExpand={setDetailExpand} />
- </div>
+ {!appInfoActions && (
+ <div className="z-20">
+ <AppInfo expand onlyShowDetail openState={detailExpand} onDetailExpand={setDetailExpand} />
+ </div>
+ )}
</>
)
}
diff --git a/web/app/components/app-sidebar/index.tsx b/web/app/components/app-sidebar/index.tsx
index 4750d7919c8..6fe5fffe8c4 100644
--- a/web/app/components/app-sidebar/index.tsx
+++ b/web/app/components/app-sidebar/index.tsx
@@ -1,3 +1,4 @@
+import type { AppInfoActions } from './app-info/use-app-info-actions'
import type { NavIcon } from './nav-link'
import { cn } from '@langgenius/dify-ui/cn'
import { useHover, useKeyPress } from 'ahooks'
@@ -10,7 +11,7 @@ import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { usePathname } from '@/next/navigation'
import Divider from '../base/divider'
import { getKeyboardKeyCodeBySystem } from '../workflow/utils'
-import AppInfo from './app-info'
+import AppInfo, { AppInfoView } from './app-info'
import AppSidebarDropdown from './app-sidebar-dropdown'
import DatasetInfo from './dataset-info'
import DatasetSidebarDropdown from './dataset-sidebar-dropdown'
@@ -36,12 +37,14 @@ type IAppDetailNavProps = {
disabled?: boolean
}>
extraInfo?: (modeState: string) => React.ReactNode
+ appInfoActions?: AppInfoActions
}
const AppDetailNav = ({
navigation,
extraInfo,
iconType = 'app',
+ appInfoActions,
}: IAppDetailNavProps) => {
const { appSidebarExpand, setAppSidebarExpand } = useAppStore(useShallow(state => ({
appSidebarExpand: state.appSidebarExpand,
@@ -89,7 +92,10 @@ const AppDetailNav = ({
if (inWorkflowCanvas && hideHeader) {
return (
<div className="flex w-0 shrink-0">
- <AppSidebarDropdown navigation={navigation} />
+ <AppSidebarDropdown
+ navigation={navigation}
+ appInfoActions={appInfoActions}
+ />
</div>
)
}
@@ -117,7 +123,15 @@ const AppDetailNav = ({
)}
>
{iconType === 'app' && (
- <AppInfo expand={expand} />
+ appInfoActions
+ ? (
+ <AppInfoView
+ expand={expand}
+ actions={appInfoActions}
+ renderDetail={false}
+ />
+ )
+ : <AppInfo expand={expand} />
)}
{iconType !== 'app' && (
<DatasetInfo expand={expand} />
diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx
index 550794cce78..0f6c27fd5a8 100644
--- a/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx
+++ b/web/app/components/app/annotation/batch-add-annotation-modal/index.tsx
@@ -1,13 +1,12 @@
'use client'
import type { FC } from 'react'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { RiCloseLine } from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import AnnotationFull from '@/app/components/billing/annotation-full'
import { useProviderContext } from '@/context/provider-context'
import { annotationBatchImport, checkAnnotationBatchImportProgress } from '@/service/annotation'
@@ -88,37 +87,40 @@ const BatchModal: FC<IBatchModalProps> = ({
}
return (
- <Modal isShow={isShow} onClose={noop} className="max-w-[520px]! rounded-xl! px-8 py-6">
- <div className="relative pb-1 system-xl-medium text-text-primary">{t('batchModal.title', { ns: 'appAnnotation' })}</div>
- <div className="absolute top-4 right-4 cursor-pointer p-2" onClick={onCancel}>
- <RiCloseLine className="h-4 w-4 text-text-tertiary" />
- </div>
- <CSVUploader
- file={currentCSV}
- updateFile={handleFile}
- />
- <CSVDownloader />
+ <Dialog open={isShow}>
+ <DialogContent className="w-full max-w-[520px]! overflow-hidden! rounded-xl! border-none px-8 py-6 text-left align-middle">
- {isAnnotationFull && (
- <div className="mt-4">
- <AnnotationFull />
+ <div className="relative pb-1 system-xl-medium text-text-primary">{t('batchModal.title', { ns: 'appAnnotation' })}</div>
+ <div className="absolute top-4 right-4 cursor-pointer p-2" onClick={onCancel}>
+ <RiCloseLine className="h-4 w-4 text-text-tertiary" />
</div>
- )}
+ <CSVUploader
+ file={currentCSV}
+ updateFile={handleFile}
+ />
+ <CSVDownloader />
- <div className="mt-[28px] flex justify-end pt-6">
- <Button className="mr-2 system-sm-medium text-text-tertiary" onClick={onCancel}>
- {t('batchModal.cancel', { ns: 'appAnnotation' })}
- </Button>
- <Button
- variant="primary"
- onClick={handleSend}
- disabled={isAnnotationFull || !currentCSV}
- loading={importStatus === ProcessStatus.PROCESSING || importStatus === ProcessStatus.WAITING}
- >
- {t('batchModal.run', { ns: 'appAnnotation' })}
- </Button>
- </div>
- </Modal>
+ {isAnnotationFull && (
+ <div className="mt-4">
+ <AnnotationFull />
+ </div>
+ )}
+
+ <div className="mt-[28px] flex justify-end pt-6">
+ <Button className="mr-2 system-sm-medium text-text-tertiary" onClick={onCancel}>
+ {t('batchModal.cancel', { ns: 'appAnnotation' })}
+ </Button>
+ <Button
+ variant="primary"
+ onClick={handleSend}
+ disabled={isAnnotationFull || !currentCSV}
+ loading={importStatus === ProcessStatus.PROCESSING || importStatus === ProcessStatus.WAITING}
+ >
+ {t('batchModal.run', { ns: 'appAnnotation' })}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(BatchModal)
diff --git a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
index 5e7b2dc1d09..f9535147024 100644
--- a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
@@ -5,129 +5,11 @@ import type { AnnotationItemBasic } from '../../type'
import type { Locale } from '@/i18n-config'
import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import * as React from 'react'
import { useLocale } from '@/context/i18n'
import { LanguagesSupported } from '@/i18n-config/language'
import { clearAllAnnotations, fetchExportAnnotationList } from '@/service/annotation'
import HeaderOptions from '../index'
-vi.mock('@headlessui/react', () => {
- type PopoverContextValue = { open: boolean, setOpen: (open: boolean) => void }
- type MenuContextValue = { open: boolean, setOpen: (open: boolean) => void }
- const PopoverContext = React.createContext<PopoverContextValue | null>(null)
- const MenuContext = React.createContext<MenuContextValue | null>(null)
-
- const Popover = ({ children }: { children: React.ReactNode | ((props: { open: boolean }) => React.ReactNode) }) => {
- const [open, setOpen] = React.useState(false)
- const value = React.useMemo(() => ({ open, setOpen }), [open])
- return (
- <PopoverContext.Provider value={value}>
- {typeof children === 'function' ? children({ open }) : children}
- </PopoverContext.Provider>
- )
- }
-
- const PopoverButton = React.forwardRef(({ onClick, children, ...props }: { onClick?: () => void, children?: React.ReactNode }, ref: React.Ref<HTMLButtonElement>) => {
- const context = React.useContext(PopoverContext)
- const handleClick = () => {
- context?.setOpen(!context.open)
- onClick?.()
- }
- return (
- <button
- ref={ref}
- type="button"
- aria-expanded={context?.open ?? false}
- onClick={handleClick}
- {...props}
- >
- {children}
- </button>
- )
- })
-
- const PopoverPanel = React.forwardRef(({ children, ...props }: { children: React.ReactNode | ((props: { close: () => void }) => React.ReactNode) }, ref: React.Ref<HTMLDivElement>) => {
- const context = React.useContext(PopoverContext)
- if (!context?.open)
- return null
- const content = typeof children === 'function' ? children({ close: () => context.setOpen(false) }) : children
- return (
- <div ref={ref} {...props}>
- {content}
- </div>
- )
- })
-
- const Menu = ({ children }: { children: React.ReactNode }) => {
- const [open, setOpen] = React.useState(false)
- const value = React.useMemo(() => ({ open, setOpen }), [open])
- return (
- <MenuContext.Provider value={value}>
- {children}
- </MenuContext.Provider>
- )
- }
-
- const MenuButton = ({ onClick, children, ...props }: { onClick?: () => void, children?: React.ReactNode }) => {
- const context = React.useContext(MenuContext)
- const handleClick = () => {
- context?.setOpen(!context.open)
- onClick?.()
- }
- return (
- <button type="button" aria-expanded={context?.open ?? false} onClick={handleClick} {...props}>
- {children}
- </button>
- )
- }
-
- const MenuItems = ({ children, ...props }: { children: React.ReactNode }) => {
- const context = React.useContext(MenuContext)
- if (!context?.open)
- return null
- return (
- <div {...props}>
- {children}
- </div>
- )
- }
-
- return {
- Dialog: ({ open, children, className }: { open?: boolean, children: React.ReactNode, className?: string }) => {
- if (open === false)
- return null
- return (
- <div role="dialog" className={className}>
- {children}
- </div>
- )
- },
- DialogBackdrop: ({ children, className, onClick }: { children?: React.ReactNode, className?: string, onClick?: () => void }) => (
- <div className={className} onClick={onClick}>
- {children}
- </div>
- ),
- DialogPanel: ({ children, className, ...props }: { children: React.ReactNode, className?: string }) => (
- <div className={className} {...props}>
- {children}
- </div>
- ),
- DialogTitle: ({ children, className, ...props }: { children: React.ReactNode, className?: string }) => (
- <div className={className} {...props}>
- {children}
- </div>
- ),
- Popover,
- PopoverButton,
- PopoverPanel,
- Menu,
- MenuButton,
- MenuItems,
- Transition: ({ show = true, children }: { show?: boolean, children: React.ReactNode }) => (show ? <>{children}</> : null),
- TransitionChild: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- }
-})
-
const mockJsonToCSV = vi.fn((_: unknown) => 'csv-content')
const mockCSVDownloader = vi.fn(({ children }) => <>{children}</>)
diff --git a/web/app/components/app/app-access-control/__tests__/access-control-dialog.spec.tsx b/web/app/components/app/app-access-control/__tests__/access-control-dialog.spec.tsx
index 13331f3f9c6..03a35bd52ab 100644
--- a/web/app/components/app/app-access-control/__tests__/access-control-dialog.spec.tsx
+++ b/web/app/components/app/app-access-control/__tests__/access-control-dialog.spec.tsx
@@ -10,6 +10,7 @@ describe('AccessControlDialog', () => {
)
expect(screen.getByRole('dialog')).toBeInTheDocument()
+ expect(screen.getByRole('dialog')).toHaveClass('custom-dialog')
expect(screen.getByText('Dialog Content')).toBeInTheDocument()
})
diff --git a/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
index 4aaea1670fc..a686ba9f2e0 100644
--- a/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
+++ b/web/app/components/app/app-access-control/__tests__/access-control.spec.tsx
@@ -1,4 +1,3 @@
-/* eslint-disable ts/no-explicit-any */
import type { AccessControlAccount, AccessControlGroup, Subject } from '@/models/access-control'
import type { App } from '@/types/app'
import { toast } from '@langgenius/dify-ui/toast'
@@ -43,34 +42,6 @@ vi.mock('@/service/access-control', () => ({
useUpdateAccessMode: () => mockUseUpdateAccessMode(),
}))
-vi.mock('@headlessui/react', () => {
- const DialogComponent: any = ({ children, className, ...rest }: any) => (
- <div role="dialog" className={className} {...rest}>{children}</div>
- )
- DialogComponent.Panel = ({ children, className, ...rest }: any) => (
- <div className={className} {...rest}>{children}</div>
- )
- const DialogTitle = ({ children, className, ...rest }: any) => (
- <div className={className} {...rest}>{children}</div>
- )
- const DialogDescription = ({ children, className, ...rest }: any) => (
- <div className={className} {...rest}>{children}</div>
- )
- const TransitionChild = ({ children }: any) => (
- <>{typeof children === 'function' ? children({}) : children}</>
- )
- const Transition = ({ show = true, children }: any) => (
- show ? <>{typeof children === 'function' ? children({}) : children}</> : null
- )
- Transition.Child = TransitionChild
- return {
- Dialog: DialogComponent,
- Transition,
- DialogTitle,
- Description: DialogDescription,
- }
-})
-
vi.mock('ahooks', async (importOriginal) => {
const actual = await importOriginal<typeof import('ahooks')>()
return {
diff --git a/web/app/components/app/app-access-control/access-control-dialog.tsx b/web/app/components/app/app-access-control/access-control-dialog.tsx
index 611c6f1c92b..ed1301386cd 100644
--- a/web/app/components/app/app-access-control/access-control-dialog.tsx
+++ b/web/app/components/app/app-access-control/access-control-dialog.tsx
@@ -23,9 +23,15 @@ const AccessControlDialog = ({
const close = useCallback(() => {
onClose?.()
}, [onClose])
+
return (
- <Dialog open={show} onOpenChange={open => !open && close()}>
- <DialogContent className={cn('min-h-[323px] w-[600px] p-0', className)}>
+ <Dialog open={show} disablePointerDismissal onOpenChange={open => !open && close()}>
+ <DialogContent
+ className={cn(
+ 'h-auto max-h-none min-h-[323px] w-[600px] max-w-none overflow-y-auto rounded-2xl border-none bg-components-panel-bg p-0 shadow-xl transition-all',
+ className,
+ )}
+ >
<DialogCloseButton className="top-5 right-5 h-8 w-8" />
{children}
</DialogContent>
diff --git a/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx b/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx
index 4a461bd942c..942a199a875 100644
--- a/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx
@@ -87,6 +87,22 @@ describe('VersionInfoModal', () => {
expect(handleClose).toHaveBeenCalledTimes(1)
})
+ it('should close when the dialog requests close', () => {
+ const handleClose = vi.fn()
+
+ render(
+ <VersionInfoModal
+ isOpen
+ onClose={handleClose}
+ onPublish={vi.fn()}
+ />,
+ )
+
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ expect(handleClose).toHaveBeenCalledTimes(1)
+ })
+
it('should validate release note length and clear previous errors before publishing', () => {
const handlePublish = vi.fn()
const handleClose = vi.fn()
diff --git a/web/app/components/app/app-publisher/version-info-modal.tsx b/web/app/components/app/app-publisher/version-info-modal.tsx
index 3fe4c61fb79..264975a08b9 100644
--- a/web/app/components/app/app-publisher/version-info-modal.tsx
+++ b/web/app/components/app/app-publisher/version-info-modal.tsx
@@ -1,12 +1,12 @@
import type { FC } from 'react'
import type { VersionHistory } from '@/types/workflow'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { RiCloseLine } from '@remixicon/react'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import Input from '../../base/input'
import Textarea from '../../base/textarea'
@@ -66,46 +66,55 @@ const VersionInfoModal: FC<VersionInfoModalProps> = ({
}, [])
return (
- <Modal className="p-0" isShow={isOpen} onClose={onClose}>
- <div className="relative w-full p-6 pr-14 pb-4">
- <div className="title-2xl-semi-bold text-text-primary first-letter:capitalize">
- {versionInfo?.marked_name ? t('versionHistory.editVersionInfo', { ns: 'workflow' }) : t('versionHistory.nameThisVersion', { ns: 'workflow' })}
- </div>
- <div className="absolute top-5 right-5 flex h-8 w-8 cursor-pointer items-center justify-center p-1.5" onClick={onClose}>
- <RiCloseLine className="h-[18px] w-[18px] text-text-tertiary" />
- </div>
- </div>
- <div className="flex flex-col gap-y-4 px-6 py-3">
- <div className="flex flex-col gap-y-1">
- <div className="flex h-6 items-center system-sm-semibold text-text-secondary">
- {t('versionHistory.editField.title', { ns: 'workflow' })}
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
+ >
+ <DialogContent className="w-full max-w-[480px] overflow-hidden! border-none p-0 text-left align-middle">
+
+ <div className="relative w-full p-6 pr-14 pb-4">
+ <div className="title-2xl-semi-bold text-text-primary first-letter:capitalize">
+ {versionInfo?.marked_name ? t('versionHistory.editVersionInfo', { ns: 'workflow' }) : t('versionHistory.nameThisVersion', { ns: 'workflow' })}
+ </div>
+ <div className="absolute top-5 right-5 flex h-8 w-8 cursor-pointer items-center justify-center p-1.5" onClick={onClose}>
+ <RiCloseLine className="h-[18px] w-[18px] text-text-tertiary" />
</div>
- <Input
- value={title}
- placeholder={`${t('versionHistory.nameThisVersion', { ns: 'workflow' })}${t('panel.optional', { ns: 'workflow' })}`}
- onChange={handleTitleChange}
- destructive={titleError}
- />
</div>
- <div className="flex flex-col gap-y-1">
- <div className="flex h-6 items-center system-sm-semibold text-text-secondary">
- {t('versionHistory.editField.releaseNotes', { ns: 'workflow' })}
+ <div className="flex flex-col gap-y-4 px-6 py-3">
+ <div className="flex flex-col gap-y-1">
+ <div className="flex h-6 items-center system-sm-semibold text-text-secondary">
+ {t('versionHistory.editField.title', { ns: 'workflow' })}
+ </div>
+ <Input
+ value={title}
+ placeholder={`${t('versionHistory.nameThisVersion', { ns: 'workflow' })}${t('panel.optional', { ns: 'workflow' })}`}
+ onChange={handleTitleChange}
+ destructive={titleError}
+ />
+ </div>
+ <div className="flex flex-col gap-y-1">
+ <div className="flex h-6 items-center system-sm-semibold text-text-secondary">
+ {t('versionHistory.editField.releaseNotes', { ns: 'workflow' })}
+ </div>
+ <Textarea
+ value={releaseNotes}
+ placeholder={`${t('versionHistory.releaseNotesPlaceholder', { ns: 'workflow' })}${t('panel.optional', { ns: 'workflow' })}`}
+ onChange={handleDescriptionChange}
+ destructive={releaseNotesError}
+ />
</div>
- <Textarea
- value={releaseNotes}
- placeholder={`${t('versionHistory.releaseNotesPlaceholder', { ns: 'workflow' })}${t('panel.optional', { ns: 'workflow' })}`}
- onChange={handleDescriptionChange}
- destructive={releaseNotesError}
- />
</div>
- </div>
- <div className="flex justify-end p-6 pt-5">
- <div className="flex items-center gap-x-3">
- <Button onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button variant="primary" onClick={handlePublish}>{t('common.publish', { ns: 'workflow' })}</Button>
+ <div className="flex justify-end p-6 pt-5">
+ <div className="flex items-center gap-x-3">
+ <Button nativeButton={false} onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button nativeButton={false} variant="primary" onClick={handlePublish}>{t('common.publish', { ns: 'workflow' })}</Button>
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx b/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
index 236f9403c92..1dd5d03889d 100644
--- a/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
+++ b/web/app/components/app/configuration/config-prompt/conversation-history/__tests__/edit-modal.spec.tsx
@@ -3,8 +3,11 @@ import { fireEvent, render, screen } from '@testing-library/react'
import * as React from 'react'
import EditModal from '../edit-modal'
-vi.mock('@/app/components/base/modal', () => ({
- default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ children, open }: { children: React.ReactNode, open?: boolean }) =>
+ open === false ? null : <>{children}</>,
+ DialogContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+ DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
describe('Conversation history edit modal', () => {
diff --git a/web/app/components/app/configuration/config-prompt/conversation-history/edit-modal.tsx b/web/app/components/app/configuration/config-prompt/conversation-history/edit-modal.tsx
index 7906a5f8da5..ad73e111c77 100644
--- a/web/app/components/app/configuration/config-prompt/conversation-history/edit-modal.tsx
+++ b/web/app/components/app/configuration/config-prompt/conversation-history/edit-modal.tsx
@@ -2,10 +2,10 @@
import type { FC } from 'react'
import type { ConversationHistoriesRole } from '@/models/debug'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
type Props = {
isShow: boolean
@@ -25,37 +25,45 @@ const EditModal: FC<Props> = ({
const { t } = useTranslation()
const [tempData, setTempData] = useState(data)
return (
- <Modal
- title={t('feature.conversationHistory.editModal.title', { ns: 'appDebug' })}
- isShow={isShow}
- onClose={onClose}
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className="mt-6 text-sm leading-[21px] font-medium text-text-primary">{t('feature.conversationHistory.editModal.userPrefix', { ns: 'appDebug' })}</div>
- <input
- className="mt-2 box-border h-10 w-full rounded-lg bg-components-input-bg-normal px-3 text-sm leading-10"
- value={tempData.user_prefix}
- onChange={e => setTempData({
- ...tempData,
- user_prefix: e.target.value,
- })}
- />
+ <DialogContent className="w-full max-w-[480px] overflow-hidden! border-none p-6 text-left align-middle">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t('feature.conversationHistory.editModal.title', { ns: 'appDebug' })}
+ </DialogTitle>
- <div className="mt-6 text-sm leading-[21px] font-medium text-text-primary">{t('feature.conversationHistory.editModal.assistantPrefix', { ns: 'appDebug' })}</div>
- <input
- className="mt-2 box-border h-10 w-full rounded-lg bg-components-input-bg-normal px-3 text-sm leading-10"
- value={tempData.assistant_prefix}
- onChange={e => setTempData({
- ...tempData,
- assistant_prefix: e.target.value,
- })}
- placeholder={t('chat.conversationNamePlaceholder', { ns: 'common' }) || ''}
- />
+ <div className="mt-6 text-sm leading-[21px] font-medium text-text-primary">{t('feature.conversationHistory.editModal.userPrefix', { ns: 'appDebug' })}</div>
+ <input
+ className="mt-2 box-border h-10 w-full rounded-lg bg-components-input-bg-normal px-3 text-sm leading-10"
+ value={tempData.user_prefix}
+ onChange={e => setTempData({
+ ...tempData,
+ user_prefix: e.target.value,
+ })}
+ />
- <div className="mt-10 flex justify-end">
- <Button className="mr-2 shrink-0" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button variant="primary" className="shrink-0" onClick={() => onSave(tempData)} loading={saveLoading}>{t('operation.save', { ns: 'common' })}</Button>
- </div>
- </Modal>
+ <div className="mt-6 text-sm leading-[21px] font-medium text-text-primary">{t('feature.conversationHistory.editModal.assistantPrefix', { ns: 'appDebug' })}</div>
+ <input
+ className="mt-2 box-border h-10 w-full rounded-lg bg-components-input-bg-normal px-3 text-sm leading-10"
+ value={tempData.assistant_prefix}
+ onChange={e => setTempData({
+ ...tempData,
+ assistant_prefix: e.target.value,
+ })}
+ placeholder={t('chat.conversationNamePlaceholder', { ns: 'common' }) || ''}
+ />
+
+ <div className="mt-10 flex justify-end">
+ <Button className="mr-2 shrink-0" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button variant="primary" className="shrink-0" onClick={() => onSave(tempData)} loading={saveLoading}>{t('operation.save', { ns: 'common' })}</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/app/configuration/config-var/config-modal/index.tsx b/web/app/components/app/configuration/config-var/config-modal/index.tsx
index 824b8a8d825..1976a4ffa0b 100644
--- a/web/app/components/app/configuration/config-var/config-modal/index.tsx
+++ b/web/app/components/app/configuration/config-var/config-modal/index.tsx
@@ -2,13 +2,13 @@
import type { ChangeEvent, FC } from 'react'
import type { Item as SelectItem } from './type-select'
import type { InputVar, InputVarType, MoreInfo } from '@/app/components/workflow/types'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { useStore as useAppStore } from '@/app/components/app/store'
-import Modal from '@/app/components/base/modal'
import ConfigContext from '@/context/debug-configuration'
import { AppModeEnum } from '@/types/app'
import { checkKeys, getNewVarInWorkflow, replaceSpaceWithUnderscoreInVarNameInput } from '@/utils/var'
@@ -141,35 +141,43 @@ const ConfigModal: FC<IConfigModalProps> = ({
}
return (
- <Modal
- title={t(`variableConfig.${isCreate ? 'addModalTitle' : 'editModalTitle'}`, { ns: 'appDebug' })}
- isShow={isShow}
- onClose={onClose}
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className="mb-8" ref={modalRef} tabIndex={-1}>
- <ConfigModalFormFields
- checkboxDefaultSelectValue={checkboxDefaultSelectValue}
- isStringInput={isStringInput}
- jsonSchemaStr={jsonSchemaStr}
- maxLength={max_length}
- modelId={modelConfig.model_id}
- onFilePayloadChange={payload => setTempPayload(payload as InputVar)}
- onJSONSchemaChange={handleJSONSchemaChange}
- onPayloadChange={handlePayloadChange}
- onTypeChange={handleTypeChange}
- onVarKeyBlur={handleVarKeyBlur}
- onVarNameChange={handleVarNameChange}
- options={options}
- selectOptions={selectOptions}
- tempPayload={tempPayload}
- t={t}
+ <DialogContent className="overflow-hidden! border-none text-left align-middle">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(`variableConfig.${isCreate ? 'addModalTitle' : 'editModalTitle'}`, { ns: 'appDebug' })}
+ </DialogTitle>
+
+ <div className="mb-8" ref={modalRef} tabIndex={-1}>
+ <ConfigModalFormFields
+ checkboxDefaultSelectValue={checkboxDefaultSelectValue}
+ isStringInput={isStringInput}
+ jsonSchemaStr={jsonSchemaStr}
+ maxLength={max_length}
+ modelId={modelConfig.model_id}
+ onFilePayloadChange={payload => setTempPayload(payload as InputVar)}
+ onJSONSchemaChange={handleJSONSchemaChange}
+ onPayloadChange={handlePayloadChange}
+ onTypeChange={handleTypeChange}
+ onVarKeyBlur={handleVarKeyBlur}
+ onVarNameChange={handleVarNameChange}
+ options={options}
+ selectOptions={selectOptions}
+ tempPayload={tempPayload}
+ t={t}
+ />
+ </div>
+ <ModalFoot
+ onConfirm={handleConfirm}
+ onCancel={onClose}
/>
- </div>
- <ModalFoot
- onConfirm={handleConfirm}
- onCancel={onClose}
- />
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(ConfigModal)
diff --git a/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx b/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx
index aff540cecfe..ba08daf9b5b 100644
--- a/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx
+++ b/web/app/components/app/configuration/config/automatic/get-automatic-res.tsx
@@ -14,6 +14,7 @@ import {
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import {
RiDatabase2Line,
@@ -32,9 +33,8 @@ import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Generator } from '@/app/components/base/icons/src/vender/other'
import Loading from '@/app/components/base/loading'
-import Modal from '@/app/components/base/modal'
-import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
import { generateBasicAppFirstTimeRule, generateRule } from '@/service/debug'
@@ -282,143 +282,148 @@ const GetAutomaticRes: FC<IGetAutomaticResProps> = ({
}
return (
- <Modal
- isShow={isShow}
- onClose={onClose}
- className="min-w-[1140px] p-0!"
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className="flex h-[680px] flex-wrap">
- <div className="h-full w-[570px] shrink-0 overflow-y-auto border-r border-divider-regular p-6">
- <div className="mb-5">
- <div className={`text-lg leading-[28px] font-bold ${s.textGradient}`}>{t('generate.title', { ns: 'appDebug' })}</div>
- <div className="mt-1 text-[13px] font-normal text-text-tertiary">{t('generate.description', { ns: 'appDebug' })}</div>
- </div>
- <div>
- <ModelParameterModal
- popupClassName="w-[520px]!"
- isAdvancedMode={true}
- provider={model.provider}
- completionParams={model.completion_params}
- modelId={model.name}
- setModel={handleModelChange}
- onCompletionParamsChange={handleCompletionParamsChange}
- hideDebugWithMultipleModel
- />
- </div>
- {isBasicMode && (
- <div className="mt-4">
- <div className="flex items-center">
- <div className="mr-3 shrink-0 text-xs leading-[18px] font-semibold text-text-tertiary uppercase">{t('generate.tryIt', { ns: 'appDebug' })}</div>
- <div
- className="h-px grow"
- style={{
- background: 'linear-gradient(to right, rgba(243, 244, 246, 1), rgba(243, 244, 246, 0))',
- }}
- >
- </div>
- </div>
- <div className="flex flex-wrap">
- {tryList.map(item => (
- <TryLabel
- key={item.key}
- Icon={item.icon}
- text={t(`generate.template.${item.key}.name`, { ns: 'appDebug' })}
- onClick={handleChooseTemplate(item.key)}
- />
- ))}
- </div>
- </div>
- )}
+ <DialogContent className="max-h-none w-[1140px] max-w-none! min-w-[1140px] overflow-hidden! border-none p-0! text-left align-middle">
- {/* inputs */}
- <div className="mt-4">
+ <div className="flex h-[680px] flex-wrap">
+ <div className="h-full w-[570px] shrink-0 overflow-y-auto border-r border-divider-regular p-6">
+ <div className="mb-5">
+ <div className={`text-lg leading-[28px] font-bold ${s.textGradient}`}>{t('generate.title', { ns: 'appDebug' })}</div>
+ <div className="mt-1 text-[13px] font-normal text-text-tertiary">{t('generate.description', { ns: 'appDebug' })}</div>
+ </div>
<div>
- <div className="mb-1.5 system-sm-semibold-uppercase text-text-secondary">{t('generate.instruction', { ns: 'appDebug' })}</div>
- {isBasicMode
- ? (
- <InstructionEditorInBasic
- editorKey={editorKey}
- generatorType={GeneratorType.prompt}
- value={instruction}
- onChange={setInstruction}
- availableVars={[]}
- availableNodes={[]}
- isShowCurrentBlock={!!currentPrompt}
- isShowLastRunBlock={false}
- />
- )
- : (
- <InstructionEditorInWorkflow
- editorKey={editorKey}
- generatorType={GeneratorType.prompt}
- value={instruction}
- onChange={setInstruction}
- nodeId={nodeId || ''}
- isShowCurrentBlock={!!currentPrompt}
- />
- )}
+ <ModelParameterModal
+ popupClassName="w-[520px]!"
+ isAdvancedMode={true}
+ provider={model.provider}
+ completionParams={model.completion_params}
+ modelId={model.name}
+ setModel={handleModelChange}
+ onCompletionParamsChange={handleCompletionParamsChange}
+ hideDebugWithMultipleModel
+ />
</div>
- <IdeaOutput
- value={ideaOutput}
- onChange={setIdeaOutput}
- />
+ {isBasicMode && (
+ <div className="mt-4">
+ <div className="flex items-center">
+ <div className="mr-3 shrink-0 text-xs leading-[18px] font-semibold text-text-tertiary uppercase">{t('generate.tryIt', { ns: 'appDebug' })}</div>
+ <div
+ className="h-px grow"
+ style={{
+ background: 'linear-gradient(to right, rgba(243, 244, 246, 1), rgba(243, 244, 246, 0))',
+ }}
+ >
+ </div>
+ </div>
+ <div className="flex flex-wrap">
+ {tryList.map(item => (
+ <TryLabel
+ key={item.key}
+ Icon={item.icon}
+ text={t(`generate.template.${item.key}.name`, { ns: 'appDebug' })}
+ onClick={handleChooseTemplate(item.key)}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* inputs */}
+ <div className="mt-4">
+ <div>
+ <div className="mb-1.5 system-sm-semibold-uppercase text-text-secondary">{t('generate.instruction', { ns: 'appDebug' })}</div>
+ {isBasicMode
+ ? (
+ <InstructionEditorInBasic
+ editorKey={editorKey}
+ generatorType={GeneratorType.prompt}
+ value={instruction}
+ onChange={setInstruction}
+ availableVars={[]}
+ availableNodes={[]}
+ isShowCurrentBlock={!!currentPrompt}
+ isShowLastRunBlock={false}
+ />
+ )
+ : (
+ <InstructionEditorInWorkflow
+ editorKey={editorKey}
+ generatorType={GeneratorType.prompt}
+ value={instruction}
+ onChange={setInstruction}
+ nodeId={nodeId || ''}
+ isShowCurrentBlock={!!currentPrompt}
+ />
+ )}
+ </div>
+ <IdeaOutput
+ value={ideaOutput}
+ onChange={setIdeaOutput}
+ />
- <div className="mt-7 flex justify-end space-x-2">
- <Button onClick={onClose}>{t(`${i18nPrefix}.dismiss`, { ns: 'appDebug' })}</Button>
- <Button
- className="flex space-x-1"
- variant="primary"
- onClick={onGenerate}
- disabled={isLoading}
- >
- <Generator className="h-4 w-4" />
- <span className="text-xs font-semibold">{t('generate.generate', { ns: 'appDebug' })}</span>
- </Button>
+ <div className="mt-7 flex justify-end space-x-2">
+ <Button onClick={onClose}>{t(`${i18nPrefix}.dismiss`, { ns: 'appDebug' })}</Button>
+ <Button
+ className="flex space-x-1"
+ variant="primary"
+ onClick={onGenerate}
+ disabled={isLoading}
+ >
+ <Generator className="h-4 w-4" />
+ <span className="text-xs font-semibold">{t('generate.generate', { ns: 'appDebug' })}</span>
+ </Button>
+ </div>
</div>
</div>
- </div>
- {(!isLoading && current) && (
- <div className="h-full w-0 grow bg-background-default-subtle p-6 pb-0">
- <Result
- current={current!}
- isBasicMode={isBasicMode}
- nodeId={nodeId!}
- currentVersionIndex={currentVersionIndex || 0}
- setCurrentVersionIndex={setCurrentVersionIndex}
- versions={versions || []}
- onApply={showConfirmOverwrite}
- generatorType={GeneratorType.prompt}
- />
- </div>
- )}
- {isLoading && renderLoading}
- {isShowAutoPromptResPlaceholder() && <ResPlaceholder />}
- <AlertDialog open={isShowConfirmOverwrite} onOpenChange={open => !open && hideShowConfirmOverwrite()}>
- <AlertDialogContent>
- <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
- <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
- {t('generate.overwriteTitle', { ns: 'appDebug' })}
- </AlertDialogTitle>
- <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
- {t('generate.overwriteMessage', { ns: 'appDebug' })}
- </AlertDialogDescription>
+ {(!isLoading && current) && (
+ <div className="h-full w-0 grow bg-background-default-subtle p-6 pb-0">
+ <Result
+ current={current!}
+ isBasicMode={isBasicMode}
+ nodeId={nodeId!}
+ currentVersionIndex={currentVersionIndex || 0}
+ setCurrentVersionIndex={setCurrentVersionIndex}
+ versions={versions || []}
+ onApply={showConfirmOverwrite}
+ generatorType={GeneratorType.prompt}
+ />
</div>
- <AlertDialogActions>
- <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>
- <AlertDialogConfirmButton
- onClick={() => {
- hideShowConfirmOverwrite()
- onFinished(current!)
- }}
- >
- {t('operation.confirm', { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogActions>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- </Modal>
+ )}
+ {isLoading && renderLoading}
+ {isShowAutoPromptResPlaceholder() && <ResPlaceholder />}
+ <AlertDialog open={isShowConfirmOverwrite} onOpenChange={open => !open && hideShowConfirmOverwrite()}>
+ <AlertDialogContent>
+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
+ {t('generate.overwriteTitle', { ns: 'appDebug' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
+ {t('generate.overwriteMessage', { ns: 'appDebug' })}
+ </AlertDialogDescription>
+ </div>
+ <AlertDialogActions>
+ <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ onClick={() => {
+ hideShowConfirmOverwrite()
+ onFinished(current!)
+ }}
+ >
+ {t('operation.confirm', { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(GetAutomaticRes)
diff --git a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx
index c69c0f5dae2..b603243e00e 100644
--- a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx
+++ b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx
@@ -13,6 +13,7 @@ import {
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import {
useBoolean,
@@ -23,7 +24,6 @@ import { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Generator } from '@/app/components/base/icons/src/vender/other'
import Loading from '@/app/components/base/loading'
-import Modal from '@/app/components/base/modal'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
@@ -202,99 +202,104 @@ export const GetCodeGeneratorResModal: FC<IGetCodeGeneratorResProps> = (
)
return (
- <Modal
- isShow={isShow}
- onClose={onClose}
- className="min-w-[1140px] p-0!"
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className="relative flex h-[680px] flex-wrap">
- <div className="h-full w-[570px] shrink-0 overflow-y-auto border-r border-divider-regular p-6">
- <div className="mb-5">
- <div className={`text-lg leading-[28px] font-bold ${s.textGradient}`}>{t('codegen.title', { ns: 'appDebug' })}</div>
- <div className="mt-1 text-[13px] font-normal text-text-tertiary">{t('codegen.description', { ns: 'appDebug' })}</div>
- </div>
- <div className="mb-4">
- <ModelParameterModal
- popupClassName="w-[520px]!"
- isAdvancedMode={true}
- provider={model.provider}
- completionParams={model.completion_params}
- modelId={model.name}
- setModel={handleModelChange}
- onCompletionParamsChange={handleCompletionParamsChange}
- hideDebugWithMultipleModel
- />
- </div>
- <div>
- <div className="text-[0px]">
- <div className="mb-1.5 system-sm-semibold-uppercase text-text-secondary">{t('codegen.instruction', { ns: 'appDebug' })}</div>
- <InstructionEditor
- editorKey={editorKey}
- value={instruction}
- onChange={setInstruction}
- nodeId={nodeId}
- generatorType={GeneratorType.code}
- isShowCurrentBlock={!!currentCode}
+ <DialogContent className="max-h-none w-full min-w-[1140px] overflow-hidden! border-none p-0! text-left align-middle">
+
+ <div className="relative flex h-[680px] flex-wrap">
+ <div className="h-full w-[570px] shrink-0 overflow-y-auto border-r border-divider-regular p-6">
+ <div className="mb-5">
+ <div className={`text-lg leading-[28px] font-bold ${s.textGradient}`}>{t('codegen.title', { ns: 'appDebug' })}</div>
+ <div className="mt-1 text-[13px] font-normal text-text-tertiary">{t('codegen.description', { ns: 'appDebug' })}</div>
+ </div>
+ <div className="mb-4">
+ <ModelParameterModal
+ popupClassName="w-[520px]!"
+ isAdvancedMode={true}
+ provider={model.provider}
+ completionParams={model.completion_params}
+ modelId={model.name}
+ setModel={handleModelChange}
+ onCompletionParamsChange={handleCompletionParamsChange}
+ hideDebugWithMultipleModel
/>
</div>
- <IdeaOutput
- value={ideaOutput}
- onChange={setIdeaOutput}
- />
+ <div>
+ <div className="text-[0px]">
+ <div className="mb-1.5 system-sm-semibold-uppercase text-text-secondary">{t('codegen.instruction', { ns: 'appDebug' })}</div>
+ <InstructionEditor
+ editorKey={editorKey}
+ value={instruction}
+ onChange={setInstruction}
+ nodeId={nodeId}
+ generatorType={GeneratorType.code}
+ isShowCurrentBlock={!!currentCode}
+ />
+ </div>
+ <IdeaOutput
+ value={ideaOutput}
+ onChange={setIdeaOutput}
+ />
- <div className="mt-7 flex justify-end space-x-2">
- <Button onClick={onClose}>{t(`${i18nPrefix}.dismiss`, { ns: 'appDebug' })}</Button>
- <Button
- className="flex space-x-1"
- variant="primary"
- onClick={onGenerate}
- disabled={isLoading}
- >
- <Generator className="h-4 w-4" />
- <span className="text-xs font-semibold">{t('codegen.generate', { ns: 'appDebug' })}</span>
- </Button>
+ <div className="mt-7 flex justify-end space-x-2">
+ <Button onClick={onClose}>{t(`${i18nPrefix}.dismiss`, { ns: 'appDebug' })}</Button>
+ <Button
+ className="flex space-x-1"
+ variant="primary"
+ onClick={onGenerate}
+ disabled={isLoading}
+ >
+ <Generator className="h-4 w-4" />
+ <span className="text-xs font-semibold">{t('codegen.generate', { ns: 'appDebug' })}</span>
+ </Button>
+ </div>
</div>
</div>
+ {isLoading && renderLoading}
+ {!isLoading && !current && <ResPlaceholder />}
+ {(!isLoading && current) && (
+ <div className="h-full w-0 grow bg-background-default-subtle p-6 pb-0">
+ <Result
+ current={current!}
+ currentVersionIndex={currentVersionIndex || 0}
+ setCurrentVersionIndex={setCurrentVersionIndex}
+ versions={versions || []}
+ onApply={showConfirmOverwrite}
+ generatorType={GeneratorType.code}
+ />
+ </div>
+ )}
</div>
- {isLoading && renderLoading}
- {!isLoading && !current && <ResPlaceholder />}
- {(!isLoading && current) && (
- <div className="h-full w-0 grow bg-background-default-subtle p-6 pb-0">
- <Result
- current={current!}
- currentVersionIndex={currentVersionIndex || 0}
- setCurrentVersionIndex={setCurrentVersionIndex}
- versions={versions || []}
- onApply={showConfirmOverwrite}
- generatorType={GeneratorType.code}
- />
- </div>
- )}
- </div>
- <AlertDialog open={isShowConfirmOverwrite} onOpenChange={open => !open && hideShowConfirmOverwrite()}>
- <AlertDialogContent>
- <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
- <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
- {t('codegen.overwriteConfirmTitle', { ns: 'appDebug' })}
- </AlertDialogTitle>
- <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
- {t('codegen.overwriteConfirmMessage', { ns: 'appDebug' })}
- </AlertDialogDescription>
- </div>
- <AlertDialogActions>
- <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>
- <AlertDialogConfirmButton
- onClick={() => {
- hideShowConfirmOverwrite()
- onFinished(current!)
- }}
- >
- {t('operation.confirm', { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogActions>
- </AlertDialogContent>
- </AlertDialog>
- </Modal>
+ <AlertDialog open={isShowConfirmOverwrite} onOpenChange={open => !open && hideShowConfirmOverwrite()}>
+ <AlertDialogContent>
+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
+ {t('codegen.overwriteConfirmTitle', { ns: 'appDebug' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
+ {t('codegen.overwriteConfirmMessage', { ns: 'appDebug' })}
+ </AlertDialogDescription>
+ </div>
+ <AlertDialogActions>
+ <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ onClick={() => {
+ hideShowConfirmOverwrite()
+ onFinished(current!)
+ }}
+ >
+ {t('operation.confirm', { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/app/configuration/dataset-config/params-config/__tests__/index.spec.tsx b/web/app/components/app/configuration/dataset-config/params-config/__tests__/index.spec.tsx
index b5924a5f237..e9f535999b4 100644
--- a/web/app/components/app/configuration/dataset-config/params-config/__tests__/index.spec.tsx
+++ b/web/app/components/app/configuration/dataset-config/params-config/__tests__/index.spec.tsx
@@ -13,37 +13,6 @@ import { RerankingModeEnum } from '@/models/datasets'
import { RETRIEVE_TYPE } from '@/types/app'
import ParamsConfig from '../index'
-vi.mock('@headlessui/react', () => ({
- Dialog: ({ children, className }: { children: React.ReactNode, className?: string }) => (
- <div role="dialog" className={className}>
- {children}
- </div>
- ),
- DialogPanel: ({ children, className, ...props }: { children: React.ReactNode, className?: string }) => (
- <div className={className} {...props}>
- {children}
- </div>
- ),
- DialogTitle: ({ children, className, ...props }: { children: React.ReactNode, className?: string }) => (
- <div className={className} {...props}>
- {children}
- </div>
- ),
- Transition: ({ show, children }: { show: boolean, children: React.ReactNode }) => (show ? <>{children}</> : null),
- TransitionChild: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- Switch: ({ checked, onChange, children, ...props }: { checked: boolean, onChange?: (value: boolean) => void, children?: React.ReactNode }) => (
- <button
- type="button"
- role="switch"
- aria-checked={checked}
- onClick={() => onChange?.(!checked)}
- {...props}
- >
- {children}
- </button>
- ),
-}))
-
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
useModelListAndDefaultModelAndCurrentProviderAndModel: vi.fn(),
useCurrentProviderAndModel: vi.fn(),
diff --git a/web/app/components/app/configuration/dataset-config/params-config/index.tsx b/web/app/components/app/configuration/dataset-config/params-config/index.tsx
index d4578af1d7f..15d34f19d78 100644
--- a/web/app/components/app/configuration/dataset-config/params-config/index.tsx
+++ b/web/app/components/app/configuration/dataset-config/params-config/index.tsx
@@ -3,12 +3,12 @@ import type { DataSet } from '@/models/datasets'
import type { DatasetConfigs } from '@/models/debug'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { RiEqualizer2Line } from '@remixicon/react'
import { memo, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
-import Modal from '@/app/components/base/modal'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useCurrentProviderAndModel, useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import {
@@ -123,32 +123,36 @@ const ParamsConfig = ({
</Button>
{
rerankSettingModalOpen && (
- <Modal
- isShow={rerankSettingModalOpen}
- onClose={() => {
- setRerankSettingModalOpen(false)
+ <Dialog
+ open={rerankSettingModalOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ setRerankSettingModalOpen(false)
+ }
}}
- className="sm:min-w-[528px]"
>
- <ConfigContent
- datasetConfigs={tempDataSetConfigs}
- onChange={handleSetTempDataSetConfigs}
- selectedDatasets={selectedDatasets}
- />
+ <DialogContent className="w-full max-w-[480px] overflow-hidden! border-none text-left align-middle sm:min-w-[528px]">
- <div className="mt-6 flex justify-end">
- <Button
- className="mr-2 shrink-0"
- onClick={() => {
- setTempDataSetConfigs(datasetConfigs)
- setRerankSettingModalOpen(false)
- }}
- >
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button variant="primary" className="shrink-0" onClick={handleSave}>{t('operation.save', { ns: 'common' })}</Button>
- </div>
- </Modal>
+ <ConfigContent
+ datasetConfigs={tempDataSetConfigs}
+ onChange={handleSetTempDataSetConfigs}
+ selectedDatasets={selectedDatasets}
+ />
+
+ <div className="mt-6 flex justify-end">
+ <Button
+ className="mr-2 shrink-0"
+ onClick={() => {
+ setTempDataSetConfigs(datasetConfigs)
+ setRerankSettingModalOpen(false)
+ }}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button variant="primary" className="shrink-0" onClick={handleSave}>{t('operation.save', { ns: 'common' })}</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/app/create-app-dialog-shell.tsx b/web/app/components/app/create-app-dialog-shell.tsx
new file mode 100644
index 00000000000..80466efaa18
--- /dev/null
+++ b/web/app/components/app/create-app-dialog-shell.tsx
@@ -0,0 +1,51 @@
+'use client'
+
+import type { ReactNode } from 'react'
+import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+
+type CreateAppDialogShellProps = {
+ children: ReactNode
+ contentClassName?: string
+ onClose: () => void
+ show: boolean
+ title: ReactNode
+}
+
+export function CreateAppDialogShell({
+ children,
+ contentClassName,
+ onClose,
+ show,
+ title,
+}: CreateAppDialogShellProps) {
+ return (
+ <Dialog
+ open={show}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen)
+ onClose()
+ }}
+ >
+ <DialogContent
+ backdropClassName="bg-background-overlay-backdrop backdrop-blur-[6px]"
+ className="top-0 left-0 h-screen max-h-none w-screen max-w-none translate-x-0 translate-y-0 overflow-hidden rounded-none border-none bg-transparent p-4 shadow-none"
+ >
+ <div className="h-full w-full rounded-2xl border border-effects-highlight bg-background-default-subtle">
+ <div className={cn('relative h-full overflow-hidden', contentClassName)}>
+ <DialogTitle className="sr-only">{title}</DialogTitle>
+ <button
+ type="button"
+ aria-label="Close"
+ className="absolute top-3 right-3 z-50 flex h-9 w-9 cursor-pointer items-center justify-center rounded-[10px] bg-components-button-tertiary-bg hover:bg-components-button-tertiary-bg-hover"
+ onClick={onClose}
+ >
+ <span aria-hidden="true" className="i-ri-close-large-line h-3.5 w-3.5 text-components-button-tertiary-text" />
+ </button>
+ {children}
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx b/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
index cc59ce7456c..59febff8d5a 100644
--- a/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
+++ b/web/app/components/app/create-app-dialog/__tests__/index.spec.tsx
@@ -25,17 +25,6 @@ vi.mock('../app-list', () => ({
},
}))
-// Store captured callbacks from useKeyPress
-let capturedEscCallback: (() => void) | undefined
-const mockUseKeyPress = vi.fn((key: string, callback: () => void) => {
- if (key === 'esc')
- capturedEscCallback = callback
-})
-
-vi.mock('ahooks', () => ({
- useKeyPress: (key: string, callback: () => void) => mockUseKeyPress(key, callback),
-}))
-
describe('CreateAppTemplateDialog', () => {
const defaultProps = {
show: false,
@@ -46,53 +35,18 @@ describe('CreateAppTemplateDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
- capturedEscCallback = undefined
})
describe('Rendering', () => {
it('should not render when show is false', () => {
render(<CreateAppTemplateDialog {...defaultProps} />)
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
- // FullScreenModal should not render any content when open is false
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('should render modal when show is true', () => {
render(<CreateAppTemplateDialog {...defaultProps} show={true} />)
- // FullScreenModal renders with role="dialog"
- // FullScreenModal renders with role="dialog"
expect(screen.getByRole('dialog'))!.toBeInTheDocument()
expect(screen.getByTestId('app-list'))!.toBeInTheDocument()
})
@@ -113,7 +67,7 @@ describe('CreateAppTemplateDialog', () => {
})
describe('Props', () => {
- it('should pass show prop to FullScreenModal', () => {
+ it('should pass show prop to the dialog shell', () => {
const { rerender } = render(<CreateAppTemplateDialog {...defaultProps} />)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
@@ -122,15 +76,17 @@ describe('CreateAppTemplateDialog', () => {
expect(screen.getByRole('dialog'))!.toBeInTheDocument()
})
- it('should pass closable prop to FullScreenModal', () => {
- // Since the FullScreenModal is always rendered with closable=true
- // we can verify that the modal renders with the proper structure
- render(<CreateAppTemplateDialog {...defaultProps} show={true} />)
+ it('should close from the dialog shell close button', () => {
+ const mockOnClose = vi.fn()
- // Verify that the modal has the proper dialog structure
- const dialog = screen.getByRole('dialog')
- expect(dialog)!.toBeInTheDocument()
- expect(dialog)!.toHaveAttribute('aria-modal', 'true')
+ render(<CreateAppTemplateDialog {...defaultProps} show={true} onClose={mockOnClose} />)
+
+ const closeButton = screen.getByRole('button', { name: 'Close' })
+ expect(closeButton)!.toBeInTheDocument()
+
+ fireEvent.click(closeButton)
+
+ expect(mockOnClose).toHaveBeenCalledTimes(1)
})
})
@@ -143,8 +99,6 @@ describe('CreateAppTemplateDialog', () => {
const dialog = screen.getByRole('dialog')
expect(dialog)!.toBeInTheDocument()
- // Test that AppList component renders (child component interactions)
- // Test that AppList component renders (child component interactions)
expect(screen.getByTestId('app-list'))!.toBeInTheDocument()
expect(screen.getByTestId('app-list-success'))!.toBeInTheDocument()
})
@@ -183,65 +137,6 @@ describe('CreateAppTemplateDialog', () => {
})
})
- describe('useKeyPress Integration', () => {
- it('should set up ESC key listener when modal is shown', () => {
- render(<CreateAppTemplateDialog {...defaultProps} show={true} />)
-
- expect(mockUseKeyPress).toHaveBeenCalledWith('esc', expect.any(Function))
- })
-
- it('should handle ESC key press to close modal', () => {
- const mockOnClose = vi.fn()
- render(
- <CreateAppTemplateDialog
- {...defaultProps}
- show={true}
- onClose={mockOnClose}
- />,
- )
-
- expect(capturedEscCallback).toBeDefined()
- expect(typeof capturedEscCallback).toBe('function')
-
- // Simulate ESC key press
- capturedEscCallback?.()
-
- expect(mockOnClose).toHaveBeenCalledTimes(1)
- })
-
- it('should not call onClose when ESC key is pressed and modal is not shown', () => {
- const mockOnClose = vi.fn()
- render(
- <CreateAppTemplateDialog
- {...defaultProps}
- show={false} // Modal not shown
- onClose={mockOnClose}
- />,
- )
-
- // The callback should still be created but not execute onClose
- expect(capturedEscCallback).toBeDefined()
-
- // Simulate ESC key press
- capturedEscCallback?.()
-
- // onClose should not be called because modal is not shown
- expect(mockOnClose).not.toHaveBeenCalled()
- })
- })
-
- describe('Callback Dependencies', () => {
- it('should create stable callback reference for ESC key handler', () => {
- render(<CreateAppTemplateDialog {...defaultProps} show={true} />)
-
- // Verify that useKeyPress was called with a function
- const calls = mockUseKeyPress.mock.calls
- expect(calls.length).toBeGreaterThan(0)
- expect(calls[0]![0]).toBe('esc')
- expect(typeof calls[0]![1]).toBe('function')
- })
- })
-
describe('Edge Cases', () => {
it('should handle null props gracefully', () => {
expect(() => {
diff --git a/web/app/components/app/create-app-dialog/index.tsx b/web/app/components/app/create-app-dialog/index.tsx
index 762dddc0281..45950a9f62a 100644
--- a/web/app/components/app/create-app-dialog/index.tsx
+++ b/web/app/components/app/create-app-dialog/index.tsx
@@ -1,7 +1,6 @@
'use client'
-import { useKeyPress } from 'ahooks'
-import { useCallback } from 'react'
-import FullScreenModal from '@/app/components/base/fullscreen-modal'
+import { useTranslation } from 'react-i18next'
+import { CreateAppDialogShell } from '../create-app-dialog-shell'
import AppList from './app-list'
type CreateAppDialogProps = {
@@ -12,19 +11,10 @@ type CreateAppDialogProps = {
}
const CreateAppTemplateDialog = ({ show, onSuccess, onClose, onCreateFromBlank }: CreateAppDialogProps) => {
- const handleEscKeyPress = useCallback(() => {
- if (show)
- onClose()
- }, [show, onClose])
-
- useKeyPress('esc', handleEscKeyPress)
+ const { t } = useTranslation()
return (
- <FullScreenModal
- open={show}
- closable
- onClose={onClose}
- >
+ <CreateAppDialogShell show={show} title={t('newApp.startFromTemplate', { ns: 'app' })} onClose={onClose}>
<AppList
onCreateFromBlank={onCreateFromBlank}
onSuccess={() => {
@@ -32,7 +22,7 @@ const CreateAppTemplateDialog = ({ show, onSuccess, onClose, onCreateFromBlank }
onClose()
}}
/>
- </FullScreenModal>
+ </CreateAppDialogShell>
)
}
diff --git a/web/app/components/app/create-app-modal/index.tsx b/web/app/components/app/create-app-modal/index.tsx
index 2ff8a0aacdf..42514e986d0 100644
--- a/web/app/components/app/create-app-modal/index.tsx
+++ b/web/app/components/app/create-app-modal/index.tsx
@@ -7,11 +7,10 @@ import { cn } from '@langgenius/dify-ui/cn'
import { toast } from '@langgenius/dify-ui/toast'
import { RiArrowRightLine, RiArrowRightSLine, RiExchange2Fill } from '@remixicon/react'
import { useDebounceFn, useKeyPress } from 'ahooks'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import Divider from '@/app/components/base/divider'
-import FullScreenModal from '@/app/components/base/fullscreen-modal'
import { BubbleTextMod, ChatBot, ListSparkle, Logic } from '@/app/components/base/icons/src/vender/solid/communication'
import Input from '@/app/components/base/input'
import Textarea from '@/app/components/base/textarea'
@@ -28,6 +27,7 @@ import { trackCreateApp } from '@/utils/create-app-tracking'
import { basePath } from '@/utils/var'
import AppIconPicker from '../../base/app-icon-picker'
import ShortcutsName from '../../workflow/shortcuts-name'
+import { CreateAppDialogShell } from '../create-app-dialog-shell'
type CreateAppProps = {
onSuccess: () => void
@@ -36,6 +36,10 @@ type CreateAppProps = {
defaultAppMode?: AppModeEnum
}
+const shouldExpandBeginnerAppTypes = (appMode?: AppModeEnum) => {
+ return appMode === AppModeEnum.CHAT || appMode === AppModeEnum.AGENT_CHAT || appMode === AppModeEnum.COMPLETION
+}
+
function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: CreateAppProps) {
const { t } = useTranslation()
const { push } = useRouter()
@@ -45,7 +49,7 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:
const [showAppIconPicker, setShowAppIconPicker] = useState(false)
const [name, setName] = useState('')
const [description, setDescription] = useState('')
- const [isAppTypeExpanded, setIsAppTypeExpanded] = useState(false)
+ const [isAppTypeExpanded, setIsAppTypeExpanded] = useState(() => shouldExpandBeginnerAppTypes(defaultAppMode))
const { plan, enableBilling } = useProviderContext()
const isAppsFull = (enableBilling && plan.usage.buildApps >= plan.total.buildApps)
@@ -53,11 +57,6 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:
const isCreatingRef = useRef(false)
- useEffect(() => {
- if (appMode === AppModeEnum.CHAT || appMode === AppModeEnum.AGENT_CHAT || appMode === AppModeEnum.COMPLETION)
- setIsAppTypeExpanded(true)
- }, [appMode])
-
const onCreate = useCallback(async () => {
if (!appMode) {
toast.error(t('newApp.appTypeRequired', { ns: 'app' }))
@@ -88,8 +87,8 @@ function CreateApp({ onClose, onSuccess, onCreateFromTemplate, defaultAppMode }:
localStorage.setItem(NEED_REFRESH_APP_LIST_KEY, '1')
getRedirection(isCurrentWorkspaceEditor, app, push)
}
- catch (e: any) {
- toast.error(e.message || t('newApp.appCreateFailed', { ns: 'app' }))
+ catch (error) {
+ toast.error(error instanceof Error ? error.message : t('newApp.appCreateFailed', { ns: 'app' }))
}
isCreatingRef.current = false
}, [name, t, appMode, appIcon, description, onSuccess, onClose, push, isCurrentWorkspaceEditor])
@@ -290,15 +289,17 @@ type CreateAppDialogProps = CreateAppProps & {
show: boolean
}
const CreateAppModal = ({ show, onClose, onSuccess, onCreateFromTemplate, defaultAppMode }: CreateAppDialogProps) => {
+ const { t } = useTranslation()
+
return (
- <FullScreenModal
- overflowVisible
- closable
- open={show}
+ <CreateAppDialogShell
+ show={show}
+ title={t('newApp.startFromBlank', { ns: 'app' })}
+ contentClassName="overflow-visible"
onClose={onClose}
>
<CreateApp onClose={onClose} onSuccess={onSuccess} onCreateFromTemplate={onCreateFromTemplate} defaultAppMode={defaultAppMode} />
- </FullScreenModal>
+ </CreateAppDialogShell>
)
}
diff --git a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
index b3d007c2e7b..dac5b22ee69 100644
--- a/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/create-from-dsl-modal/__tests__/index.spec.tsx
@@ -307,6 +307,78 @@ describe('CreateFromDSLModal', () => {
expect(mockTrackCreateApp).toHaveBeenCalledWith({ appMode: AppModeEnum.WORKFLOW })
})
+ it('should close the DSL mismatch modal when dialog requests close', async () => {
+ vi.useFakeTimers()
+ mockImportDSL.mockResolvedValue({
+ id: 'import-close',
+ status: DSLImportStatus.PENDING,
+ imported_dsl_version: '1.0.0',
+ current_dsl_version: '2.0.0',
+ })
+
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ })
+
+ await act(async () => {
+ vi.advanceTimersByTime(300)
+ })
+
+ expect(screen.getByText('newApp.appCreateDSLErrorTitle'))!.toBeInTheDocument()
+
+ vi.useRealTimers()
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ await waitFor(() => {
+ expect(screen.queryByText('newApp.appCreateDSLErrorTitle')).not.toBeInTheDocument()
+ })
+ })
+
+ it('should close the DSL mismatch modal when cancel is clicked', async () => {
+ vi.useFakeTimers()
+ mockImportDSL.mockResolvedValue({
+ id: 'import-cancel',
+ status: DSLImportStatus.PENDING,
+ imported_dsl_version: '1.0.0',
+ current_dsl_version: '2.0.0',
+ })
+
+ render(
+ <CreateFromDSLModal
+ show
+ onClose={vi.fn()}
+ activeTab={CreateFromDSLModalTab.FROM_URL}
+ dslUrl="https://example.com/app.yml"
+ />,
+ )
+
+ await act(async () => {
+ fireEvent.click(getCreateButton())
+ })
+
+ await act(async () => {
+ vi.advanceTimersByTime(300)
+ })
+
+ expect(screen.getByText('newApp.appCreateDSLErrorTitle'))!.toBeInTheDocument()
+
+ vi.useRealTimers()
+ fireEvent.click(screen.getAllByRole('button', { name: 'newApp.Cancel' }).at(-1)!)
+
+ await waitFor(() => {
+ expect(screen.queryByText('newApp.appCreateDSLErrorTitle')).not.toBeInTheDocument()
+ })
+ })
+
it('should ignore empty import responses and prevent duplicate submissions while a request is in flight', async () => {
let resolveImport!: (value: { id: string, status: DSLImportStatus, app_id: string, app_mode: string }) => void
mockImportDSL.mockImplementationOnce(() => new Promise((resolve) => {
@@ -397,6 +469,7 @@ describe('CreateFromDSLModal', () => {
mockImportDSL.mockResolvedValueOnce({
id: 'import-failed',
status: DSLImportStatus.FAILED,
+ error: 'Invalid YAML format',
})
mockImportDSL.mockRejectedValueOnce(new Error('boom'))
@@ -412,7 +485,7 @@ describe('CreateFromDSLModal', () => {
await act(async () => {
fireEvent.click(getCreateButton())
})
- expect(toastMocks.error).toHaveBeenCalledWith('newApp.appCreateFailed')
+ expect(toastMocks.error).toHaveBeenCalledWith('Invalid YAML format')
rerender(
<CreateFromDSLModal
@@ -427,6 +500,7 @@ describe('CreateFromDSLModal', () => {
fireEvent.click(getCreateButton())
})
expect(toastMocks.error).toHaveBeenCalledTimes(2)
+ expect(toastMocks.error).toHaveBeenLastCalledWith('newApp.appCreateFailed')
})
it('should handle pending import confirmation failures and cancellation', async () => {
@@ -438,7 +512,7 @@ describe('CreateFromDSLModal', () => {
current_dsl_version: '2.0.0',
})
mockImportDSLConfirm
- .mockResolvedValueOnce({ status: DSLImportStatus.FAILED })
+ .mockResolvedValueOnce({ status: DSLImportStatus.FAILED, error: 'Confirm failed' })
.mockRejectedValueOnce(new Error('boom'))
render(
@@ -465,11 +539,12 @@ describe('CreateFromDSLModal', () => {
await act(async () => {
fireEvent.click(screen.getAllByRole('button', { name: 'newApp.Confirm' })[0]!)
})
- expect(toastMocks.error).toHaveBeenCalledWith('newApp.appCreateFailed')
+ expect(toastMocks.error).toHaveBeenCalledWith('Confirm failed')
await act(async () => {
fireEvent.click(screen.getAllByRole('button', { name: 'newApp.Confirm' })[0]!)
})
expect(toastMocks.error).toHaveBeenCalledTimes(2)
+ expect(toastMocks.error).toHaveBeenLastCalledWith('newApp.appCreateFailed')
})
})
diff --git a/web/app/components/app/create-from-dsl-modal/dsl-confirm-modal.tsx b/web/app/components/app/create-from-dsl-modal/dsl-confirm-modal.tsx
index d0c97e185c8..726b3f17422 100644
--- a/web/app/components/app/create-from-dsl-modal/dsl-confirm-modal.tsx
+++ b/web/app/components/app/create-from-dsl-modal/dsl-confirm-modal.tsx
@@ -1,6 +1,13 @@
-import { Button } from '@langgenius/dify-ui/button'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
type DSLConfirmModalProps = {
versions?: {
@@ -20,32 +27,36 @@ const DSLConfirmModal = ({
const { t } = useTranslation()
return (
- <Modal
- isShow
- onClose={() => onCancel()}
- className="w-[480px]"
+ <AlertDialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
>
- <div className="flex flex-col items-start gap-2 self-stretch pb-4">
- <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>
- <div className="flex grow flex-col system-md-regular text-text-secondary">
- <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
- <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
- <br />
- <div>
- {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
- <span className="system-md-medium">{versions.importedVersion}</span>
- </div>
- <div>
- {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
- <span className="system-md-medium">{versions.systemVersion}</span>
- </div>
+ <AlertDialogContent className="w-[480px] overflow-hidden! border-none text-left align-middle shadow-xl">
+ <div className="flex flex-col items-start gap-2 self-stretch p-6 pb-4">
+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</AlertDialogTitle>
+ <AlertDialogDescription render={<div />} className="flex grow flex-col system-md-regular text-text-secondary">
+ <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
+ <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
+ <br />
+ <div>
+ {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
+ <span className="system-md-medium">{versions.importedVersion}</span>
+ </div>
+ <div>
+ {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
+ <span className="system-md-medium">{versions.systemVersion}</span>
+ </div>
+ </AlertDialogDescription>
</div>
- </div>
- <div className="flex items-start justify-end gap-2 self-stretch pt-6">
- <Button variant="secondary" onClick={() => onCancel()}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button variant="primary" tone="destructive" onClick={onConfirm} disabled={confirmDisabled}>{t('newApp.Confirm', { ns: 'app' })}</Button>
- </div>
- </Modal>
+ <AlertDialogActions>
+ <AlertDialogCancelButton variant="secondary">{t('newApp.Cancel', { ns: 'app' })}</AlertDialogCancelButton>
+ <AlertDialogConfirmButton onClick={onConfirm} disabled={confirmDisabled}>{t('newApp.Confirm', { ns: 'app' })}</AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
)
}
diff --git a/web/app/components/app/create-from-dsl-modal/index.tsx b/web/app/components/app/create-from-dsl-modal/index.tsx
index bc5f3526340..5b8a4e74696 100644
--- a/web/app/components/app/create-from-dsl-modal/index.tsx
+++ b/web/app/components/app/create-from-dsl-modal/index.tsx
@@ -3,14 +3,12 @@
import type { MouseEventHandler } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
-import { RiCloseLine } from '@remixicon/react'
import { useDebounceFn, useKeyPress } from 'ahooks'
-import { noop } from 'es-toolkit/function'
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import AppsFull from '@/app/components/billing/apps-full-in-dialog'
import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'
import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
@@ -47,7 +45,7 @@ export enum CreateFromDSLModalTab {
const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSLModalTab.FROM_FILE, dslUrl = '', droppedFile }: CreateFromDSLModalProps) => {
const { push } = useRouter()
const { t } = useTranslation()
- const [currentFile, setDSLFile] = useState<File | undefined>(droppedFile)
+ const [currentFile, setCurrentFile] = useState<File | undefined>(droppedFile)
const [fileContent, setFileContent] = useState<string>()
const [currentTab, setCurrentTab] = useState(activeTab)
const [dslUrlValue, setDslUrlValue] = useState(dslUrl)
@@ -56,22 +54,22 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDS
const [importId, setImportId] = useState<string>()
const { handleCheckPluginDependencies } = usePluginDependencies()
- const readFile = (file: File) => {
+ const readFile = useCallback((file: File) => {
const reader = new FileReader()
reader.onload = function (event) {
const content = event.target?.result
setFileContent(content as string)
}
reader.readAsText(file)
- }
+ }, [])
- const handleFile = (file?: File) => {
- setDSLFile(file)
+ const handleFile = useCallback((file?: File) => {
+ setCurrentFile(file)
if (file)
readFile(file)
if (!file)
setFileContent('')
- }
+ }, [readFile])
const { isCurrentWorkspaceEditor } = useAppContext()
const { plan, enableBilling } = useProviderContext()
@@ -82,7 +80,7 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDS
useEffect(() => {
if (droppedFile)
handleFile(droppedFile)
- }, [droppedFile])
+ }, [droppedFile, handleFile])
const onCreate = async (_e?: React.MouseEvent) => {
if (currentTab === CreateFromDSLModalTab.FROM_FILE && !currentFile)
@@ -141,11 +139,10 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDS
setImportId(id)
}
else {
- toast.error(t('newApp.appCreateFailed', { ns: 'app' }))
+ toast.error(response.error || t('newApp.appCreateFailed', { ns: 'app' }))
}
}
- // eslint-disable-next-line unused-imports/no-unused-vars
- catch (e) {
+ catch {
toast.error(t('newApp.appCreateFailed', { ns: 'app' }))
}
isCreatingRef.current = false
@@ -187,11 +184,10 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDS
getRedirection(isCurrentWorkspaceEditor, { id: app_id!, mode: app_mode }, push)
}
else if (status === DSLImportStatus.FAILED) {
- toast.error(t('newApp.appCreateFailed', { ns: 'app' }))
+ toast.error(response.error || t('newApp.appCreateFailed', { ns: 'app' }))
}
}
- // eslint-disable-next-line unused-imports/no-unused-vars
- catch (e) {
+ catch {
toast.error(t('newApp.appCreateFailed', { ns: 'app' }))
}
}
@@ -219,108 +215,112 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDS
return (
<>
- <Modal
- className="w-[520px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0 shadow-xl"
- isShow={show}
- onClose={noop}
- >
- <div className="flex items-center justify-between pt-6 pr-5 pb-3 pl-6 title-2xl-semi-bold text-text-primary">
- {t('importApp', { ns: 'app' })}
- <div
- className="flex h-8 w-8 cursor-pointer items-center"
- onClick={() => onClose()}
- >
- <RiCloseLine className="h-5 w-5 text-text-tertiary" />
+ <Dialog open={show}>
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden! rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0! text-left align-middle shadow-xl">
+
+ <div className="flex items-center justify-between pt-6 pr-5 pb-3 pl-6 title-2xl-semi-bold text-text-primary">
+ {t('importApp', { ns: 'app' })}
+ <div
+ className="flex h-8 w-8 cursor-pointer items-center"
+ onClick={() => onClose()}
+ >
+ <span className="i-ri-close-line h-5 w-5 text-text-tertiary" />
+ </div>
</div>
- </div>
- <div className="flex h-9 items-center space-x-6 border-b border-divider-subtle px-6 system-md-semibold text-text-tertiary">
- {
- tabs.map(tab => (
- <div
- key={tab.key}
- className={cn(
- 'relative flex h-full cursor-pointer items-center',
- currentTab === tab.key && 'text-text-primary',
- )}
- onClick={() => setCurrentTab(tab.key)}
- >
- {tab.label}
- {
- currentTab === tab.key && (
- <div className="absolute bottom-0 h-[2px] w-full bg-util-colors-blue-brand-blue-brand-600"></div>
- )
- }
- </div>
- ))
- }
- </div>
- <div className="px-6 py-4">
- {
- currentTab === CreateFromDSLModalTab.FROM_FILE && (
- <Uploader
- className="mt-0"
- file={currentFile}
- updateFile={handleFile}
- />
- )
- }
- {
- currentTab === CreateFromDSLModalTab.FROM_URL && (
- <div>
- <div className="mb-1 system-md-semibold text-text-secondary">DSL URL</div>
- <Input
- placeholder={t('importFromDSLUrlPlaceholder', { ns: 'app' }) || ''}
- value={dslUrlValue}
- onChange={e => setDslUrlValue(e.target.value)}
+ <div className="flex h-9 items-center space-x-6 border-b border-divider-subtle px-6 system-md-semibold text-text-tertiary">
+ {
+ tabs.map(tab => (
+ <div
+ key={tab.key}
+ className={cn(
+ 'relative flex h-full cursor-pointer items-center',
+ currentTab === tab.key && 'text-text-primary',
+ )}
+ onClick={() => setCurrentTab(tab.key)}
+ >
+ {tab.label}
+ {
+ currentTab === tab.key && (
+ <div className="absolute bottom-0 h-[2px] w-full bg-util-colors-blue-brand-blue-brand-600"></div>
+ )
+ }
+ </div>
+ ))
+ }
+ </div>
+ <div className="px-6 py-4">
+ {
+ currentTab === CreateFromDSLModalTab.FROM_FILE && (
+ <Uploader
+ className="mt-0"
+ file={currentFile}
+ updateFile={handleFile}
/>
- </div>
- )
- }
- </div>
- {isAppsFull && (
- <div className="px-6">
- <AppsFull className="mt-0" loc="app-create-dsl" />
+ )
+ }
+ {
+ currentTab === CreateFromDSLModalTab.FROM_URL && (
+ <div>
+ <div className="mb-1 system-md-semibold text-text-secondary">DSL URL</div>
+ <Input
+ placeholder={t('importFromDSLUrlPlaceholder', { ns: 'app' }) || ''}
+ value={dslUrlValue}
+ onChange={e => setDslUrlValue(e.target.value)}
+ />
+ </div>
+ )
+ }
</div>
- )}
- <div className="flex justify-end px-6 py-5">
- <Button className="mr-2" onClick={onClose}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button
- disabled={buttonDisabled}
- variant="primary"
- onClick={handleCreateApp}
- className="gap-1"
- >
- <span>{t('newApp.Create', { ns: 'app' })}</span>
- <ShortcutsName keys={['ctrl', '↵']} bgColor="white" />
- </Button>
- </div>
- </Modal>
- <Modal
- isShow={showErrorModal}
- onClose={() => setShowErrorModal(false)}
- className="w-[480px]"
- >
- <div className="flex flex-col items-start gap-2 self-stretch pb-4">
- <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>
- <div className="flex grow flex-col system-md-regular text-text-secondary">
- <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
- <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
- <br />
- <div>
- {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
- <span className="system-md-medium">{versions?.importedVersion}</span>
+ {isAppsFull && (
+ <div className="px-6">
+ <AppsFull className="mt-0" loc="app-create-dsl" />
</div>
- <div>
- {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
- <span className="system-md-medium">{versions?.systemVersion}</span>
+ )}
+ <div className="flex justify-end px-6 py-5">
+ <Button className="mr-2" onClick={onClose}>{t('newApp.Cancel', { ns: 'app' })}</Button>
+ <Button
+ disabled={buttonDisabled}
+ variant="primary"
+ onClick={handleCreateApp}
+ className="gap-1"
+ >
+ <span>{t('newApp.Create', { ns: 'app' })}</span>
+ <ShortcutsName keys={['ctrl', '↵']} bgColor="white" />
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog
+ open={showErrorModal}
+ onOpenChange={(open) => {
+ if (!open)
+ setShowErrorModal(false)
+ }}
+ >
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden! border-none text-left align-middle">
+
+ <div className="flex flex-col items-start gap-2 self-stretch pb-4">
+ <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>
+ <div className="flex grow flex-col system-md-regular text-text-secondary">
+ <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
+ <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
+ <br />
+ <div>
+ {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
+ <span className="system-md-medium">{versions?.importedVersion}</span>
+ </div>
+ <div>
+ {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
+ <span className="system-md-medium">{versions?.systemVersion}</span>
+ </div>
</div>
</div>
- </div>
- <div className="flex items-start justify-end gap-2 self-stretch pt-6">
- <Button variant="secondary" onClick={() => setShowErrorModal(false)}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button variant="primary" tone="destructive" onClick={onDSLConfirm}>{t('newApp.Confirm', { ns: 'app' })}</Button>
- </div>
- </Modal>
+ <div className="flex items-start justify-end gap-2 self-stretch pt-6">
+ <Button variant="secondary" onClick={() => setShowErrorModal(false)}>{t('newApp.Cancel', { ns: 'app' })}</Button>
+ <Button variant="primary" tone="destructive" onClick={onDSLConfirm}>{t('newApp.Confirm', { ns: 'app' })}</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
</>
)
}
diff --git a/web/app/components/app/duplicate-modal/index.tsx b/web/app/components/app/duplicate-modal/index.tsx
index e55ac6cf660..7a83c6c277b 100644
--- a/web/app/components/app/duplicate-modal/index.tsx
+++ b/web/app/components/app/duplicate-modal/index.tsx
@@ -1,16 +1,14 @@
'use client'
import type { AppIconType } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { RiCloseLine } from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import AppsFull from '@/app/components/billing/apps-full-in-dialog'
import { useProviderContext } from '@/context/provider-context'
import AppIconPicker from '../../base/app-icon-picker'
@@ -71,40 +69,39 @@ const DuplicateAppModal = ({
return (
<>
- <Modal
- isShow={show}
- onClose={noop}
- className={cn('relative max-w-[480px]!', 'px-8')}
- >
- <div className="absolute top-4 right-4 cursor-pointer p-2" onClick={onHide}>
- <RiCloseLine className="h-4 w-4 text-text-tertiary" />
- </div>
- <div className="relative mt-3 mb-9 text-xl leading-[30px] font-semibold text-text-primary">{t('duplicateTitle', { ns: 'app' })}</div>
- <div className="mb-9 system-sm-regular text-text-secondary">
- <div className="mb-2 system-md-medium">{t('appCustomize.subTitle', { ns: 'explore' })}</div>
- <div className="flex items-center justify-between space-x-2">
- <AppIcon
- size="large"
- onClick={() => { setShowAppIconPicker(true) }}
- className="cursor-pointer"
- iconType={appIcon.type}
- icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon}
- background={appIcon.type === 'image' ? undefined : appIcon.background}
- imageUrl={appIcon.type === 'image' ? appIcon.url : undefined}
- />
- <Input
- value={name}
- onChange={e => setName(e.target.value)}
- className="h-10"
- />
+ <Dialog open={show}>
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden! border-none px-8 text-left align-middle">
+
+ <div className="absolute top-4 right-4 cursor-pointer p-2" onClick={onHide}>
+ <RiCloseLine className="h-4 w-4 text-text-tertiary" />
+ </div>
+ <div className="relative mt-3 mb-9 text-xl leading-[30px] font-semibold text-text-primary">{t('duplicateTitle', { ns: 'app' })}</div>
+ <div className="mb-9 system-sm-regular text-text-secondary">
+ <div className="mb-2 system-md-medium">{t('appCustomize.subTitle', { ns: 'explore' })}</div>
+ <div className="flex items-center justify-between space-x-2">
+ <AppIcon
+ size="large"
+ onClick={() => { setShowAppIconPicker(true) }}
+ className="cursor-pointer"
+ iconType={appIcon.type}
+ icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon}
+ background={appIcon.type === 'image' ? undefined : appIcon.background}
+ imageUrl={appIcon.type === 'image' ? appIcon.url : undefined}
+ />
+ <Input
+ value={name}
+ onChange={e => setName(e.target.value)}
+ className="h-10"
+ />
+ </div>
+ {isAppsFull && <AppsFull className="mt-4" loc="app-duplicate-create" />}
+ </div>
+ <div className="flex flex-row-reverse">
+ <Button disabled={isAppsFull} className="ml-2 w-24" variant="primary" onClick={submit}>{t('duplicate', { ns: 'app' })}</Button>
+ <Button className="w-24" onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
</div>
- {isAppsFull && <AppsFull className="mt-4" loc="app-duplicate-create" />}
- </div>
- <div className="flex flex-row-reverse">
- <Button disabled={isAppsFull} className="ml-2 w-24" variant="primary" onClick={submit}>{t('duplicate', { ns: 'app' })}</Button>
- <Button className="w-24" onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
{showAppIconPicker && (
<AppIconPicker
onSelect={(payload) => {
diff --git a/web/app/components/app/switch-app-modal/index.tsx b/web/app/components/app/switch-app-modal/index.tsx
index 8da710210e3..c46ce7ad13c 100644
--- a/web/app/components/app/switch-app-modal/index.tsx
+++ b/web/app/components/app/switch-app-modal/index.tsx
@@ -12,9 +12,9 @@ import {
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { RiCloseLine } from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore as useAppStore } from '@/app/components/app/store'
@@ -22,7 +22,6 @@ import AppIcon from '@/app/components/base/app-icon'
import Checkbox from '@/app/components/base/checkbox'
import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import AppsFull from '@/app/components/billing/apps-full-in-dialog'
import { NEED_REFRESH_APP_LIST_KEY } from '@/config'
import { useAppContext } from '@/context/app-context'
@@ -109,69 +108,68 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onSuccess, onClo
return (
<>
- <Modal
- className={cn('w-[600px] max-w-[600px] p-8')}
- isShow={show}
- onClose={noop}
- >
- <div className="absolute top-4 right-4 cursor-pointer p-2" onClick={onClose}>
- <RiCloseLine className="h-4 w-4 text-text-tertiary" />
- </div>
- <div className="h-12 w-12 rounded-xl border-[0.5px] border-divider-regular bg-background-default-burn p-3 shadow-xl">
- <AlertTriangle className="h-6 w-6 text-[rgb(247,144,9)]" />
- </div>
- <div className="relative mt-3 text-xl leading-[30px] font-semibold text-text-primary">{t('switch', { ns: 'app' })}</div>
- <div className="my-1 text-sm leading-5 text-text-tertiary">
- <span>{t('switchTipStart', { ns: 'app' })}</span>
- <span className="font-medium text-text-secondary">{t('switchTip', { ns: 'app' })}</span>
- <span>{t('switchTipEnd', { ns: 'app' })}</span>
- </div>
- <div className="pb-4">
- <div className="py-2 text-sm leading-[20px] font-medium text-text-primary">{t('switchLabel', { ns: 'app' })}</div>
- <div className="flex items-center justify-between space-x-2">
- <AppIcon
- size="large"
- onClick={() => { setShowAppIconPicker(true) }}
- className="cursor-pointer"
- iconType={appIcon.type}
- icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon}
- background={appIcon.type === 'image' ? undefined : appIcon.background}
- imageUrl={appIcon.type === 'image' ? appIcon.url : undefined}
- />
- <Input
- value={name}
- onChange={e => setName(e.target.value)}
- placeholder={t('newApp.appNamePlaceholder', { ns: 'app' }) || ''}
- className="h-10 grow"
- />
+ <Dialog open={show}>
+ <DialogContent className={cn('w-full overflow-hidden! border-none text-left align-middle', cn('w-[600px] max-w-[600px] p-8'))}>
+
+ <div className="absolute top-4 right-4 cursor-pointer p-2" onClick={onClose}>
+ <RiCloseLine className="h-4 w-4 text-text-tertiary" />
+ </div>
+ <div className="h-12 w-12 rounded-xl border-[0.5px] border-divider-regular bg-background-default-burn p-3 shadow-xl">
+ <AlertTriangle className="h-6 w-6 text-[rgb(247,144,9)]" />
+ </div>
+ <div className="relative mt-3 text-xl leading-[30px] font-semibold text-text-primary">{t('switch', { ns: 'app' })}</div>
+ <div className="my-1 text-sm leading-5 text-text-tertiary">
+ <span>{t('switchTipStart', { ns: 'app' })}</span>
+ <span className="font-medium text-text-secondary">{t('switchTip', { ns: 'app' })}</span>
+ <span>{t('switchTipEnd', { ns: 'app' })}</span>
</div>
- {showAppIconPicker && (
- <AppIconPicker
- onSelect={(payload) => {
- setAppIcon(payload)
- setShowAppIconPicker(false)
- }}
- onClose={() => {
- setAppIcon(appDetail.icon_type === 'image'
- ? { type: 'image' as const, url: appDetail.icon_url, fileId: appDetail.icon }
- : { type: 'emoji' as const, icon: appDetail.icon, background: appDetail.icon_background })
- setShowAppIconPicker(false)
- }}
- />
- )}
- </div>
- {isAppsFull && <AppsFull loc="app-switch" />}
- <div className="flex items-center justify-between pt-6">
- <div className="flex items-center">
- <Checkbox className="shrink-0" checked={removeOriginal} onCheck={() => setRemoveOriginal(!removeOriginal)} />
- <div className="ml-2 cursor-pointer text-sm leading-5 text-text-secondary" onClick={() => setRemoveOriginal(!removeOriginal)}>{t('removeOriginal', { ns: 'app' })}</div>
+ <div className="pb-4">
+ <div className="py-2 text-sm leading-[20px] font-medium text-text-primary">{t('switchLabel', { ns: 'app' })}</div>
+ <div className="flex items-center justify-between space-x-2">
+ <AppIcon
+ size="large"
+ onClick={() => { setShowAppIconPicker(true) }}
+ className="cursor-pointer"
+ iconType={appIcon.type}
+ icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon}
+ background={appIcon.type === 'image' ? undefined : appIcon.background}
+ imageUrl={appIcon.type === 'image' ? appIcon.url : undefined}
+ />
+ <Input
+ value={name}
+ onChange={e => setName(e.target.value)}
+ placeholder={t('newApp.appNamePlaceholder', { ns: 'app' }) || ''}
+ className="h-10 grow"
+ />
+ </div>
+ {showAppIconPicker && (
+ <AppIconPicker
+ onSelect={(payload) => {
+ setAppIcon(payload)
+ setShowAppIconPicker(false)
+ }}
+ onClose={() => {
+ setAppIcon(appDetail.icon_type === 'image'
+ ? { type: 'image' as const, url: appDetail.icon_url, fileId: appDetail.icon }
+ : { type: 'emoji' as const, icon: appDetail.icon, background: appDetail.icon_background })
+ setShowAppIconPicker(false)
+ }}
+ />
+ )}
</div>
- <div className="flex items-center">
- <Button className="mr-2" onClick={onClose}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button className="border-red-700" disabled={isAppsFull || !name} variant="primary" tone="destructive" onClick={goStart}>{t('switchStart', { ns: 'app' })}</Button>
+ {isAppsFull && <AppsFull loc="app-switch" />}
+ <div className="flex items-center justify-between pt-6">
+ <div className="flex items-center">
+ <Checkbox className="shrink-0" checked={removeOriginal} onCheck={() => setRemoveOriginal(!removeOriginal)} />
+ <div className="ml-2 cursor-pointer text-sm leading-5 text-text-secondary" onClick={() => setRemoveOriginal(!removeOriginal)}>{t('removeOriginal', { ns: 'app' })}</div>
+ </div>
+ <div className="flex items-center">
+ <Button className="mr-2" onClick={onClose}>{t('newApp.Cancel', { ns: 'app' })}</Button>
+ <Button className="border-red-700" disabled={isAppsFull || !name} variant="primary" tone="destructive" onClick={goStart}>{t('switchStart', { ns: 'app' })}</Button>
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
<AlertDialog
open={showConfirmDelete}
onOpenChange={handleConfirmDeleteOpenChange}
diff --git a/web/app/components/app/workflow-log/__tests__/list.spec.tsx b/web/app/components/app/workflow-log/__tests__/list.spec.tsx
index 35e6369e676..2259ed30c50 100644
--- a/web/app/components/app/workflow-log/__tests__/list.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/list.spec.tsx
@@ -460,9 +460,10 @@ describe('WorkflowAppLogList', () => {
// Open drawer
const dataRows = screen.getAllByRole('row')
await user.click(dataRows[1]!)
- await screen.findByRole('dialog')
+ const dialog = await screen.findByRole('dialog')
// Close drawer using Escape key
+ dialog.focus()
await user.keyboard('{Escape}')
await waitFor(() => {
diff --git a/web/app/components/base/app-icon-picker/index.tsx b/web/app/components/base/app-icon-picker/index.tsx
index 64a88f16e12..52a52541e9a 100644
--- a/web/app/components/base/app-icon-picker/index.tsx
+++ b/web/app/components/base/app-icon-picker/index.tsx
@@ -4,15 +4,14 @@ import type { OnImageInput } from './ImageInput'
import type { AppIconType, ImageFile } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { RiImageCircleAiLine } from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { DISABLE_UPLOAD_IMAGE_AS_ICON } from '@/config'
import Divider from '../divider'
import EmojiPickerInner from '../emoji-picker/Inner'
import { useLocalFileUploader } from '../image-uploader/hooks'
-import Modal from '../modal'
import ImageInput from './ImageInput'
import s from './style.module.css'
import getCroppedImg from './utils'
@@ -45,7 +44,6 @@ const AppIconPicker: FC<AppIconPickerProps> = ({
onSelect,
onClose,
initialEmoji,
- className,
}) => {
const { t } = useTranslation()
@@ -113,57 +111,54 @@ const AppIconPicker: FC<AppIconPickerProps> = ({
}
return (
- <Modal
- onClose={noop}
- isShow
- closable={false}
- wrapperClassName={className}
- className={cn(s.container, 'h-[462px]! w-[362px]! p-0!')}
- >
- {!DISABLE_UPLOAD_IMAGE_AS_ICON && (
- <div className="w-full p-2 pb-0">
- <div className="flex items-center justify-center gap-2 rounded-xl bg-background-body p-1 text-text-primary">
- {tabs.map(tab => (
- <button
- type="button"
- key={tab.key}
- className={cn(
- 'flex h-8 flex-1 shrink-0 items-center justify-center rounded-lg p-2 system-sm-medium text-text-tertiary',
- activeTab === tab.key && 'bg-components-main-nav-nav-button-bg-active text-text-accent shadow-md',
- )}
- onClick={() => setActiveTab(tab.key as AppIconType)}
- >
- {tab.icon}
- {' '}
+ <Dialog open>
+ <DialogContent className={cn('max-h-none w-full overflow-hidden! border-none text-left align-middle', s.container, 'h-[462px]! w-[362px]! p-0!')}>
+
+ {!DISABLE_UPLOAD_IMAGE_AS_ICON && (
+ <div className="w-full p-2 pb-0">
+ <div className="flex items-center justify-center gap-2 rounded-xl bg-background-body p-1 text-text-primary">
+ {tabs.map(tab => (
+ <button
+ type="button"
+ key={tab.key}
+ className={cn(
+ 'flex h-8 flex-1 shrink-0 items-center justify-center rounded-lg p-2 system-sm-medium text-text-tertiary',
+ activeTab === tab.key && 'bg-components-main-nav-nav-button-bg-active text-text-accent shadow-md',
+ )}
+ onClick={() => setActiveTab(tab.key as AppIconType)}
+ >
+ {tab.icon}
+ {' '}
&nbsp;
- {tab.label}
- </button>
- ))}
+ {tab.label}
+ </button>
+ ))}
+ </div>
</div>
+ )}
+
+ {activeTab === 'emoji' && (
+ <EmojiPickerInner
+ className={cn('flex-1 overflow-hidden pt-2')}
+ emoji={initialEmoji?.icon}
+ background={initialEmoji?.background ?? undefined}
+ onSelect={handleSelectEmoji}
+ />
+ )}
+ {activeTab === 'image' && <ImageInput className={cn('flex-1 overflow-hidden')} onImageInput={handleImageInput} />}
+
+ <Divider className="m-0" />
+ <div className="flex w-full items-center justify-center gap-2 p-3">
+ <Button className="w-full" onClick={() => onClose?.()}>
+ {t('iconPicker.cancel', { ns: 'app' })}
+ </Button>
+
+ <Button variant="primary" className="w-full" disabled={uploading} loading={uploading} onClick={handleSelect}>
+ {t('iconPicker.ok', { ns: 'app' })}
+ </Button>
</div>
- )}
-
- {activeTab === 'emoji' && (
- <EmojiPickerInner
- className={cn('flex-1 overflow-hidden pt-2')}
- emoji={initialEmoji?.icon}
- background={initialEmoji?.background ?? undefined}
- onSelect={handleSelectEmoji}
- />
- )}
- {activeTab === 'image' && <ImageInput className={cn('flex-1 overflow-hidden')} onImageInput={handleImageInput} />}
-
- <Divider className="m-0" />
- <div className="flex w-full items-center justify-center gap-2 p-3">
- <Button className="w-full" onClick={() => onClose?.()}>
- {t('iconPicker.cancel', { ns: 'app' })}
- </Button>
-
- <Button variant="primary" className="w-full" disabled={uploading} loading={uploading} onClick={handleSelect}>
- {t('iconPicker.ok', { ns: 'app' })}
- </Button>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
index 33e25dbe01c..19513deff1f 100644
--- a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/index.spec.tsx
@@ -62,18 +62,15 @@ vi.mock('@/next/navigation', () => ({
usePathname: () => '/test',
}))
-// Mock Modal to avoid Headless UI issues in tests
-vi.mock('@/app/components/base/modal', () => ({
- default: ({ children, isShow, title }: { children: React.ReactNode, isShow: boolean, title: React.ReactNode }) => {
- if (!isShow)
- return null
- return (
- <div data-testid="modal">
- {!!title && <div data-testid="modal-title">{title}</div>}
- {children}
- </div>
- )
- },
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ children, open }: { children: React.ReactNode, open?: boolean }) =>
+ open === false ? null : <>{children}</>,
+ DialogContent: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="modal">{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="modal-title">{children}</div>
+ ),
}))
describe('Sidebar Index', () => {
diff --git a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/rename-modal.spec.tsx b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/rename-modal.spec.tsx
index 754d5c89b4a..9c741beb0e2 100644
--- a/web/app/components/base/chat/chat-with-history/sidebar/__tests__/rename-modal.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/sidebar/__tests__/rename-modal.spec.tsx
@@ -4,25 +4,13 @@ import userEvent from '@testing-library/user-event'
import * as ReactI18next from 'react-i18next'
import RenameModal from '../rename-modal'
-vi.mock('@/app/components/base/modal', () => ({
- default: ({
- title,
- isShow,
- children,
- }: {
- title: ReactNode
- isShow: boolean
- children: ReactNode
- }) => {
- if (!isShow)
- return null
- return (
- <div role="dialog">
- <h2>{title}</h2>
- {children}
- </div>
- )
- },
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ children, open }: { children: ReactNode, open?: boolean }) =>
+ open === false ? null : <>{children}</>,
+ DialogContent: ({ children }: { children: ReactNode }) => (
+ <div role="dialog">{children}</div>
+ ),
+ DialogTitle: ({ children }: { children: ReactNode }) => <h2>{children}</h2>,
}))
describe('RenameModal', () => {
diff --git a/web/app/components/base/content-dialog/__tests__/index.spec.tsx b/web/app/components/base/content-dialog/__tests__/index.spec.tsx
deleted file mode 100644
index e987d306a16..00000000000
--- a/web/app/components/base/content-dialog/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import ContentDialog from '../index'
-
-describe('ContentDialog', () => {
- it('renders children when show is true', async () => {
- render(
- <ContentDialog show={true}>
- <div>Dialog body</div>
- </ContentDialog>,
- )
-
- await screen.findByText('Dialog body')
- expect(screen.getByText('Dialog body')).toBeInTheDocument()
-
- const backdrop = document.querySelector('.bg-app-detail-overlay-bg')
- expect(backdrop).toBeTruthy()
- })
-
- it('does not render children when show is false', () => {
- render(
- <ContentDialog show={false}>
- <div>Hidden content</div>
- </ContentDialog>,
- )
-
- expect(screen.queryByText('Hidden content')).toBeNull()
- expect(document.querySelector('.bg-app-detail-overlay-bg')).toBeNull()
- })
-
- it('calls onClose when backdrop is clicked', async () => {
- const onClose = vi.fn()
- render(
- <ContentDialog show={true} onClose={onClose}>
- <div>Body</div>
- </ContentDialog>,
- )
-
- const user = userEvent.setup()
- const backdrop = document.querySelector('.bg-app-detail-overlay-bg') as HTMLElement | null
- expect(backdrop).toBeTruthy()
-
- await user.click(backdrop!)
- expect(onClose).toHaveBeenCalledTimes(1)
- })
-
- it('applies provided className to the content panel', () => {
- render(
- <ContentDialog show={true} className="my-panel-class">
- <div>Panel content</div>
- </ContentDialog>,
- )
-
- const contentPanel = document.querySelector('.bg-app-detail-bg') as HTMLElement | null
- expect(contentPanel).toBeTruthy()
- expect(contentPanel?.className).toContain('my-panel-class')
- expect(screen.getByText('Panel content')).toBeInTheDocument()
- })
-})
diff --git a/web/app/components/base/content-dialog/index.stories.tsx b/web/app/components/base/content-dialog/index.stories.tsx
deleted file mode 100644
index 8ddd5c667d0..00000000000
--- a/web/app/components/base/content-dialog/index.stories.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import { useEffect, useState } from 'react'
-import ContentDialog from '.'
-
-type Props = React.ComponentProps<typeof ContentDialog>
-
-const meta = {
- title: 'Base/Feedback/ContentDialog',
- component: ContentDialog,
- parameters: {
- layout: 'fullscreen',
- docs: {
- description: {
- component: 'Sliding panel overlay used in the app detail view. Includes dimmed backdrop and animated entrance/exit transitions.',
- },
- },
- },
- tags: ['autodocs'],
- argTypes: {
- className: {
- control: 'text',
- description: 'Additional classes applied to the sliding panel container.',
- },
- show: {
- control: 'boolean',
- description: 'Controls visibility of the dialog.',
- },
- onClose: {
- control: false,
- description: 'Invoked when the overlay/backdrop is clicked.',
- },
- children: {
- control: false,
- table: { disable: true },
- },
- },
- args: {
- show: false,
- children: null,
- },
-} satisfies Meta<typeof ContentDialog>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-const DemoWrapper = (props: Props) => {
- const [open, setOpen] = useState(props.show)
-
- useEffect(() => {
- setOpen(props.show)
- }, [props.show])
-
- return (
- <div className="relative h-[480px] w-full overflow-hidden bg-gray-100">
- <div className="flex h-full items-center justify-center">
- <button
- className="rounded-md bg-primary-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-primary-700"
- onClick={() => setOpen(true)}
- >
- Open dialog
- </button>
- </div>
-
- <ContentDialog
- {...props}
- show={open}
- onClose={() => {
- props.onClose?.()
- setOpen(false)
- }}
- >
- <div className="flex h-full flex-col space-y-4 bg-white p-6">
- <h2 className="text-lg font-semibold text-gray-900">Plan summary</h2>
- <p className="text-sm text-gray-600">
- Use this area to present rich content for the selected run, configuration details, or
- any supporting context.
- </p>
- <div className="flex-1 overflow-y-auto rounded-md border border-dashed border-gray-200 bg-gray-50 p-4 text-xs text-gray-500">
- Scrollable placeholder content. Add domain-specific information, activity logs, or
- editors in the real application.
- </div>
- <div className="flex justify-end gap-2 pt-4">
- <button
- className="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50"
- onClick={() => setOpen(false)}
- >
- Cancel
- </button>
- <button className="rounded-md bg-primary-600 px-3 py-1.5 text-sm text-white hover:bg-primary-700">
- Apply changes
- </button>
- </div>
- </div>
- </ContentDialog>
- </div>
- )
-}
-
-export const Default: Story = {
- args: {
- children: null,
- },
- render: args => <DemoWrapper {...args} />,
-}
-
-export const NarrowPanel: Story = {
- render: args => <DemoWrapper {...args} />,
- args: {
- className: 'max-w-[420px]',
- children: null,
- },
- parameters: {
- docs: {
- description: {
- story: 'Applies a custom width class to show the dialog as a narrower information panel.',
- },
- },
- },
-}
diff --git a/web/app/components/base/content-dialog/index.tsx b/web/app/components/base/content-dialog/index.tsx
deleted file mode 100644
index 5367a35fc4d..00000000000
--- a/web/app/components/base/content-dialog/index.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import type { ReactNode } from 'react'
-import { Transition, TransitionChild } from '@headlessui/react'
-import { cn } from '@langgenius/dify-ui/cn'
-
-type ContentDialogProps = {
- className?: string
- show: boolean
- onClose?: () => void
- children: ReactNode
-}
-
-const ContentDialog = ({
- className,
- show,
- onClose,
- children,
-}: ContentDialogProps) => {
- return (
- <Transition
- show={show}
- as="div"
- className="absolute top-0 left-0 z-[70] box-border h-full w-full p-2"
- >
- <TransitionChild>
- <div
- className={cn('absolute inset-0 left-0 w-full bg-app-detail-overlay-bg', 'duration-300 ease-in data-closed:opacity-0', 'data-enter:opacity-100', 'data-leave:opacity-0')}
- onClick={onClose}
- />
- </TransitionChild>
-
- <TransitionChild>
- <div className={cn('absolute left-0 w-full border-r border-divider-burn bg-app-detail-bg', 'duration-100 ease-in data-closed:-translate-x-full', 'data-enter:translate-x-0 data-enter:duration-300 data-enter:ease-out', 'data-leave:-translate-x-full data-leave:duration-200 data-leave:ease-in', className)}>
- {children}
- </div>
- </TransitionChild>
- </Transition>
- )
-}
-
-export default ContentDialog
diff --git a/web/app/components/base/date-and-time-picker/date-picker/index.tsx b/web/app/components/base/date-and-time-picker/date-picker/index.tsx
index 7858fa2fbe7..60888a6ec49 100644
--- a/web/app/components/base/date-and-time-picker/date-picker/index.tsx
+++ b/web/app/components/base/date-and-time-picker/date-picker/index.tsx
@@ -31,7 +31,6 @@ const DatePicker = ({
needTimePicker = true,
renderTrigger,
triggerWrapClassName,
- popupZIndexClassname,
noConfirm,
getIsDateDisabled,
}: DatePickerProps) => {
@@ -236,7 +235,6 @@ const DatePicker = ({
<PopoverContent
placement="bottom-end"
sideOffset={0}
- className={popupZIndexClassname}
popupClassName="border-none bg-transparent shadow-none"
>
<div className="mt-1 w-[252px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg shadow-shadow-shadow-5">
diff --git a/web/app/components/base/date-and-time-picker/index.stories.tsx b/web/app/components/base/date-and-time-picker/index.stories.tsx
index 1ed35afe88d..430688d0e82 100644
--- a/web/app/components/base/date-and-time-picker/index.stories.tsx
+++ b/web/app/components/base/date-and-time-picker/index.stories.tsx
@@ -35,7 +35,6 @@ const DatePickerPlayground = (props: DatePickerProps) => {
return (
<div className="inline-flex flex-col items-start gap-3">
<DatePicker
- popupZIndexClassname="z-50"
{...props}
value={value}
onChange={setValue}
@@ -65,7 +64,6 @@ export const Playground: Story = {
const [value, setValue] = useState(getDateWithTimezone({}))
<DatePicker
- popupZIndexClassname="z-50"
value={value}
timezone={dayjs.tz.guess()}
onChange={setValue}
diff --git a/web/app/components/base/date-and-time-picker/types.ts b/web/app/components/base/date-and-time-picker/types.ts
index 7dda1d013cb..8d27f03ad12 100644
--- a/web/app/components/base/date-and-time-picker/types.ts
+++ b/web/app/components/base/date-and-time-picker/types.ts
@@ -30,7 +30,6 @@ export type DatePickerProps = {
triggerWrapClassName?: string
renderTrigger?: (props: TriggerProps) => React.ReactElement
minuteFilter?: (minutes: string[]) => string[]
- popupZIndexClassname?: string
noConfirm?: boolean
getIsDateDisabled?: (date: Dayjs) => boolean
}
diff --git a/web/app/components/base/dialog/__tests__/index.spec.tsx b/web/app/components/base/dialog/__tests__/index.spec.tsx
deleted file mode 100644
index 241e89be262..00000000000
--- a/web/app/components/base/dialog/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-import { act, render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { describe, expect, it, vi } from 'vitest'
-import CustomDialog from '../index'
-
-describe('CustomDialog Component', () => {
- const setup = () => userEvent.setup()
-
- it('should render children and title when show is true', async () => {
- render(
- <CustomDialog show={true} title="Modal Title">
- <div data-testid="dialog-content">Main Content</div>
- </CustomDialog>,
- )
-
- const title = await screen.findByText('Modal Title')
- const content = screen.getByTestId('dialog-content')
-
- expect(title).toBeInTheDocument()
- expect(content).toBeInTheDocument()
- expect(screen.getByRole('dialog')).toBeInTheDocument()
- })
-
- it('should not render anything when show is false', async () => {
- render(
- <CustomDialog show={false} title="Hidden Title">
- <div>Content</div>
- </CustomDialog>,
- )
-
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
- expect(screen.queryByText('Hidden Title')).not.toBeInTheDocument()
- })
-
- it('should apply the correct semantic tag to title using titleAs', async () => {
- render(
- <CustomDialog show={true} title="Semantic Title" titleAs="h1">
- Content
- </CustomDialog>,
- )
-
- const title = await screen.findByRole('heading', { level: 1 })
- expect(title).toHaveTextContent('Semantic Title')
- })
-
- it('should render the footer only when the prop is provided', async () => {
- const { rerender } = render(
- <CustomDialog show={true}>Content</CustomDialog>,
- )
-
- await screen.findByRole('dialog')
- expect(screen.queryByText('Footer Content')).not.toBeInTheDocument()
-
- rerender(
- <CustomDialog show={true} footer={<div data-testid="footer-node">Footer Content</div>}>
- Content
- </CustomDialog>,
- )
-
- expect(await screen.findByTestId('footer-node')).toBeInTheDocument()
- })
-
- it('should call onClose when Escape key is pressed', async () => {
- const user = setup()
- const onCloseMock = vi.fn()
-
- render(
- <CustomDialog show={true} onClose={onCloseMock}>
- Content
- </CustomDialog>,
- )
-
- await screen.findByRole('dialog')
-
- await act(async () => {
- await user.keyboard('{Escape}')
- })
-
- expect(onCloseMock).toHaveBeenCalledTimes(1)
- })
-
- it('should call onClose when the backdrop is clicked', async () => {
- const user = setup()
- const onCloseMock = vi.fn()
-
- render(
- <CustomDialog show={true} onClose={onCloseMock}>
- Content
- </CustomDialog>,
- )
-
- await screen.findByRole('dialog')
-
- const backdrop = document.querySelector('.bg-background-overlay-backdrop')
- expect(backdrop).toBeInTheDocument()
-
- await act(async () => {
- await user.click(backdrop!)
- })
-
- expect(onCloseMock).toHaveBeenCalledTimes(1)
- })
-
- it('should apply custom class names to internal elements', async () => {
- render(
- <CustomDialog
- show={true}
- title="Title"
- className="custom-panel-container"
- titleClassName="custom-title-style"
- bodyClassName="custom-body-style"
- footer="Footer"
- footerClassName="custom-footer-style"
- >
- <div data-testid="content">Content</div>
- </CustomDialog>,
- )
-
- await screen.findByRole('dialog')
-
- expect(document.querySelector('.custom-panel-container')).toBeInTheDocument()
- expect(document.querySelector('.custom-title-style')).toBeInTheDocument()
- expect(document.querySelector('.custom-body-style')).toBeInTheDocument()
- expect(document.querySelector('.custom-footer-style')).toBeInTheDocument()
- })
-
- it('should maintain accessibility attributes (aria-modal)', async () => {
- render(
- <CustomDialog show={true} title="Accessibility Test">
- <button>Focusable Item</button>
- </CustomDialog>,
- )
-
- const dialog = await screen.findByRole('dialog')
- // Headless UI should automatically set aria-modal="true"
- expect(dialog).toHaveAttribute('aria-modal', 'true')
- })
-})
diff --git a/web/app/components/base/dialog/index.stories.tsx b/web/app/components/base/dialog/index.stories.tsx
deleted file mode 100644
index 2c9863da3b3..00000000000
--- a/web/app/components/base/dialog/index.stories.tsx
+++ /dev/null
@@ -1,152 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import { useEffect, useState } from 'react'
-import Dialog from '.'
-
-const meta = {
- title: 'Base/Feedback/Dialog',
- component: Dialog,
- parameters: {
- layout: 'fullscreen',
- docs: {
- description: {
- component: 'Modal dialog built on Headless UI. Provides animated overlay, title slot, and optional footer region.',
- },
- },
- },
- tags: ['autodocs'],
- argTypes: {
- className: {
- control: 'text',
- description: 'Additional classes applied to the panel.',
- },
- titleClassName: {
- control: 'text',
- description: 'Extra classes for the title element.',
- },
- bodyClassName: {
- control: 'text',
- description: 'Extra classes for the content area.',
- },
- footerClassName: {
- control: 'text',
- description: 'Extra classes for the footer container.',
- },
- title: {
- control: 'text',
- description: 'Dialog title.',
- },
- show: {
- control: 'boolean',
- description: 'Controls visibility of the dialog.',
- },
- onClose: {
- control: false,
- description: 'Called when the dialog backdrop or close handler fires.',
- },
- },
- args: {
- title: 'Manage API Keys',
- show: false,
- children: null,
- },
-} satisfies Meta<typeof Dialog>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-const DialogDemo = (props: React.ComponentProps<typeof Dialog>) => {
- const [open, setOpen] = useState(props.show)
- useEffect(() => {
- setOpen(props.show)
- }, [props.show])
-
- return (
- <div className="relative flex h-[480px] items-center justify-center bg-gray-100">
- <button
- className="rounded-md bg-primary-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-primary-700"
- onClick={() => setOpen(true)}
- >
- Show dialog
- </button>
-
- <Dialog
- {...props}
- show={open}
- onClose={() => {
- props.onClose?.()
- setOpen(false)
- }}
- >
- <div className="space-y-4 text-sm text-gray-600">
- <p>
- Centralize API key management for collaborators. You can revoke, rotate, or generate new keys directly from this dialog.
- </p>
- <div className="rounded-lg border border-dashed border-gray-200 bg-gray-50 p-4 text-xs text-gray-500">
- This placeholder area represents a form or table that would live inside the dialog body.
- </div>
- </div>
- </Dialog>
- </div>
- )
-}
-
-export const Default: Story = {
- render: args => <DialogDemo {...args} />,
- args: {
- footer: (
- <>
- <button className="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50">
- Cancel
- </button>
- <button className="rounded-md bg-primary-600 px-3 py-1.5 text-sm text-white hover:bg-primary-700">
- Save changes
- </button>
- </>
- ),
- },
-}
-
-export const WithoutFooter: Story = {
- render: args => <DialogDemo {...args} />,
- args: {
- footer: undefined,
- title: 'Read-only summary',
- },
- parameters: {
- docs: {
- description: {
- story: 'Demonstrates the dialog when no footer actions are provided.',
- },
- },
- },
-}
-
-export const CustomStyling: Story = {
- render: args => <DialogDemo {...args} />,
- args: {
- className: 'max-w-[560px] bg-white/95 backdrop-blur-sm',
- bodyClassName: 'bg-gray-50 rounded-xl p-5',
- footerClassName: 'justify-between px-4 pb-4 pt-4',
- titleClassName: 'text-lg text-primary-600',
- footer: (
- <>
- <span className="text-xs text-gray-400">Last synced 2 minutes ago</span>
- <div className="flex gap-2">
- <button className="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50">
- Close
- </button>
- <button className="rounded-md bg-primary-600 px-3 py-1.5 text-sm text-white hover:bg-primary-700">
- Refresh data
- </button>
- </div>
- </>
- ),
- },
- parameters: {
- docs: {
- description: {
- story: 'Applies custom classes to the panel, body, title, and footer to match different surfaces.',
- },
- },
- },
-}
diff --git a/web/app/components/base/dialog/index.tsx b/web/app/components/base/dialog/index.tsx
deleted file mode 100644
index 84d0c9b9994..00000000000
--- a/web/app/components/base/dialog/index.tsx
+++ /dev/null
@@ -1,70 +0,0 @@
-import type { ElementType, ReactNode } from 'react'
-import { Dialog, DialogPanel, DialogTitle, Transition, TransitionChild } from '@headlessui/react'
-import { cn } from '@langgenius/dify-ui/cn'
-import { Fragment, useCallback } from 'react'
-
-// https://headlessui.com/react/dialog
-
-type DialogProps = {
- className?: string
- titleClassName?: string
- bodyClassName?: string
- footerClassName?: string
- titleAs?: ElementType
- title?: ReactNode
- children: ReactNode
- footer?: ReactNode
- show: boolean
- onClose?: () => void
-}
-
-const CustomDialog = ({
- className,
- titleClassName,
- bodyClassName,
- footerClassName,
- titleAs,
- title,
- children,
- footer,
- show,
- onClose,
-}: DialogProps) => {
- const close = useCallback(() => onClose?.(), [onClose])
- return (
- <Transition appear show={show} as={Fragment}>
- <Dialog as="div" className="relative z-40" onClose={close}>
- <TransitionChild>
- <div className={cn('fixed inset-0 bg-background-overlay-backdrop backdrop-blur-[6px]', 'duration-300 ease-in data-closed:opacity-0', 'data-enter:opacity-100', 'data-leave:opacity-0')} />
- </TransitionChild>
-
- <div className="fixed inset-0 overflow-y-auto">
- <div className="flex min-h-full items-center justify-center">
- <TransitionChild>
- <DialogPanel className={cn('w-full max-w-[800px] overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-6 shadow-xl transition-all', 'duration-100 ease-in data-closed:scale-95 data-closed:opacity-0', 'data-enter:scale-100 data-enter:opacity-100', 'data-enter:scale-95 data-leave:opacity-0', className)}>
- {Boolean(title) && (
- <DialogTitle
- as={titleAs || 'h3'}
- className={cn('pr-8 pb-3 title-2xl-semi-bold text-text-primary', titleClassName)}
- >
- {title}
- </DialogTitle>
- )}
- <div className={cn(bodyClassName)}>
- {children}
- </div>
- {Boolean(footer) && (
- <div className={cn('flex items-center justify-end gap-2 px-6 pt-3 pb-6', footerClassName)}>
- {footer}
- </div>
- )}
- </DialogPanel>
- </TransitionChild>
- </div>
- </div>
- </Dialog>
- </Transition>
- )
-}
-
-export default CustomDialog
diff --git a/web/app/components/base/drawer-plus/__tests__/index.spec.tsx b/web/app/components/base/drawer-plus/__tests__/index.spec.tsx
index 2d3667dd8fc..b3a7d2cd2b8 100644
--- a/web/app/components/base/drawer-plus/__tests__/index.spec.tsx
+++ b/web/app/components/base/drawer-plus/__tests__/index.spec.tsx
@@ -172,8 +172,7 @@ describe('DrawerPlus', () => {
/>,
)
- const dialog = screen.getByRole('dialog')
- expect(dialog.className).toContain('custom-dialog')
+ expect(document.querySelector('.custom-dialog')).toBeInTheDocument()
})
it('should apply custom contentClassName', () => {
diff --git a/web/app/components/base/drawer/__tests__/index.spec.tsx b/web/app/components/base/drawer/__tests__/index.spec.tsx
index cd7eb937cc4..1f9c1c258f5 100644
--- a/web/app/components/base/drawer/__tests__/index.spec.tsx
+++ b/web/app/components/base/drawer/__tests__/index.spec.tsx
@@ -6,52 +6,60 @@ import Drawer from '../index'
// Capture dialog onClose for testing
let capturedDialogOnClose: (() => void) | null = null
-// Mock @headlessui/react
-vi.mock('@headlessui/react', () => ({
- Dialog: ({ children, open, onClose, className, unmount }: {
- children: React.ReactNode
- open: boolean
- onClose: () => void
- className: string
- unmount: boolean
- }) => {
- capturedDialogOnClose = onClose
- if (!open)
- return null
- return (
+// Mock Base UI Dialog anatomy; behavior is covered at the legacy wrapper boundary here.
+vi.mock('@base-ui/react/dialog', () => ({
+ Dialog: {
+ Root: ({ children, open, onOpenChange }: {
+ children: React.ReactNode
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ }) => {
+ capturedDialogOnClose = () => onOpenChange(false)
+ if (!open)
+ return null
+ return <>{children}</>
+ },
+ Portal: ({ children }: {
+ children: React.ReactNode
+ }) => <>{children}</>,
+ Backdrop: ({ children, className }: {
+ children?: React.ReactNode
+ className: string
+ }) => (
+ <div
+ data-testid="dialog-backdrop"
+ className={className}
+ onClick={() => capturedDialogOnClose?.()}
+ >
+ {children}
+ </div>
+ ),
+ Popup: ({ children, className, ...props }: {
+ children: React.ReactNode
+ className: string
+ }) => (
<div
data-testid="dialog"
- data-open={open}
- data-unmount={unmount}
className={className}
role="dialog"
+ {...props}
>
{children}
</div>
- )
+ ),
+ Title: ({ children, className, render, ...props }: {
+ children: React.ReactNode
+ className?: string
+ render?: React.ReactElement
+ }) => {
+ const Component = render?.type ?? 'h2'
+ return (
+ <Component data-testid="dialog-title" className={className} {...props}>
+ {children}
+ </Component>
+ )
+ },
},
- DialogBackdrop: ({ children, className, onClick }: {
- children?: React.ReactNode
- className: string
- onClick: () => void
- }) => (
- <div
- data-testid="dialog-backdrop"
- className={className}
- onClick={onClick}
- >
- {children}
- </div>
- ),
- DialogTitle: ({ children, as: _as, className, ...props }: {
- children: React.ReactNode
- as?: string
- className?: string
- }) => (
- <div data-testid="dialog-title" className={className} {...props}>
- {children}
- </div>
- ),
}))
// Mock XMarkIcon
@@ -343,10 +351,10 @@ describe('Drawer', () => {
describe('Custom ClassNames', () => {
it('should apply custom dialogClassName', () => {
// Arrange & Act
- renderDrawer({ dialogClassName: 'custom-dialog-class' })
+ const { container } = renderDrawer({ dialogClassName: 'custom-dialog-class' })
// Assert
- expect(screen.getByRole('dialog').className).toContain('custom-dialog-class')
+ expect(container.querySelector('.custom-dialog-class')).toBeInTheDocument()
})
it('should apply custom dialogBackdropClassName', () => {
diff --git a/web/app/components/base/drawer/index.stories.tsx b/web/app/components/base/drawer/index.stories.tsx
index ca7b3bc243b..57ab35281c6 100644
--- a/web/app/components/base/drawer/index.stories.tsx
+++ b/web/app/components/base/drawer/index.stories.tsx
@@ -10,7 +10,7 @@ const meta = {
layout: 'fullscreen',
docs: {
description: {
- component: 'Sliding panel built on Headless UI dialog primitives. Supports optional mask, custom footer, and close behaviour.',
+ component: 'Sliding panel built on Base UI dialog primitives. Supports optional mask, custom footer, and close behaviour.',
},
},
},
diff --git a/web/app/components/base/drawer/index.tsx b/web/app/components/base/drawer/index.tsx
index 88c5874dd5d..d6c0d58e7cd 100644
--- a/web/app/components/base/drawer/index.tsx
+++ b/web/app/components/base/drawer/index.tsx
@@ -1,5 +1,6 @@
'use client'
-import { Dialog, DialogBackdrop, DialogTitle } from '@headlessui/react'
+// eslint-disable-next-line no-restricted-imports -- Temporary legacy drawer exception: remove this direct Base UI wrapper after callers migrate to dify-ui drawer primitives.
+import { Dialog as BaseDialog } from '@base-ui/react/dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { useTranslation } from 'react-i18next'
@@ -47,80 +48,81 @@ export default function Drawer({
}: IDrawerProps) {
const { t } = useTranslation()
return (
- <Dialog
- unmount={unmount}
+ <BaseDialog.Root
open={isOpen}
- onClose={() => {
- if (!clickOutsideNotOpen)
+ disablePointerDismissal={clickOutsideNotOpen}
+ onOpenChange={(open) => {
+ if (!open && !clickOutsideNotOpen)
onClose()
}}
- className={cn('fixed inset-0 z-30 overflow-y-auto', dialogClassName)}
>
- <div className={cn('flex h-screen w-screen justify-end', positionCenter && 'justify-center!', containerClassName)}>
- {/* mask */}
- {!noOverlay && (
- <DialogBackdrop
- className={cn('fixed inset-0 z-40', mask && 'bg-black/30', dialogBackdropClassName)}
- onClick={() => {
- if (!clickOutsideNotOpen)
- onClose()
- }}
- />
- )}
- <div className={cn('relative z-50 flex w-full max-w-sm flex-col justify-between overflow-hidden bg-components-panel-bg p-6 text-left align-middle shadow-xl', panelClassName)}>
- <>
- <div className="flex justify-between">
- {title && (
- <DialogTitle
- as="h3"
- className="text-lg leading-6 font-medium text-text-primary"
- >
- {title}
- </DialogTitle>
- )}
- {showClose && (
- <DialogTitle className="mb-4 flex cursor-pointer items-center" as="div">
- <span
- className="i-heroicons-x-mark h-4 w-4 text-text-tertiary"
- onClick={onClose}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ')
- onClose()
- }}
- role="button"
- tabIndex={0}
- aria-label={t('operation.close', { ns: 'common' })}
- data-testid="close-icon"
- />
- </DialogTitle>
- )}
- </div>
- {description && <div className="mt-2 text-xs font-normal text-text-tertiary">{description}</div>}
- {children}
- </>
- {footer || (footer === null
- ? null
- : (
- <div className="mt-10 flex flex-row justify-end">
- <Button
- className="mr-2"
- onClick={() => {
- onCancel?.()
- }}
- >
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button
- onClick={() => {
- onOk?.()
- }}
- >
- {t('operation.save', { ns: 'common' })}
- </Button>
+ <BaseDialog.Portal>
+ <div className={cn('fixed inset-0 z-30 overflow-y-auto', dialogClassName)}>
+ <div className={cn('flex h-screen w-screen justify-end', positionCenter && 'justify-center!', containerClassName)}>
+ {!noOverlay && (
+ <BaseDialog.Backdrop
+ className={cn('fixed inset-0 z-40', mask && 'bg-black/30', dialogBackdropClassName)}
+ />
+ )}
+ <BaseDialog.Popup
+ data-unmount={unmount}
+ className={cn('relative z-50 flex w-full max-w-sm flex-col justify-between overflow-hidden bg-components-panel-bg p-6 text-left align-middle shadow-xl', panelClassName)}
+ >
+ <>
+ <div className="flex justify-between">
+ {title && (
+ <BaseDialog.Title
+ render={<h3 />}
+ className="text-lg leading-6 font-medium text-text-primary"
+ >
+ {title}
+ </BaseDialog.Title>
+ )}
+ {showClose && (
+ <div className="mb-4 flex cursor-pointer items-center">
+ <span
+ className="i-heroicons-x-mark h-4 w-4 text-text-tertiary"
+ onClick={onClose}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ')
+ onClose()
+ }}
+ role="button"
+ tabIndex={0}
+ aria-label={t('operation.close', { ns: 'common' })}
+ data-testid="close-icon"
+ />
+ </div>
+ )}
</div>
- ))}
+ {description && <div className="mt-2 text-xs font-normal text-text-tertiary">{description}</div>}
+ {children}
+ </>
+ {footer || (footer === null
+ ? null
+ : (
+ <div className="mt-10 flex flex-row justify-end">
+ <Button
+ className="mr-2"
+ onClick={() => {
+ onCancel?.()
+ }}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ onClick={() => {
+ onOk?.()
+ }}
+ >
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ </div>
+ ))}
+ </BaseDialog.Popup>
+ </div>
</div>
- </div>
- </Dialog>
+ </BaseDialog.Portal>
+ </BaseDialog.Root>
)
}
diff --git a/web/app/components/base/emoji-picker/index.tsx b/web/app/components/base/emoji-picker/index.tsx
index 75112e70ebd..9ff81b999f8 100644
--- a/web/app/components/base/emoji-picker/index.tsx
+++ b/web/app/components/base/emoji-picker/index.tsx
@@ -2,12 +2,11 @@
import type { FC } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { noop } from 'es-toolkit/function'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Divider from '@/app/components/base/divider'
-import Modal from '@/app/components/base/modal'
import EmojiPickerInner from './Inner'
type IEmojiPickerProps = {
@@ -34,39 +33,42 @@ const EmojiPicker: FC<IEmojiPickerProps> = ({
return isModal
? (
- <Modal
- onClose={noop}
- isShow
- closable={false}
- wrapperClassName={className}
- className={cn('flex max-h-[552px] flex-col rounded-xl border-[0.5px] border-divider-subtle p-0 shadow-xl')}
- >
- <EmojiPickerInner
- className="pt-3"
- onSelect={handleSelectEmoji}
- />
- <Divider className="mt-3 mb-0" />
- <div className="flex w-full items-center justify-center gap-2 p-3">
- <Button
- className="w-full"
- onClick={() => {
- onClose?.()
- }}
- >
- {t('iconPicker.cancel', { ns: 'app' })}
- </Button>
- <Button
- disabled={selectedEmoji === '' || !selectedBackground}
- variant="primary"
- className="w-full"
- onClick={() => {
- onSelect?.(selectedEmoji, selectedBackground!)
- }}
- >
- {t('iconPicker.ok', { ns: 'app' })}
- </Button>
- </div>
- </Modal>
+ <Dialog open>
+ <DialogContent
+ className={cn(
+ 'max-h-none w-full overflow-hidden! text-left align-middle',
+ 'flex max-h-[552px] flex-col rounded-xl border-[0.5px] border-divider-subtle p-0 shadow-xl',
+ className,
+ )}
+ >
+
+ <EmojiPickerInner
+ className="pt-3"
+ onSelect={handleSelectEmoji}
+ />
+ <Divider className="mt-3 mb-0" />
+ <div className="flex w-full items-center justify-center gap-2 p-3">
+ <Button
+ className="w-full"
+ onClick={() => {
+ onClose?.()
+ }}
+ >
+ {t('iconPicker.cancel', { ns: 'app' })}
+ </Button>
+ <Button
+ disabled={selectedEmoji === '' || !selectedBackground}
+ variant="primary"
+ className="w-full"
+ onClick={() => {
+ onSelect?.(selectedEmoji, selectedBackground!)
+ }}
+ >
+ {t('iconPicker.ok', { ns: 'app' })}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
: <></>
}
diff --git a/web/app/components/base/features/new-feature-panel/__tests__/dialog-wrapper.spec.tsx b/web/app/components/base/features/new-feature-panel/__tests__/feature-panel-drawer.spec.tsx
similarity index 51%
rename from web/app/components/base/features/new-feature-panel/__tests__/dialog-wrapper.spec.tsx
rename to web/app/components/base/features/new-feature-panel/__tests__/feature-panel-drawer.spec.tsx
index 374976c366d..a4c45ff1e40 100644
--- a/web/app/components/base/features/new-feature-panel/__tests__/dialog-wrapper.spec.tsx
+++ b/web/app/components/base/features/new-feature-panel/__tests__/feature-panel-drawer.spec.tsx
@@ -1,7 +1,7 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import DialogWrapper from '../dialog-wrapper'
+import { FeaturePanelDrawer } from '../feature-panel-drawer'
-describe('DialogWrapper', () => {
+describe('FeaturePanelDrawer', () => {
beforeEach(() => {
vi.clearAllMocks()
})
@@ -9,9 +9,9 @@ describe('DialogWrapper', () => {
describe('Rendering', () => {
it('should render children when show is true', () => {
render(
- <DialogWrapper show>
+ <FeaturePanelDrawer show>
<div data-testid="content">Content</div>
- </DialogWrapper>,
+ </FeaturePanelDrawer>,
)
expect(screen.getByTestId('content')).toBeInTheDocument()
@@ -19,9 +19,9 @@ describe('DialogWrapper', () => {
it('should not render children when show is false', () => {
render(
- <DialogWrapper show={false}>
+ <FeaturePanelDrawer show={false}>
<div data-testid="content">Content</div>
- </DialogWrapper>,
+ </FeaturePanelDrawer>,
)
expect(screen.queryByTestId('content')).not.toBeInTheDocument()
@@ -31,45 +31,44 @@ describe('DialogWrapper', () => {
describe('Props', () => {
it('should apply workflow styles by default', () => {
render(
- <DialogWrapper show>
+ <FeaturePanelDrawer show>
<div data-testid="content">Content</div>
- </DialogWrapper>,
+ </FeaturePanelDrawer>,
)
- const wrapper = screen.getByTestId('content').parentElement
- expect(wrapper).toHaveClass('rounded-l-2xl')
- expect(wrapper).not.toHaveClass('rounded-2xl')
+ const drawer = screen.getByRole('dialog')
+ expect(drawer).toHaveClass('data-[swipe-direction=right]:!top-[112px]')
+ expect(drawer).toHaveClass('data-[swipe-direction=right]:!rounded-l-2xl')
+ expect(drawer).not.toHaveClass('data-[swipe-direction=right]:!rounded-2xl')
})
it('should apply non-workflow styles when inWorkflow is false', () => {
render(
- <DialogWrapper show inWorkflow={false}>
+ <FeaturePanelDrawer show inWorkflow={false}>
<div data-testid="content">Content</div>
- </DialogWrapper>,
+ </FeaturePanelDrawer>,
)
- const content = screen.getByTestId('content')
- const panel = content.parentElement
- const layoutContainer = screen.getByTestId('dialog-layout-container')
+ const drawer = screen.getByRole('dialog')
+ const layoutContainer = screen.getByTestId('feature-panel-drawer-layout')
- expect(layoutContainer).toHaveClass('pr-2')
- expect(layoutContainer).toHaveClass('pt-[64px]')
- expect(layoutContainer).not.toHaveClass('pt-[112px]')
+ expect(layoutContainer).toBeInTheDocument()
- expect(panel).toHaveClass('rounded-2xl')
- expect(panel).toHaveClass('border-[0.5px]')
- expect(panel).not.toHaveClass('rounded-l-2xl')
+ expect(drawer).toHaveClass('data-[swipe-direction=right]:!top-[64px]')
+ expect(drawer).toHaveClass('data-[swipe-direction=right]:!right-2')
+ expect(drawer).toHaveClass('data-[swipe-direction=right]:!rounded-2xl')
+ expect(drawer).toHaveClass('data-[swipe-direction=right]:!border-[0.5px]')
+ expect(drawer).not.toHaveClass('data-[swipe-direction=right]:!rounded-l-2xl')
})
it('should accept custom className', () => {
render(
- <DialogWrapper show className="custom-class">
+ <FeaturePanelDrawer show className="custom-class">
<div data-testid="content">Content</div>
- </DialogWrapper>,
+ </FeaturePanelDrawer>,
)
- const wrapper = screen.getByTestId('content').parentElement
- expect(wrapper).toHaveClass('custom-class')
+ expect(screen.getByRole('dialog')).toHaveClass('custom-class')
})
})
@@ -78,9 +77,9 @@ describe('DialogWrapper', () => {
const onClose = vi.fn()
render(
- <DialogWrapper show onClose={onClose}>
+ <FeaturePanelDrawer show onClose={onClose}>
<div>Content</div>
- </DialogWrapper>,
+ </FeaturePanelDrawer>,
)
fireEvent.keyDown(document, { key: 'Escape' })
@@ -92,9 +91,9 @@ describe('DialogWrapper', () => {
it('should not throw when escape is pressed without onClose', () => {
render(
- <DialogWrapper show>
+ <FeaturePanelDrawer show>
<div>Content</div>
- </DialogWrapper>,
+ </FeaturePanelDrawer>,
)
expect(() => {
diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx
index 13b4133ab6c..73f76a6ce62 100644
--- a/web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx
+++ b/web/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal.tsx
@@ -2,11 +2,11 @@
import type { FC } from 'react'
import type { AnnotationReplyConfig } from '@/models/debug'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useModelListAndDefaultModelAndCurrentProviderAndModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'
@@ -58,52 +58,61 @@ const ConfigParamModal: FC<Props> = ({ isShow, onHide: doHide, onSave, isInit, a
setLoading(false)
}
return (
- <Modal isShow={isShow} onClose={onHide} className="!mt-14 !w-[640px] !max-w-none !p-6">
- <div className="mb-2 title-2xl-semi-bold text-text-primary">
- {t(`initSetup.${isInit ? 'title' : 'configTitle'}`, { ns: 'appAnnotation' })}
- </div>
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
+ >
+ <DialogContent className="!mt-14 !w-[640px] !max-w-none overflow-hidden! border-none !p-6 text-left align-middle">
- <div className="mt-6 space-y-3">
- <Item title={t('feature.annotation.scoreThreshold.title', { ns: 'appDebug' })} tooltip={t('feature.annotation.scoreThreshold.description', { ns: 'appDebug' })}>
- <ScoreSlider
- className="mt-1"
- value={(annotationConfig.score_threshold || ANNOTATION_DEFAULT.score_threshold) * 100}
- onChange={(val) => {
- setAnnotationConfig({
- ...annotationConfig,
- score_threshold: val / 100,
- })
- }}
- />
- </Item>
+ <div className="mb-2 title-2xl-semi-bold text-text-primary">
+ {t(`initSetup.${isInit ? 'title' : 'configTitle'}`, { ns: 'appAnnotation' })}
+ </div>
- <Item title={t('modelProvider.embeddingModel.key', { ns: 'common' })} tooltip={t('embeddingModelSwitchTip', { ns: 'appAnnotation' })}>
- <div className="pt-1">
- <ModelSelector
- defaultModel={embeddingModel && {
- provider: embeddingModel.providerName,
- model: embeddingModel.modelName,
- }}
- modelList={embeddingsModelList}
- onSelect={(val) => {
- setEmbeddingModel({
- providerName: val.provider,
- modelName: val.model,
+ <div className="mt-6 space-y-3">
+ <Item title={t('feature.annotation.scoreThreshold.title', { ns: 'appDebug' })} tooltip={t('feature.annotation.scoreThreshold.description', { ns: 'appDebug' })}>
+ <ScoreSlider
+ className="mt-1"
+ value={(annotationConfig.score_threshold || ANNOTATION_DEFAULT.score_threshold) * 100}
+ onChange={(val) => {
+ setAnnotationConfig({
+ ...annotationConfig,
+ score_threshold: val / 100,
})
}}
/>
- </div>
- </Item>
- </div>
+ </Item>
+
+ <Item title={t('modelProvider.embeddingModel.key', { ns: 'common' })} tooltip={t('embeddingModelSwitchTip', { ns: 'appAnnotation' })}>
+ <div className="pt-1">
+ <ModelSelector
+ defaultModel={embeddingModel && {
+ provider: embeddingModel.providerName,
+ model: embeddingModel.modelName,
+ }}
+ modelList={embeddingsModelList}
+ onSelect={(val) => {
+ setEmbeddingModel({
+ providerName: val.provider,
+ modelName: val.model,
+ })
+ }}
+ />
+ </div>
+ </Item>
+ </div>
- <div className="mt-6 flex justify-end gap-2">
- <Button onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button variant="primary" onClick={handleSave} loading={isLoading}>
- <div></div>
- <div>{t(`initSetup.${isInit ? 'confirmBtn' : 'configConfirmBtn'}`, { ns: 'appAnnotation' })}</div>
- </Button>
- </div>
- </Modal>
+ <div className="mt-6 flex justify-end gap-2">
+ <Button onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button variant="primary" onClick={handleSave} loading={isLoading}>
+ <div></div>
+ <div>{t(`initSetup.${isInit ? 'confirmBtn' : 'configConfirmBtn'}`, { ns: 'appAnnotation' })}</div>
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(ConfigParamModal)
diff --git a/web/app/components/base/features/new-feature-panel/dialog-wrapper.tsx b/web/app/components/base/features/new-feature-panel/dialog-wrapper.tsx
deleted file mode 100644
index d3e08147778..00000000000
--- a/web/app/components/base/features/new-feature-panel/dialog-wrapper.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { ReactNode } from 'react'
-import { Dialog, DialogPanel, Transition, TransitionChild } from '@headlessui/react'
-import { cn } from '@langgenius/dify-ui/cn'
-import { Fragment, useCallback } from 'react'
-
-type DialogProps = {
- className?: string
- children: ReactNode
- show: boolean
- onClose?: () => void
- inWorkflow?: boolean
-}
-
-const DialogWrapper = ({
- className,
- children,
- show,
- onClose,
- inWorkflow = true,
-}: DialogProps) => {
- const close = useCallback(() => onClose?.(), [onClose])
- return (
- <Transition appear show={show} as={Fragment}>
- <Dialog as="div" className="relative z-40" onClose={close}>
- <TransitionChild>
- <div className={cn(
- 'fixed inset-0 bg-black/25',
- 'data-closed:opacity-0',
- 'data-enter:opacity-100 data-enter:duration-300 data-enter:ease-out',
- 'data-leave:opacity-0 data-leave:duration-200 data-leave:ease-in',
- )}
- />
- </TransitionChild>
-
- <div className="fixed inset-0">
- <div className={cn('flex min-h-full flex-col items-end justify-center pb-2', inWorkflow ? 'pt-[112px]' : 'pt-[64px] pr-2')} data-testid="dialog-layout-container">
- <TransitionChild>
- <DialogPanel className={cn(
- 'relative flex h-0 w-[420px] grow flex-col overflow-hidden border-components-panel-border bg-components-panel-bg-alt p-0 text-left align-middle shadow-xl transition-all',
- inWorkflow ? 'rounded-l-2xl border-t-[0.5px] border-b-[0.5px] border-l-[0.5px]' : 'rounded-2xl border-[0.5px]',
- 'data-closed:scale-95 data-closed:opacity-0',
- 'data-enter:scale-100 data-enter:opacity-100 data-enter:duration-300 data-enter:ease-out',
- 'data-leave:scale-95 data-leave:opacity-0 data-leave:duration-200 data-leave:ease-in',
- className,
- )}
- >
- {children}
- </DialogPanel>
- </TransitionChild>
- </div>
- </div>
- </Dialog>
- </Transition>
- )
-}
-
-export default DialogWrapper
diff --git a/web/app/components/base/features/new-feature-panel/feature-panel-drawer.tsx b/web/app/components/base/features/new-feature-panel/feature-panel-drawer.tsx
new file mode 100644
index 00000000000..42a89a156d7
--- /dev/null
+++ b/web/app/components/base/features/new-feature-panel/feature-panel-drawer.tsx
@@ -0,0 +1,60 @@
+import type { ReactNode } from 'react'
+import { cn } from '@langgenius/dify-ui/cn'
+import {
+ Drawer,
+ DrawerBackdrop,
+ DrawerContent,
+ DrawerPopup,
+ DrawerPortal,
+ DrawerViewport,
+} from '@langgenius/dify-ui/drawer'
+import { useCallback } from 'react'
+
+type FeaturePanelDrawerProps = {
+ className?: string
+ children: ReactNode
+ show: boolean
+ onClose?: () => void
+ inWorkflow?: boolean
+}
+
+export function FeaturePanelDrawer({
+ className,
+ children,
+ show,
+ onClose,
+ inWorkflow = true,
+}: FeaturePanelDrawerProps) {
+ const close = useCallback(() => onClose?.(), [onClose])
+
+ return (
+ <Drawer
+ open={show}
+ swipeDirection="right"
+ onOpenChange={(open) => {
+ if (!open)
+ close()
+ }}
+ >
+ <DrawerPortal>
+ <DrawerBackdrop className="bg-black/25" />
+ <DrawerViewport data-testid="feature-panel-drawer-layout">
+ <DrawerPopup
+ className={cn(
+ 'border-components-panel-border bg-components-panel-bg-alt p-0 text-left align-middle',
+ 'data-[swipe-direction=right]:!h-auto data-[swipe-direction=right]:!w-[420px] data-[swipe-direction=right]:!max-w-[calc(100vw-2rem)]',
+ inWorkflow
+ ? 'data-[swipe-direction=right]:!top-[112px] data-[swipe-direction=right]:!right-0 data-[swipe-direction=right]:!bottom-2 data-[swipe-direction=right]:!rounded-l-2xl data-[swipe-direction=right]:!rounded-r-none data-[swipe-direction=right]:!border-t-[0.5px] data-[swipe-direction=right]:!border-r-0 data-[swipe-direction=right]:!border-b-[0.5px] data-[swipe-direction=right]:!border-l-[0.5px]'
+ : 'data-[swipe-direction=right]:!top-[64px] data-[swipe-direction=right]:!right-2 data-[swipe-direction=right]:!bottom-2 data-[swipe-direction=right]:!rounded-2xl data-[swipe-direction=right]:!border-[0.5px]',
+ className,
+ )}
+ >
+ <DrawerContent className="flex min-h-0 flex-1 touch-auto flex-col overflow-hidden p-0 pb-0">
+ {children}
+ </DrawerContent>
+ </DrawerPopup>
+ </DrawerViewport>
+ </DrawerPortal>
+ </Drawer>
+ )
+}
diff --git a/web/app/components/base/features/new-feature-panel/index.tsx b/web/app/components/base/features/new-feature-panel/index.tsx
index 84c77155772..61e961c82b6 100644
--- a/web/app/components/base/features/new-feature-panel/index.tsx
+++ b/web/app/components/base/features/new-feature-panel/index.tsx
@@ -1,13 +1,13 @@
import type { OnFeaturesChange } from '@/app/components/base/features/types'
import type { InputVar } from '@/app/components/workflow/types'
import type { PromptVariable } from '@/models/debug'
-import { RiCloseLine } from '@remixicon/react'
+import { DrawerCloseButton } from '@langgenius/dify-ui/drawer'
import { useTranslation } from 'react-i18next'
import AnnotationReply from '@/app/components/base/features/new-feature-panel/annotation-reply'
import Citation from '@/app/components/base/features/new-feature-panel/citation'
import ConversationOpener from '@/app/components/base/features/new-feature-panel/conversation-opener'
-import DialogWrapper from '@/app/components/base/features/new-feature-panel/dialog-wrapper'
+import { FeaturePanelDrawer } from '@/app/components/base/features/new-feature-panel/feature-panel-drawer'
import FileUpload from '@/app/components/base/features/new-feature-panel/file-upload'
import FollowUp from '@/app/components/base/features/new-feature-panel/follow-up'
import ImageUpload from '@/app/components/base/features/new-feature-panel/image-upload'
@@ -48,7 +48,7 @@ const NewFeaturePanel = ({
const { data: text2speechDefaultModel } = useDefaultModel(ModelTypeEnum.tts)
return (
- <DialogWrapper
+ <FeaturePanelDrawer
show={show}
onClose={onClose}
inWorkflow={inWorkflow}
@@ -60,7 +60,10 @@ const NewFeaturePanel = ({
<div className="system-xl-semibold text-text-primary">{t('common.features', { ns: 'workflow' })}</div>
<div className="body-xs-regular text-text-tertiary">{t('common.featuresDescription', { ns: 'workflow' })}</div>
</div>
- <div className="h-8 w-8 cursor-pointer p-2" onClick={onClose}><RiCloseLine className="h-4 w-4 text-text-tertiary" /></div>
+ <DrawerCloseButton
+ aria-label={t('operation.close', { ns: 'common' })}
+ className="h-8 w-8 p-2"
+ />
</div>
{/* list */}
<div className="grow basis-0 overflow-y-auto px-4 pb-4">
@@ -96,7 +99,7 @@ const NewFeaturePanel = ({
)}
</div>
</div>
- </DialogWrapper>
+ </FeaturePanelDrawer>
)
}
diff --git a/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx b/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx
index 0ae2f458e1e..7522c734453 100644
--- a/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx
+++ b/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx
@@ -3,12 +3,11 @@ import type { CodeBasedExtensionItem } from '@/models/common'
import type { ModerationConfig, ModerationContentConfig } from '@/models/debug'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
-import { noop } from 'es-toolkit/function'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Divider from '@/app/components/base/divider'
-import Modal from '@/app/components/base/modal'
import ApiBasedExtensionSelector from '@/app/components/header/account-setting/api-based-extension-page/selector'
import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'
import { CustomConfigurationStatusEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
@@ -226,165 +225,164 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({
}
return (
- <Modal
- isShow
- onClose={noop}
- className="mt-14! w-[600px]! max-w-none! p-6!"
- >
- <div className="flex items-center justify-between">
- <div className="title-2xl-semi-bold text-text-primary">{t('feature.moderation.modal.title', { ns: 'appDebug' })}</div>
- <div
- role="button"
- tabIndex={0}
- className="cursor-pointer p-1"
- onClick={onCancel}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault()
- onCancel()
- }
- }}
- >
- <span className="i-ri-close-line h-4 w-4 text-text-tertiary" />
- </div>
- </div>
- <div className="py-2">
- <div className="text-sm leading-9 font-medium text-text-primary">
- {t('feature.moderation.modal.provider.title', { ns: 'appDebug' })}
+ <Dialog open>
+ <DialogContent className="mt-14! w-[600px]! max-w-none! overflow-hidden! border-none p-6! text-left align-middle">
+
+ <div className="flex items-center justify-between">
+ <div className="title-2xl-semi-bold text-text-primary">{t('feature.moderation.modal.title', { ns: 'appDebug' })}</div>
+ <div
+ role="button"
+ tabIndex={0}
+ className="cursor-pointer p-1"
+ onClick={onCancel}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ onCancel()
+ }
+ }}
+ >
+ <span className="i-ri-close-line h-4 w-4 text-text-tertiary" />
+ </div>
</div>
- <div className="grid grid-cols-3 gap-2.5">
- {
- providers.map(provider => (
- <div
- key={provider.key}
- className={cn(
- 'flex h-8 cursor-default items-center rounded-md border border-components-option-card-option-border bg-components-option-card-option-bg px-2 system-sm-regular text-text-secondary',
- localeData.type !== provider.key && 'cursor-pointer hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',
- localeData.type === provider.key && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg system-sm-medium shadow-xs',
- localeData.type === 'openai_moderation' && provider.key === 'openai_moderation' && !isOpenAIProviderConfigured && 'text-text-disabled',
- )}
- onClick={() => handleDataTypeChange(provider.key)}
- >
- <div className={cn(
- 'mr-2 h-4 w-4 rounded-full border border-components-radio-border bg-components-radio-bg shadow-xs',
- localeData.type === provider.key && 'border-[5px] border-components-radio-border-checked',
- )}
+ <div className="py-2">
+ <div className="text-sm leading-9 font-medium text-text-primary">
+ {t('feature.moderation.modal.provider.title', { ns: 'appDebug' })}
+ </div>
+ <div className="grid grid-cols-3 gap-2.5">
+ {
+ providers.map(provider => (
+ <div
+ key={provider.key}
+ className={cn(
+ 'flex h-8 cursor-default items-center rounded-md border border-components-option-card-option-border bg-components-option-card-option-bg px-2 system-sm-regular text-text-secondary',
+ localeData.type !== provider.key && 'cursor-pointer hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',
+ localeData.type === provider.key && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg system-sm-medium shadow-xs',
+ localeData.type === 'openai_moderation' && provider.key === 'openai_moderation' && !isOpenAIProviderConfigured && 'text-text-disabled',
+ )}
+ onClick={() => handleDataTypeChange(provider.key)}
>
+ <div className={cn(
+ 'mr-2 h-4 w-4 rounded-full border border-components-radio-border bg-components-radio-bg shadow-xs',
+ localeData.type === provider.key && 'border-[5px] border-components-radio-border-checked',
+ )}
+ >
+ </div>
+ {provider.name}
+ </div>
+ ))
+ }
+ </div>
+ {
+ !isLoading && !isOpenAIProviderConfigured && localeData.type === 'openai_moderation' && (
+ <div className="mt-2 flex items-center rounded-lg border border-[#FEF0C7] bg-[#FFFAEB] px-3 py-2">
+ <span className="mr-1 i-custom-vender-line-general-info-circle h-4 w-4 text-[#F79009]" />
+ <div className="flex items-center text-xs font-medium text-gray-700">
+ {t('feature.moderation.modal.openaiNotConfig.before', { ns: 'appDebug' })}
+ <span
+ className="cursor-pointer text-primary-600"
+ onClick={handleOpenSettingsModal}
+ >
+ &nbsp;
+ {t('settings.provider', { ns: 'common' })}
+&nbsp;
+ </span>
+ {t('feature.moderation.modal.openaiNotConfig.after', { ns: 'appDebug' })}
</div>
- {provider.name}
</div>
- ))
+ )
}
</div>
{
- !isLoading && !isOpenAIProviderConfigured && localeData.type === 'openai_moderation' && (
- <div className="mt-2 flex items-center rounded-lg border border-[#FEF0C7] bg-[#FFFAEB] px-3 py-2">
- <span className="mr-1 i-custom-vender-line-general-info-circle h-4 w-4 text-[#F79009]" />
- <div className="flex items-center text-xs font-medium text-gray-700">
- {t('feature.moderation.modal.openaiNotConfig.before', { ns: 'appDebug' })}
- <span
- className="cursor-pointer text-primary-600"
- onClick={handleOpenSettingsModal}
- >
- &nbsp;
- {t('settings.provider', { ns: 'common' })}
-&nbsp;
- </span>
- {t('feature.moderation.modal.openaiNotConfig.after', { ns: 'appDebug' })}
+ localeData.type === 'keywords' && (
+ <div className="py-2">
+ <div className="mb-1 text-sm font-medium text-text-primary">{t('feature.moderation.modal.provider.keywords', { ns: 'appDebug' })}</div>
+ <div className="mb-2 text-xs text-text-tertiary">{t('feature.moderation.modal.keywords.tip', { ns: 'appDebug' })}</div>
+ <div className="relative h-[88px] rounded-lg bg-components-input-bg-normal px-3 py-2">
+ <textarea
+ value={localeData.config?.keywords || ''}
+ onChange={handleDataKeywordsChange}
+ className="block h-full w-full resize-none appearance-none bg-transparent text-sm text-text-secondary outline-hidden"
+ placeholder={t('feature.moderation.modal.keywords.placeholder', { ns: 'appDebug' }) || ''}
+ />
+ <div className="absolute right-2 bottom-2 flex h-5 items-center rounded-md bg-background-section px-1 text-xs font-medium text-text-quaternary">
+ <span>{(localeData.config?.keywords || '').split('\n').filter(Boolean).length}</span>
+ /
+ <span className="text-text-tertiary">
+ 100
+ {t('feature.moderation.modal.keywords.line', { ns: 'appDebug' })}
+ </span>
+ </div>
</div>
</div>
)
}
- </div>
- {
- localeData.type === 'keywords' && (
- <div className="py-2">
- <div className="mb-1 text-sm font-medium text-text-primary">{t('feature.moderation.modal.provider.keywords', { ns: 'appDebug' })}</div>
- <div className="mb-2 text-xs text-text-tertiary">{t('feature.moderation.modal.keywords.tip', { ns: 'appDebug' })}</div>
- <div className="relative h-[88px] rounded-lg bg-components-input-bg-normal px-3 py-2">
- <textarea
- value={localeData.config?.keywords || ''}
- onChange={handleDataKeywordsChange}
- className="block h-full w-full resize-none appearance-none bg-transparent text-sm text-text-secondary outline-hidden"
- placeholder={t('feature.moderation.modal.keywords.placeholder', { ns: 'appDebug' }) || ''}
- />
- <div className="absolute right-2 bottom-2 flex h-5 items-center rounded-md bg-background-section px-1 text-xs font-medium text-text-quaternary">
- <span>{(localeData.config?.keywords || '').split('\n').filter(Boolean).length}</span>
- /
- <span className="text-text-tertiary">
- 100
- {t('feature.moderation.modal.keywords.line', { ns: 'appDebug' })}
- </span>
+ {
+ localeData.type === 'api' && (
+ <div className="py-2">
+ <div className="flex h-9 items-center justify-between">
+ <div className="text-sm font-medium text-text-primary">{t('apiBasedExtension.selector.title', { ns: 'common' })}</div>
+ <a
+ href={docLink('/use-dify/workspace/api-extension/api-extension')}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="group flex items-center text-xs text-text-tertiary hover:text-primary-600"
+ >
+ <span className="mr-1 i-custom-vender-line-education-book-open-01 h-3 w-3 text-text-tertiary group-hover:text-primary-600" />
+ {t('apiBasedExtension.link', { ns: 'common' })}
+ </a>
</div>
+ <ApiBasedExtensionSelector
+ value={localeData.config?.api_based_extension_id || ''}
+ onChange={handleDataApiBasedChange}
+ />
</div>
- </div>
- )
- }
- {
- localeData.type === 'api' && (
- <div className="py-2">
- <div className="flex h-9 items-center justify-between">
- <div className="text-sm font-medium text-text-primary">{t('apiBasedExtension.selector.title', { ns: 'common' })}</div>
- <a
- href={docLink('/use-dify/workspace/api-extension/api-extension')}
- target="_blank"
- rel="noopener noreferrer"
- className="group flex items-center text-xs text-text-tertiary hover:text-primary-600"
- >
- <span className="mr-1 i-custom-vender-line-education-book-open-01 h-3 w-3 text-text-tertiary group-hover:text-primary-600" />
- {t('apiBasedExtension.link', { ns: 'common' })}
- </a>
- </div>
- <ApiBasedExtensionSelector
- value={localeData.config?.api_based_extension_id || ''}
- onChange={handleDataApiBasedChange}
+ )
+ }
+ {
+ systemTypes.findIndex(t => t === localeData.type) < 0
+ && currentProvider?.form_schema
+ && (
+ <FormGeneration
+ forms={currentProvider?.form_schema}
+ value={localeData.config}
+ onChange={handleDataExtraChange}
/>
- </div>
- )
- }
- {
- systemTypes.findIndex(t => t === localeData.type) < 0
- && currentProvider?.form_schema
- && (
- <FormGeneration
- forms={currentProvider?.form_schema}
- value={localeData.config}
- onChange={handleDataExtraChange}
- />
- )
- }
- <Divider bgStyle="gradient" className="my-3 h-px" />
- <ModerationContent
- title={t('feature.moderation.modal.content.input', { ns: 'appDebug' }) || ''}
- config={localeData.config?.inputs_config || { enabled: false, preset_response: '' }}
- onConfigChange={config => handleDataContentChange('inputs_config', config)}
- info={(localeData.type === 'api' && t('feature.moderation.modal.content.fromApi', { ns: 'appDebug' })) || ''}
- showPreset={localeData.type !== 'api'}
- />
- <ModerationContent
- title={t('feature.moderation.modal.content.output', { ns: 'appDebug' }) || ''}
- config={localeData.config?.outputs_config || { enabled: false, preset_response: '' }}
- onConfigChange={config => handleDataContentChange('outputs_config', config)}
- info={(localeData.type === 'api' && t('feature.moderation.modal.content.fromApi', { ns: 'appDebug' })) || ''}
- showPreset={localeData.type !== 'api'}
- />
- <div className="mt-1 mb-8 text-xs font-medium text-text-tertiary">{t('feature.moderation.modal.content.condition', { ns: 'appDebug' })}</div>
- <div className="flex items-center justify-end">
- <Button
- onClick={onCancel}
- className="mr-2"
- >
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button
- variant="primary"
- onClick={handleSave}
- disabled={localeData.type === 'openai_moderation' && !isOpenAIProviderConfigured}
- >
- {t('operation.save', { ns: 'common' })}
- </Button>
- </div>
- </Modal>
+ )
+ }
+ <Divider bgStyle="gradient" className="my-3 h-px" />
+ <ModerationContent
+ title={t('feature.moderation.modal.content.input', { ns: 'appDebug' }) || ''}
+ config={localeData.config?.inputs_config || { enabled: false, preset_response: '' }}
+ onConfigChange={config => handleDataContentChange('inputs_config', config)}
+ info={(localeData.type === 'api' && t('feature.moderation.modal.content.fromApi', { ns: 'appDebug' })) || ''}
+ showPreset={localeData.type !== 'api'}
+ />
+ <ModerationContent
+ title={t('feature.moderation.modal.content.output', { ns: 'appDebug' }) || ''}
+ config={localeData.config?.outputs_config || { enabled: false, preset_response: '' }}
+ onConfigChange={config => handleDataContentChange('outputs_config', config)}
+ info={(localeData.type === 'api' && t('feature.moderation.modal.content.fromApi', { ns: 'appDebug' })) || ''}
+ showPreset={localeData.type !== 'api'}
+ />
+ <div className="mt-1 mb-8 text-xs font-medium text-text-tertiary">{t('feature.moderation.modal.content.condition', { ns: 'appDebug' })}</div>
+ <div className="flex items-center justify-end">
+ <Button
+ onClick={onCancel}
+ className="mr-2"
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ variant="primary"
+ onClick={handleSave}
+ disabled={localeData.type === 'openai_moderation' && !isOpenAIProviderConfigured}
+ >
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/base/file-uploader/__tests__/audio-preview.spec.tsx b/web/app/components/base/file-uploader/__tests__/audio-preview.spec.tsx
index 5a5740ef0d1..7029bc8e0a5 100644
--- a/web/app/components/base/file-uploader/__tests__/audio-preview.spec.tsx
+++ b/web/app/components/base/file-uploader/__tests__/audio-preview.spec.tsx
@@ -39,15 +39,14 @@ describe('AudioPreview', () => {
expect(onCancel).toHaveBeenCalled()
})
- it('should stop propagation when backdrop is clicked', () => {
- const { baseElement } = render(<AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={vi.fn()} />)
+ it('should not close when backdrop is clicked', () => {
+ const onCancel = vi.fn()
+ render(<AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={onCancel} />)
- const backdrop = baseElement.querySelector('[tabindex="-1"]')
- const event = new MouseEvent('click', { bubbles: true })
- const stopPropagation = vi.spyOn(event, 'stopPropagation')
- backdrop!.dispatchEvent(event)
+ const dialog = screen.getByRole('dialog')
+ fireEvent.click(dialog)
- expect(stopPropagation).toHaveBeenCalled()
+ expect(onCancel).not.toHaveBeenCalled()
})
it('should call onCancel when Escape key is pressed', () => {
@@ -64,6 +63,6 @@ describe('AudioPreview', () => {
render(<AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={vi.fn()} />)
const audio = document.querySelector('audio')
- expect(audio?.closest('[tabindex="-1"]')?.parentElement).toBe(document.body)
+ expect(audio?.closest('[data-base-ui-portal]')?.parentElement).toBe(document.body)
})
})
diff --git a/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx b/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx
index b3c48a70611..3aa0f9e6d65 100644
--- a/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx
+++ b/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx
@@ -35,7 +35,7 @@ describe('PdfPreview', () => {
}
const getControl = (rightClass: 'right-24' | 'right-16' | 'right-6') => {
- const control = document.querySelector(`div.absolute.${rightClass}.top-6`) as HTMLDivElement | null
+ const control = document.querySelector(`button.absolute.${rightClass}.top-6`) as HTMLButtonElement | null
expect(control).toBeInTheDocument()
return control!
}
@@ -129,14 +129,12 @@ describe('PdfPreview', () => {
expect(mockOnCancel).toHaveBeenCalled()
})
- it('should render the overlay and stop click propagation', () => {
+ it('should render the overlay and keep backdrop clicks from closing', () => {
render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
- const overlay = document.querySelector('[tabindex="-1"]')
+ const overlay = screen.getByRole('dialog')
expect(overlay).toBeInTheDocument()
- const event = new MouseEvent('click', { bubbles: true })
- const stopPropagation = vi.spyOn(event, 'stopPropagation')
- overlay!.dispatchEvent(event)
- expect(stopPropagation).toHaveBeenCalled()
+ fireEvent.click(overlay)
+ expect(mockOnCancel).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/base/file-uploader/__tests__/video-preview.spec.tsx b/web/app/components/base/file-uploader/__tests__/video-preview.spec.tsx
index c95455caf30..0430bd37f93 100644
--- a/web/app/components/base/file-uploader/__tests__/video-preview.spec.tsx
+++ b/web/app/components/base/file-uploader/__tests__/video-preview.spec.tsx
@@ -1,4 +1,4 @@
-import { fireEvent, render } from '@testing-library/react'
+import { fireEvent, render, screen } from '@testing-library/react'
import VideoPreview from '../video-preview'
describe('VideoPreview', () => {
@@ -39,15 +39,14 @@ describe('VideoPreview', () => {
expect(onCancel).toHaveBeenCalled()
})
- it('should stop propagation when backdrop is clicked', () => {
- const { baseElement } = render(<VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={vi.fn()} />)
+ it('should not close when backdrop is clicked', () => {
+ const onCancel = vi.fn()
+ render(<VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={onCancel} />)
- const backdrop = baseElement.querySelector('[tabindex="-1"]')
- const event = new MouseEvent('click', { bubbles: true })
- const stopPropagation = vi.spyOn(event, 'stopPropagation')
- backdrop!.dispatchEvent(event)
+ const dialog = screen.getByRole('dialog')
+ fireEvent.click(dialog)
- expect(stopPropagation).toHaveBeenCalled()
+ expect(onCancel).not.toHaveBeenCalled()
})
it('should call onCancel when Escape key is pressed', () => {
@@ -64,6 +63,6 @@ describe('VideoPreview', () => {
render(<VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={vi.fn()} />)
const video = document.querySelector('video')
- expect(video?.closest('[tabindex="-1"]')?.parentElement).toBe(document.body)
+ expect(video?.closest('[data-base-ui-portal]')?.parentElement).toBe(document.body)
})
})
diff --git a/web/app/components/base/file-uploader/audio-preview.tsx b/web/app/components/base/file-uploader/audio-preview.tsx
index 28988b3a7cb..6d38fad169a 100644
--- a/web/app/components/base/file-uploader/audio-preview.tsx
+++ b/web/app/components/base/file-uploader/audio-preview.tsx
@@ -1,8 +1,5 @@
import type { FC } from 'react'
-import * as React from 'react'
-import { createPortal } from 'react-dom'
-
-import { useHotkeys } from 'react-hotkeys-hook'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
type AudioPreviewProps = {
url: string
@@ -14,31 +11,40 @@ const AudioPreview: FC<AudioPreviewProps> = ({
title,
onCancel,
}) => {
- useHotkeys('esc', onCancel)
-
- return createPortal(
- <div
- className="fixed inset-0 z-1000 flex items-center justify-center bg-black/80 p-8"
- onClick={e => e.stopPropagation()}
- tabIndex={-1}
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
+ disablePointerDismissal
>
- <div>
- <audio controls title={title} autoPlay={false} preload="metadata">
- <source
- type="audio/mpeg"
- src={url}
- className="max-h-full max-w-full"
- />
- </audio>
- </div>
- <div
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/[0.08] backdrop-blur-[2px]"
- onClick={onCancel}
+ <DialogContent
+ className="inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-x-0! translate-y-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
+ backdropClassName="bg-transparent!"
>
- <span className="i-ri-close-line h-4 w-4 text-gray-500" data-testid="close-btn" />
- </div>
- </div>,
- document.body,
+ <div
+ aria-label={title}
+ tabIndex={-1}
+ onClick={e => e.stopPropagation()}
+ >
+ <audio controls title={title} autoPlay={false} preload="metadata">
+ <source
+ type="audio/mpeg"
+ src={url}
+ className="max-h-full max-w-full"
+ />
+ </audio>
+ </div>
+ <div
+ className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/[0.08] backdrop-blur-[2px]"
+ onClick={onCancel}
+ >
+ <span className="i-ri-close-line h-4 w-4 text-gray-500" data-testid="close-btn" />
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.spec.tsx
index 002eced6ca0..183313cd913 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.spec.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-attachment/__tests__/file-item.spec.tsx
@@ -186,7 +186,7 @@ describe('FileInAttachmentItem', () => {
const buttons = screen.getAllByRole('button')
fireEvent.click(buttons[0]!)
- // ImagePreview renders via createPortal with class "image-preview-container"
+ // ImagePreview renders through Dialog with class "image-preview-container"
const previewContainer = document.querySelector('.image-preview-container')!
expect(previewContainer)!.toBeInTheDocument()
diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-image-item.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-image-item.spec.tsx
index cfe6719b20c..c84d9e3d69a 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-image-item.spec.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-image-item.spec.tsx
@@ -95,8 +95,7 @@ describe('FileImageItem', () => {
const img = screen.getByRole('img')
fireEvent.click(img.parentElement!)
- // ImagePreview renders via createPortal with class "image-preview-container", not role="dialog"
- // ImagePreview renders via createPortal with class "image-preview-container", not role="dialog"
+ // ImagePreview renders through Dialog with class "image-preview-container"
expect(document.querySelector('.image-preview-container'))!.toBeInTheDocument()
})
@@ -114,7 +113,7 @@ describe('FileImageItem', () => {
const img = screen.getByRole('img')
fireEvent.click(img.parentElement!)
- // ImagePreview renders via createPortal with class "image-preview-container"
+ // ImagePreview renders through Dialog with class "image-preview-container"
const previewContainer = document.querySelector('.image-preview-container')!
expect(previewContainer)!.toBeInTheDocument()
diff --git a/web/app/components/base/file-uploader/pdf-preview.tsx b/web/app/components/base/file-uploader/pdf-preview.tsx
index c129f9cfb33..07fb2bab765 100644
--- a/web/app/components/base/file-uploader/pdf-preview.tsx
+++ b/web/app/components/base/file-uploader/pdf-preview.tsx
@@ -1,12 +1,11 @@
import type { FC } from 'react'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { RiCloseLine, RiZoomInLine, RiZoomOutLine } from '@remixicon/react'
import { noop } from 'es-toolkit/function'
-import { t } from 'i18next'
-import * as React from 'react'
import { useState } from 'react'
-import { createPortal } from 'react-dom'
import { useHotkeys } from 'react-hotkeys-hook'
+import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { PdfHighlighter, PdfLoader } from './pdf-highlighter-adapter'
@@ -20,6 +19,7 @@ const PdfPreview: FC<PdfPreviewProps> = ({
url,
onCancel,
}) => {
+ const { t } = useTranslation()
const media = useBreakpoints()
const [scale, setScale] = useState(1)
const [position, setPosition] = useState({ x: 0, y: 0 })
@@ -42,87 +42,106 @@ const PdfPreview: FC<PdfPreviewProps> = ({
})
}
- useHotkeys('esc', onCancel)
useHotkeys('up', zoomIn)
useHotkeys('down', zoomOut)
- return createPortal(
- <div
- className={`fixed inset-0 z-1000 flex items-center justify-center bg-black/80 ${!isMobile && 'p-8'}`}
- onClick={e => e.stopPropagation()}
- tabIndex={-1}
+ const zoomOutLabel = t('operation.zoomOut', { ns: 'common' })
+ const zoomInLabel = t('operation.zoomIn', { ns: 'common' })
+ const cancelLabel = t('operation.cancel', { ns: 'common' })
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
+ disablePointerDismissal
>
- <div
- className="h-[95vh] max-h-full w-screen max-w-full overflow-hidden"
- style={{ transform: `scale(${scale})`, transformOrigin: 'center', scrollbarWidth: 'none', msOverflowStyle: 'none' }}
+ <DialogContent
+ className={`inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-x-0! translate-y-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 shadow-none! ${!isMobile ? 'p-8!' : 'p-0!'}`}
+ backdropClassName="bg-transparent!"
>
- <PdfLoader
- workerSrc="/pdf.worker.min.mjs"
- url={url}
- beforeLoad={<div className="flex h-64 items-center justify-center"><Loading type="app" /></div>}
+ <div
+ aria-label={url}
+ tabIndex={-1}
+ onClick={e => e.stopPropagation()}
+ className="h-[95vh] max-h-full w-screen max-w-full overflow-hidden"
+ style={{ transform: `scale(${scale})`, transformOrigin: 'center', scrollbarWidth: 'none', msOverflowStyle: 'none' }}
>
- {(pdfDocument) => {
- return (
- <PdfHighlighter
- pdfDocument={pdfDocument}
- enableAreaSelection={event => event.altKey}
- scrollRef={noop}
- onScrollChange={noop}
- onSelectionFinished={() => null}
- highlightTransform={() => { return <div /> }}
- highlights={[]}
- />
- )
- }}
- </PdfLoader>
- </div>
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-24 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={zoomOut}
- >
- <RiZoomOutLine className="h-4 w-4 text-gray-500" />
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.zoomOut', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-16 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={zoomIn}
- >
- <RiZoomInLine className="h-4 w-4 text-gray-500" />
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.zoomIn', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/8 backdrop-blur-[2px]"
- onClick={onCancel}
- >
- <RiCloseLine className="h-4 w-4 text-gray-500" />
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.cancel', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- </div>,
- document.body,
+ <PdfLoader
+ workerSrc="/pdf.worker.min.mjs"
+ url={url}
+ beforeLoad={<div className="flex h-64 items-center justify-center"><Loading type="app" /></div>}
+ >
+ {(pdfDocument) => {
+ return (
+ <PdfHighlighter
+ pdfDocument={pdfDocument}
+ enableAreaSelection={event => event.altKey}
+ scrollRef={noop}
+ onScrollChange={noop}
+ onSelectionFinished={() => null}
+ highlightTransform={() => { return <div /> }}
+ highlights={[]}
+ />
+ )
+ }}
+ </PdfLoader>
+ </div>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={zoomOutLabel}
+ className="absolute top-6 right-24 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={zoomOut}
+ >
+ <RiZoomOutLine className="h-4 w-4 text-gray-500" />
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {zoomOutLabel}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={zoomInLabel}
+ className="absolute top-6 right-16 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={zoomIn}
+ >
+ <RiZoomInLine className="h-4 w-4 text-gray-500" />
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {zoomInLabel}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={cancelLabel}
+ className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/8 backdrop-blur-[2px]"
+ onClick={onCancel}
+ >
+ <RiCloseLine className="h-4 w-4 text-gray-500" />
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {cancelLabel}
+ </TooltipContent>
+ </Tooltip>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/base/file-uploader/video-preview.tsx b/web/app/components/base/file-uploader/video-preview.tsx
index ec1644400f3..986bf61dce4 100644
--- a/web/app/components/base/file-uploader/video-preview.tsx
+++ b/web/app/components/base/file-uploader/video-preview.tsx
@@ -1,7 +1,5 @@
import type { FC } from 'react'
-import * as React from 'react'
-import { createPortal } from 'react-dom'
-import { useHotkeys } from 'react-hotkeys-hook'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
type VideoPreviewProps = {
url: string
@@ -13,31 +11,40 @@ const VideoPreview: FC<VideoPreviewProps> = ({
title,
onCancel,
}) => {
- useHotkeys('esc', onCancel)
-
- return createPortal(
- <div
- className="fixed inset-0 z-1000 flex items-center justify-center bg-black/80 p-8"
- onClick={e => e.stopPropagation()}
- tabIndex={-1}
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
+ disablePointerDismissal
>
- <div>
- <video controls title={title} autoPlay={false} preload="metadata">
- <source
- type="video/mp4"
- src={url}
- className="max-h-full max-w-full"
- />
- </video>
- </div>
- <div
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/[0.08] backdrop-blur-[2px]"
- onClick={onCancel}
+ <DialogContent
+ className="inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-x-0! translate-y-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
+ backdropClassName="bg-transparent!"
>
- <span className="i-ri-close-line h-4 w-4 text-gray-500" data-testid="video-preview-close-btn" />
- </div>
- </div>,
- document.body,
+ <div
+ aria-label={title}
+ tabIndex={-1}
+ onClick={e => e.stopPropagation()}
+ >
+ <video controls title={title} autoPlay={false} preload="metadata">
+ <source
+ type="video/mp4"
+ src={url}
+ className="max-h-full max-w-full"
+ />
+ </video>
+ </div>
+ <div
+ className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/[0.08] backdrop-blur-[2px]"
+ onClick={onCancel}
+ >
+ <span className="i-ri-close-line h-4 w-4 text-gray-500" data-testid="video-preview-close-btn" />
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/base/float-right-container/__tests__/index.spec.tsx b/web/app/components/base/float-right-container/__tests__/index.spec.tsx
index ee820230d80..236a30dd206 100644
--- a/web/app/components/base/float-right-container/__tests__/index.spec.tsx
+++ b/web/app/components/base/float-right-container/__tests__/index.spec.tsx
@@ -153,10 +153,11 @@ describe('FloatRightContainer', () => {
)
const dialog = await screen.findByRole('dialog')
- expect(dialog).toHaveClass('custom-dialog-class')
+ expect(document.querySelector('.custom-dialog-class')).toBeInTheDocument()
const panel = document.querySelector('.custom-panel-class')
expect(panel).toBeInTheDocument()
+ expect(dialog).toHaveClass('custom-panel-class')
})
})
diff --git a/web/app/components/base/fullscreen-modal/__tests__/index.spec.tsx b/web/app/components/base/fullscreen-modal/__tests__/index.spec.tsx
deleted file mode 100644
index f238ea79f73..00000000000
--- a/web/app/components/base/fullscreen-modal/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,214 +0,0 @@
-import { act, fireEvent, render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { describe, expect, it, vi } from 'vitest'
-import FullScreenModal from '../index'
-
-describe('FullScreenModal Component', () => {
- it('should not render anything when open is false', () => {
- render(
- <FullScreenModal open={false}>
- <div data-testid="modal-content">Content</div>
- </FullScreenModal>,
- )
- expect(screen.queryByTestId('modal-content')).not.toBeInTheDocument()
- })
-
- it('should render content when open is true', async () => {
- render(
- <FullScreenModal open={true}>
- <div data-testid="modal-content">Content</div>
- </FullScreenModal>,
- )
- expect(await screen.findByTestId('modal-content')).toBeInTheDocument()
- })
-
- it('should not crash when provided with title and description props', async () => {
- await act(async () => {
- render(
- <FullScreenModal
- open={true}
- title="My Title"
- description="My Description"
- >
- Content
- </FullScreenModal>,
- )
- })
- })
-
- describe('Props Handling', () => {
- it('should apply wrapperClassName to the dialog root', async () => {
- render(
- <FullScreenModal
- open={true}
- wrapperClassName="custom-wrapper-class"
- >
- Content
- </FullScreenModal>,
- )
-
- await screen.findByRole('dialog')
- const element = document.querySelector('.custom-wrapper-class')
- expect(element).toBeInTheDocument()
- expect(element).toHaveClass('relative', 'z-50')
- })
-
- it('should apply className to the inner panel', async () => {
- await act(async () => {
- render(
- <FullScreenModal
- open={true}
- className="custom-panel-class"
- >
- Content
- </FullScreenModal>,
- )
- })
- const panel = document.querySelector('.custom-panel-class')
- expect(panel).toBeInTheDocument()
- expect(panel).toHaveClass('h-full')
- })
-
- it('should handle overflowVisible prop', async () => {
- const { rerender } = await act(async () => {
- return render(
- <FullScreenModal
- open={true}
- overflowVisible={true}
- className="target-panel"
- >
- Content
- </FullScreenModal>,
- )
- })
- let panel = document.querySelector('.target-panel')
- expect(panel).toHaveClass('overflow-visible')
- expect(panel).not.toHaveClass('overflow-hidden')
-
- await act(async () => {
- rerender(
- <FullScreenModal
- open={true}
- overflowVisible={false}
- className="target-panel"
- >
- Content
- </FullScreenModal>,
- )
- })
- panel = document.querySelector('.target-panel')
- expect(panel).toHaveClass('overflow-hidden')
- expect(panel).not.toHaveClass('overflow-visible')
- })
-
- it('should render close button when closable is true', async () => {
- await act(async () => {
- render(
- <FullScreenModal open={true} closable={true}>
- Content
- </FullScreenModal>,
- )
- })
- const closeButton = document.querySelector('.bg-components-button-tertiary-bg')
- expect(closeButton).toBeInTheDocument()
- })
-
- it('should not render close button when closable is false', async () => {
- await act(async () => {
- render(
- <FullScreenModal open={true} closable={false}>
- Content
- </FullScreenModal>,
- )
- })
- const closeButton = document.querySelector('.bg-components-button-tertiary-bg')
- expect(closeButton).not.toBeInTheDocument()
- })
- })
-
- describe('Interactions', () => {
- it('should call onClose when close button is clicked', async () => {
- const user = userEvent.setup()
- const onClose = vi.fn()
-
- render(
- <FullScreenModal open={true} closable={true} onClose={onClose}>
- Content
- </FullScreenModal>,
- )
-
- const closeBtn = document.querySelector('.bg-components-button-tertiary-bg')
- expect(closeBtn).toBeInTheDocument()
-
- await user.click(closeBtn!)
- expect(onClose).toHaveBeenCalledTimes(1)
- })
-
- it('should call onClose when clicking the backdrop', async () => {
- const user = userEvent.setup()
- const onClose = vi.fn()
-
- render(
- <FullScreenModal open={true} onClose={onClose}>
- <div data-testid="inner">Content</div>
- </FullScreenModal>,
- )
-
- const dialog = document.querySelector('.relative.z-50')
- if (dialog) {
- await user.click(dialog)
- expect(onClose).toHaveBeenCalled()
- }
- else {
- throw new Error('Dialog root not found')
- }
- })
-
- it('should call onClose when Escape key is pressed', async () => {
- const user = userEvent.setup()
- const onClose = vi.fn()
-
- render(
- <FullScreenModal open={true} onClose={onClose}>
- Content
- </FullScreenModal>,
- )
-
- await user.keyboard('{Escape}')
- expect(onClose).toHaveBeenCalled()
- })
-
- it('should not call onClose when clicking inside the content', async () => {
- const user = userEvent.setup()
- const onClose = vi.fn()
-
- render(
- <FullScreenModal open={true} onClose={onClose}>
- <div className="bg-background-default-subtle">
- <button>Action</button>
- </div>
- </FullScreenModal>,
- )
-
- const innerButton = screen.getByRole('button', { name: 'Action' })
- await user.click(innerButton)
- expect(onClose).not.toHaveBeenCalled()
-
- const contentPanel = document.querySelector('.bg-background-default-subtle')
- await act(async () => {
- fireEvent.click(contentPanel!)
- })
- expect(onClose).not.toHaveBeenCalled()
- })
- })
-
- describe('Default Props', () => {
- it('should not throw if onClose is not provided', async () => {
- const user = userEvent.setup()
- render(<FullScreenModal open={true} closable={true}>Content</FullScreenModal>)
-
- const closeButton = document.querySelector('.bg-components-button-tertiary-bg')
- await user.click(closeButton!)
- })
- })
-})
diff --git a/web/app/components/base/fullscreen-modal/index.stories.tsx b/web/app/components/base/fullscreen-modal/index.stories.tsx
deleted file mode 100644
index 3285b1c4ea0..00000000000
--- a/web/app/components/base/fullscreen-modal/index.stories.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import { useState } from 'react'
-import FullScreenModal from '.'
-
-const meta = {
- title: 'Base/Feedback/FullScreenModal',
- component: FullScreenModal,
- parameters: {
- layout: 'fullscreen',
- docs: {
- description: {
- component: 'Backdrop-blurred fullscreen modal. Supports close button, custom content, and optional overflow visibility.',
- },
- },
- },
- tags: ['autodocs'],
-} satisfies Meta<typeof FullScreenModal>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-const ModalDemo = (props: React.ComponentProps<typeof FullScreenModal>) => {
- const [open, setOpen] = useState(false)
-
- return (
- <div className="flex h-[360px] items-center justify-center bg-background-default-subtle">
- <button
- type="button"
- className="rounded-md bg-primary-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-primary-700"
- onClick={() => setOpen(true)}
- >
- Launch full-screen modal
- </button>
-
- <FullScreenModal
- {...props}
- open={open}
- onClose={() => setOpen(false)}
- closable
- >
- <div className="flex h-full flex-col bg-background-default-subtle">
- <div className="flex h-16 items-center justify-center border-b border-divider-subtle text-lg font-semibold text-text-primary">
- Full-screen experience
- </div>
- <div className="flex flex-1 items-center justify-center text-sm text-text-secondary">
- Place dashboards, flow builders, or immersive previews here.
- </div>
- </div>
- </FullScreenModal>
- </div>
- )
-}
-
-export const Playground: Story = {
- render: args => <ModalDemo {...args} />,
- args: {
- open: false,
- },
-}
diff --git a/web/app/components/base/fullscreen-modal/index.tsx b/web/app/components/base/fullscreen-modal/index.tsx
deleted file mode 100644
index 95f593ec3d9..00000000000
--- a/web/app/components/base/fullscreen-modal/index.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { Dialog, DialogPanel, Transition, TransitionChild } from '@headlessui/react'
-import { cn } from '@langgenius/dify-ui/cn'
-import { RiCloseLargeLine } from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
-
-type IModal = {
- className?: string
- wrapperClassName?: string
- open: boolean
- onClose?: () => void
- title?: React.ReactNode
- description?: React.ReactNode
- children?: React.ReactNode
- closable?: boolean
- overflowVisible?: boolean
-}
-
-export default function FullScreenModal({
- className,
- wrapperClassName,
- open,
- onClose = noop,
- children,
- closable = false,
- overflowVisible = false,
-}: IModal) {
- return (
- <Transition show={open} appear>
- <Dialog as="div" className={cn('relative z-50', wrapperClassName)} onClose={onClose}>
- <TransitionChild>
- <div className={cn('fixed inset-0 bg-background-overlay-backdrop backdrop-blur-[6px]', 'duration-300 ease-in data-closed:opacity-0', 'data-enter:opacity-100', 'data-leave:opacity-0')} />
- </TransitionChild>
-
- <div
- className="fixed inset-0 h-screen w-screen p-4"
- onClick={(e) => {
- e.preventDefault()
- e.stopPropagation()
- }}
- >
- <div className="relative h-full w-full rounded-2xl border border-effects-highlight bg-background-default-subtle">
- <TransitionChild>
- <DialogPanel className={cn('h-full', overflowVisible ? 'overflow-visible' : 'overflow-hidden', 'duration-100 ease-in data-closed:scale-95 data-closed:opacity-0', 'data-enter:scale-100 data-enter:opacity-100', 'data-enter:scale-95 data-leave:opacity-0', className)}>
- {closable
- && (
- <div
- className="absolute top-3 right-3 z-50 flex h-9 w-9 cursor-pointer items-center justify-center
- rounded-[10px] bg-components-button-tertiary-bg hover:bg-components-button-tertiary-bg-hover"
- onClick={(e) => {
- e.stopPropagation()
- onClose()
- }}
- >
- <RiCloseLargeLine className="h-3.5 w-3.5 text-components-button-tertiary-text" />
- </div>
- )}
- {children}
- </DialogPanel>
- </TransitionChild>
- </div>
- </div>
- </Dialog>
- </Transition>
- )
-}
diff --git a/web/app/components/base/image-gallery/__tests__/index.spec.tsx b/web/app/components/base/image-gallery/__tests__/index.spec.tsx
index 4975ac8f1cf..92ff807d75b 100644
--- a/web/app/components/base/image-gallery/__tests__/index.spec.tsx
+++ b/web/app/components/base/image-gallery/__tests__/index.spec.tsx
@@ -113,7 +113,7 @@ describe('ImageGallery', () => {
await user.click(getImages(container)[0]!)
expect(screen.queryByTestId('image-preview-container'))!.toBeInTheDocument()
- await user.keyboard('{Escape}')
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
await waitFor(() => {
expect(screen.queryByTestId('image-preview-container')).not.toBeInTheDocument()
diff --git a/web/app/components/base/image-uploader/__tests__/audio-preview.spec.tsx b/web/app/components/base/image-uploader/__tests__/audio-preview.spec.tsx
index 0c92afba0a5..da15c1c339b 100644
--- a/web/app/components/base/image-uploader/__tests__/audio-preview.spec.tsx
+++ b/web/app/components/base/image-uploader/__tests__/audio-preview.spec.tsx
@@ -43,7 +43,7 @@ describe('AudioPreview', () => {
render(<AudioPreview {...defaultProps} />)
const overlay = screen.getByTestId('audio-preview-overlay')
expect(overlay).toBeInTheDocument()
- expect(overlay.parentElement).toBe(document.body)
+ expect(overlay.closest('[data-base-ui-portal]')?.parentElement).toBe(document.body)
})
})
diff --git a/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx b/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx
index b2a2952bf83..48db2df3d2a 100644
--- a/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx
+++ b/web/app/components/base/image-uploader/__tests__/image-preview.spec.tsx
@@ -1,4 +1,4 @@
-import { act, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import ImagePreview from '../image-preview'
@@ -89,7 +89,7 @@ describe('ImagePreview', () => {
const overlay = getOverlay()
expect(overlay).toBeInTheDocument()
- expect(overlay?.parentElement).toBe(document.body)
+ expect(overlay.closest('[data-base-ui-portal]')?.parentElement).toBe(document.body)
expect(screen.getByRole('img', { name: 'Preview Image' })).toHaveAttribute('src', 'https://example.com/image.png')
})
@@ -108,7 +108,6 @@ describe('ImagePreview', () => {
describe('Hotkeys', () => {
it('should trigger esc/left/right handlers from keyboard', async () => {
- const user = userEvent.setup()
const onCancel = vi.fn()
const onPrev = vi.fn()
const onNext = vi.fn()
@@ -122,7 +121,9 @@ describe('ImagePreview', () => {
/>,
)
- await user.keyboard('{Escape}{ArrowLeft}{ArrowRight}')
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+ fireEvent.keyDown(document, { key: 'ArrowLeft', code: 'ArrowLeft' })
+ fireEvent.keyDown(document, { key: 'ArrowRight', code: 'ArrowRight' })
expect(onCancel).toHaveBeenCalledTimes(1)
expect(onPrev).toHaveBeenCalledTimes(1)
@@ -130,7 +131,6 @@ describe('ImagePreview', () => {
})
it('should zoom in and out from keyboard up/down hotkeys', async () => {
- const user = userEvent.setup()
render(
<ImagePreview
url="https://example.com/image.png"
@@ -140,12 +140,12 @@ describe('ImagePreview', () => {
)
const image = screen.getByRole('img', { name: 'Preview Image' })
- await user.keyboard('{ArrowUp}')
+ fireEvent.keyDown(document, { key: 'ArrowUp', code: 'ArrowUp' })
await waitFor(() => {
expect(image).toHaveStyle({ transform: 'scale(1.2) translate(0px, 0px)' })
})
- await user.keyboard('{ArrowDown}')
+ fireEvent.keyDown(document, { key: 'ArrowDown', code: 'ArrowDown' })
await waitFor(() => {
expect(image).toHaveStyle({ transform: 'scale(1) translate(0px, 0px)' })
})
diff --git a/web/app/components/base/image-uploader/__tests__/video-preview.spec.tsx b/web/app/components/base/image-uploader/__tests__/video-preview.spec.tsx
index f56a4b82e47..90d7e1ea8f9 100644
--- a/web/app/components/base/image-uploader/__tests__/video-preview.spec.tsx
+++ b/web/app/components/base/image-uploader/__tests__/video-preview.spec.tsx
@@ -51,7 +51,7 @@ describe('VideoPreview', () => {
const overlay = getOverlay()
expect(overlay).toBeInTheDocument()
- expect(overlay.parentElement).toBe(document.body)
+ expect(overlay.closest('[data-base-ui-portal]')?.parentElement).toBe(document.body)
})
})
diff --git a/web/app/components/base/image-uploader/audio-preview.tsx b/web/app/components/base/image-uploader/audio-preview.tsx
index aa87d9d04e7..4f7dd83400d 100644
--- a/web/app/components/base/image-uploader/audio-preview.tsx
+++ b/web/app/components/base/image-uploader/audio-preview.tsx
@@ -1,5 +1,5 @@
import type { FC } from 'react'
-import { createPortal } from 'react-dom'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
type AudioPreviewProps = {
url: string
@@ -11,26 +11,42 @@ const AudioPreview: FC<AudioPreviewProps> = ({
title,
onCancel,
}) => {
- return createPortal(
- <div className="fixed inset-0 z-1000 flex items-center justify-center bg-black/80 p-8" onClick={e => e.stopPropagation()} data-testid="audio-preview-overlay">
- <div>
- <audio controls title={title} autoPlay={false} preload="metadata" data-testid="audio-element">
- <source
- type="audio/mpeg"
- src={url}
- className="max-h-full max-w-full"
- />
- </audio>
- </div>
- <div
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/[0.08] backdrop-blur-[2px]"
- onClick={onCancel}
- data-testid="close-preview"
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
+ disablePointerDismissal
+ >
+ <DialogContent
+ className="inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-x-0! translate-y-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
+ backdropClassName="bg-transparent!"
>
- <span className="i-ri-close-line h-4 w-4 text-gray-500" />
- </div>
- </div>,
- document.body,
+ <div
+ aria-label={title}
+ data-testid="audio-preview-overlay"
+ tabIndex={-1}
+ onClick={e => e.stopPropagation()}
+ >
+ <audio controls title={title} autoPlay={false} preload="metadata" data-testid="audio-element">
+ <source
+ type="audio/mpeg"
+ src={url}
+ className="max-h-full max-w-full"
+ />
+ </audio>
+ </div>
+ <div
+ className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/[0.08] backdrop-blur-[2px]"
+ onClick={onCancel}
+ data-testid="close-preview"
+ >
+ <span className="i-ri-close-line h-4 w-4 text-gray-500" />
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/base/image-uploader/image-preview.tsx b/web/app/components/base/image-uploader/image-preview.tsx
index 354fb5ff2ad..071188bf12f 100644
--- a/web/app/components/base/image-uploader/image-preview.tsx
+++ b/web/app/components/base/image-uploader/image-preview.tsx
@@ -1,12 +1,12 @@
import type { FC } from 'react'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { noop } from 'es-toolkit/function'
-import { t } from 'i18next'
import * as React from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
-import { createPortal } from 'react-dom'
import { useHotkeys } from 'react-hotkeys-hook'
+import { useTranslation } from 'react-i18next'
import { downloadUrl } from '@/utils/download'
type ImagePreviewProps = {
@@ -33,6 +33,7 @@ const ImagePreview: FC<ImagePreviewProps> = ({
onPrev,
onNext,
}) => {
+ const { t } = useTranslation()
const [scale, setScale] = useState(1)
const [position, setPosition] = useState({ x: 0, y: 0 })
const [isDragging, setIsDragging] = useState(false)
@@ -119,7 +120,7 @@ const ImagePreview: FC<ImagePreviewProps> = ({
}
}
shareImage()
- }, [title, url])
+ }, [t, title, url])
const handleWheel = useCallback((e: React.WheelEvent<HTMLDivElement>) => {
if (e.deltaY < 0)
@@ -167,131 +168,161 @@ const ImagePreview: FC<ImagePreviewProps> = ({
}
}, [handleMouseUp])
- useHotkeys('esc', onCancel)
useHotkeys('up', zoomIn)
useHotkeys('down', zoomOut)
useHotkeys('left', onPrev || noop)
useHotkeys('right', onNext || noop)
- return createPortal(
- <div
- className="image-preview-container fixed inset-0 z-1000 flex items-center justify-center bg-black/80 p-8"
- onClick={e => e.stopPropagation()}
- onWheel={handleWheel}
- onMouseDown={handleMouseDown}
- onMouseMove={handleMouseMove}
- onMouseUp={handleMouseUp}
- style={{ cursor: scale > 1 ? 'move' : 'default' }}
- tabIndex={-1}
- data-testid="image-preview-container"
+ const copyImageLabel = t('operation.copyImage', { ns: 'common' })
+ const zoomOutLabel = t('operation.zoomOut', { ns: 'common' })
+ const zoomInLabel = t('operation.zoomIn', { ns: 'common' })
+ const downloadLabel = t('operation.download', { ns: 'common' })
+ const openInNewTabLabel = t('operation.openInNewTab', { ns: 'common' })
+ const cancelLabel = t('operation.cancel', { ns: 'common' })
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
+ disablePointerDismissal
>
- { }
- { }
- <img
- ref={imgRef}
- alt={title}
- src={isBase64(url) ? `data:image/png;base64,${url}` : url}
- className="max-h-full max-w-full"
- style={{
- transform: `scale(${scale}) translate(${position.x}px, ${position.y}px)`,
- transition: isDragging ? 'none' : 'transform 0.2s ease-in-out',
- }}
- data-testid="image-preview-image"
- />
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-48 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={imageCopy}
- >
- {isCopied
- ? <span className="i-ri-file-copy-line h-4 w-4 text-green-500" data-testid="image-preview-copied-icon" />
- : <span className="i-ri-file-copy-line h-4 w-4 text-gray-500" data-testid="image-preview-copy-button" />}
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.copyImage', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-40 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={zoomOut}
- >
- <span className="i-ri-zoom-out-line h-4 w-4 text-gray-500" data-testid="image-preview-zoom-out-button" />
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.zoomOut', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-32 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={zoomIn}
- >
- <span className="i-ri-zoom-in-line h-4 w-4 text-gray-500" data-testid="image-preview-zoom-in-button" />
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.zoomIn', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-24 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={downloadImage}
- >
- <span className="i-ri-download-cloud-2-line h-4 w-4 text-gray-500" data-testid="image-preview-download-button" />
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.download', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-16 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={openInNewTab}
- >
- <span className="i-ri-add-box-line h-4 w-4 text-gray-500" data-testid="image-preview-open-in-tab-button" />
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.openInNewTab', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={(
- <div
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/8 backdrop-blur-[2px]"
- onClick={onCancel}
- >
- <span className="i-ri-close-line h-4 w-4 text-gray-500" data-testid="image-preview-close-button" />
- </div>
- )}
- />
- <TooltipContent>
- {t('operation.cancel', { ns: 'common' })}
- </TooltipContent>
- </Tooltip>
- </div>,
- document.body,
+ <DialogContent
+ className="image-preview-container inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-x-0! translate-y-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
+ backdropClassName="bg-transparent!"
+ >
+ <div
+ aria-label={title}
+ data-testid="image-preview-container"
+ tabIndex={-1}
+ className="flex h-full w-full items-center justify-center"
+ onClick={e => e.stopPropagation()}
+ onWheel={handleWheel}
+ onMouseDown={handleMouseDown}
+ onMouseMove={handleMouseMove}
+ onMouseUp={handleMouseUp}
+ style={{ cursor: scale > 1 ? 'move' : 'default' }}
+ >
+ <img
+ ref={imgRef}
+ alt={title}
+ src={isBase64(url) ? `data:image/png;base64,${url}` : url}
+ className="max-h-full max-w-full"
+ style={{
+ transform: `scale(${scale}) translate(${position.x}px, ${position.y}px)`,
+ transition: isDragging ? 'none' : 'transform 0.2s ease-in-out',
+ }}
+ data-testid="image-preview-image"
+ />
+ </div>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={copyImageLabel}
+ className="absolute top-6 right-48 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={imageCopy}
+ >
+ {isCopied
+ ? <span className="i-ri-file-copy-line h-4 w-4 text-green-500" data-testid="image-preview-copied-icon" />
+ : <span className="i-ri-file-copy-line h-4 w-4 text-gray-500" data-testid="image-preview-copy-button" />}
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {copyImageLabel}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={zoomOutLabel}
+ className="absolute top-6 right-40 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={zoomOut}
+ >
+ <span className="i-ri-zoom-out-line h-4 w-4 text-gray-500" data-testid="image-preview-zoom-out-button" />
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {zoomOutLabel}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={zoomInLabel}
+ className="absolute top-6 right-32 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={zoomIn}
+ >
+ <span className="i-ri-zoom-in-line h-4 w-4 text-gray-500" data-testid="image-preview-zoom-in-button" />
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {zoomInLabel}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={downloadLabel}
+ className="absolute top-6 right-24 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={downloadImage}
+ >
+ <span className="i-ri-download-cloud-2-line h-4 w-4 text-gray-500" data-testid="image-preview-download-button" />
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {downloadLabel}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={openInNewTabLabel}
+ className="absolute top-6 right-16 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={openInNewTab}
+ >
+ <span className="i-ri-add-box-line h-4 w-4 text-gray-500" data-testid="image-preview-open-in-tab-button" />
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {openInNewTabLabel}
+ </TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <button
+ type="button"
+ aria-label={cancelLabel}
+ className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/8 backdrop-blur-[2px]"
+ onClick={onCancel}
+ >
+ <span className="i-ri-close-line h-4 w-4 text-gray-500" data-testid="image-preview-close-button" />
+ </button>
+ )}
+ />
+ <TooltipContent>
+ {cancelLabel}
+ </TooltipContent>
+ </Tooltip>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/base/image-uploader/video-preview.tsx b/web/app/components/base/image-uploader/video-preview.tsx
index d2a0179b575..8d5cb4dab3a 100644
--- a/web/app/components/base/image-uploader/video-preview.tsx
+++ b/web/app/components/base/image-uploader/video-preview.tsx
@@ -1,5 +1,5 @@
import type { FC } from 'react'
-import { createPortal } from 'react-dom'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
type VideoPreviewProps = {
url: string
@@ -11,25 +11,41 @@ const VideoPreview: FC<VideoPreviewProps> = ({
title,
onCancel,
}) => {
- return createPortal(
- <div className="fixed inset-0 z-1000 flex items-center justify-center bg-black/80 p-8" onClick={e => e.stopPropagation()} data-testid="video-preview">
- <div>
- <video controls title={title} autoPlay={false} preload="metadata" data-testid="video-element">
- <source
- type="video/mp4"
- src={url}
- className="max-h-full max-w-full"
- />
- </video>
- </div>
- <div
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/[0.08] backdrop-blur-[2px]"
- onClick={onCancel}
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
+ disablePointerDismissal
+ >
+ <DialogContent
+ className="inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-x-0! translate-y-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
+ backdropClassName="bg-transparent!"
>
- <span className="i-ri-close-line h-4 w-4 text-gray-500" data-testid="close-button" />
- </div>
- </div>,
- document.body,
+ <div
+ aria-label={title}
+ data-testid="video-preview"
+ tabIndex={-1}
+ onClick={e => e.stopPropagation()}
+ >
+ <video controls title={title} autoPlay={false} preload="metadata" data-testid="video-element">
+ <source
+ type="video/mp4"
+ src={url}
+ className="max-h-full max-w-full"
+ />
+ </video>
+ </div>
+ <div
+ className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/[0.08] backdrop-blur-[2px]"
+ onClick={onCancel}
+ >
+ <span className="i-ri-close-line h-4 w-4 text-gray-500" data-testid="close-button" />
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/base/modal-like-wrap/__tests__/index.spec.tsx b/web/app/components/base/modal-like-wrap/__tests__/index.spec.tsx
deleted file mode 100644
index dc7b0758faf..00000000000
--- a/web/app/components/base/modal-like-wrap/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { act, fireEvent, render, screen } from '@testing-library/react'
-import ModalLikeWrap from '..'
-
-describe('ModalLikeWrap', () => {
- const defaultProps = {
- title: 'Test Title',
- onClose: vi.fn(),
- onConfirm: vi.fn(),
- children: <div>Test Content</div>,
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- describe('Render', () => {
- it('renders title and content correctly', () => {
- render(<ModalLikeWrap {...defaultProps} />)
-
- expect(screen.getByText('Test Title')).toBeInTheDocument()
- expect(screen.getByText('Test Content')).toBeInTheDocument()
- })
-
- it('renders beforeHeader if provided', () => {
- const beforeHeader = <div data-testid="before-header">Before Header</div>
- render(<ModalLikeWrap {...defaultProps} beforeHeader={beforeHeader} />)
-
- expect(screen.getByTestId('before-header')).toBeInTheDocument()
- expect(screen.getByText('Before Header')).toBeInTheDocument()
- })
- })
-
- describe('Interactions', () => {
- it('calls onClose when close icon is clicked', async () => {
- render(<ModalLikeWrap {...defaultProps} />)
-
- const closeBtn = screen.getByTestId('modal-close-btn')
- expect(closeBtn).toBeInTheDocument()
-
- await act(async () => {
- fireEvent.click(closeBtn)
- })
-
- expect(defaultProps.onClose).toHaveBeenCalledTimes(1)
- })
-
- it('calls onClose when Cancel button is clicked', async () => {
- render(<ModalLikeWrap {...defaultProps} />)
-
- const cancelBtn = screen.getByText('common.operation.cancel')
- await act(async () => {
- fireEvent.click(cancelBtn)
- })
-
- expect(defaultProps.onClose).toHaveBeenCalled()
- })
-
- it('calls onConfirm when Save button is clicked', async () => {
- render(<ModalLikeWrap {...defaultProps} />)
-
- const saveBtn = screen.getByText('common.operation.save')
- await act(async () => {
- fireEvent.click(saveBtn)
- })
-
- expect(defaultProps.onConfirm).toHaveBeenCalled()
- })
- })
-
- describe('Props', () => {
- it('hides close icon when hideCloseBtn is true', () => {
- render(<ModalLikeWrap {...defaultProps} hideCloseBtn={true} />)
-
- const closeBtn = document.querySelector('.remixicon')
- expect(closeBtn).not.toBeInTheDocument()
- })
-
- it('applies custom className', () => {
- const { container } = render(<ModalLikeWrap {...defaultProps} className="custom-class" />)
-
- expect(container.firstChild).toHaveClass('custom-class')
- })
- })
-})
diff --git a/web/app/components/base/modal-like-wrap/index.stories.tsx b/web/app/components/base/modal-like-wrap/index.stories.tsx
deleted file mode 100644
index 38d969b2cec..00000000000
--- a/web/app/components/base/modal-like-wrap/index.stories.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import ModalLikeWrap from '.'
-
-const meta = {
- title: 'Base/Feedback/ModalLikeWrap',
- component: ModalLikeWrap,
- parameters: {
- layout: 'centered',
- docs: {
- description: {
- component: 'Compact “modal-like” card used in wizards. Provides header actions, optional back slot, and confirm/cancel buttons.',
- },
- },
- },
- tags: ['autodocs'],
- argTypes: {
- title: {
- control: 'text',
- description: 'Header title text.',
- },
- className: {
- control: 'text',
- description: 'Additional classes on the wrapper.',
- },
- beforeHeader: {
- control: false,
- description: 'Slot rendered before the header (commonly a back link).',
- },
- hideCloseBtn: {
- control: 'boolean',
- description: 'Hides the top-right close icon when true.',
- },
- children: {
- control: false,
- },
- onClose: {
- control: false,
- },
- onConfirm: {
- control: false,
- },
- },
- args: {
- title: 'Create dataset field',
- hideCloseBtn: false,
- onClose: () => console.log('close'),
- onConfirm: () => console.log('confirm'),
- children: null,
- },
-} satisfies Meta<typeof ModalLikeWrap>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-const BaseContent = () => (
- <div className="space-y-3 text-sm text-gray-600">
- <p>
- Describe the new field your dataset should collect. Provide a clear label and optional helper text.
- </p>
- <div className="rounded-lg border border-dashed border-gray-200 bg-gray-50 p-4 text-xs text-gray-500">
- Form inputs would be placed here in the real flow.
- </div>
- </div>
-)
-
-export const Default: Story = {
- render: args => (
- <ModalLikeWrap {...args}>
- <BaseContent />
- </ModalLikeWrap>
- ),
- args: {
- children: null,
- },
-}
-
-export const WithBackLink: Story = {
- render: args => (
- <ModalLikeWrap
- {...args}
- hideCloseBtn
- beforeHeader={(
- <button
- className="mb-1 flex items-center gap-1 text-xs font-medium text-text-accent uppercase"
- onClick={() => console.log('back')}
- >
- <span className="inline-block h-4 w-4 rounded-sm bg-text-accent/10 text-center text-[10px] leading-4 text-text-accent">{'<'}</span>
- Back
- </button>
- )}
- >
- <BaseContent />
- </ModalLikeWrap>
- ),
- args: {
- title: 'Select metadata type',
- children: null,
- },
- parameters: {
- docs: {
- description: {
- story: 'Demonstrates feeding content into `beforeHeader` while hiding the close button.',
- },
- },
- },
-}
-
-export const CustomWidth: Story = {
- render: args => (
- <ModalLikeWrap
- {...args}
- className="w-[420px]"
- >
- <BaseContent />
- <div className="mt-4 rounded-md bg-blue-50 p-3 text-xs text-blue-600">
- Tip: metadata keys may only include letters, numbers, and underscores.
- </div>
- </ModalLikeWrap>
- ),
- args: {
- title: 'Advanced configuration',
- children: null,
- },
- parameters: {
- docs: {
- description: {
- story: 'Applies extra width and helper messaging to emulate configuration panels.',
- },
- },
- },
-}
diff --git a/web/app/components/base/modal-like-wrap/index.tsx b/web/app/components/base/modal-like-wrap/index.tsx
deleted file mode 100644
index 1c049eb5f44..00000000000
--- a/web/app/components/base/modal-like-wrap/index.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-'use client'
-import type { FC } from 'react'
-import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
-import * as React from 'react'
-import { useTranslation } from 'react-i18next'
-
-type Props = {
- title: string
- className?: string
- beforeHeader?: React.ReactNode
- onClose: () => void
- hideCloseBtn?: boolean
- onConfirm: () => void
- children: React.ReactNode
-}
-
-const ModalLikeWrap: FC<Props> = ({
- title,
- className,
- beforeHeader,
- children,
- onClose,
- hideCloseBtn,
- onConfirm,
-}) => {
- const { t } = useTranslation()
-
- return (
- <div className={cn('w-[320px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg px-3 pt-3.5 pb-4 shadow-xl', className)}>
- {beforeHeader || null}
- <div className="mb-1 flex h-6 items-center justify-between">
- <div className="system-xl-semibold text-text-primary">{title}</div>
- {!hideCloseBtn && (
- <div
- className="cursor-pointer p-1.5 text-text-tertiary"
- onClick={onClose}
- >
- <span className="i-ri-close-line size-4" data-testid="modal-close-btn" />
- </div>
- )}
- </div>
- <div className="mt-2">{children}</div>
- <div className="mt-4 flex justify-end">
- <Button
- className="mr-2"
- onClick={onClose}
- >
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button
- onClick={onConfirm}
- variant="primary"
- >
- {t('operation.save', { ns: 'common' })}
- </Button>
- </div>
- </div>
- )
-}
-
-export default React.memo(ModalLikeWrap)
diff --git a/web/app/components/base/modal/__tests__/index.spec.tsx b/web/app/components/base/modal/__tests__/index.spec.tsx
deleted file mode 100644
index 4705d0defdd..00000000000
--- a/web/app/components/base/modal/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,172 +0,0 @@
-import { act, fireEvent, render, screen } from '@testing-library/react'
-import Modal from '..'
-
-describe('Modal', () => {
- describe('Render', () => {
- it('should not render content when isShow is false', () => {
- render(
- <Modal isShow={false} title="Test Modal">
- <div>Modal Content</div>
- </Modal>,
- )
-
- expect(screen.queryByText('Test Modal')).not.toBeInTheDocument()
- expect(screen.queryByText('Modal Content')).not.toBeInTheDocument()
- })
-
- it('should render content when isShow is true', async () => {
- await act(async () => {
- render(
- <Modal isShow={true} title="Test Modal">
- <div>Modal Content</div>
- </Modal>,
- )
- })
-
- expect(screen.getByText('Test Modal')).toBeInTheDocument()
- expect(screen.getByText('Modal Content')).toBeInTheDocument()
- })
-
- it('should render description when provided', async () => {
- await act(async () => {
- render(
- <Modal isShow={true} title="Test Modal" description="Test Description">
- <div>Content</div>
- </Modal>,
- )
- })
-
- expect(screen.getByText('Test Description')).toBeInTheDocument()
- })
- })
-
- describe('Interaction', () => {
- it('should call onClose when close button is clicked', async () => {
- const handleClose = vi.fn()
- await act(async () => {
- render(
- <Modal isShow={true} title="Test Modal" closable={true} onClose={handleClose}>
- <div>Content</div>
- </Modal>,
- )
- })
-
- const closeButton = screen.getByTestId('modal-close-button')
- expect(closeButton).toBeInTheDocument()
- await act(async () => {
- fireEvent.click(closeButton!)
- })
- expect(handleClose).toHaveBeenCalledTimes(1)
- })
-
- it('should prevent propagation when clicking the scrollable container', async () => {
- await act(async () => {
- render(
- <Modal isShow={true} title="Test Modal">
- <div>Content</div>
- </Modal>,
- )
- })
-
- const wrapper = document.querySelector('.overflow-y-auto')
- expect(wrapper).toBeInTheDocument()
-
- const event = new MouseEvent('click', { bubbles: true, cancelable: true })
- const stopPropagationSpy = vi.spyOn(event, 'stopPropagation')
- const preventDefaultSpy = vi.spyOn(event, 'preventDefault')
-
- await act(async () => {
- wrapper!.dispatchEvent(event)
- })
-
- expect(stopPropagationSpy).toHaveBeenCalled()
- expect(preventDefaultSpy).toHaveBeenCalled()
- })
-
- it('should handle clickOutsideNotClose prop', async () => {
- const handleClose = vi.fn()
- await act(async () => {
- render(
- <Modal isShow={true} title="Test Modal" clickOutsideNotClose={true} onClose={handleClose}>
- <div>Content</div>
- </Modal>,
- )
- })
-
- await act(async () => {
- fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape', code: 'Escape' })
- })
-
- expect(handleClose).not.toHaveBeenCalled()
- })
- })
-
- describe('Props', () => {
- it('should apply custom className to the panel', async () => {
- await act(async () => {
- render(
- <Modal isShow={true} title="Test Modal" className="custom-panel-class">
- <div>Content</div>
- </Modal>,
- )
- })
-
- const panel = screen.getByText('Test Modal').parentElement
- expect(panel).toHaveClass('custom-panel-class')
- })
-
- it('should apply wrapperClassName and containerClassName', async () => {
- await act(async () => {
- render(
- <Modal
- isShow={true}
- title="Test Modal"
- wrapperClassName="custom-wrapper"
- containerClassName="custom-container"
- >
- <div>Content</div>
- </Modal>,
- )
- })
-
- const dialog = document.querySelector('.custom-wrapper')
- expect(dialog).toBeInTheDocument()
- const container = document.querySelector('.custom-container')
- expect(container).toBeInTheDocument()
- })
-
- it('should apply overlayOpacity background when overlayOpacity is true', async () => {
- await act(async () => {
- render(
- <Modal isShow={true} title="Test Modal" overlayOpacity={true}>
- <div>Content</div>
- </Modal>,
- )
- })
-
- const overlay = document.querySelector('.bg-workflow-canvas-canvas-overlay')
- expect(overlay).toBeInTheDocument()
- })
-
- it('should toggle overflow-visible class based on overflowVisible prop', async () => {
- const { rerender } = render(
- <Modal isShow={true} title="Test Modal" overflowVisible={true}>
- <div>Content</div>
- </Modal>,
- )
-
- let panel = screen.getByText('Test Modal').parentElement
- expect(panel).toHaveClass('overflow-visible')
-
- await act(async () => {
- rerender(
- <Modal isShow={true} title="Test Modal" overflowVisible={false}>
- <div>Content</div>
- </Modal>,
- )
- })
- panel = screen.getByText('Test Modal').parentElement
- expect(panel).toHaveClass('overflow-hidden')
- })
- })
-})
diff --git a/web/app/components/base/modal/index.stories.tsx b/web/app/components/base/modal/index.stories.tsx
deleted file mode 100644
index 33d0366324d..00000000000
--- a/web/app/components/base/modal/index.stories.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import { useEffect, useState } from 'react'
-import Modal from '.'
-
-const meta = {
- title: 'Base/Feedback/Modal',
- component: Modal,
- parameters: {
- layout: 'fullscreen',
- docs: {
- description: {
- component: 'Lightweight modal wrapper with optional header/description and close icon.',
- },
- },
- },
- tags: ['autodocs'],
- argTypes: {
- className: {
- control: 'text',
- description: 'Extra classes applied to the modal panel.',
- },
- wrapperClassName: {
- control: 'text',
- description: 'Additional wrapper classes for the dialog.',
- },
- isShow: {
- control: 'boolean',
- description: 'Controls whether the modal is visible.',
- },
- title: {
- control: 'text',
- description: 'Heading displayed at the top of the modal.',
- },
- description: {
- control: 'text',
- description: 'Secondary text beneath the title.',
- },
- closable: {
- control: 'boolean',
- description: 'Whether the close icon should be shown.',
- },
- overflowVisible: {
- control: 'boolean',
- description: 'Allows content to overflow the modal panel.',
- },
- onClose: {
- control: false,
- description: 'Callback invoked when the modal requests to close.',
- },
- },
- args: {
- isShow: false,
- title: 'Create new API key',
- description: 'Generate a scoped key for this workspace. You can revoke it at any time.',
- closable: true,
- },
-} satisfies Meta<typeof Modal>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-const ModalDemo = (props: React.ComponentProps<typeof Modal>) => {
- const [open, setOpen] = useState(props.isShow)
-
- useEffect(() => {
- setOpen(props.isShow)
- }, [props.isShow])
-
- return (
- <div className="relative flex h-[480px] items-center justify-center bg-gray-100">
- <button
- className="rounded-md bg-primary-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-primary-700"
- onClick={() => setOpen(true)}
- >
- Show modal
- </button>
-
- <Modal
- {...props}
- isShow={open}
- onClose={() => {
- props.onClose?.()
- setOpen(false)
- }}
- >
- <div className="mt-6 space-y-4 text-sm text-gray-600">
- <p>
- Provide a descriptive name for this key so collaborators know its purpose. Restrict usage with scopes to limit access.
- </p>
- <div className="rounded-lg border border-dashed border-gray-200 bg-gray-50 p-4 text-xs text-gray-500">
- Form fields and validation messaging would appear here. This placeholder keeps the story lightweight.
- </div>
- </div>
- <div className="mt-8 flex justify-end gap-3">
- <button
- className="rounded-md border border-gray-300 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-50"
- onClick={() => setOpen(false)}
- >
- Cancel
- </button>
- <button className="rounded-md bg-primary-600 px-3 py-1.5 text-sm text-white hover:bg-primary-700">
- Create key
- </button>
- </div>
- </Modal>
- </div>
- )
-}
-
-export const Default: Story = {
- render: args => <ModalDemo {...args} />,
-}
-
-export const OverflowVisible: Story = {
- render: args => <ModalDemo {...args} />,
- args: {
- overflowVisible: true,
- description: 'Demonstrates the modal configured to let the body content overflow.',
- className: 'max-w-[540px]',
- },
- parameters: {
- docs: {
- description: {
- story: 'Shows the modal with `overflowVisible` enabled for content that needs to escape the panel bounds.',
- },
- },
- },
-}
diff --git a/web/app/components/base/modal/index.tsx b/web/app/components/base/modal/index.tsx
deleted file mode 100644
index 8b4b6174a36..00000000000
--- a/web/app/components/base/modal/index.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * @deprecated Use `@langgenius/dify-ui/dialog` instead.
- * This component will be removed after migration is complete.
- * See: https://github.com/langgenius/dify/issues/32767
- */
-import { Dialog, DialogPanel, DialogTitle, Transition, TransitionChild } from '@headlessui/react'
-import { cn } from '@langgenius/dify-ui/cn'
-import { noop } from 'es-toolkit/function'
-import { Fragment } from 'react'
-// https://headlessui.com/react/dialog
-
-type IModal = {
- className?: string
- wrapperClassName?: string
- containerClassName?: string
- isShow: boolean
- onClose?: () => void
- title?: React.ReactNode
- description?: React.ReactNode
- children?: React.ReactNode
- closable?: boolean
- overflowVisible?: boolean
- overlayOpacity?: boolean // For semi-transparent overlay instead of default
- clickOutsideNotClose?: boolean // Prevent closing when clicking outside modal
-}
-
-export default function Modal({
- className,
- wrapperClassName,
- containerClassName,
- isShow,
- onClose = noop,
- title,
- description,
- children,
- closable = false,
- overflowVisible = false,
- overlayOpacity = false,
- clickOutsideNotClose = false,
-}: IModal) {
- return (
- <Transition appear show={isShow} as={Fragment}>
- <Dialog as="div" className={cn('relative z-60', wrapperClassName)} onClose={clickOutsideNotClose ? noop : onClose}>
- <TransitionChild>
- <div className={cn('fixed inset-0', overlayOpacity ? 'bg-workflow-canvas-canvas-overlay' : 'bg-background-overlay', 'duration-300 ease-in data-closed:opacity-0', 'data-enter:opacity-100', 'data-leave:opacity-0')} />
- </TransitionChild>
- <div
- className="fixed inset-0 overflow-y-auto"
- onClick={(e) => {
- e.preventDefault()
- e.stopPropagation()
- }}
- >
- <div className={cn('flex min-h-full items-center justify-center p-4 text-center', containerClassName)}>
- <TransitionChild>
- <DialogPanel className={cn('relative w-full max-w-[480px] rounded-2xl bg-components-panel-bg p-6 text-left align-middle shadow-xl transition-all', overflowVisible ? 'overflow-visible' : 'overflow-hidden', 'duration-100 ease-in data-closed:scale-95 data-closed:opacity-0', 'data-enter:scale-100 data-enter:opacity-100', 'data-enter:scale-95 data-leave:opacity-0', className)}>
- {!!title && (
- <DialogTitle
- as="h3"
- className="title-2xl-semi-bold text-text-primary"
- >
- {title}
- </DialogTitle>
- )}
- {!!description && (
- <div className="mt-2 body-md-regular text-text-secondary">
- {description}
- </div>
- )}
- {closable
- && (
- <div className="absolute top-6 right-6 z-10 flex h-5 w-5 items-center justify-center rounded-2xl hover:cursor-pointer hover:bg-state-base-hover">
- <span
- className="i-ri-close-line h-4 w-4 text-text-tertiary"
- onClick={
- (e) => {
- e.stopPropagation()
- onClose()
- }
- }
- data-testid="modal-close-button"
- />
- </div>
- )}
- {children}
- </DialogPanel>
- </TransitionChild>
- </div>
- </div>
- </Dialog>
- </Transition>
- )
-}
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx
index 9a752062ea7..f3fc1a605c9 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/component-ui.tsx
@@ -4,6 +4,7 @@ import type { WorkflowNodesMap } from '../workflow-variable-block/node'
import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
import type { Type } from '@/app/components/workflow/nodes/llm/types'
import type { ValueSelector, Var } from '@/app/components/workflow/types'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { useBoolean } from 'ahooks'
import * as React from 'react'
import { useCallback, useEffect, useMemo, useRef } from 'react'
@@ -11,7 +12,6 @@ import { useTranslation } from 'react-i18next'
import { InputVarType } from '@/app/components/workflow/types'
import ActionButton from '../../../action-button'
import { VariableX } from '../../../icons/src/vender/workflow'
-import Modal from '../../../modal'
import InputField from './input-field'
import VariableBlock from './variable-block'
@@ -157,20 +157,24 @@ const HITLInputComponentUI: FC<HITLInputComponentUIProps> = ({
</div>
{isShowEditModal && (
- <Modal
- isShow
- onClose={hideEditModal}
- wrapperClassName="z-999"
- className="max-w-[372px] p-0!"
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ hideEditModal()
+ }}
>
- <InputField
- nodeId={nodeId}
- isEdit
- payload={formInput}
- onChange={handleChange}
- onCancel={hideEditModal}
- />
- </Modal>
+ <DialogContent className="w-full max-w-[372px] overflow-hidden! border-none p-0! text-left align-middle">
+
+ <InputField
+ nodeId={nodeId}
+ isEdit
+ payload={formInput}
+ onChange={handleChange}
+ onCancel={hideEditModal}
+ />
+ </DialogContent>
+ </Dialog>
)}
</div>
)
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
index 7511406718e..e0fcd3bdba9 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/input-field.tsx
@@ -82,7 +82,9 @@ const InputField: React.FC<InputFieldProps> = ({
}, [handleSave])
return (
- <div className="w-[372px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-3 shadow-lg backdrop-blur-[5px]">
+ <div className="w-[372px]
+ rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-3 shadow-lg backdrop-blur-[5px]"
+ >
<div className="system-md-semibold text-text-primary">{t(`${i18nPrefix}.title`, { ns: 'workflow' })}</div>
<div className="mt-3">
<div className="system-xs-medium text-text-secondary">
diff --git a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/__tests__/index.spec.tsx b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/__tests__/index.spec.tsx
index e3fba27cf2d..114d1d78026 100644
--- a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/__tests__/index.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/__tests__/index.spec.tsx
@@ -1,4 +1,4 @@
-import type { LexicalCommand } from 'lexical'
+import type { ShortcutPopupInsertHandler } from '../index'
import { LexicalComposer } from '@lexical/react/LexicalComposer'
import { ContentEditable } from '@lexical/react/LexicalContentEditable'
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'
@@ -50,7 +50,7 @@ const CONTENT_EDITABLE_ID = 'ce'
type MinimalEditorProps = {
withContainer?: boolean
hotkey?: string | string[] | string[][] | ((e: KeyboardEvent) => boolean)
- children?: React.ReactNode | ((close: () => void, onInsert: (command: LexicalCommand<unknown>, params: unknown[]) => void) => React.ReactNode)
+ children?: React.ReactNode | ((close: () => void, onInsert: ShortcutPopupInsertHandler) => React.ReactNode)
className?: string
onOpen?: () => void
onClose?: () => void
@@ -316,7 +316,7 @@ describe('ShortcutsPopupPlugin', () => {
it('renders children as render function and provides close/onInsert', async () => {
const TEST_COMMAND = createCommand<unknown>('TEST_COMMAND')
- const childrenFn = vi.fn((close: () => void, onInsert: (cmd: LexicalCommand<unknown>, params: unknown[]) => void) => (
+ const childrenFn = vi.fn((close: () => void, onInsert: ShortcutPopupInsertHandler) => (
<div>
<button type="button" data-testid="close-btn" onClick={close}>Close</button>
<button type="button" data-testid="insert-btn" onClick={() => onInsert(TEST_COMMAND, ['param1'])}>Insert</button>
@@ -346,7 +346,7 @@ describe('ShortcutsPopupPlugin', () => {
const TEST_COMMAND = createCommand<unknown>('TEST_INSERT_COMMAND')
render(
<MinimalEditor>
- {(close: () => void, onInsert: (cmd: LexicalCommand<unknown>, params: unknown[]) => void) => (
+ {(close: () => void, onInsert: ShortcutPopupInsertHandler) => (
<div>
<button type="button" data-testid="insert-btn" onClick={() => onInsert(TEST_COMMAND, ['value'])}>Insert</button>
</div>
diff --git a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx
index 19a2efb5bcb..ec03b2fc3da 100644
--- a/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx
+++ b/web/app/components/base/prompt-editor/plugins/shortcuts-popup-plugin/index.tsx
@@ -23,6 +23,7 @@ import {
import { createPortal } from 'react-dom'
export const SHORTCUTS_EMPTY_CONTENT = 'shortcuts_empty_content'
+export type ShortcutPopupInsertHandler = <Payload>(command: LexicalCommand<Payload>, params: Payload) => void
// Hotkey can be:
// - string: 'mod+/'
@@ -33,7 +34,7 @@ export type Hotkey = string | string[] | string[][] | ((e: KeyboardEvent) => boo
type ShortcutPopupPluginProps = {
hotkey?: Hotkey
- children?: React.ReactNode | ((close: () => void, onInsert: (command: LexicalCommand<unknown>, params: any[]) => void) => React.ReactNode)
+ children?: React.ReactNode | ((close: () => void, onInsert: ShortcutPopupInsertHandler) => React.ReactNode)
className?: string
container?: Element | null
onOpen?: () => void
@@ -158,8 +159,9 @@ export default function ShortcutsPopupPlugin({
apply({ availableWidth, availableHeight, elements }) {
Object.assign(elements.floating.style, {
maxWidth: `${Math.min(400, availableWidth)}px`,
- maxHeight: `${Math.min(300, availableHeight)}px`,
- overflow: 'auto',
+ maxHeight: `${Math.max(0, availableHeight)}px`,
+ overflowX: 'hidden',
+ overflowY: 'auto',
})
},
padding: 8,
@@ -236,7 +238,7 @@ export default function ShortcutsPopupPlugin({
setOpen(true)
onOpen?.()
- }, [onOpen])
+ }, [editor, onOpen, refs])
const closePortal = useCallback(() => {
setOpen(false)
@@ -280,7 +282,7 @@ export default function ShortcutsPopupPlugin({
return () => document.removeEventListener('mousedown', onMouseDown, false)
}, [open, closePortal])
- const handleInsert = useCallback((command: LexicalCommand<unknown>, params: any) => {
+ const handleInsert = useCallback(<Payload,>(command: LexicalCommand<Payload>, params: Payload) => {
editor.dispatchCommand(command, params)
closePortal()
}, [editor, closePortal])
diff --git a/web/app/components/billing/annotation-full/__tests__/modal.spec.tsx b/web/app/components/billing/annotation-full/__tests__/modal.spec.tsx
index 0033ced4ce0..3f7862b24bd 100644
--- a/web/app/components/billing/annotation-full/__tests__/modal.spec.tsx
+++ b/web/app/components/billing/annotation-full/__tests__/modal.spec.tsx
@@ -29,26 +29,26 @@ type ModalSnapshot = {
className?: string
}
let mockModalProps: ModalSnapshot | null = null
-vi.mock('../../../base/modal', () => ({
- default: ({ isShow, children, onClose, closable, className }: { isShow: boolean, children: React.ReactNode, onClose: () => void, closable?: boolean, className?: string }) => {
+let mockOnOpenChange: ((open: boolean) => void) | undefined
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ open, onOpenChange, children }: { open?: boolean, onOpenChange?: (open: boolean) => void, children: React.ReactNode }) => {
+ mockOnOpenChange = onOpenChange
+ mockModalProps = { isShow: open !== false }
+ return open === false ? null : <>{children}</>
+ },
+ DialogContent: ({ children, className }: { children: React.ReactNode, className?: string }) => {
mockModalProps = {
- isShow,
- closable,
+ isShow: true,
+ closable: true,
className,
}
- if (!isShow)
- return null
return (
<div data-testid="annotation-full-modal" data-classname={className ?? ''}>
- {closable && (
- <button type="button" data-testid="mock-modal-close" onClick={onClose}>
- close
- </button>
- )}
{children}
</div>
)
},
+ DialogCloseButton: () => <button type="button" data-testid="mock-modal-close" onClick={() => mockOnOpenChange?.(false)}>close</button>,
}))
describe('AnnotationFullModal', () => {
@@ -56,6 +56,7 @@ describe('AnnotationFullModal', () => {
vi.clearAllMocks()
mockUpgradeBtnProps = null
mockModalProps = null
+ mockOnOpenChange = undefined
})
// Rendering marketing copy inside modal
@@ -71,8 +72,9 @@ describe('AnnotationFullModal', () => {
expect(mockModalProps).toEqual(expect.objectContaining({
isShow: true,
closable: true,
- className: 'p-0!',
+ className: expect.stringContaining('p-0!'),
}))
+ expect(mockModalProps?.className).toContain('w-full')
})
})
diff --git a/web/app/components/billing/annotation-full/modal.tsx b/web/app/components/billing/annotation-full/modal.tsx
index 4308cad160d..c3c6aab2ce3 100644
--- a/web/app/components/billing/annotation-full/modal.tsx
+++ b/web/app/components/billing/annotation-full/modal.tsx
@@ -1,10 +1,10 @@
'use client'
import type { FC } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogCloseButton, DialogContent } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import GridMask from '@/app/components/base/grid-mask'
-import Modal from '../../base/modal'
import UpgradeBtn from '../upgrade-btn'
import s from './style.module.css'
import Usage from './usage'
@@ -20,28 +20,33 @@ const AnnotationFullModal: FC<Props> = ({
const { t } = useTranslation()
return (
- <Modal
- isShow={show}
- onClose={onHide}
- closable
- className="p-0!"
+ <Dialog
+ open={show}
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
>
- <GridMask wrapperClassName="rounded-lg" canvasClassName="rounded-lg" gradientClassName="rounded-lg">
- <div className="mt-6 flex cursor-pointer flex-col rounded-lg border-2 border-solid border-transparent px-7 py-6 shadow-md transition-all duration-200 ease-in-out">
- <div className="flex items-center justify-between">
- <div className={cn(s.textGradient, 'text-[18px] leading-[27px] font-semibold')}>
- <div>{t('annotatedResponse.fullTipLine1', { ns: 'billing' })}</div>
- <div>{t('annotatedResponse.fullTipLine2', { ns: 'billing' })}</div>
- </div>
+ <DialogContent className="w-full overflow-hidden! border-none p-0! text-left align-middle">
+ <DialogCloseButton data-testid="modal-close-button" />
+ <GridMask wrapperClassName="rounded-lg" canvasClassName="rounded-lg" gradientClassName="rounded-lg">
+ <div className="mt-6 flex cursor-pointer flex-col rounded-lg border-2 border-solid border-transparent px-7 py-6 shadow-md transition-all duration-200 ease-in-out">
+ <div className="flex items-center justify-between">
+ <div className={cn(s.textGradient, 'text-[18px] leading-[27px] font-semibold')}>
+ <div>{t('annotatedResponse.fullTipLine1', { ns: 'billing' })}</div>
+ <div>{t('annotatedResponse.fullTipLine2', { ns: 'billing' })}</div>
+ </div>
+
+ </div>
+ <Usage className="mt-4" />
+ <div className="mt-7 flex justify-end">
+ <UpgradeBtn loc="annotation-create" />
+ </div>
</div>
- <Usage className="mt-4" />
- <div className="mt-7 flex justify-end">
- <UpgradeBtn loc="annotation-create" />
- </div>
- </div>
- </GridMask>
- </Modal>
+ </GridMask>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(AnnotationFullModal)
diff --git a/web/app/components/datasets/common/image-list/__tests__/index.spec.tsx b/web/app/components/datasets/common/image-list/__tests__/index.spec.tsx
index e1fde328bb7..cc60160595c 100644
--- a/web/app/components/datasets/common/image-list/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/common/image-list/__tests__/index.spec.tsx
@@ -42,7 +42,7 @@ type ImageInfo = {
size: number
}
-// Mock ImagePreviewer since it uses createPortal
+// Mock ImagePreviewer since it renders through a Dialog portal
vi.mock('../../image-previewer', () => ({
default: ({ images, initialIndex, onClose }: ImagePreviewerProps) => (
<div data-testid="image-previewer">
diff --git a/web/app/components/datasets/common/image-previewer/__tests__/index.spec.tsx b/web/app/components/datasets/common/image-previewer/__tests__/index.spec.tsx
index 1ff5cb33f8d..aea1a181ffc 100644
--- a/web/app/components/datasets/common/image-previewer/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/common/image-previewer/__tests__/index.spec.tsx
@@ -474,23 +474,18 @@ describe('ImagePreviewer', () => {
expect(nextButton)!.toBeDisabled()
})
- it('should stop event propagation on container click', async () => {
+ it('should not close on container click', async () => {
const onClose = vi.fn()
- const parentClick = vi.fn()
const images = createMockImages()
await act(async () => {
- render(
- <div onClick={parentClick}>
- <ImagePreviewer images={images} onClose={onClose} />
- </div>,
- )
+ render(<ImagePreviewer images={images} onClose={onClose} />)
})
const container = document.querySelector('.image-previewer')
if (container) {
fireEvent.click(container)
- expect(parentClick).not.toHaveBeenCalled()
+ expect(onClose).not.toHaveBeenCalled()
}
})
diff --git a/web/app/components/datasets/common/image-previewer/index.tsx b/web/app/components/datasets/common/image-previewer/index.tsx
index 42b4ce33a9f..7520f62f81e 100644
--- a/web/app/components/datasets/common/image-previewer/index.tsx
+++ b/web/app/components/datasets/common/image-previewer/index.tsx
@@ -1,7 +1,7 @@
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { RiArrowLeftLine, RiArrowRightLine, RiCloseLine, RiRefreshLine } from '@remixicon/react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { createPortal } from 'react-dom'
import { useHotkeys } from 'react-hotkeys-hook'
import Loading from '@/app/components/base/loading'
import { formatFileSize } from '@/utils/format'
@@ -145,81 +145,87 @@ const ImagePreviewer = ({
fetchImage(image)
}, [fetchImage])
- useHotkeys('esc', onClose)
useHotkeys('left', prevImage)
useHotkeys('right', nextImage)
- return createPortal(
- <div
- className="image-previewer fixed inset-0 z-10000 flex items-center justify-center bg-background-overlay-fullscreen p-5 pb-4 backdrop-blur-[6px]"
- onClick={e => e.stopPropagation()}
- tabIndex={-1}
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
+ disablePointerDismissal
>
- <div className="absolute top-6 right-6 z-10 flex cursor-pointer flex-col items-center gap-y-1">
- <Button
- variant="tertiary"
- onClick={onClose}
- className="size-9 rounded-[10px] p-0"
- size="large"
- >
- <RiCloseLine className="size-5" />
- </Button>
- <span className="system-2xs-medium-uppercase text-text-tertiary">
- Esc
- </span>
- </div>
- {cachedImages[currentImage!.url]!.status === 'loading' && (
- <Loading type="app" />
- )}
- {cachedImages[currentImage!.url]!.status === 'error' && (
- <div className="flex max-w-sm flex-col items-center gap-y-2 system-sm-regular text-text-tertiary">
- <span>{`Failed to load image: ${currentImage!.url}. Please try again.`}</span>
+ <DialogContent
+ className="image-previewer inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-x-0! translate-y-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-background-overlay-fullscreen p-5! pb-4! shadow-none! backdrop-blur-[6px]"
+ backdropClassName="bg-transparent!"
+ >
+ <div className="absolute top-6 right-6 z-10 flex cursor-pointer flex-col items-center gap-y-1">
<Button
- variant="secondary"
- onClick={() => retryImage(currentImage!)}
- className="size-9 rounded-full p-0"
+ variant="tertiary"
+ onClick={onClose}
+ className="size-9 rounded-[10px] p-0"
size="large"
>
- <RiRefreshLine className="size-5" />
+ <RiCloseLine className="size-5" />
</Button>
+ <span className="system-2xs-medium-uppercase text-text-tertiary">
+ Esc
+ </span>
</div>
- )}
- {cachedImages[currentImage!.url]!.status === 'loaded' && (
- <div className="flex size-full flex-col items-center justify-center gap-y-2">
- <img
- alt={currentImage!.name}
- src={cachedImages[currentImage!.url]!.blobUrl}
- className="max-h-[calc(100%-2.5rem)] max-w-full object-contain shadow-lg ring-8 ring-effects-image-frame backdrop-blur-[5px]"
- />
- <div className="flex shrink-0 gap-x-2 pt-3 pb-1 system-sm-regular text-text-tertiary">
- <span>{currentImage!.name}</span>
- <span>·</span>
- <span>{`${cachedImages[currentImage!.url]!.width} ×  ${cachedImages[currentImage!.url]!.height}`}</span>
- <span>·</span>
- <span>{formatFileSize(currentImage!.size)}</span>
+ {cachedImages[currentImage!.url]!.status === 'loading' && (
+ <Loading type="app" />
+ )}
+ {cachedImages[currentImage!.url]!.status === 'error' && (
+ <div className="flex max-w-sm flex-col items-center gap-y-2 system-sm-regular text-text-tertiary">
+ <span>{`Failed to load image: ${currentImage!.url}. Please try again.`}</span>
+ <Button
+ variant="secondary"
+ onClick={() => retryImage(currentImage!)}
+ className="size-9 rounded-full p-0"
+ size="large"
+ >
+ <RiRefreshLine className="size-5" />
+ </Button>
</div>
- </div>
- )}
- <Button
- variant="secondary"
- onClick={prevImage}
- className="absolute top-1/2 left-8 z-10 size-9 -translate-y-1/2 rounded-full p-0"
- disabled={currentIndex === 0}
- size="large"
- >
- <RiArrowLeftLine className="size-5" />
- </Button>
- <Button
- variant="secondary"
- onClick={nextImage}
- className="absolute top-1/2 right-8 z-10 size-9 -translate-y-1/2 rounded-full p-0"
- disabled={currentIndex === images.length - 1}
- size="large"
- >
- <RiArrowRightLine className="size-5" />
- </Button>
- </div>,
- document.body,
+ )}
+ {cachedImages[currentImage!.url]!.status === 'loaded' && (
+ <div className="flex size-full flex-col items-center justify-center gap-y-2">
+ <img
+ alt={currentImage!.name}
+ src={cachedImages[currentImage!.url]!.blobUrl}
+ className="max-h-[calc(100%-2.5rem)] max-w-full object-contain shadow-lg ring-8 ring-effects-image-frame backdrop-blur-[5px]"
+ />
+ <div className="flex shrink-0 gap-x-2 pt-3 pb-1 system-sm-regular text-text-tertiary">
+ <span>{currentImage!.name}</span>
+ <span>·</span>
+ <span>{`${cachedImages[currentImage!.url]!.width} ×  ${cachedImages[currentImage!.url]!.height}`}</span>
+ <span>·</span>
+ <span>{formatFileSize(currentImage!.size)}</span>
+ </div>
+ </div>
+ )}
+ <Button
+ variant="secondary"
+ onClick={prevImage}
+ className="absolute top-1/2 left-8 z-10 size-9 -translate-y-1/2 rounded-full p-0"
+ disabled={currentIndex === 0}
+ size="large"
+ >
+ <RiArrowLeftLine className="size-5" />
+ </Button>
+ <Button
+ variant="secondary"
+ onClick={nextImage}
+ className="absolute top-1/2 right-8 z-10 size-9 -translate-y-1/2 rounded-full p-0"
+ disabled={currentIndex === images.length - 1}
+ size="large"
+ >
+ <RiArrowRightLine className="size-5" />
+ </Button>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/dsl-confirm-modal.tsx b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/dsl-confirm-modal.tsx
index d0c97e185c8..849d36807f7 100644
--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/dsl-confirm-modal.tsx
+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/dsl-confirm-modal.tsx
@@ -1,6 +1,13 @@
-import { Button } from '@langgenius/dify-ui/button'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
type DSLConfirmModalProps = {
versions?: {
@@ -20,32 +27,36 @@ const DSLConfirmModal = ({
const { t } = useTranslation()
return (
- <Modal
- isShow
- onClose={() => onCancel()}
- className="w-[480px]"
+ <AlertDialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
>
- <div className="flex flex-col items-start gap-2 self-stretch pb-4">
- <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>
- <div className="flex grow flex-col system-md-regular text-text-secondary">
- <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
- <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
- <br />
- <div>
- {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
- <span className="system-md-medium">{versions.importedVersion}</span>
- </div>
- <div>
- {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
- <span className="system-md-medium">{versions.systemVersion}</span>
- </div>
+ <AlertDialogContent className="w-[480px] max-w-none! overflow-hidden! border-none p-6 text-left align-middle shadow-xl">
+ <div className="flex flex-col items-start gap-2 self-stretch pb-4">
+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</AlertDialogTitle>
+ <AlertDialogDescription render={<div />} className="flex grow flex-col system-md-regular text-text-secondary">
+ <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
+ <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
+ <br />
+ <div>
+ {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
+ <span className="system-md-medium">{versions.importedVersion}</span>
+ </div>
+ <div>
+ {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
+ <span className="system-md-medium">{versions.systemVersion}</span>
+ </div>
+ </AlertDialogDescription>
</div>
- </div>
- <div className="flex items-start justify-end gap-2 self-stretch pt-6">
- <Button variant="secondary" onClick={() => onCancel()}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button variant="primary" tone="destructive" onClick={onConfirm} disabled={confirmDisabled}>{t('newApp.Confirm', { ns: 'app' })}</Button>
- </div>
- </Modal>
+ <AlertDialogActions className="items-start p-0 pt-6">
+ <AlertDialogCancelButton variant="secondary">{t('newApp.Cancel', { ns: 'app' })}</AlertDialogCancelButton>
+ <AlertDialogConfirmButton onClick={onConfirm} disabled={confirmDisabled}>{t('newApp.Confirm', { ns: 'app' })}</AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
)
}
diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx
index b95fa4d5dbf..a00cdf6098a 100644
--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx
+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/__tests__/use-dsl-import.spec.tsx
@@ -418,7 +418,10 @@ describe('useDSLImport', () => {
it('should handle FAILED status', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
- mockImportDSL.mockResolvedValue(createImportDSLResponse({ status: 'failed' }))
+ mockImportDSL.mockResolvedValue(createImportDSLResponse({
+ status: 'failed',
+ error: 'Missing rag_pipeline data in YAML content',
+ }))
const { result } = renderHook(
() => useDSLImport({
@@ -434,9 +437,42 @@ describe('useDSLImport', () => {
})
await waitFor(() => {
- expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({
+ expect(toastMocks.record).toHaveBeenCalledWith({
type: 'error',
- }))
+ message: 'Missing rag_pipeline data in YAML content',
+ })
+ })
+
+ vi.useRealTimers()
+ })
+
+ it('should show response error when import request rejects with a response body', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ mockImportDSL.mockRejectedValue(new Response(JSON.stringify({
+ error: 'Missing rag_pipeline data in YAML content',
+ }), {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ }))
+
+ const { result } = renderHook(
+ () => useDSLImport({
+ activeTab: CreateFromDSLModalTab.FROM_URL,
+ dslUrl: 'https://example.com/test.pipeline',
+ }),
+ { wrapper: createWrapper() },
+ )
+
+ await act(async () => {
+ result.current.handleCreateApp()
+ vi.advanceTimersByTime(400)
+ })
+
+ await waitFor(() => {
+ expect(toastMocks.record).toHaveBeenCalledWith({
+ type: 'error',
+ message: 'Missing rag_pipeline data in YAML content',
+ })
})
vi.useRealTimers()
@@ -692,6 +728,7 @@ describe('useDSLImport', () => {
status: 'failed',
pipeline_id: 'pipeline-456',
dataset_id: 'dataset-789',
+ error: 'Import information expired or does not exist',
})
const { result } = renderHook(
@@ -718,9 +755,56 @@ describe('useDSLImport', () => {
})
await waitFor(() => {
- expect(toastMocks.record).toHaveBeenCalledWith(expect.objectContaining({
+ expect(toastMocks.record).toHaveBeenCalledWith({
type: 'error',
- }))
+ message: 'Import information expired or does not exist',
+ })
+ })
+
+ vi.useRealTimers()
+ })
+
+ it('should show response error when confirm request rejects with a response body', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+
+ mockImportDSL.mockResolvedValue(createImportDSLResponse({
+ id: 'import-123',
+ status: 'pending',
+ }))
+
+ mockImportDSLConfirm.mockRejectedValue(new Response(JSON.stringify({
+ error: 'Import information expired or does not exist',
+ }), {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ }))
+
+ const { result } = renderHook(
+ () => useDSLImport({
+ activeTab: CreateFromDSLModalTab.FROM_URL,
+ dslUrl: 'https://example.com/test.pipeline',
+ }),
+ { wrapper: createWrapper() },
+ )
+
+ await act(async () => {
+ result.current.handleCreateApp()
+ vi.advanceTimersByTime(400)
+ })
+
+ await act(async () => {
+ vi.advanceTimersByTime(400)
+ })
+
+ await act(async () => {
+ result.current.onDSLConfirm()
+ })
+
+ await waitFor(() => {
+ expect(toastMocks.record).toHaveBeenCalledWith({
+ type: 'error',
+ message: 'Import information expired or does not exist',
+ })
})
vi.useRealTimers()
diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts
index e085ffe1bcd..0dbfdf21569 100644
--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts
+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/hooks/use-dsl-import.ts
@@ -22,6 +22,31 @@ type DSLVersions = {
importedVersion: string
systemVersion: string
}
+type ImportErrorResponse = {
+ message?: unknown
+ error?: unknown
+}
+const getNonEmptyString = (value: unknown): string | undefined => {
+ if (typeof value !== 'string')
+ return undefined
+
+ const trimmedValue = value.trim()
+ return trimmedValue || undefined
+}
+const getImportErrorMessage = async (error: unknown): Promise<string | undefined> => {
+ if (error instanceof Response && !error.bodyUsed) {
+ try {
+ const errorData = await error.clone().json() as ImportErrorResponse
+ return getNonEmptyString(errorData.message) ?? getNonEmptyString(errorData.error)
+ }
+ catch {}
+ }
+
+ if (error instanceof Error)
+ return getNonEmptyString(error.message)
+
+ return undefined
+}
export const useDSLImport = ({ activeTab = CreateFromDSLModalTab.FROM_FILE, dslUrl = '', onSuccess, onClose }: UseDSLImportOptions) => {
const { push } = useRouter()
const { t } = useTranslation()
@@ -37,6 +62,9 @@ export const useDSLImport = ({ activeTab = CreateFromDSLModalTab.FROM_FILE, dslU
const isCreatingRef = useRef(false)
const { mutateAsync: importDSL } = useImportPipelineDSL()
const { mutateAsync: importDSLConfirm } = useImportPipelineDSLConfirm()
+ const notifyError = useCallback((message?: string) => {
+ toast.error(message || t('creation.errorTip', { ns: 'datasetPipeline' }))
+ }, [t])
const readFile = useCallback((file: File) => {
const reader = new FileReader()
reader.onload = (event) => {
@@ -60,51 +88,55 @@ export const useDSLImport = ({ activeTab = CreateFromDSLModalTab.FROM_FILE, dslU
if (isCreatingRef.current)
return
isCreatingRef.current = true
- let response
- if (currentTab === CreateFromDSLModalTab.FROM_FILE) {
- response = await importDSL({
- mode: DSLImportMode.YAML_CONTENT,
- yaml_content: fileContent || '',
- })
+ try {
+ let response
+ if (currentTab === CreateFromDSLModalTab.FROM_FILE) {
+ response = await importDSL({
+ mode: DSLImportMode.YAML_CONTENT,
+ yaml_content: fileContent || '',
+ })
+ }
+ if (currentTab === CreateFromDSLModalTab.FROM_URL) {
+ response = await importDSL({
+ mode: DSLImportMode.YAML_URL,
+ yaml_url: dslUrlValue || '',
+ })
+ }
+ if (!response) {
+ notifyError()
+ return
+ }
+ const { id, status, pipeline_id, dataset_id, imported_dsl_version, current_dsl_version } = response
+ if (status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS) {
+ onSuccess?.()
+ onClose?.()
+ toast(t(status === DSLImportStatus.COMPLETED ? 'creation.successTip' : 'creation.caution', { ns: 'datasetPipeline' }), {
+ type: status === DSLImportStatus.COMPLETED ? 'success' : 'warning',
+ description: status === DSLImportStatus.COMPLETED_WITH_WARNINGS && t('newApp.appCreateDSLWarning', { ns: 'app' }),
+ })
+ if (pipeline_id)
+ await handleCheckPluginDependencies(pipeline_id, true)
+ push(`/datasets/${dataset_id}/pipeline`)
+ }
+ else if (status === DSLImportStatus.PENDING) {
+ setVersions({
+ importedVersion: imported_dsl_version ?? '',
+ systemVersion: current_dsl_version ?? '',
+ })
+ onClose?.()
+ setTimeout(() => {
+ setShowConfirmModal(true)
+ }, 300)
+ setImportId(id)
+ }
+ else {
+ notifyError(response.error)
+ }
}
- if (currentTab === CreateFromDSLModalTab.FROM_URL) {
- response = await importDSL({
- mode: DSLImportMode.YAML_URL,
- yaml_url: dslUrlValue || '',
- })
+ catch (error) {
+ notifyError(await getImportErrorMessage(error))
}
- if (!response) {
- toast.error(t('creation.errorTip', { ns: 'datasetPipeline' }))
- isCreatingRef.current = false
- return
- }
- const { id, status, pipeline_id, dataset_id, imported_dsl_version, current_dsl_version } = response
- if (status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS) {
- onSuccess?.()
- onClose?.()
- toast(t(status === DSLImportStatus.COMPLETED ? 'creation.successTip' : 'creation.caution', { ns: 'datasetPipeline' }), {
- type: status === DSLImportStatus.COMPLETED ? 'success' : 'warning',
- description: status === DSLImportStatus.COMPLETED_WITH_WARNINGS && t('newApp.appCreateDSLWarning', { ns: 'app' }),
- })
- if (pipeline_id)
- await handleCheckPluginDependencies(pipeline_id, true)
- push(`/datasets/${dataset_id}/pipeline`)
- isCreatingRef.current = false
- }
- else if (status === DSLImportStatus.PENDING) {
- setVersions({
- importedVersion: imported_dsl_version ?? '',
- systemVersion: current_dsl_version ?? '',
- })
- onClose?.()
- setTimeout(() => {
- setShowConfirmModal(true)
- }, 300)
- setImportId(id)
- isCreatingRef.current = false
- }
- else {
- toast.error(t('creation.errorTip', { ns: 'datasetPipeline' }))
+ finally {
isCreatingRef.current = false
}
}, [
@@ -114,6 +146,7 @@ export const useDSLImport = ({ activeTab = CreateFromDSLModalTab.FROM_FILE, dslU
fileContent,
importDSL,
t,
+ notifyError,
onSuccess,
onClose,
handleCheckPluginDependencies,
@@ -124,25 +157,32 @@ export const useDSLImport = ({ activeTab = CreateFromDSLModalTab.FROM_FILE, dslU
if (!importId)
return
setIsConfirming(true)
- const response = await importDSLConfirm(importId)
- setIsConfirming(false)
- if (!response) {
- toast.error(t('creation.errorTip', { ns: 'datasetPipeline' }))
- return
+ try {
+ const response = await importDSLConfirm(importId)
+ if (!response) {
+ notifyError()
+ return
+ }
+ const { status, pipeline_id, dataset_id, error } = response
+ if (status === DSLImportStatus.COMPLETED) {
+ onSuccess?.()
+ setShowConfirmModal(false)
+ toast.success(t('creation.successTip', { ns: 'datasetPipeline' }))
+ if (pipeline_id)
+ await handleCheckPluginDependencies(pipeline_id, true)
+ push(`/datasets/${dataset_id}/pipeline`)
+ }
+ else if (status === DSLImportStatus.FAILED) {
+ notifyError(error)
+ }
}
- const { status, pipeline_id, dataset_id } = response
- if (status === DSLImportStatus.COMPLETED) {
- onSuccess?.()
- setShowConfirmModal(false)
- toast.success(t('creation.successTip', { ns: 'datasetPipeline' }))
- if (pipeline_id)
- await handleCheckPluginDependencies(pipeline_id, true)
- push(`/datasets/${dataset_id}/pipeline`)
+ catch (error) {
+ notifyError(await getImportErrorMessage(error))
}
- else if (status === DSLImportStatus.FAILED) {
- toast.error(t('creation.errorTip', { ns: 'datasetPipeline' }))
+ finally {
+ setIsConfirming(false)
}
- }, [importId, importDSLConfirm, t, onSuccess, handleCheckPluginDependencies, push])
+ }, [importId, importDSLConfirm, notifyError, t, onSuccess, handleCheckPluginDependencies, push])
const handleCancelConfirm = useCallback(() => {
setShowConfirmModal(false)
}, [])
diff --git a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/index.tsx b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/index.tsx
index 4f5b5c23fdf..8aeaed3ebda 100644
--- a/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/index.tsx
+++ b/web/app/components/datasets/create-from-pipeline/create-options/create-from-dsl-modal/index.tsx
@@ -1,10 +1,9 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { useKeyPress } from 'ahooks'
-import { noop } from 'es-toolkit/function'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import DSLConfirmModal from './dsl-confirm-modal'
import Header from './header'
import { CreateFromDSLModalTab, useDSLImport } from './hooks/use-dsl-import'
@@ -54,55 +53,54 @@ const CreateFromDSLModal = ({
useKeyPress('esc', () => {
if (show && !showConfirmModal)
onClose()
- })
+ }, { target: () => document })
return (
<>
- <Modal
- className="w-[520px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0 shadow-xl"
- isShow={show}
- onClose={noop}
- >
- <Header onClose={onClose} />
- <Tab
- currentTab={currentTab}
- setCurrentTab={setCurrentTab}
- />
- <div className="px-6 py-4">
- {currentTab === CreateFromDSLModalTab.FROM_FILE && (
- <Uploader
- className="mt-0"
- file={currentFile}
- updateFile={handleFile}
- />
- )}
- {currentTab === CreateFromDSLModalTab.FROM_URL && (
- <div>
- <div className="leading6 mb-1 system-md-semibold text-text-secondary">
- DSL URL
- </div>
- <Input
- placeholder={t('importFromDSLUrlPlaceholder', { ns: 'app' }) || ''}
- value={dslUrlValue}
- onChange={e => setDslUrlValue(e.target.value)}
+ <Dialog open={show}>
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden! rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0! text-left align-middle shadow-xl">
+
+ <Header onClose={onClose} />
+ <Tab
+ currentTab={currentTab}
+ setCurrentTab={setCurrentTab}
+ />
+ <div className="px-6 py-4">
+ {currentTab === CreateFromDSLModalTab.FROM_FILE && (
+ <Uploader
+ className="mt-0"
+ file={currentFile}
+ updateFile={handleFile}
/>
- </div>
- )}
- </div>
- <div className="flex justify-end gap-x-2 p-6 pt-5">
- <Button onClick={onClose}>
- {t('newApp.Cancel', { ns: 'app' })}
- </Button>
- <Button
- disabled={buttonDisabled}
- variant="primary"
- onClick={handleCreateApp}
- className="gap-1"
- >
- <span>{t('newApp.import', { ns: 'app' })}</span>
- </Button>
- </div>
- </Modal>
+ )}
+ {currentTab === CreateFromDSLModalTab.FROM_URL && (
+ <div>
+ <div className="leading6 mb-1 system-md-semibold text-text-secondary">
+ DSL URL
+ </div>
+ <Input
+ placeholder={t('importFromDSLUrlPlaceholder', { ns: 'app' }) || ''}
+ value={dslUrlValue}
+ onChange={e => setDslUrlValue(e.target.value)}
+ />
+ </div>
+ )}
+ </div>
+ <div className="flex justify-end gap-x-2 p-6 pt-5">
+ <Button onClick={onClose}>
+ {t('newApp.Cancel', { ns: 'app' })}
+ </Button>
+ <Button
+ disabled={buttonDisabled}
+ variant="primary"
+ onClick={handleCreateApp}
+ className="gap-1"
+ >
+ <span>{t('newApp.import', { ns: 'app' })}</span>
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
{showConfirmModal && (
<DSLConfirmModal
versions={versions}
diff --git a/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/index.spec.tsx b/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/index.spec.tsx
index bcf2c068ef1..8f28f750459 100644
--- a/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/index.spec.tsx
@@ -323,6 +323,21 @@ describe('TemplateCard', () => {
})
})
+ it('should close details modal when dialog requests close', async () => {
+ render(<TemplateCard {...defaultProps} />)
+ fireEvent.click(screen.getByTestId('action-details'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('details-component')).toBeInTheDocument()
+ })
+
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('details-component')).not.toBeInTheDocument()
+ })
+ })
+
it('should trigger use template from details modal', async () => {
mockCreateDataset.mockImplementation((_data, callbacks) => {
callbacks.onSuccess({ dataset_id: 'new-dataset-123', pipeline_id: 'pipe-123' })
@@ -593,6 +608,21 @@ describe('TemplateCard', () => {
expect(screen.queryByTestId('edit-pipeline-info')).not.toBeInTheDocument()
})
})
+
+ it('should close edit modal when dialog requests close', async () => {
+ render(<TemplateCard {...defaultProps} />)
+ fireEvent.click(screen.getByTestId('action-edit'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('edit-pipeline-info')).toBeInTheDocument()
+ })
+
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('edit-pipeline-info')).not.toBeInTheDocument()
+ })
+ })
})
// Props Tests
diff --git a/web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx b/web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx
index 03bda31f1fe..4663c55e38f 100644
--- a/web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/template-card/index.tsx
@@ -8,12 +8,12 @@ import {
AlertDialogDescription,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { trackEvent } from '@/app/components/base/amplitude'
-import Modal from '@/app/components/base/modal'
import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'
import { useRouter } from '@/next/navigation'
import { useCreatePipelineDatasetFromCustomized } from '@/service/knowledge/use-create-dataset'
@@ -153,16 +153,21 @@ const TemplateCard = ({
handleDelete={handleDelete}
/>
{showEditModal && (
- <Modal
- isShow={showEditModal}
- onClose={closeEditModal}
- className="max-w-[520px] p-0"
+ <Dialog
+ open={showEditModal}
+ onOpenChange={(open) => {
+ if (!open)
+ closeEditModal()
+ }}
>
- <EditPipelineInfo
- pipeline={pipeline}
- onClose={closeEditModal}
- />
- </Modal>
+ <DialogContent className="w-[calc(100vw-2rem)] max-w-[520px]! overflow-hidden! border-none p-0 text-left align-middle">
+
+ <EditPipelineInfo
+ pipeline={pipeline}
+ onClose={closeEditModal}
+ />
+ </DialogContent>
+ </Dialog>
)}
<AlertDialog open={showDeleteConfirm} onOpenChange={open => !open && onCancelDelete()}>
<AlertDialogContent>
@@ -183,18 +188,23 @@ const TemplateCard = ({
</AlertDialogContent>
</AlertDialog>
{showDetailModal && (
- <Modal
- isShow={showDetailModal}
- onClose={closeDetailsModal}
- className="h-[calc(100vh-64px)] max-w-[1680px] rounded-3xl p-0"
+ <Dialog
+ open={showDetailModal}
+ onOpenChange={(open) => {
+ if (!open)
+ closeDetailsModal()
+ }}
>
- <Details
- id={pipeline.id}
- type={type}
- onClose={closeDetailsModal}
- onApplyTemplate={handleUseTemplate}
- />
- </Modal>
+ <DialogContent className="h-[calc(100vh-64px)] max-h-none w-[calc(100vw-2rem)] max-w-[1680px]! overflow-hidden! rounded-3xl border-none p-0 text-left align-middle">
+
+ <Details
+ id={pipeline.id}
+ type={type}
+ onClose={closeDetailsModal}
+ onApplyTemplate={handleUseTemplate}
+ />
+ </DialogContent>
+ </Dialog>
)}
</div>
)
diff --git a/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx b/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx
index fdb032b1ef7..0de10a8ecd4 100644
--- a/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx
+++ b/web/app/components/datasets/create/empty-dataset-creation-modal/index.tsx
@@ -1,13 +1,13 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { trackEvent } from '@/app/components/base/amplitude'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import { useRouter } from '@/next/navigation'
import { createEmptyDataset } from '@/service/datasets'
import { useInvalidDatasetList } from '@/service/knowledge/use-dataset'
@@ -46,21 +46,30 @@ const EmptyDatasetCreationModal = ({ show = false, onHide }: IProps) => {
}
}
return (
- <Modal isShow={show} onClose={onHide} className={cn(s.modal, '!max-w-[520px]', 'px-8')}>
- <div className={s.modalHeader}>
- <div className={s.title}>{t('stepOne.modal.title', { ns: 'datasetCreation' })}</div>
- <span className={s.close} onClick={onHide} />
- </div>
- <div className={s.tip}>{t('stepOne.modal.tip', { ns: 'datasetCreation' })}</div>
- <div className={s.form}>
- <div className={s.label}>{t('stepOne.modal.input', { ns: 'datasetCreation' })}</div>
- <Input value={inputValue} placeholder={t('stepOne.modal.placeholder', { ns: 'datasetCreation' }) || ''} onChange={e => setInputValue(e.target.value)} />
- </div>
- <div className="flex flex-row-reverse">
- <Button className="ml-2 w-24" variant="primary" onClick={submit}>{t('stepOne.modal.confirmButton', { ns: 'datasetCreation' })}</Button>
- <Button className="w-24" onClick={onHide}>{t('stepOne.modal.cancelButton', { ns: 'datasetCreation' })}</Button>
- </div>
- </Modal>
+ <Dialog
+ open={show}
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
+ >
+ <DialogContent className={cn('w-full overflow-hidden! border-none text-left align-middle', cn(s.modal, '!max-w-[520px]', 'px-8'))}>
+
+ <div className={s.modalHeader}>
+ <div className={s.title}>{t('stepOne.modal.title', { ns: 'datasetCreation' })}</div>
+ <span className={s.close} onClick={onHide} />
+ </div>
+ <div className={s.tip}>{t('stepOne.modal.tip', { ns: 'datasetCreation' })}</div>
+ <div className={s.form}>
+ <div className={s.label}>{t('stepOne.modal.input', { ns: 'datasetCreation' })}</div>
+ <Input value={inputValue} placeholder={t('stepOne.modal.placeholder', { ns: 'datasetCreation' }) || ''} onChange={e => setInputValue(e.target.value)} />
+ </div>
+ <div className="flex flex-row-reverse">
+ <Button className="ml-2 w-24" variant="primary" onClick={submit}>{t('stepOne.modal.confirmButton', { ns: 'datasetCreation' })}</Button>
+ <Button className="w-24" onClick={onHide}>{t('stepOne.modal.cancelButton', { ns: 'datasetCreation' })}</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
export default EmptyDatasetCreationModal
diff --git a/web/app/components/datasets/create/stop-embedding-modal/__tests__/index.spec.tsx b/web/app/components/datasets/create/stop-embedding-modal/__tests__/index.spec.tsx
index 1b3abfeadc5..840c5cc0e53 100644
--- a/web/app/components/datasets/create/stop-embedding-modal/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/create/stop-embedding-modal/__tests__/index.spec.tsx
@@ -25,8 +25,7 @@ const renderStopEmbeddingModal = (props: Partial<StopEmbeddingModalProps> = {})
// StopEmbeddingModal Component Tests
describe('StopEmbeddingModal', () => {
- // Suppress Headless UI warnings in tests
- // These warnings are from the library's internal behavior, not our code
+ // Suppress expected modal warnings in tests.
let consoleWarnSpy: MockInstance
let consoleErrorSpy: MockInstance
diff --git a/web/app/components/datasets/create/stop-embedding-modal/index.tsx b/web/app/components/datasets/create/stop-embedding-modal/index.tsx
index 93df58d276e..41faf58b09a 100644
--- a/web/app/components/datasets/create/stop-embedding-modal/index.tsx
+++ b/web/app/components/datasets/create/stop-embedding-modal/index.tsx
@@ -1,9 +1,16 @@
'use client'
-import { Button } from '@langgenius/dify-ui/button'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
import { cn } from '@langgenius/dify-ui/cn'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import s from './index.module.css'
type IProps = {
@@ -25,20 +32,24 @@ const StopEmbeddingModal = ({
}
return (
- <Modal
- isShow={show}
- onClose={onHide}
- className={cn(s.modal, 'max-w-[480px]!', 'px-8')}
+ <AlertDialog
+ open={show}
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
>
- <div className={s.icon} />
- <span className={s.close} onClick={onHide} />
- <div className={s.title}>{t('stepThree.modelTitle', { ns: 'datasetCreation' })}</div>
- <div className={s.content}>{t('stepThree.modelContent', { ns: 'datasetCreation' })}</div>
- <div className="flex flex-row-reverse">
- <Button className="ml-2 w-24" variant="primary" onClick={submit}>{t('stepThree.modelButtonConfirm', { ns: 'datasetCreation' })}</Button>
- <Button className="w-24" onClick={onHide}>{t('stepThree.modelButtonCancel', { ns: 'datasetCreation' })}</Button>
- </div>
- </Modal>
+ <AlertDialogContent className={cn(s.modal, 'max-w-[480px]! overflow-hidden! border-none px-8 py-6 text-left align-middle shadow-xl')}>
+ <div className={s.icon} />
+ <span className={s.close} onClick={onHide} />
+ <AlertDialogTitle className={s.title}>{t('stepThree.modelTitle', { ns: 'datasetCreation' })}</AlertDialogTitle>
+ <AlertDialogDescription className={s.content}>{t('stepThree.modelContent', { ns: 'datasetCreation' })}</AlertDialogDescription>
+ <AlertDialogActions className="flex-row-reverse gap-0 p-0">
+ <AlertDialogConfirmButton className="ml-2 w-24" tone="default" onClick={submit}>{t('stepThree.modelButtonConfirm', { ns: 'datasetCreation' })}</AlertDialogConfirmButton>
+ <AlertDialogCancelButton className="w-24" variant="secondary">{t('stepThree.modelButtonCancel', { ns: 'datasetCreation' })}</AlertDialogCancelButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
)
}
diff --git a/web/app/components/datasets/documents/components/rename-modal.tsx b/web/app/components/datasets/documents/components/rename-modal.tsx
index fc4626676bd..ac4fc7fc848 100644
--- a/web/app/components/datasets/documents/components/rename-modal.tsx
+++ b/web/app/components/datasets/documents/components/rename-modal.tsx
@@ -1,13 +1,13 @@
'use client'
import type { FC } from 'react'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { useBoolean } from 'ahooks'
import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import { renameDocumentName } from '@/service/datasets'
type Props = {
@@ -55,23 +55,31 @@ const RenameModal: FC<Props> = ({
}
return (
- <Modal
- title={t('list.table.rename', { ns: 'datasetDocuments' })}
- isShow
- onClose={onClose}
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className="mt-6 text-sm leading-[21px] font-medium text-text-primary">{t('list.table.name', { ns: 'datasetDocuments' })}</div>
- <Input
- className="mt-2 h-10"
- value={newName}
- onChange={e => setNewName(e.target.value)}
- />
+ <DialogContent className="overflow-hidden! border-none text-left align-middle">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t('list.table.rename', { ns: 'datasetDocuments' })}
+ </DialogTitle>
- <div className="mt-10 flex justify-end">
- <Button className="mr-2 shrink-0" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button variant="primary" className="shrink-0" onClick={handleSave} loading={saveLoading}>{t('operation.save', { ns: 'common' })}</Button>
- </div>
- </Modal>
+ <div className="mt-6 text-sm leading-[21px] font-medium text-text-primary">{t('list.table.name', { ns: 'datasetDocuments' })}</div>
+ <Input
+ className="mt-2 h-10"
+ value={newName}
+ onChange={e => setNewName(e.target.value)}
+ />
+
+ <div className="mt-10 flex justify-end">
+ <Button className="mr-2 shrink-0" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button variant="primary" className="shrink-0" onClick={handleSave} loading={saveLoading}>{t('operation.save', { ns: 'common' })}</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(RenameModal)
diff --git a/web/app/components/datasets/documents/detail/completed/common/regeneration-modal.tsx b/web/app/components/datasets/documents/detail/completed/common/regeneration-modal.tsx
index 9b2a2e36ee3..3999e113afe 100644
--- a/web/app/components/datasets/documents/detail/completed/common/regeneration-modal.tsx
+++ b/web/app/components/datasets/documents/detail/completed/common/regeneration-modal.tsx
@@ -1,12 +1,16 @@
import type { FC } from 'react'
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { RiLoader2Line } from '@remixicon/react'
import { useCountDown } from 'ahooks'
-import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import { useEventEmitterContextContext } from '@/context/event-emitter'
type IDefaultContentProps = {
@@ -23,8 +27,8 @@ const DefaultContent: FC<IDefaultContentProps> = React.memo(({
return (
<>
<div className="pb-4">
- <span className="title-2xl-semi-bold text-text-primary">{t('segment.regenerationConfirmTitle', { ns: 'datasetDocuments' })}</span>
- <p className="system-md-regular text-text-secondary">{t('segment.regenerationConfirmMessage', { ns: 'datasetDocuments' })}</p>
+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">{t('segment.regenerationConfirmTitle', { ns: 'datasetDocuments' })}</AlertDialogTitle>
+ <AlertDialogDescription className="system-md-regular text-text-secondary">{t('segment.regenerationConfirmMessage', { ns: 'datasetDocuments' })}</AlertDialogDescription>
</div>
<div className="flex justify-end gap-x-2 pt-6">
<Button onClick={onCancel}>
@@ -123,11 +127,13 @@ const RegenerationModal: FC<IRegenerationModalProps> = ({
})
return (
- <Modal isShow={isShow} onClose={noop} className="max-w-[480px]! rounded-2xl!" wrapperClassName="z-10000!">
- {!loading && !updateSucceeded && <DefaultContent onCancel={onCancel} onConfirm={onConfirm} />}
- {loading && !updateSucceeded && <RegeneratingContent />}
- {!loading && updateSucceeded && <RegenerationCompletedContent onClose={onClose} />}
- </Modal>
+ <AlertDialog open={isShow}>
+ <AlertDialogContent className="w-[calc(100vw-2rem)] max-w-[480px]! overflow-hidden! rounded-2xl! border-none p-6 text-left align-middle shadow-xl">
+ {!loading && !updateSucceeded && <DefaultContent onCancel={onCancel} onConfirm={onConfirm} />}
+ {loading && !updateSucceeded && <RegeneratingContent />}
+ {!loading && updateSucceeded && <RegenerationCompletedContent onClose={onClose} />}
+ </AlertDialogContent>
+ </AlertDialog>
)
}
diff --git a/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-modal.spec.tsx b/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-modal.spec.tsx
index 109d2f9cfea..b4d017d0dfd 100644
--- a/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-modal.spec.tsx
+++ b/web/app/components/datasets/hit-testing/components/__tests__/chunk-detail-modal.spec.tsx
@@ -1,5 +1,5 @@
import type { HitTesting } from '@/models/datasets'
-import { render, screen } from '@testing-library/react'
+import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import ChunkDetailModal from '../chunk-detail-modal'
@@ -11,16 +11,6 @@ vi.mock('@/app/components/base/markdown', () => ({
Markdown: ({ content }: { content: string }) => <div data-testid="markdown">{content}</div>,
}))
-vi.mock('@/app/components/base/modal', () => ({
- default: ({ children, title, onClose }: { children: React.ReactNode, title: string, onClose: () => void }) => (
- <div data-testid="modal">
- <div data-testid="modal-title">{title}</div>
- <button data-testid="modal-close" onClick={onClose}>close</button>
- {children}
- </div>
- ),
-}))
-
vi.mock('../../../common/image-list', () => ({
default: () => <div data-testid="image-list" />,
}))
@@ -85,7 +75,7 @@ describe('ChunkDetailModal', () => {
it('should render modal with title', () => {
render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)
- expect(screen.getByTestId('modal-title')).toHaveTextContent('chunkDetail')
+ expect(screen.getByRole('dialog')).toHaveTextContent('chunkDetail')
})
it('should render segment index tag and score', () => {
@@ -134,4 +124,18 @@ describe('ChunkDetailModal', () => {
render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)
expect(screen.getByTestId('mask')).toBeInTheDocument()
})
+
+ it('should call onHide when close button is clicked', () => {
+ render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)
+ fireEvent.click(screen.getByTestId('modal-close-button'))
+ expect(onHide).toHaveBeenCalled()
+ })
+
+ it('should call onHide when the dialog requests close', () => {
+ render(<ChunkDetailModal payload={makePayload()} onHide={onHide} />)
+
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ expect(onHide).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx b/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx
index ee0d949a7e2..6f789a81ce6 100644
--- a/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx
+++ b/web/app/components/datasets/hit-testing/components/chunk-detail-modal.tsx
@@ -2,12 +2,12 @@
import type { FileAppearanceTypeEnum } from '@/app/components/base/file-uploader/types'
import type { HitTesting } from '@/models/datasets'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import FileIcon from '@/app/components/base/file-uploader/file-type-icon'
import { Markdown } from '@/app/components/base/markdown'
-import Modal from '@/app/components/base/modal'
import Tag from '@/app/components/datasets/documents/detail/completed/common/tag'
import ImageList from '../../common/image-list'
import Dot from '../../documents/detail/completed/common/dot'
@@ -52,93 +52,106 @@ const ChunkDetailModal = ({
const showKeywords = !isParentChildRetrieval && keywords && keywords.length > 0
return (
- <Modal
- title={t(`${i18nPrefix}chunkDetail`, { ns: 'datasetHitTesting' })}
- isShow
- closable
- onClose={onHide}
- className={cn(isParentChildRetrieval ? 'min-w-[1200px]!' : 'min-w-[800px]!')}
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
>
- <div className="mt-4 flex">
- <div className={cn('flex-1', isParentChildRetrieval && 'pr-6')}>
- {/* Meta info */}
- <div className="flex items-center justify-between">
- <div className="flex grow items-center space-x-2">
- <SegmentIndexTag
- labelPrefix={labelPrefix}
- positionId={position}
- className={cn('w-fit group-hover:opacity-100')}
- />
- <Dot />
- <div className="flex grow items-center space-x-1">
- <FileIcon type={extension} size="sm" />
- <span className="w-0 grow truncate text-[13px] font-normal text-text-secondary">{document.name}</span>
+ <DialogContent className={cn('max-h-none overflow-hidden! border-none p-6 text-left align-middle', isParentChildRetrieval ? 'w-[1200px] max-w-none! min-w-[1200px]!' : 'w-[800px] max-w-none! min-w-[800px]!')}>
+ <DialogCloseButton
+ data-testid="modal-close-button"
+ onClick={(e) => {
+ e.stopPropagation()
+ onHide()
+ }}
+ />
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(`${i18nPrefix}chunkDetail`, { ns: 'datasetHitTesting' })}
+ </DialogTitle>
+
+ <div className="mt-4 flex">
+ <div className={cn('flex-1', isParentChildRetrieval && 'pr-6')}>
+ {/* Meta info */}
+ <div className="flex items-center justify-between">
+ <div className="flex grow items-center space-x-2">
+ <SegmentIndexTag
+ labelPrefix={labelPrefix}
+ positionId={position}
+ className={cn('w-fit group-hover:opacity-100')}
+ />
+ <Dot />
+ <div className="flex grow items-center space-x-1">
+ <FileIcon type={extension} size="sm" />
+ <span className="w-0 grow truncate text-[13px] font-normal text-text-secondary">{document.name}</span>
+ </div>
</div>
+ <Score value={score} />
</div>
- <Score value={score} />
- </div>
- {/* Content */}
- <div className="relative">
- {!answer && (
- <Markdown
- className={cn('mt-2! text-text-secondary!', heighClassName)}
- content={sign_content || content}
- customDisallowedElements={['input']}
- />
- )}
- {answer && (
- <div className="break-all">
- <div className="flex gap-x-1">
- <div className="w-4 shrink-0 text-[13px] leading-[20px] font-medium text-text-tertiary">Q</div>
- <div className={cn('line-clamp-20 body-md-regular text-text-secondary')}>
- {content}
+ {/* Content */}
+ <div className="relative">
+ {!answer && (
+ <Markdown
+ className={cn('mt-2! text-text-secondary!', heighClassName)}
+ content={sign_content || content}
+ customDisallowedElements={['input']}
+ />
+ )}
+ {answer && (
+ <div className="break-all">
+ <div className="flex gap-x-1">
+ <div className="w-4 shrink-0 text-[13px] leading-[20px] font-medium text-text-tertiary">Q</div>
+ <div className={cn('line-clamp-20 body-md-regular text-text-secondary')}>
+ {content}
+ </div>
</div>
- </div>
- <div className="flex gap-x-1">
- <div className="w-4 shrink-0 text-[13px] leading-[20px] font-medium text-text-tertiary">A</div>
- <div className={cn('line-clamp-20 body-md-regular text-text-secondary')}>
- {answer}
+ <div className="flex gap-x-1">
+ <div className="w-4 shrink-0 text-[13px] leading-[20px] font-medium text-text-tertiary">A</div>
+ <div className={cn('line-clamp-20 body-md-regular text-text-secondary')}>
+ {answer}
+ </div>
</div>
</div>
+ )}
+ {/* Mask */}
+ <Mask className="absolute inset-x-0 bottom-0" />
+ </div>
+ {(showImages || showKeywords || !!summary) && (
+ <div className="flex flex-col gap-y-3 pt-3">
+ {showImages && (
+ <ImageList images={images} size="md" className="py-1" />
+ )}
+ {!!summary && (
+ <SummaryText value={summary} disabled />
+ )}
+ {showKeywords && (
+ <div className="flex flex-col gap-y-1">
+ <div className="text-xs font-medium text-text-tertiary uppercase">{t(`${i18nPrefix}keyword`, { ns: 'datasetHitTesting' })}</div>
+ <div className="flex flex-wrap gap-x-2">
+ {keywords.map(keyword => (
+ <Tag key={keyword} text={keyword} />
+ ))}
+ </div>
+ </div>
+ )}
</div>
)}
- {/* Mask */}
- <Mask className="absolute inset-x-0 bottom-0" />
</div>
- {(showImages || showKeywords || !!summary) && (
- <div className="flex flex-col gap-y-3 pt-3">
- {showImages && (
- <ImageList images={images} size="md" className="py-1" />
- )}
- {!!summary && (
- <SummaryText value={summary} disabled />
- )}
- {showKeywords && (
- <div className="flex flex-col gap-y-1">
- <div className="text-xs font-medium text-text-tertiary uppercase">{t(`${i18nPrefix}keyword`, { ns: 'datasetHitTesting' })}</div>
- <div className="flex flex-wrap gap-x-2">
- {keywords.map(keyword => (
- <Tag key={keyword} text={keyword} />
- ))}
- </div>
- </div>
- )}
+
+ {isParentChildRetrieval && (
+ <div className="flex-1 pb-6 pl-6">
+ <div className="system-xs-semibold-uppercase text-text-secondary">{t(`${i18nPrefix}hitChunks`, { ns: 'datasetHitTesting', num: child_chunks.length })}</div>
+ <div className={cn('mt-1 space-y-2', heighClassName)}>
+ {child_chunks.map(item => (
+ <ChildChunksItem key={item.id} payload={item} isShowAll />
+ ))}
+ </div>
</div>
)}
</div>
-
- {isParentChildRetrieval && (
- <div className="flex-1 pb-6 pl-6">
- <div className="system-xs-semibold-uppercase text-text-secondary">{t(`${i18nPrefix}hitChunks`, { ns: 'datasetHitTesting', num: child_chunks.length })}</div>
- <div className={cn('mt-1 space-y-2', heighClassName)}>
- {child_chunks.map(item => (
- <ChildChunksItem key={item.id} payload={item} isShowAll />
- ))}
- </div>
- </div>
- )}
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/datasets/hit-testing/components/result-item-external.tsx b/web/app/components/datasets/hit-testing/components/result-item-external.tsx
index 68e99306659..9f68e054d1c 100644
--- a/web/app/components/datasets/hit-testing/components/result-item-external.tsx
+++ b/web/app/components/datasets/hit-testing/components/result-item-external.tsx
@@ -2,11 +2,11 @@
import type { FC } from 'react'
import type { ExternalKnowledgeBaseHitTesting } from '@/models/datasets'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { useBoolean } from 'ahooks'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { FileAppearanceTypeEnum } from '@/app/components/base/file-uploader/types'
-import Modal from '@/app/components/base/modal'
import ResultItemFooter from './result-item-footer'
import ResultItemMeta from './result-item-meta'
@@ -38,20 +38,27 @@ const ResultItemExternal: FC<Props> = ({ payload, positionId }) => {
<ResultItemFooter docType={FileAppearanceTypeEnum.custom} docTitle={title} showDetailModal={showDetailModal} />
{isShowDetailModal && (
- <Modal
- title={t(`${i18nPrefix}chunkDetail`, { ns: 'datasetHitTesting' })}
- className="min-w-[800px]!"
- closable
- onClose={hideDetailModal}
- isShow={isShowDetailModal}
+ <Dialog
+ open={isShowDetailModal}
+ onOpenChange={(open) => {
+ if (!open)
+ hideDetailModal()
+ }}
>
- <div className="mt-4 flex-1">
- <ResultItemMeta labelPrefix="Chunk" positionId={positionId} wordCount={content.length} score={score} />
- <div className={cn('mt-2 body-md-regular break-all text-text-secondary', 'h-[min(539px,80vh)] overflow-y-auto')}>
- {content}
+ <DialogContent className="w-full min-w-[800px]! overflow-hidden! border-none text-left align-middle">
+ <DialogCloseButton data-testid="modal-close-button" />
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(`${i18nPrefix}chunkDetail`, { ns: 'datasetHitTesting' })}
+ </DialogTitle>
+
+ <div className="mt-4 flex-1">
+ <ResultItemMeta labelPrefix="Chunk" positionId={positionId} wordCount={content.length} score={score} />
+ <div className={cn('mt-2 body-md-regular break-all text-text-secondary', 'h-[min(539px,80vh)] overflow-y-auto')}>
+ {content}
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)}
</div>
)
diff --git a/web/app/components/datasets/metadata/base/date-picker.tsx b/web/app/components/datasets/metadata/base/date-picker.tsx
index 79c61469de0..ed583b8411b 100644
--- a/web/app/components/datasets/metadata/base/date-picker.tsx
+++ b/web/app/components/datasets/metadata/base/date-picker.tsx
@@ -70,7 +70,6 @@ const WrappedDatePicker = ({
onClear={handleDateChange}
renderTrigger={renderTrigger}
triggerWrapClassName="w-full"
- popupZIndexClassname="z-1000"
/>
)
}
diff --git a/web/app/components/datasets/metadata/edit-metadata-batch/modal.tsx b/web/app/components/datasets/metadata/edit-metadata-batch/modal.tsx
index f76284b36f8..a8b58755412 100644
--- a/web/app/components/datasets/metadata/edit-metadata-batch/modal.tsx
+++ b/web/app/components/datasets/metadata/edit-metadata-batch/modal.tsx
@@ -2,6 +2,7 @@
import type { FC } from 'react'
import type { BuiltInMetadataItem, MetadataItemInBatchEdit, MetadataItemWithEdit } from '../types'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { produce } from 'immer'
import * as React from 'react'
@@ -11,7 +12,6 @@ import Divider from '@/app/components/base/divider'
import { useCreateMetaData } from '@/service/knowledge/use-metadata'
import Checkbox from '../../../base/checkbox'
import { Infotip } from '../../../base/infotip'
-import Modal from '../../../base/modal'
import AddMetadataButton from '../add-metadata-button'
import useCheckMetadataName from '../hooks/use-check-metadata-name'
import SelectMetadataModal from '../metadata-dataset/select-metadata-modal'
@@ -90,49 +90,62 @@ const EditMetadataBatchModal: FC<Props> = ({ datasetId, documentNum, list, onSav
onSave(templeList.filter(item => item.updateType !== UpdateType.delete), addedList, isApplyToAllSelectDocument)
}, [templeList, addedList, isApplyToAllSelectDocument, onSave])
return (
- <Modal title={t(`${i18nPrefix}.editMetadata`, { ns: 'dataset' })} isShow closable onClose={onHide} className="!max-w-[640px]">
- <div className="mt-1 system-xs-medium text-text-accent">{t(`${i18nPrefix}.editDocumentsNum`, { ns: 'dataset', num: documentNum })}</div>
- <div className="max-h-[305px] overflow-x-hidden overflow-y-auto">
- <div className="mt-4 space-y-2">
- {templeList.map(item => (<EditMetadataBatchItem key={item.id} payload={item} onChange={handleTemplesChange} onRemove={handleTempleItemRemove} onReset={handleItemReset} />))}
- </div>
- <div className="mt-4 pl-[18px]">
- <div className="flex items-center">
- <div className="mr-2 shrink-0 system-xs-medium-uppercase text-text-tertiary">{t('metadata.createMetadata.title', { ns: 'dataset' })}</div>
- <Divider bgStyle="gradient" />
- </div>
- <div className="mt-2 space-y-2">
- {addedList.map((item, i) => (<AddedMetadataItem key={i} payload={item} onChange={handleAddedListChange} onRemove={handleAddedItemRemove(i)} />))}
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
+ >
+ <DialogContent className="w-full !max-w-[640px] overflow-hidden! border-none text-left align-middle">
+ <DialogCloseButton data-testid="modal-close-button" />
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(`${i18nPrefix}.editMetadata`, { ns: 'dataset' })}
+ </DialogTitle>
+
+ <div className="mt-1 system-xs-medium text-text-accent">{t(`${i18nPrefix}.editDocumentsNum`, { ns: 'dataset', num: documentNum })}</div>
+ <div className="max-h-[305px] overflow-x-hidden overflow-y-auto">
+ <div className="mt-4 space-y-2">
+ {templeList.map(item => (<EditMetadataBatchItem key={item.id} payload={item} onChange={handleTemplesChange} onRemove={handleTempleItemRemove} onReset={handleItemReset} />))}
</div>
- <div className="mt-3">
- <SelectMetadataModal datasetId={datasetId} popupPlacement="top-start" popupOffset={{ mainAxis: 4, crossAxis: 0 }} trigger={<AddMetadataButton />} onSave={handleAddMetaData} onSelect={data => setAddedList([...addedList, data as MetadataItemWithEdit])} onManage={onShowManage} />
+ <div className="mt-4 pl-[18px]">
+ <div className="flex items-center">
+ <div className="mr-2 shrink-0 system-xs-medium-uppercase text-text-tertiary">{t('metadata.createMetadata.title', { ns: 'dataset' })}</div>
+ <Divider bgStyle="gradient" />
+ </div>
+ <div className="mt-2 space-y-2">
+ {addedList.map((item, i) => (<AddedMetadataItem key={i} payload={item} onChange={handleAddedListChange} onRemove={handleAddedItemRemove(i)} />))}
+ </div>
+ <div className="mt-3">
+ <SelectMetadataModal datasetId={datasetId} popupPlacement="top-start" popupOffset={{ mainAxis: 4, crossAxis: 0 }} trigger={<AddMetadataButton />} onSave={handleAddMetaData} onSelect={data => setAddedList([...addedList, data as MetadataItemWithEdit])} onManage={onShowManage} />
+ </div>
</div>
</div>
- </div>
- <div className="mt-4 flex items-center justify-between">
- <div className="flex items-center select-none">
- <Checkbox checked={isApplyToAllSelectDocument} onCheck={() => setIsApplyToAllSelectDocument(!isApplyToAllSelectDocument)} id="apply-to-all" />
- <div className="mr-1 ml-2 system-xs-medium text-text-secondary">{t(`${i18nPrefix}.applyToAllSelectDocument`, { ns: 'dataset' })}</div>
- <Infotip
- aria-label={t(`${i18nPrefix}.applyToAllSelectDocumentTip`, { ns: 'dataset' })}
- className="p-px"
- iconClassName="size-3.5 text-text-tertiary"
- popupClassName="max-w-[240px]"
- >
- {t(`${i18nPrefix}.applyToAllSelectDocumentTip`, { ns: 'dataset' })}
- </Infotip>
- </div>
- <div className="flex items-center space-x-2">
- <Button onClick={onHide}>
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button onClick={handleSave} variant="primary">
- {t('operation.save', { ns: 'common' })}
- </Button>
+ <div className="mt-4 flex items-center justify-between">
+ <div className="flex items-center select-none">
+ <Checkbox checked={isApplyToAllSelectDocument} onCheck={() => setIsApplyToAllSelectDocument(!isApplyToAllSelectDocument)} id="apply-to-all" />
+ <div className="mr-1 ml-2 system-xs-medium text-text-secondary">{t(`${i18nPrefix}.applyToAllSelectDocument`, { ns: 'dataset' })}</div>
+ <Infotip
+ aria-label={t(`${i18nPrefix}.applyToAllSelectDocumentTip`, { ns: 'dataset' })}
+ className="p-px"
+ iconClassName="size-3.5 text-text-tertiary"
+ popupClassName="max-w-[240px]"
+ >
+ {t(`${i18nPrefix}.applyToAllSelectDocumentTip`, { ns: 'dataset' })}
+ </Infotip>
+ </div>
+ <div className="flex items-center space-x-2">
+ <Button onClick={onHide}>
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button onClick={handleSave} variant="primary">
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(EditMetadataBatchModal)
diff --git a/web/app/components/datasets/metadata/metadata-dataset/__tests__/create-content.spec.tsx b/web/app/components/datasets/metadata/metadata-dataset/__tests__/create-content.spec.tsx
index 80700617765..da77a50419f 100644
--- a/web/app/components/datasets/metadata/metadata-dataset/__tests__/create-content.spec.tsx
+++ b/web/app/components/datasets/metadata/metadata-dataset/__tests__/create-content.spec.tsx
@@ -1,148 +1,117 @@
+import type { Props as CreateContentProps } from '../create-content'
+import { Popover } from '@langgenius/dify-ui/popover'
import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { DataType } from '../../types'
import CreateContent from '../create-content'
-type ModalLikeWrapProps = {
- children: React.ReactNode
- title: string
- onClose?: () => void
- onConfirm: () => void
- beforeHeader?: React.ReactNode
+const renderCreateContent = (props: CreateContentProps) => {
+ return render(
+ <Popover open>
+ <CreateContent {...props} />
+ </Popover>,
+ )
}
-type OptionCardProps = {
- title: string
- selected: boolean
- onSelect: () => void
-}
-
-type FieldProps = {
- label: string
- children: React.ReactNode
-}
-
-// Mock ModalLikeWrap
-vi.mock('../../../../base/modal-like-wrap', () => ({
- default: ({ children, title, onClose, onConfirm, beforeHeader }: ModalLikeWrapProps) => (
- <div data-testid="modal-wrap">
- <div data-testid="modal-title">{title}</div>
- {!!beforeHeader && <div data-testid="before-header">{beforeHeader}</div>}
- <div data-testid="modal-content">{children}</div>
- <button data-testid="close-btn" onClick={onClose}>Close</button>
- <button data-testid="confirm-btn" onClick={onConfirm}>Confirm</button>
- </div>
- ),
-}))
-
-// Mock OptionCard
-vi.mock('../../../../workflow/nodes/_base/components/option-card', () => ({
- default: ({ title, selected, onSelect }: OptionCardProps) => (
- <button
- data-testid={`option-${title.toLowerCase()}`}
- data-selected={selected}
- onClick={onSelect}
- >
- {title}
- </button>
- ),
-}))
-
-// Mock Field
-vi.mock('../field', () => ({
- default: ({ label, children }: FieldProps) => (
- <div data-testid="field">
- <label data-testid="field-label">{label}</label>
- {children}
- </div>
- ),
-}))
-
describe('CreateContent', () => {
describe('Rendering', () => {
it('should render without crashing', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
- expect(screen.getByTestId('modal-wrap')).toBeInTheDocument()
+ renderCreateContent({ onSave: handleSave })
+ expect(screen.getByText('dataset.metadata.createMetadata.title')).toBeInTheDocument()
})
it('should render modal title', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
- expect(screen.getByTestId('modal-title')).toBeInTheDocument()
+ renderCreateContent({ onSave: handleSave })
+ expect(screen.getByText('dataset.metadata.createMetadata.title')).toBeInTheDocument()
})
it('should render type selection options', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
- expect(screen.getByTestId('option-string')).toBeInTheDocument()
- expect(screen.getByTestId('option-number')).toBeInTheDocument()
- expect(screen.getByTestId('option-time')).toBeInTheDocument()
+ renderCreateContent({ onSave: handleSave })
+ expect(screen.getByText('String')).toBeInTheDocument()
+ expect(screen.getByText('Number')).toBeInTheDocument()
+ expect(screen.getByText('Time')).toBeInTheDocument()
})
it('should render name input field', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
expect(screen.getByRole('textbox')).toBeInTheDocument()
})
it('should render confirm button', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
- expect(screen.getByTestId('confirm-btn')).toBeInTheDocument()
+ renderCreateContent({ onSave: handleSave })
+ expect(screen.getByRole('button', { name: 'common.operation.save' })).toBeInTheDocument()
})
it('should render close button', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
- expect(screen.getByTestId('close-btn')).toBeInTheDocument()
+ renderCreateContent({ onSave: handleSave })
+ expect(screen.getByTestId('modal-close-btn')).toBeInTheDocument()
})
})
describe('Type Selection', () => {
- it('should default to string type', () => {
+ it('should save string type by default', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
- expect(screen.getByTestId('option-string')).toHaveAttribute('data-selected', 'true')
+ renderCreateContent({ onSave: handleSave })
+
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
+
+ expect(handleSave).toHaveBeenCalledWith({
+ type: DataType.string,
+ name: '',
+ })
})
- it('should select number type when clicked', () => {
+ it('should save number type when number is clicked', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
- fireEvent.click(screen.getByTestId('option-number'))
+ fireEvent.click(screen.getByText('Number'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(screen.getByTestId('option-number')).toHaveAttribute('data-selected', 'true')
+ expect(handleSave).toHaveBeenCalledWith({
+ type: DataType.number,
+ name: '',
+ })
})
- it('should select time type when clicked', () => {
+ it('should save time type when time is clicked', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
- fireEvent.click(screen.getByTestId('option-time'))
+ fireEvent.click(screen.getByText('Time'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(screen.getByTestId('option-time')).toHaveAttribute('data-selected', 'true')
+ expect(handleSave).toHaveBeenCalledWith({
+ type: DataType.time,
+ name: '',
+ })
})
- it('should deselect previous type when new type is selected', () => {
+ it('should use the latest selected type when type changes', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
-
- // Initially string is selected
- expect(screen.getByTestId('option-string')).toHaveAttribute('data-selected', 'true')
+ renderCreateContent({ onSave: handleSave })
- // Select number
- fireEvent.click(screen.getByTestId('option-number'))
+ fireEvent.click(screen.getByText('Number'))
+ fireEvent.click(screen.getByText('Time'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(screen.getByTestId('option-string')).toHaveAttribute('data-selected', 'false')
- expect(screen.getByTestId('option-number')).toHaveAttribute('data-selected', 'true')
+ expect(handleSave).toHaveBeenCalledWith({
+ type: DataType.time,
+ name: '',
+ })
})
})
describe('Name Input', () => {
it('should update name when typing', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
const input = screen.getByRole('textbox')
fireEvent.change(input, { target: { value: 'new_field' } })
@@ -152,7 +121,7 @@ describe('CreateContent', () => {
it('should start with empty name', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
expect(screen.getByRole('textbox')).toHaveValue('')
})
@@ -161,11 +130,11 @@ describe('CreateContent', () => {
describe('User Interactions', () => {
it('should call onSave with type and name when confirmed', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
const input = screen.getByRole('textbox')
fireEvent.change(input, { target: { value: 'test_field' } })
- fireEvent.click(screen.getByTestId('confirm-btn'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(handleSave).toHaveBeenCalledWith({
type: DataType.string,
@@ -175,12 +144,12 @@ describe('CreateContent', () => {
it('should call onSave with correct type after changing type', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
- fireEvent.click(screen.getByTestId('option-number'))
+ fireEvent.click(screen.getByText('Number'))
const input = screen.getByRole('textbox')
fireEvent.change(input, { target: { value: 'num_field' } })
- fireEvent.click(screen.getByTestId('confirm-btn'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(handleSave).toHaveBeenCalledWith({
type: DataType.number,
@@ -191,9 +160,9 @@ describe('CreateContent', () => {
it('should call onClose when close button is clicked', () => {
const handleSave = vi.fn()
const handleClose = vi.fn()
- render(<CreateContent onSave={handleSave} onClose={handleClose} />)
+ renderCreateContent({ onSave: handleSave, onClose: handleClose })
- fireEvent.click(screen.getByTestId('close-btn'))
+ fireEvent.click(screen.getByTestId('modal-close-btn'))
expect(handleClose).toHaveBeenCalled()
})
@@ -202,40 +171,35 @@ describe('CreateContent', () => {
describe('Back Button', () => {
it('should show back button when hasBack is true', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} hasBack />)
+ renderCreateContent({ onSave: handleSave, hasBack: true })
- expect(screen.getByTestId('before-header')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /dataset\.metadata\.createMetadata\.back/ })).toBeInTheDocument()
})
it('should not show back button when hasBack is false', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} hasBack={false} />)
+ renderCreateContent({ onSave: handleSave, hasBack: false })
- expect(screen.queryByTestId('before-header')).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /dataset\.metadata\.createMetadata\.back/ })).not.toBeInTheDocument()
})
it('should call onBack when back button is clicked', () => {
const handleSave = vi.fn()
const handleBack = vi.fn()
- render(<CreateContent onSave={handleSave} hasBack onBack={handleBack} />)
+ renderCreateContent({ onSave: handleSave, hasBack: true, onBack: handleBack })
- const backButton = screen.getByTestId('before-header')
- // Find the clickable element inside
- const clickable = backButton.querySelector('.cursor-pointer') || backButton.firstChild
- if (clickable)
- fireEvent.click(clickable)
+ fireEvent.click(screen.getByRole('button', { name: /dataset\.metadata\.createMetadata\.back/ }))
- // The back functionality is tested through the actual implementation
- expect(screen.getByTestId('before-header')).toBeInTheDocument()
+ expect(handleBack).toHaveBeenCalled()
})
})
describe('Edge Cases', () => {
it('should handle empty name submission', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
- fireEvent.click(screen.getByTestId('confirm-btn'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
expect(handleSave).toHaveBeenCalledWith({
type: DataType.string,
@@ -245,19 +209,23 @@ describe('CreateContent', () => {
it('should handle type cycling', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
// Cycle through all types
- fireEvent.click(screen.getByTestId('option-number'))
- fireEvent.click(screen.getByTestId('option-time'))
- fireEvent.click(screen.getByTestId('option-string'))
+ fireEvent.click(screen.getByText('Number'))
+ fireEvent.click(screen.getByText('Time'))
+ fireEvent.click(screen.getByText('String'))
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(screen.getByTestId('option-string')).toHaveAttribute('data-selected', 'true')
+ expect(handleSave).toHaveBeenCalledWith({
+ type: DataType.string,
+ name: '',
+ })
})
it('should handle special characters in name', () => {
const handleSave = vi.fn()
- render(<CreateContent onSave={handleSave} />)
+ renderCreateContent({ onSave: handleSave })
const input = screen.getByRole('textbox')
fireEvent.change(input, { target: { value: 'test_field_123' } })
diff --git a/web/app/components/datasets/metadata/metadata-dataset/__tests__/dataset-metadata-drawer.spec.tsx b/web/app/components/datasets/metadata/metadata-dataset/__tests__/dataset-metadata-drawer.spec.tsx
index 55e5f9de65e..f05bd53b7f0 100644
--- a/web/app/components/datasets/metadata/metadata-dataset/__tests__/dataset-metadata-drawer.spec.tsx
+++ b/web/app/components/datasets/metadata/metadata-dataset/__tests__/dataset-metadata-drawer.spec.tsx
@@ -135,6 +135,19 @@ describe('DatasetMetadataDrawer', () => {
})
describe('User Interactions', () => {
+ it('should call onClose when drawer close button is clicked', async () => {
+ const onClose = vi.fn()
+ render(<DatasetMetadataDrawer {...defaultProps} onClose={onClose} />)
+
+ await waitFor(() => {
+ expect(screen.getByRole('dialog'))!.toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('close-icon'))
+
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
it('should call onIsBuiltInEnabledChange when switch is toggled', async () => {
const onIsBuiltInEnabledChange = vi.fn()
render(
@@ -280,8 +293,8 @@ describe('DatasetMetadataDrawer', () => {
expect(inputs.length).toBeGreaterThan(0)
})
- const inputs = document.querySelectorAll('input')
- fireEvent.change(inputs[0]!, { target: { value: 'renamed_field' } })
+ const input = screen.getByPlaceholderText('dataset.metadata.datasetMetadata.namePlaceholder')
+ fireEvent.change(input, { target: { value: 'renamed_field' } })
// Find and click save button
fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))
@@ -322,8 +335,8 @@ describe('DatasetMetadataDrawer', () => {
})
// Change name first
- const inputs = document.querySelectorAll('input')
- fireEvent.change(inputs[0]!, { target: { value: 'changed_name' } })
+ const input = screen.getByPlaceholderText('dataset.metadata.datasetMetadata.namePlaceholder')
+ fireEvent.change(input, { target: { value: 'changed_name' } })
// Find and click cancel button
fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
@@ -335,7 +348,7 @@ describe('DatasetMetadataDrawer', () => {
})
})
- it('should close rename modal when modal close button is clicked', async () => {
+ it('should close rename modal when dialog requests close', async () => {
render(<DatasetMetadataDrawer {...defaultProps} />)
await waitFor(() => {
@@ -357,23 +370,12 @@ describe('DatasetMetadataDrawer', () => {
expect(inputs.length).toBeGreaterThan(0)
})
- // Find and click the modal close button (X button)
- // The Modal component has a close button in the header
- const dialogs = screen.getAllByRole('dialog')
- const renameModal = dialogs.find(d => d.querySelector('input'))
- if (renameModal) {
- // Find close button by looking for a button with close-related class or X icon
- const closeButtons = renameModal.querySelectorAll('button')
- for (const btn of Array.from(closeButtons)) {
- // Skip cancel/save buttons
- if (!btn.textContent?.toLowerCase().includes('cancel')
- && !btn.textContent?.toLowerCase().includes('save')
- && btn.querySelector('svg')) {
- fireEvent.click(btn)
- break
- }
- }
- }
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ await waitFor(() => {
+ expect(screen.queryByRole('dialog', { name: 'dataset.metadata.datasetMetadata.rename' })).not.toBeInTheDocument()
+ expect(screen.getAllByRole('dialog')).toHaveLength(1)
+ })
})
})
diff --git a/web/app/components/datasets/metadata/metadata-dataset/create-content.tsx b/web/app/components/datasets/metadata/metadata-dataset/create-content.tsx
index ee1b9cbcdc5..b0824d14a96 100644
--- a/web/app/components/datasets/metadata/metadata-dataset/create-content.tsx
+++ b/web/app/components/datasets/metadata/metadata-dataset/create-content.tsx
@@ -1,12 +1,13 @@
'use client'
import type { FC } from 'react'
-import { RiArrowLeftLine } from '@remixicon/react'
+import type { BuiltInMetadataItem } from '../types'
+import { Button } from '@langgenius/dify-ui/button'
+import { PopoverTitle } from '@langgenius/dify-ui/popover'
import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
-import ModalLikeWrap from '../../../base/modal-like-wrap'
import OptionCard from '../../../workflow/nodes/_base/components/option-card'
import { DataType } from '../types'
import Field from './field'
@@ -15,7 +16,7 @@ const i18nPrefix = 'metadata.createMetadata'
export type Props = {
onClose?: () => void
- onSave: (data: any) => void
+ onSave: (data: BuiltInMetadataItem) => void
hasBack?: boolean
onBack?: () => void
}
@@ -45,47 +46,77 @@ const CreateContent: FC<Props> = ({
}, [onSave, type, name])
return (
- <ModalLikeWrap
- title={t(`${i18nPrefix}.title`, { ns: 'dataset' })}
- onClose={onClose}
- onConfirm={handleSave}
- hideCloseBtn={hasBack}
- beforeHeader={hasBack && (
- <div className="relative left-[-4px] mb-1 flex cursor-pointer items-center space-x-1 py-1 text-text-accent" onClick={onBack}>
- <RiArrowLeftLine className="size-4" />
- <div className="system-xs-semibold-uppercase">{t(`${i18nPrefix}.back`, { ns: 'dataset' })}</div>
- </div>
+ <div className="w-[320px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg px-3 pt-3.5 pb-4 shadow-xl">
+ {hasBack && (
+ <button
+ type="button"
+ className="relative left-[-4px] mb-1 flex cursor-pointer items-center space-x-1 py-1 text-text-accent"
+ onClick={onBack}
+ >
+ <span className="i-ri-arrow-left-line size-4" />
+ <span className="system-xs-semibold-uppercase">{t(`${i18nPrefix}.back`, { ns: 'dataset' })}</span>
+ </button>
)}
- >
- <div className="space-y-3">
- <Field label={t(`${i18nPrefix}.type`, { ns: 'dataset' })}>
- <div className="grid grid-cols-3 gap-2">
- <OptionCard
- title="String"
- selected={type === DataType.string}
- onSelect={handleTypeChange(DataType.string)}
- />
- <OptionCard
- title="Number"
- selected={type === DataType.number}
- onSelect={handleTypeChange(DataType.number)}
- />
- <OptionCard
- title="Time"
- selected={type === DataType.time}
- onSelect={handleTypeChange(DataType.time)}
+ <div className="mb-1 flex h-6 items-center justify-between">
+ <PopoverTitle className="system-xl-semibold text-text-primary">
+ {t(`${i18nPrefix}.title`, { ns: 'dataset' })}
+ </PopoverTitle>
+ {!hasBack && (
+ <button
+ type="button"
+ aria-label={t('operation.close', { ns: 'common' })}
+ className="cursor-pointer p-1.5 text-text-tertiary"
+ onClick={onClose}
+ >
+ <span className="i-ri-close-line size-4" data-testid="modal-close-btn" />
+ </button>
+ )}
+ </div>
+ <div className="mt-2">
+ <div className="space-y-3">
+ <Field label={t(`${i18nPrefix}.type`, { ns: 'dataset' })}>
+ <div className="grid grid-cols-3 gap-2">
+ <OptionCard
+ title="String"
+ selected={type === DataType.string}
+ onSelect={handleTypeChange(DataType.string)}
+ />
+ <OptionCard
+ title="Number"
+ selected={type === DataType.number}
+ onSelect={handleTypeChange(DataType.number)}
+ />
+ <OptionCard
+ title="Time"
+ selected={type === DataType.time}
+ onSelect={handleTypeChange(DataType.time)}
+ />
+ </div>
+ </Field>
+ <Field label={t(`${i18nPrefix}.name`, { ns: 'dataset' })}>
+ <Input
+ value={name}
+ onChange={handleNameChange}
+ placeholder={t(`${i18nPrefix}.namePlaceholder`, { ns: 'dataset' })}
/>
- </div>
- </Field>
- <Field label={t(`${i18nPrefix}.name`, { ns: 'dataset' })}>
- <Input
- value={name}
- onChange={handleNameChange}
- placeholder={t(`${i18nPrefix}.namePlaceholder`, { ns: 'dataset' })}
- />
- </Field>
+ </Field>
+ </div>
+ </div>
+ <div className="mt-4 flex justify-end">
+ <Button
+ className="mr-2"
+ onClick={onClose}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ onClick={handleSave}
+ variant="primary"
+ >
+ {t('operation.save', { ns: 'common' })}
+ </Button>
</div>
- </ModalLikeWrap>
+ </div>
)
}
export default React.memo(CreateContent)
diff --git a/web/app/components/datasets/metadata/metadata-dataset/create-metadata-modal.tsx b/web/app/components/datasets/metadata/metadata-dataset/create-metadata-modal.tsx
index 687266eed98..fad6fd6bb46 100644
--- a/web/app/components/datasets/metadata/metadata-dataset/create-metadata-modal.tsx
+++ b/web/app/components/datasets/metadata/metadata-dataset/create-metadata-modal.tsx
@@ -8,7 +8,6 @@ import CreateContent from './create-content'
type Props = {
open: boolean
setOpen: (open: boolean) => void
- onSave: (data: any) => void
trigger: React.ReactNode
popupLeft?: number
} & CreateContentProps
diff --git a/web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx b/web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx
index 69a8712c67b..b6597e5f510 100644
--- a/web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx
+++ b/web/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer.tsx
@@ -12,6 +12,17 @@ import {
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import {
+ Drawer,
+ DrawerBackdrop,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerPopup,
+ DrawerPortal,
+ DrawerTitle,
+ DrawerViewport,
+} from '@langgenius/dify-ui/drawer'
import { Switch } from '@langgenius/dify-ui/switch'
import { toast } from '@langgenius/dify-ui/toast'
import { RiAddLine, RiDeleteBinLine, RiEditLine } from '@remixicon/react'
@@ -19,10 +30,8 @@ import { useBoolean, useHover } from 'ahooks'
import * as React from 'react'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Drawer from '@/app/components/base/drawer'
import { Infotip } from '@/app/components/base/infotip'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import CreateModal from '@/app/components/datasets/metadata/metadata-dataset/create-metadata-modal'
import { getIcon } from '../utils/get-icon'
import Field from './field'
@@ -149,7 +158,7 @@ const DatasetMetadataDrawer: FC<Props> = ({
}, [setCurrPayload, setIsShowRenameModal])
const [open, setOpen] = useState(false)
- const handleAdd = useCallback(async (data: MetadataItemWithValueLength) => {
+ const handleAdd = useCallback(async (data: BuiltInMetadataItem) => {
await onAdd(data)
toast.success(t('api.actionSuccess', { ns: 'common' }))
setOpen(false)
@@ -176,91 +185,123 @@ const DatasetMetadataDrawer: FC<Props> = ({
return (
<Drawer
- isOpen={true}
- onClose={onClose}
- showClose
- title={t('metadata.metadata', { ns: 'dataset' })}
- footer={null}
- panelClassName="px-4 block max-w-[420px]! my-2 rounded-l-2xl"
+ open
+ modal
+ swipeDirection="right"
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className="h-full overflow-y-auto">
- <div className="system-sm-regular text-text-tertiary">{t(`${i18nPrefix}.description`, { ns: 'dataset' })}</div>
- <CreateModal
- open={open}
- setOpen={setOpen}
- trigger={(
- <Button variant="primary" className="mt-3">
- <RiAddLine className="mr-1" />
- {t(`${i18nPrefix}.addMetaData`, { ns: 'dataset' })}
- </Button>
- )}
- hasBack
- onSave={handleAdd}
- />
+ <DrawerPortal>
+ <DrawerBackdrop />
+ <DrawerViewport>
+ <DrawerPopup className="data-[swipe-direction=right]:top-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-[calc(100dvh-16px)] data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-[420px]">
+ <DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">
+ <div className="flex shrink-0 justify-between px-4 pt-6 pb-4">
+ <DrawerTitle className="text-lg leading-6 font-medium text-text-primary">
+ {t('metadata.metadata', { ns: 'dataset' })}
+ </DrawerTitle>
+ <DrawerCloseButton
+ aria-label={t('operation.close', { ns: 'common' })}
+ className="h-6 w-6 rounded-md"
+ data-testid="close-icon"
+ />
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-6">
+ <div className="system-sm-regular text-text-tertiary">{t(`${i18nPrefix}.description`, { ns: 'dataset' })}</div>
+ <CreateModal
+ open={open}
+ setOpen={setOpen}
+ trigger={(
+ <Button variant="primary" className="mt-3">
+ <RiAddLine className="mr-1" />
+ {t(`${i18nPrefix}.addMetaData`, { ns: 'dataset' })}
+ </Button>
+ )}
+ hasBack
+ onSave={handleAdd}
+ />
- <div className="mt-3 space-y-1">
- {userMetadata.map(payload => (
- <Item
- key={payload.id}
- payload={payload}
- onRename={handleRename(payload)}
- onDelete={handleDelete(payload)}
- />
- ))}
- </div>
+ <div className="mt-3 space-y-1">
+ {userMetadata.map(payload => (
+ <Item
+ key={payload.id}
+ payload={payload}
+ onRename={handleRename(payload)}
+ onDelete={handleDelete(payload)}
+ />
+ ))}
+ </div>
- <div className="mt-3 flex h-6 items-center">
- <Switch
- checked={isBuiltInEnabled}
- onCheckedChange={onIsBuiltInEnabledChange}
- />
- <div className="mr-0.5 ml-2 system-sm-semibold text-text-secondary">{t(`${i18nPrefix}.builtIn`, { ns: 'dataset' })}</div>
- <Infotip aria-label={t(`${i18nPrefix}.builtInDescription`, { ns: 'dataset' })} popupClassName="max-w-[100px]">
- {t(`${i18nPrefix}.builtInDescription`, { ns: 'dataset' })}
- </Infotip>
- </div>
+ <div className="mt-3 flex h-6 items-center">
+ <Switch
+ checked={isBuiltInEnabled}
+ onCheckedChange={onIsBuiltInEnabledChange}
+ />
+ <div className="mr-0.5 ml-2 system-sm-semibold text-text-secondary">{t(`${i18nPrefix}.builtIn`, { ns: 'dataset' })}</div>
+ <Infotip aria-label={t(`${i18nPrefix}.builtInDescription`, { ns: 'dataset' })} popupClassName="max-w-[100px]">
+ {t(`${i18nPrefix}.builtInDescription`, { ns: 'dataset' })}
+ </Infotip>
+ </div>
- <div className="mt-1 space-y-1">
- {builtInMetadata.map(payload => (
- <Item
- key={payload.name}
- readonly
- disabled={!isBuiltInEnabled}
- payload={payload as MetadataItemWithValueLength}
- />
- ))}
- </div>
+ <div className="mt-1 space-y-1">
+ {builtInMetadata.map(payload => (
+ <Item
+ key={payload.name}
+ readonly
+ disabled={!isBuiltInEnabled}
+ payload={payload as MetadataItemWithValueLength}
+ />
+ ))}
+ </div>
- {isShowRenameModal && (
- <Modal isShow title={t(`${i18nPrefix}.rename`, { ns: 'dataset' })} onClose={() => setIsShowRenameModal(false)}>
- <Field label={t(`${i18nPrefix}.name`, { ns: 'dataset' })} className="mt-4">
- <Input
- value={templeName}
- onChange={e => setTempleName(e.target.value)}
- placeholder={t(`${i18nPrefix}.namePlaceholder`, { ns: 'dataset' })}
- />
- </Field>
- <div className="mt-4 flex justify-end">
- <Button
- className="mr-2"
- onClick={() => {
- setIsShowRenameModal(false)
- setTempleName(currPayload!.name)
- }}
- >
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button
- onClick={handleRenamed}
- variant="primary"
- disabled={!templeName}
- >
- {t('operation.save', { ns: 'common' })}
- </Button>
- </div>
- </Modal>
- )}
- </div>
+ {isShowRenameModal && (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ setIsShowRenameModal(false)
+ }}
+ >
+ <DialogContent className="overflow-hidden! border-none text-left align-middle">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(`${i18nPrefix}.rename`, { ns: 'dataset' })}
+ </DialogTitle>
+
+ <Field label={t(`${i18nPrefix}.name`, { ns: 'dataset' })} className="mt-4">
+ <Input
+ value={templeName}
+ onChange={e => setTempleName(e.target.value)}
+ placeholder={t(`${i18nPrefix}.namePlaceholder`, { ns: 'dataset' })}
+ />
+ </Field>
+ <div className="mt-4 flex justify-end">
+ <Button
+ className="mr-2"
+ onClick={() => {
+ setIsShowRenameModal(false)
+ setTempleName(currPayload!.name)
+ }}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ onClick={handleRenamed}
+ variant="primary"
+ disabled={!templeName}
+ >
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )}
+ </div>
+ </DrawerContent>
+ </DrawerPopup>
+ </DrawerViewport>
+ </DrawerPortal>
</Drawer>
)
}
diff --git a/web/app/components/datasets/metadata/metadata-dataset/select-metadata-modal.tsx b/web/app/components/datasets/metadata/metadata-dataset/select-metadata-modal.tsx
index e0ed692677c..352b95f2486 100644
--- a/web/app/components/datasets/metadata/metadata-dataset/select-metadata-modal.tsx
+++ b/web/app/components/datasets/metadata/metadata-dataset/select-metadata-modal.tsx
@@ -1,7 +1,7 @@
'use client'
import type { Placement } from '@langgenius/dify-ui/popover'
import type { FC } from 'react'
-import type { MetadataItem } from '../types'
+import type { BuiltInMetadataItem, MetadataItem } from '../types'
import type { Props as CreateContentProps } from './create-content'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import * as React from 'react'
@@ -15,15 +15,16 @@ type Props = {
popupPlacement?: Placement
popupOffset?: { mainAxis: number, crossAxis: number }
onSelect: (data: MetadataItem) => void
- onSave: (data: MetadataItem) => void
trigger: React.ReactNode
onManage: () => void
} & CreateContentProps
-enum Step {
- select = 'select',
- create = 'create',
-}
+const Step = {
+ select: 'select',
+ create: 'create',
+} as const
+
+type Step = typeof Step[keyof typeof Step]
const SelectMetadataModal: FC<Props> = ({
datasetId,
@@ -37,7 +38,7 @@ const SelectMetadataModal: FC<Props> = ({
const { data: datasetMetaData } = useDatasetMetaData(datasetId)
const [open, setOpen] = useState(false)
- const [step, setStep] = useState(Step.select)
+ const [step, setStep] = useState<Step>(Step.select)
const triggerElement = React.isValidElement(trigger)
? trigger
: <button type="button">{trigger}</button>
@@ -47,7 +48,7 @@ const SelectMetadataModal: FC<Props> = ({
setStep(Step.select)
}, [])
- const handleSave = useCallback(async (data: MetadataItem) => {
+ const handleSave = useCallback(async (data: BuiltInMetadataItem) => {
await onSave(data)
setStep(Step.select)
}, [onSave])
diff --git a/web/app/components/datasets/metadata/metadata-document/info-group.tsx b/web/app/components/datasets/metadata/metadata-document/info-group.tsx
index 16f5e573fb3..5d174b25341 100644
--- a/web/app/components/datasets/metadata/metadata-document/info-group.tsx
+++ b/web/app/components/datasets/metadata/metadata-document/info-group.tsx
@@ -1,6 +1,6 @@
'use client'
import type { FC } from 'react'
-import type { MetadataItemWithValue } from '../types'
+import type { BuiltInMetadataItem, MetadataItemWithValue } from '../types'
import { cn } from '@langgenius/dify-ui/cn'
import { RiDeleteBinLine } from '@remixicon/react'
import * as React from 'react'
@@ -29,7 +29,7 @@ type Props = {
onChange?: (item: MetadataItemWithValue) => void
onDelete?: (item: MetadataItemWithValue) => void
onSelect?: (item: MetadataItemWithValue) => void
- onAdd?: (item: MetadataItemWithValue) => void
+ onAdd?: (item: BuiltInMetadataItem) => void
}
const InfoGroup: FC<Props> = ({
diff --git a/web/app/components/datasets/rename-modal/index.tsx b/web/app/components/datasets/rename-modal/index.tsx
index a62c1c93bee..ae8f9f5d6af 100644
--- a/web/app/components/datasets/rename-modal/index.tsx
+++ b/web/app/components/datasets/rename-modal/index.tsx
@@ -4,13 +4,12 @@ import type { AppIconSelection } from '../../base/app-icon-picker'
import type { DataSet } from '@/models/datasets'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { RiCloseLine } from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import Textarea from '@/app/components/base/textarea'
import { updateDatasetSetting } from '@/service/datasets'
import AppIcon from '../../base/app-icon'
@@ -89,38 +88,41 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDataset
}
}, [appIcon, description, dataset.id, externalKnowledgeApiId, externalKnowledgeId, name, onClose, onSuccess, t])
return (
- <Modal className="w-[520px] max-w-[520px] rounded-xl px-8 py-6" isShow={show} onClose={noop}>
- <div className="flex items-center justify-between pb-2">
- <div className="text-xl leading-[30px] font-medium text-text-primary">{t('title', { ns: 'datasetSettings' })}</div>
- <div className="cursor-pointer p-2" onClick={onClose}>
- <RiCloseLine className="h-4 w-4 text-text-tertiary" />
- </div>
- </div>
- <div>
- <div className={cn('flex flex-col py-4')}>
- <div className="shrink-0 py-2 text-sm leading-[20px] font-medium text-text-primary">
- {t('form.name', { ns: 'datasetSettings' })}
- </div>
- <div className="flex items-center gap-x-2">
- <AppIcon size="medium" onClick={handleOpenAppIconPicker} className="cursor-pointer" iconType={appIcon.type} icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon} background={appIcon.type === 'image' ? undefined : appIcon.background} imageUrl={appIcon.type === 'image' ? appIcon.url : undefined} showEditIcon />
- <Input value={name} onChange={e => setName(e.target.value)} className="h-9 grow" placeholder={t('form.namePlaceholder', { ns: 'datasetSettings' }) || ''} />
+ <Dialog open={show}>
+ <DialogContent className="w-full max-w-[520px] overflow-hidden! rounded-xl border-none px-8 py-6 text-left align-middle">
+
+ <div className="flex items-center justify-between pb-2">
+ <div className="text-xl leading-[30px] font-medium text-text-primary">{t('title', { ns: 'datasetSettings' })}</div>
+ <div className="cursor-pointer p-2" onClick={onClose}>
+ <RiCloseLine className="h-4 w-4 text-text-tertiary" />
</div>
</div>
- <div className={cn('flex flex-col py-4')}>
- <div className="shrink-0 py-2 text-sm leading-[20px] font-medium text-text-primary">
- {t('form.desc', { ns: 'datasetSettings' })}
+ <div>
+ <div className={cn('flex flex-col py-4')}>
+ <div className="shrink-0 py-2 text-sm leading-[20px] font-medium text-text-primary">
+ {t('form.name', { ns: 'datasetSettings' })}
+ </div>
+ <div className="flex items-center gap-x-2">
+ <AppIcon size="medium" onClick={handleOpenAppIconPicker} className="cursor-pointer" iconType={appIcon.type} icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon} background={appIcon.type === 'image' ? undefined : appIcon.background} imageUrl={appIcon.type === 'image' ? appIcon.url : undefined} showEditIcon />
+ <Input value={name} onChange={e => setName(e.target.value)} className="h-9 grow" placeholder={t('form.namePlaceholder', { ns: 'datasetSettings' }) || ''} />
+ </div>
</div>
- <div className="w-full">
- <Textarea value={description} onChange={e => setDescription(e.target.value)} className="resize-none" placeholder={t('form.descPlaceholder', { ns: 'datasetSettings' }) || ''} />
+ <div className={cn('flex flex-col py-4')}>
+ <div className="shrink-0 py-2 text-sm leading-[20px] font-medium text-text-primary">
+ {t('form.desc', { ns: 'datasetSettings' })}
+ </div>
+ <div className="w-full">
+ <Textarea value={description} onChange={e => setDescription(e.target.value)} className="resize-none" placeholder={t('form.descPlaceholder', { ns: 'datasetSettings' }) || ''} />
+ </div>
</div>
</div>
- </div>
- <div className="flex justify-end pt-6">
- <Button className="mr-2" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button disabled={loading} variant="primary" onClick={onConfirm}>{t('operation.save', { ns: 'common' })}</Button>
- </div>
- {showAppIconPicker && (<AppIconPicker onSelect={handleSelectAppIcon} onClose={handleCloseAppIconPicker} />)}
- </Modal>
+ <div className="flex justify-end pt-6">
+ <Button className="mr-2" onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button disabled={loading} variant="primary" onClick={onConfirm}>{t('operation.save', { ns: 'common' })}</Button>
+ </div>
+ {showAppIconPicker && (<AppIconPicker onSelect={handleSelectAppIcon} onClose={handleCloseAppIconPicker} />)}
+ </DialogContent>
+ </Dialog>
)
}
export default RenameDatasetModal
diff --git a/web/app/components/develop/secret-key/__tests__/secret-key-modal.spec.tsx b/web/app/components/develop/secret-key/__tests__/secret-key-modal.spec.tsx
index 333ef451622..0dbf7318b2b 100644
--- a/web/app/components/develop/secret-key/__tests__/secret-key-modal.spec.tsx
+++ b/web/app/components/develop/secret-key/__tests__/secret-key-modal.spec.tsx
@@ -88,7 +88,7 @@ describe('SecretKeyModal', () => {
beforeEach(() => {
vi.clearAllMocks()
- // Suppress expected React act() warnings from Headless UI Dialog transitions and async API state updates
+ // Suppress expected React act() warnings from modal transitions and async API state updates.
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.useFakeTimers({ shouldAdvanceTime: true })
mockCurrentWorkspace.mockReturnValue({ id: 'workspace-1', name: 'Test Workspace' })
@@ -290,6 +290,36 @@ describe('SecretKeyModal', () => {
})
})
+ it('should place the generated key backdrop above the API keys modal', async () => {
+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
+ mockAppApiKeysData.mockReturnValue({
+ data: [
+ { id: 'key-1', token: 'sk-abc123def456ghi789', created_at: 1700000000, last_used_at: null },
+ ],
+ })
+ await renderModal(<SecretKeyModal {...defaultProps} appId="app-123" />)
+
+ const createButton = screen.getByText('appApi.apiKeyModal.createNewSecretKey')
+ await act(async () => {
+ await user.click(createButton)
+ })
+
+ await waitFor(() => {
+ expect(screen.getByText('appApi.apiKeyModal.generateTips')).toBeInTheDocument()
+ })
+
+ const parentDialog = screen.getByText('appApi.apiKeyModal.apiSecretKeyTips').closest('[role="dialog"]')
+ const generatedKeyDialog = screen.getByText('appApi.apiKeyModal.generateTips').closest('[role="dialog"]')
+ const backdrops = document.body.querySelectorAll('.bg-background-overlay')
+ const generatedKeyBackdrop = backdrops[1]
+
+ expect(parentDialog).toBeInTheDocument()
+ expect(generatedKeyDialog).toBeInTheDocument()
+ expect(backdrops).toHaveLength(2)
+ expect(parentDialog!.compareDocumentPosition(generatedKeyBackdrop!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ expect(generatedKeyBackdrop!.compareDocumentPosition(generatedKeyDialog!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ })
+
it('should invalidate app API keys after creating', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
await renderModal(<SecretKeyModal {...defaultProps} appId="app-123" />)
diff --git a/web/app/components/develop/secret-key/secret-key-generate.tsx b/web/app/components/develop/secret-key/secret-key-generate.tsx
index 1fb6e657144..cc9b4c778df 100644
--- a/web/app/components/develop/secret-key/secret-key-generate.tsx
+++ b/web/app/components/develop/secret-key/secret-key-generate.tsx
@@ -2,8 +2,9 @@
import type { CreateApiKeyResponse } from '@/models/app'
import { XMarkIcon } from '@heroicons/react/20/solid'
import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import InputCopy from './input-copy'
import s from './style.module.css'
@@ -22,21 +23,33 @@ const SecretKeyGenerateModal = ({
}: ISecretKeyGenerateModalProps) => {
const { t } = useTranslation()
return (
- <Modal isShow={isShow} onClose={onClose} title={`${t('apiKeyModal.apiSecretKey', { ns: 'appApi' })}`} className={`px-8 ${className}`}>
- <div className="-mt-6 -mr-2 mb-4 flex justify-end">
- <XMarkIcon className="h-6 w-6 cursor-pointer text-text-tertiary" onClick={onClose} />
- </div>
- <p className="mt-1 text-[13px] leading-5 font-normal text-text-tertiary">{t('apiKeyModal.generateTips', { ns: 'appApi' })}</p>
- <div className="my-4">
- <InputCopy className="w-full" value={newKey?.token} />
- </div>
- <div className="my-4 flex justify-end">
- <Button className={`shrink-0 ${s.w64}`} onClick={onClose}>
- <span className="text-xs font-medium text-text-secondary">{t('actionMsg.ok', { ns: 'appApi' })}</span>
- </Button>
- </div>
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
+ >
+ <DialogContent className={cn('w-full max-w-[480px] overflow-hidden! border-none px-8 text-left align-middle', className)}>
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {`${t('apiKeyModal.apiSecretKey', { ns: 'appApi' })}`}
+ </DialogTitle>
- </Modal>
+ <div className="-mt-6 -mr-2 mb-4 flex justify-end">
+ <XMarkIcon className="h-6 w-6 cursor-pointer text-text-tertiary" onClick={onClose} />
+ </div>
+ <p className="mt-1 text-[13px] leading-5 font-normal text-text-tertiary">{t('apiKeyModal.generateTips', { ns: 'appApi' })}</p>
+ <div className="my-4">
+ <InputCopy className="w-full" value={newKey?.token} />
+ </div>
+ <div className="my-4 flex justify-end">
+ <Button className={`shrink-0 ${s.w64}`} onClick={onClose}>
+ <span className="text-xs font-medium text-text-secondary">{t('actionMsg.ok', { ns: 'appApi' })}</span>
+ </Button>
+ </div>
+
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/develop/secret-key/secret-key-modal.tsx b/web/app/components/develop/secret-key/secret-key-modal.tsx
index e8d92043184..71cb87019cd 100644
--- a/web/app/components/develop/secret-key/secret-key-modal.tsx
+++ b/web/app/components/develop/secret-key/secret-key-modal.tsx
@@ -11,6 +11,8 @@ import {
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { RiDeleteBinLine } from '@remixicon/react'
import {
useState,
@@ -19,7 +21,6 @@ import { useTranslation } from 'react-i18next'
import ActionButton from '@/app/components/base/action-button'
import CopyFeedback from '@/app/components/base/copy-feedback'
import Loading from '@/app/components/base/loading'
-import Modal from '@/app/components/base/modal'
import { useAppContext } from '@/context/app-context'
import useTimestamp from '@/hooks/use-timestamp'
import {
@@ -103,78 +104,99 @@ const SecretKeyModal = ({
setShowConfirmDelete(false)
}
+ const handleClose = () => {
+ setVisible(false)
+ onClose()
+ }
+
return (
- <Modal isShow={isShow} onClose={onClose} title={`${t('apiKeyModal.apiSecretKey', { ns: 'appApi' })}`} className={`${s.customModal} flex flex-col px-8`}>
- <div className="-mt-6 -mr-2 mb-4 flex justify-end">
- <XMarkIcon className="h-6 w-6 cursor-pointer text-text-tertiary" onClick={onClose} />
- </div>
- <p className="mt-1 shrink-0 text-[13px] leading-5 font-normal text-text-tertiary">{t('apiKeyModal.apiSecretKeyTips', { ns: 'appApi' })}</p>
- {isApiKeysLoading && <div className="mt-4"><Loading /></div>}
- {
- !!apiKeysList?.data?.length && (
- <div className="mt-4 flex grow flex-col overflow-hidden">
- <div className="flex h-9 shrink-0 items-center border-b border-divider-regular text-xs font-semibold text-text-tertiary">
- <div className="w-64 shrink-0 px-3">{t('apiKeyModal.secretKey', { ns: 'appApi' })}</div>
- <div className="w-[200px] shrink-0 px-3">{t('apiKeyModal.created', { ns: 'appApi' })}</div>
- <div className="w-[200px] shrink-0 px-3">{t('apiKeyModal.lastUsed', { ns: 'appApi' })}</div>
- <div className="grow px-3"></div>
- </div>
- <div className="grow overflow-auto">
- {apiKeysList.data.map(api => (
- <div className="flex h-9 items-center border-b border-divider-regular text-sm font-normal text-text-secondary" key={api.id}>
- <div className="w-64 shrink-0 truncate px-3 font-mono">{generateToken(api.token)}</div>
- <div className="w-[200px] shrink-0 truncate px-3">{formatTime(Number(api.created_at), t('dateTimeFormat', { ns: 'appLog' }) as string)}</div>
- <div className="w-[200px] shrink-0 truncate px-3">{api.last_used_at ? formatTime(Number(api.last_used_at), t('dateTimeFormat', { ns: 'appLog' }) as string) : t('never', { ns: 'appApi' })}</div>
- <div className="flex grow space-x-2 px-3">
- <CopyFeedback content={api.token} />
- {isCurrentWorkspaceManager && (
- <ActionButton
- onClick={() => {
- setDelKeyId(api.id)
- setShowConfirmDelete(true)
- }}
- >
- <RiDeleteBinLine className="h-4 w-4" />
- </ActionButton>
- )}
- </div>
- </div>
- ))}
- </div>
- </div>
- )
- }
- <div className="flex">
- <Button className={`mt-4 flex shrink-0 ${s.autoWidth}`} onClick={onCreate} disabled={!currentWorkspace || !isCurrentWorkspaceEditor}>
- <PlusIcon className="mr-1 flex h-4 w-4 shrink-0" />
- <div className="text-xs font-medium text-text-secondary">{t('apiKeyModal.createNewSecretKey', { ns: 'appApi' })}</div>
- </Button>
- </div>
- <SecretKeyGenerateModal className="shrink-0" isShow={isVisible} onClose={() => setVisible(false)} newKey={newKey} />
- <AlertDialog
- open={showConfirmDelete}
- onOpenChange={handleDeleteConfirmOpenChange}
+ <>
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ handleClose()
+ }}
>
- <AlertDialogContent>
- <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
- <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
- {t('actionMsg.deleteConfirmTitle', { ns: 'appApi' })}
- </AlertDialogTitle>
- <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
- {t('actionMsg.deleteConfirmTips', { ns: 'appApi' })}
- </AlertDialogDescription>
+ <DialogContent className={cn('max-h-[calc(100vh-80px)]! w-full max-w-[800px]! overflow-hidden! border-none text-left align-middle', `${s.customModal} flex flex-col px-8`)}>
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {`${t('apiKeyModal.apiSecretKey', { ns: 'appApi' })}`}
+ </DialogTitle>
+
+ <div className="-mt-6 -mr-2 mb-4 flex justify-end">
+ <XMarkIcon className="h-6 w-6 cursor-pointer text-text-tertiary" onClick={handleClose} />
+ </div>
+ <p className="mt-1 shrink-0 text-[13px] leading-5 font-normal text-text-tertiary">{t('apiKeyModal.apiSecretKeyTips', { ns: 'appApi' })}</p>
+ {isApiKeysLoading && <div className="mt-4"><Loading /></div>}
+ {
+ !!apiKeysList?.data?.length && (
+ <div className="mt-4 flex grow flex-col overflow-hidden">
+ <div className="flex h-9 shrink-0 items-center border-b border-divider-regular text-xs font-semibold text-text-tertiary">
+ <div className="w-64 shrink-0 px-3">{t('apiKeyModal.secretKey', { ns: 'appApi' })}</div>
+ <div className="w-[200px] shrink-0 px-3">{t('apiKeyModal.created', { ns: 'appApi' })}</div>
+ <div className="w-[200px] shrink-0 px-3">{t('apiKeyModal.lastUsed', { ns: 'appApi' })}</div>
+ <div className="grow px-3"></div>
+ </div>
+ <div className="grow overflow-auto">
+ {apiKeysList.data.map(api => (
+ <div className="flex h-9 items-center border-b border-divider-regular text-sm font-normal text-text-secondary" key={api.id}>
+ <div className="w-64 shrink-0 truncate px-3 font-mono">{generateToken(api.token)}</div>
+ <div className="w-[200px] shrink-0 truncate px-3">{formatTime(Number(api.created_at), t('dateTimeFormat', { ns: 'appLog' }) as string)}</div>
+ <div className="w-[200px] shrink-0 truncate px-3">{api.last_used_at ? formatTime(Number(api.last_used_at), t('dateTimeFormat', { ns: 'appLog' }) as string) : t('never', { ns: 'appApi' })}</div>
+ <div className="flex grow space-x-2 px-3">
+ <CopyFeedback content={api.token} />
+ {isCurrentWorkspaceManager && (
+ <ActionButton
+ onClick={() => {
+ setDelKeyId(api.id)
+ setShowConfirmDelete(true)
+ }}
+ >
+ <RiDeleteBinLine className="h-4 w-4" />
+ </ActionButton>
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+ }
+ <div className="flex">
+ <Button className={`mt-4 flex shrink-0 ${s.autoWidth}`} onClick={onCreate} disabled={!currentWorkspace || !isCurrentWorkspaceEditor}>
+ <PlusIcon className="mr-1 flex h-4 w-4 shrink-0" />
+ <div className="text-xs font-medium text-text-secondary">{t('apiKeyModal.createNewSecretKey', { ns: 'appApi' })}</div>
+ </Button>
</div>
- <AlertDialogActions>
- <AlertDialogCancelButton>
- {t('operation.cancel', { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton onClick={onDel}>
- {t('operation.confirm', { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogActions>
- </AlertDialogContent>
- </AlertDialog>
- </Modal>
+ <AlertDialog
+ open={showConfirmDelete}
+ onOpenChange={handleDeleteConfirmOpenChange}
+ >
+ <AlertDialogContent>
+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
+ {t('actionMsg.deleteConfirmTitle', { ns: 'appApi' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
+ {t('actionMsg.deleteConfirmTips', { ns: 'appApi' })}
+ </AlertDialogDescription>
+ </div>
+ <AlertDialogActions>
+ <AlertDialogCancelButton>
+ {t('operation.cancel', { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton onClick={onDel}>
+ {t('operation.confirm', { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
+ </DialogContent>
+ </Dialog>
+ {isShow && (
+ <SecretKeyGenerateModal className="shrink-0" isShow={isVisible} onClose={() => setVisible(false)} newKey={newKey} />
+ )}
+ </>
)
}
diff --git a/web/app/components/explore/try-app/__tests__/index.spec.tsx b/web/app/components/explore/try-app/__tests__/index.spec.tsx
index b93598b64aa..84d6332e67a 100644
--- a/web/app/components/explore/try-app/__tests__/index.spec.tsx
+++ b/web/app/components/explore/try-app/__tests__/index.spec.tsx
@@ -120,6 +120,42 @@ describe('TryApp (main index.tsx)', () => {
expect(document.body.querySelector('[role="status"]')).toBeInTheDocument()
})
+
+ it('renders unavailable state when the app detail request fails', () => {
+ mockUseGetTryAppInfo.mockReturnValue({
+ data: null,
+ isError: true,
+ error: new Error('App is unavailable'),
+ })
+
+ render(
+ <TryApp
+ appId="test-app-id"
+ onClose={vi.fn()}
+ onCreate={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText('App is unavailable')).toBeInTheDocument()
+ })
+
+ it('renders unknown unavailable state when app detail is empty', () => {
+ mockUseGetTryAppInfo.mockReturnValue({
+ data: null,
+ isLoading: false,
+ isError: false,
+ })
+
+ render(
+ <TryApp
+ appId="test-app-id"
+ onClose={vi.fn()}
+ onCreate={vi.fn()}
+ />,
+ )
+
+ expect(screen.getByText('share.common.appUnknownError')).toBeInTheDocument()
+ })
})
describe('content rendering', () => {
@@ -257,6 +293,26 @@ describe('TryApp (main index.tsx)', () => {
expect(mockOnClose).toHaveBeenCalled()
})
+
+ it('calls onClose when the dialog requests close', async () => {
+ const mockOnClose = vi.fn()
+
+ render(
+ <TryApp
+ appId="test-app-id"
+ onClose={mockOnClose}
+ onCreate={vi.fn()}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ })
+
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ expect(mockOnClose).toHaveBeenCalledTimes(1)
+ })
})
describe('create functionality', () => {
diff --git a/web/app/components/explore/try-app/index.tsx b/web/app/components/explore/try-app/index.tsx
index eb5ea952da1..95e312c4c88 100644
--- a/web/app/components/explore/try-app/index.tsx
+++ b/web/app/components/explore/try-app/index.tsx
@@ -3,12 +3,12 @@
import type { FC } from 'react'
import type { App as AppType } from '@/models/explore'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useState } from 'react'
import AppUnavailable from '@/app/components/base/app-unavailable'
import Loading from '@/app/components/base/loading'
-import Modal from '@/app/components/base/modal/index'
import { IS_CLOUD_EDITION } from '@/config'
import { systemFeaturesQueryOptions } from '@/service/system-features'
import { useGetTryAppInfo } from '@/service/use-try-app'
@@ -40,54 +40,59 @@ const TryApp: FC<Props> = ({
const { data: appDetail, isLoading, isError, error } = useGetTryAppInfo(appId)
return (
- <Modal
- isShow
- onClose={onClose}
- className="h-[calc(100vh-32px)] max-w-[calc(100vw-32px)] min-w-[1280px] overflow-x-auto p-2"
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- {isLoading ? (
- <div className="flex h-full items-center justify-center">
- <Loading type="area" />
- </div>
- ) : isError ? (
- <div className="flex h-full items-center justify-center">
- <AppUnavailable className="h-auto w-auto" isUnknownReason={!error} unknownReason={error instanceof Error ? error.message : undefined} />
- </div>
- ) : !appDetail ? (
- <div className="flex h-full items-center justify-center">
- <AppUnavailable className="h-auto w-auto" isUnknownReason />
- </div>
- ) : (
- <div className="flex h-full flex-col">
- <div className="flex shrink-0 justify-between pl-4">
- <Tab
- value={activeType}
- onChange={setType}
- disableTry={app ? !isTrialApp : false}
- />
- <Button
- size="large"
- variant="tertiary"
- className="flex size-7 items-center justify-center rounded-[10px] p-0 text-components-button-tertiary-text"
- onClick={onClose}
- >
- <span className="i-ri-close-line size-5" />
- </Button>
+ <DialogContent className="h-[calc(100vh-32px)] max-h-none w-full max-w-[calc(100vw-32px)] min-w-[1280px] overflow-hidden overflow-x-auto border-none p-2 text-left align-middle">
+
+ {isLoading ? (
+ <div className="flex h-full items-center justify-center">
+ <Loading type="area" />
+ </div>
+ ) : isError ? (
+ <div className="flex h-full items-center justify-center">
+ <AppUnavailable className="h-auto w-auto" isUnknownReason={!error} unknownReason={error instanceof Error ? error.message : undefined} />
+ </div>
+ ) : !appDetail ? (
+ <div className="flex h-full items-center justify-center">
+ <AppUnavailable className="h-auto w-auto" isUnknownReason />
</div>
- {/* Main content */}
- <div className="mt-2 flex h-0 grow justify-between space-x-2">
- {activeType === TypeEnum.TRY ? <App appId={appId} appDetail={appDetail} /> : <Preview appId={appId} appDetail={appDetail} />}
- <AppInfo
- className="w-[360px] shrink-0"
- appDetail={appDetail}
- appId={appId}
- categories={categories}
- onCreate={onCreate}
- />
+ ) : (
+ <div className="flex h-full flex-col">
+ <div className="flex shrink-0 justify-between pl-4">
+ <Tab
+ value={activeType}
+ onChange={setType}
+ disableTry={app ? !isTrialApp : false}
+ />
+ <Button
+ size="large"
+ variant="tertiary"
+ className="flex size-7 items-center justify-center rounded-[10px] p-0 text-components-button-tertiary-text"
+ onClick={onClose}
+ >
+ <span className="i-ri-close-line size-5" />
+ </Button>
+ </div>
+ {/* Main content */}
+ <div className="mt-2 flex h-0 grow justify-between space-x-2">
+ {activeType === TypeEnum.TRY ? <App appId={appId} appDetail={appDetail} /> : <Preview appId={appId} appDetail={appDetail} />}
+ <AppInfo
+ className="w-[360px] shrink-0"
+ appDetail={appDetail}
+ appId={appId}
+ categories={categories}
+ onCreate={onCreate}
+ />
+ </div>
</div>
- </div>
- )}
- </Modal>
+ )}
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(TryApp)
diff --git a/web/app/components/header/account-about/__tests__/index.spec.tsx b/web/app/components/header/account-about/__tests__/index.spec.tsx
index 694a6320399..8ec7d8800de 100644
--- a/web/app/components/header/account-about/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-about/__tests__/index.spec.tsx
@@ -90,7 +90,7 @@ describe('AccountAbout', () => {
describe('User Interactions', () => {
it('should call onCancel when close button is clicked', () => {
renderWithSystemFeatures(<AccountAbout langGeniusVersionInfo={mockVersionInfo} onCancel={mockOnCancel} />)
- // Modal uses Headless UI Dialog which renders into a portal, so we need to use document
+ // Modal content renders into a portal, so we need to use document.
const closeButton = document.querySelector('div.absolute.cursor-pointer')
if (!closeButton)
diff --git a/web/app/components/header/account-about/index.tsx b/web/app/components/header/account-about/index.tsx
index e2535144f93..ba3eba59935 100644
--- a/web/app/components/header/account-about/index.tsx
+++ b/web/app/components/header/account-about/index.tsx
@@ -1,15 +1,15 @@
'use client'
import type { LangGeniusVersionResponse } from '@/models/common'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { RiCloseLine } from '@remixicon/react'
import { useSuspenseQuery } from '@tanstack/react-query'
import dayjs from 'dayjs'
import { useTranslation } from 'react-i18next'
import DifyLogo from '@/app/components/base/logo/dify-logo'
-import Modal from '@/app/components/base/modal'
import { IS_CE_EDITION } from '@/config'
-import Link from '@/next/link'
+import Link from '@/next/link'
import { systemFeaturesQueryOptions } from '@/service/system-features'
type IAccountSettingProps = {
@@ -26,87 +26,92 @@ export default function AccountAbout({
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return (
- <Modal
- isShow
- onClose={onCancel}
- className="w-[480px]! max-w-[480px]! px-6! py-4!"
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
>
- <div className="relative">
- <div className="absolute top-0 right-0 flex h-8 w-8 cursor-pointer items-center justify-center" onClick={onCancel}>
- <RiCloseLine className="h-4 w-4 text-text-tertiary" />
- </div>
- <div className="flex flex-col items-center gap-4 py-8">
- {systemFeatures.branding.enabled && systemFeatures.branding.workspace_logo
- ? (
- <img
- src={systemFeatures.branding.workspace_logo}
- className="block h-7 w-auto object-contain"
- alt="logo"
- />
- )
- : <DifyLogo size="large" className="mx-auto" />}
+ <DialogContent className="w-[calc(100vw-2rem)]! max-w-[480px]! overflow-hidden! border-none px-6! py-4! text-left align-middle">
- <div className="text-center text-xs font-normal text-text-tertiary">
- Version
- {langGeniusVersionInfo?.current_version}
+ <div className="relative">
+ <div className="absolute top-0 right-0 flex h-8 w-8 cursor-pointer items-center justify-center" onClick={onCancel}>
+ <RiCloseLine className="h-4 w-4 text-text-tertiary" />
+ </div>
+ <div className="flex flex-col items-center gap-4 py-8">
+ {systemFeatures.branding.enabled && systemFeatures.branding.workspace_logo
+ ? (
+ <img
+ src={systemFeatures.branding.workspace_logo}
+ className="block h-7 w-auto object-contain"
+ alt="logo"
+ />
+ )
+ : <DifyLogo size="large" className="mx-auto" />}
+
+ <div className="text-center text-xs font-normal text-text-tertiary">
+ Version
+ {langGeniusVersionInfo?.current_version}
+ </div>
+ <div className="flex flex-col items-center gap-2 text-center text-xs font-normal text-text-secondary">
+ <div>
+ ©
+ {dayjs().year()}
+ {' '}
+ LangGenius, Inc., Contributors.
+ </div>
+ <div className="text-text-accent">
+ {
+ IS_CE_EDITION
+ ? <Link href="https://github.com/langgenius/dify/blob/main/LICENSE" target="_blank" rel="noopener noreferrer">Open Source License</Link>
+ : (
+ <>
+ <Link href="https://dify.ai/privacy" target="_blank" rel="noopener noreferrer">Privacy Policy</Link>
+ ,&nbsp;
+ <Link href="https://dify.ai/terms" target="_blank" rel="noopener noreferrer">Terms of Service</Link>
+ </>
+ )
+ }
+ </div>
+ </div>
</div>
- <div className="flex flex-col items-center gap-2 text-center text-xs font-normal text-text-secondary">
- <div>
- ©
- {dayjs().year()}
- {' '}
- LangGenius, Inc., Contributors.
+ <div className="-mx-6 mb-4 h-[0.5px] bg-divider-regular" />
+ <div className="flex items-center justify-between gap-3">
+ <div className="min-w-0 text-xs font-medium text-text-tertiary">
+ {
+ isLatest
+ ? t('about.latestAvailable', { ns: 'common', version: langGeniusVersionInfo.latest_version })
+ : t('about.nowAvailable', { ns: 'common', version: langGeniusVersionInfo.latest_version })
+ }
</div>
- <div className="text-text-accent">
+ <div className="flex shrink-0 items-center">
+ <Button className="mr-2" size="small">
+ <Link
+ href="https://github.com/langgenius/dify/releases"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {t('about.changeLog', { ns: 'common' })}
+ </Link>
+ </Button>
{
- IS_CE_EDITION
- ? <Link href="https://github.com/langgenius/dify/blob/main/LICENSE" target="_blank" rel="noopener noreferrer">Open Source License</Link>
- : (
- <>
- <Link href="https://dify.ai/privacy" target="_blank" rel="noopener noreferrer">Privacy Policy</Link>
- ,&nbsp;
- <Link href="https://dify.ai/terms" target="_blank" rel="noopener noreferrer">Terms of Service</Link>
- </>
- )
+ !isLatest && !IS_CE_EDITION && (
+ <Button variant="primary" size="small">
+ <Link
+ href={langGeniusVersionInfo.release_notes}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {t('about.updateNow', { ns: 'common' })}
+ </Link>
+ </Button>
+ )
}
</div>
</div>
</div>
- <div className="-mx-8 mb-4 h-[0.5px] bg-divider-regular" />
- <div className="flex items-center justify-between">
- <div className="text-xs font-medium text-text-tertiary">
- {
- isLatest
- ? t('about.latestAvailable', { ns: 'common', version: langGeniusVersionInfo.latest_version })
- : t('about.nowAvailable', { ns: 'common', version: langGeniusVersionInfo.latest_version })
- }
- </div>
- <div className="flex items-center">
- <Button className="mr-2" size="small">
- <Link
- href="https://github.com/langgenius/dify/releases"
- target="_blank"
- rel="noopener noreferrer"
- >
- {t('about.changeLog', { ns: 'common' })}
- </Link>
- </Button>
- {
- !isLatest && !IS_CE_EDITION && (
- <Button variant="primary" size="small">
- <Link
- href={langGeniusVersionInfo.release_notes}
- target="_blank"
- rel="noopener noreferrer"
- >
- {t('about.updateNow', { ns: 'common' })}
- </Link>
- </Button>
- )
- }
- </div>
- </div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/header/account-setting/api-based-extension-page/modal.tsx b/web/app/components/header/account-setting/api-based-extension-page/modal.tsx
index b7d2e09734c..f75b42bc451 100644
--- a/web/app/components/header/account-setting/api-based-extension-page/modal.tsx
+++ b/web/app/components/header/account-setting/api-based-extension-page/modal.tsx
@@ -1,12 +1,11 @@
import type { FC } from 'react'
import type { ApiBasedExtension } from '@/models/common'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
-import { noop } from 'es-toolkit/function'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { BookOpen01 } from '@/app/components/base/icons/src/vender/line/education'
-import Modal from '@/app/components/base/modal'
import { useDocLink } from '@/context/i18n'
import { addApiBasedExtension, updateApiBasedExtension } from '@/service/common'
@@ -61,45 +60,48 @@ const ApiBasedExtensionModal: FC<ApiBasedExtensionModalProps> = ({ data, onCance
}
}
return (
- <Modal isShow onClose={noop} wrapperClassName="z-1002" className="w-[640px]! max-w-none! p-8! pb-6!">
- <div className="mb-2 text-xl font-semibold text-text-primary">
- {data.name
- ? t('apiBasedExtension.modal.editTitle', { ns: 'common' })
- : t('apiBasedExtension.modal.title', { ns: 'common' })}
- </div>
- <div className="py-2">
- <div className="text-sm leading-9 font-medium text-text-primary">
- {t('apiBasedExtension.modal.name.title', { ns: 'common' })}
+ <Dialog open>
+ <DialogContent className="w-[640px]! max-w-none! overflow-hidden! border-none p-8! pb-6! text-left align-middle">
+
+ <div className="mb-2 text-xl font-semibold text-text-primary">
+ {data.name
+ ? t('apiBasedExtension.modal.editTitle', { ns: 'common' })
+ : t('apiBasedExtension.modal.title', { ns: 'common' })}
+ </div>
+ <div className="py-2">
+ <div className="text-sm leading-9 font-medium text-text-primary">
+ {t('apiBasedExtension.modal.name.title', { ns: 'common' })}
+ </div>
+ <input value={localeData.name || ''} onChange={e => handleDataChange('name', e.target.value)} className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-hidden" placeholder={t('apiBasedExtension.modal.name.placeholder', { ns: 'common' }) || ''} />
</div>
- <input value={localeData.name || ''} onChange={e => handleDataChange('name', e.target.value)} className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-hidden" placeholder={t('apiBasedExtension.modal.name.placeholder', { ns: 'common' }) || ''} />
- </div>
- <div className="py-2">
- <div className="flex h-9 items-center justify-between text-sm font-medium text-text-primary">
- {t('apiBasedExtension.modal.apiEndpoint.title', { ns: 'common' })}
- <a href={docLink('/use-dify/workspace/api-extension/api-extension')} target="_blank" rel="noopener noreferrer" className="group flex items-center text-xs font-normal text-text-accent">
- <BookOpen01 className="mr-1 h-3 w-3" />
- {t('apiBasedExtension.link', { ns: 'common' })}
- </a>
+ <div className="py-2">
+ <div className="flex h-9 items-center justify-between text-sm font-medium text-text-primary">
+ {t('apiBasedExtension.modal.apiEndpoint.title', { ns: 'common' })}
+ <a href={docLink('/use-dify/workspace/api-extension/api-extension')} target="_blank" rel="noopener noreferrer" className="group flex items-center text-xs font-normal text-text-accent">
+ <BookOpen01 className="mr-1 h-3 w-3" />
+ {t('apiBasedExtension.link', { ns: 'common' })}
+ </a>
+ </div>
+ <input value={localeData.api_endpoint || ''} onChange={e => handleDataChange('api_endpoint', e.target.value)} className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-hidden" placeholder={t('apiBasedExtension.modal.apiEndpoint.placeholder', { ns: 'common' }) || ''} />
</div>
- <input value={localeData.api_endpoint || ''} onChange={e => handleDataChange('api_endpoint', e.target.value)} className="block h-9 w-full appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-hidden" placeholder={t('apiBasedExtension.modal.apiEndpoint.placeholder', { ns: 'common' }) || ''} />
- </div>
- <div className="py-2">
- <div className="text-sm leading-9 font-medium text-text-primary">
- {t('apiBasedExtension.modal.apiKey.title', { ns: 'common' })}
+ <div className="py-2">
+ <div className="text-sm leading-9 font-medium text-text-primary">
+ {t('apiBasedExtension.modal.apiKey.title', { ns: 'common' })}
+ </div>
+ <div className="flex items-center">
+ <input value={localeData.api_key || ''} onChange={e => handleDataChange('api_key', e.target.value)} className="mr-2 block h-9 grow appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-hidden" placeholder={t('apiBasedExtension.modal.apiKey.placeholder', { ns: 'common' }) || ''} />
+ </div>
</div>
- <div className="flex items-center">
- <input value={localeData.api_key || ''} onChange={e => handleDataChange('api_key', e.target.value)} className="mr-2 block h-9 grow appearance-none rounded-lg bg-components-input-bg-normal px-3 text-sm text-text-primary outline-hidden" placeholder={t('apiBasedExtension.modal.apiKey.placeholder', { ns: 'common' }) || ''} />
+ <div className="mt-6 flex items-center justify-end">
+ <Button onClick={onCancel} className="mr-2">
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button variant="primary" disabled={!localeData.name || !localeData.api_endpoint || !localeData.api_key || loading} onClick={handleSave}>
+ {t('operation.save', { ns: 'common' })}
+ </Button>
</div>
- </div>
- <div className="mt-6 flex items-center justify-end">
- <Button onClick={onCancel} className="mr-2">
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button variant="primary" disabled={!localeData.name || !localeData.api_endpoint || !localeData.api_key || loading} onClick={handleSave}>
- {t('operation.save', { ns: 'common' })}
- </Button>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
export default ApiBasedExtensionModal
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-modal.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-modal.spec.tsx
index c4794c9775a..002908ce8b6 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-modal.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-load-balancing-modal.spec.tsx
@@ -4,14 +4,6 @@ import userEvent from '@testing-library/user-event'
import { ConfigurationMethodEnum } from '../../declarations'
import ModelLoadBalancingModal from '../model-load-balancing-modal'
-vi.mock('@headlessui/react', () => ({
- Transition: ({ show, children }: { show: boolean, children: React.ReactNode }) => (show ? <>{children}</> : null),
- TransitionChild: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- Dialog: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
- DialogPanel: ({ children, className }: { children: React.ReactNode, className?: string }) => <div className={className}>{children}</div>,
- DialogTitle: ({ children, className }: { children: React.ReactNode, className?: string }) => <h3 className={className}>{children}</h3>,
-}))
-
type CredentialData = {
load_balancing: {
enabled: boolean
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx
index 34b9d1578f8..15632fb8985 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-load-balancing-modal.tsx
@@ -9,11 +9,11 @@ import {
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
-import Modal from '@/app/components/base/modal'
import { SwitchCredentialInLoadBalancing } from '@/app/components/header/account-setting/model-provider-page/model-auth'
import { useGetModelCredential, useUpdateModelLoadBalancingConfig } from '@/service/use-models'
import { ConfigurationMethodEnum, FormTypeEnum } from '../declarations'
@@ -180,114 +180,118 @@ const ModelLoadBalancingModal = ({ provider, configurateMethod, currentCustomCon
}, [refetch, onClose])
return (
<>
- <Modal
- isShow={Boolean(model) && open}
- onClose={onClose}
- wrapperClassName="z-1002"
- className="w-[640px] max-w-none px-8 pt-8"
- title={(
- <div className="pb-3 font-semibold">
- <div className="h-[30px]">
- {draftConfig?.enabled
- ? t('modelProvider.auth.configLoadBalancing', { ns: 'common' })
- : t('modelProvider.auth.configModel', { ns: 'common' })}
- </div>
- {Boolean(model) && (
- <div className="flex h-5 items-center">
- <ModelIcon className="mr-2 shrink-0" provider={provider} modelName={model!.model} />
- <ModelName className="grow system-md-regular text-text-secondary" modelItem={model!} showModelType showMode showContextSize />
- </div>
- )}
- </div>
- )}
+ <Dialog
+ open={Boolean(model) && open}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose?.()
+ }}
>
- {!draftConfig
- ? <Loading type="area" />
- : (
- <>
- <div className="py-2">
- <div className={cn('min-h-16 rounded-xl border bg-components-panel-bg transition-colors', draftConfig.enabled ? 'cursor-pointer border-components-panel-border' : 'cursor-default border-util-colors-blue-blue-600')} onClick={draftConfig.enabled ? () => toggleModalBalancing(false) : undefined}>
- <div className="flex items-center gap-2 px-[15px] py-3 select-none">
- <div className="flex h-8 w-8 shrink-0 grow-0 items-center justify-center rounded-lg border border-components-card-border bg-components-card-bg">
- {Boolean(model) && (<ModelIcon className="shrink-0" provider={provider} modelName={model!.model} />)}
- </div>
- <div className="grow">
- <div className="text-sm text-text-secondary">
- {providerFormSchemaPredefined
- ? t('modelProvider.auth.providerManaged', { ns: 'common' })
- : t('modelProvider.auth.specifyModelCredential', { ns: 'common' })}
+ <DialogContent className="w-[640px] max-w-none overflow-hidden! border-none px-8 pt-8 text-left align-middle">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ <div className="pb-3 font-semibold">
+ <div className="h-[30px]">
+ {draftConfig?.enabled
+ ? t('modelProvider.auth.configLoadBalancing', { ns: 'common' })
+ : t('modelProvider.auth.configModel', { ns: 'common' })}
+ </div>
+ {Boolean(model) && (
+ <div className="flex h-5 items-center">
+ <ModelIcon className="mr-2 shrink-0" provider={provider} modelName={model!.model} />
+ <ModelName className="grow system-md-regular text-text-secondary" modelItem={model!} showModelType showMode showContextSize />
+ </div>
+ )}
+ </div>
+ </DialogTitle>
+
+ {!draftConfig
+ ? <Loading type="area" />
+ : (
+ <>
+ <div className="py-2">
+ <div className={cn('min-h-16 rounded-xl border bg-components-panel-bg transition-colors', draftConfig.enabled ? 'cursor-pointer border-components-panel-border' : 'cursor-default border-util-colors-blue-blue-600')} onClick={draftConfig.enabled ? () => toggleModalBalancing(false) : undefined}>
+ <div className="flex items-center gap-2 px-[15px] py-3 select-none">
+ <div className="flex h-8 w-8 shrink-0 grow-0 items-center justify-center rounded-lg border border-components-card-border bg-components-card-bg">
+ {Boolean(model) && (<ModelIcon className="shrink-0" provider={provider} modelName={model!.model} />)}
</div>
- <div className="text-xs text-text-tertiary">
- {providerFormSchemaPredefined
- ? t('modelProvider.auth.providerManagedTip', { ns: 'common' })
- : t('modelProvider.auth.specifyModelCredentialTip', { ns: 'common' })}
+ <div className="grow">
+ <div className="text-sm text-text-secondary">
+ {providerFormSchemaPredefined
+ ? t('modelProvider.auth.providerManaged', { ns: 'common' })
+ : t('modelProvider.auth.specifyModelCredential', { ns: 'common' })}
+ </div>
+ <div className="text-xs text-text-tertiary">
+ {providerFormSchemaPredefined
+ ? t('modelProvider.auth.providerManagedTip', { ns: 'common' })
+ : t('modelProvider.auth.specifyModelCredentialTip', { ns: 'common' })}
+ </div>
</div>
+ {!providerFormSchemaPredefined && (<SwitchCredentialInLoadBalancing provider={provider} customModelCredential={customModelCredential ?? initialCustomModelCredential} setCustomModelCredential={setCustomModelCredential} model={model} credentials={available_credentials} onUpdate={handleUpdateWhenSwitchCredential} onRemove={handleUpdateWhenSwitchCredential} />)}
</div>
- {!providerFormSchemaPredefined && (<SwitchCredentialInLoadBalancing provider={provider} customModelCredential={customModelCredential ?? initialCustomModelCredential} setCustomModelCredential={setCustomModelCredential} model={model} credentials={available_credentials} onUpdate={handleUpdateWhenSwitchCredential} onRemove={handleUpdateWhenSwitchCredential} />)}
</div>
+ {modelCredential && (
+ <ModelLoadBalancingConfigs {...{
+ draftConfig,
+ setDraftConfig,
+ provider,
+ currentCustomConfigurationModelFixedFields: {
+ __model_name: model.model,
+ __model_type: model.model_type,
+ },
+ configurationMethod: model.fetch_from,
+ className: 'mt-2',
+ modelCredential,
+ onUpdate: handleUpdate,
+ onRemove: handleUpdateWhenSwitchCredential,
+ model: {
+ model: model.model,
+ model_type: model.model_type,
+ },
+ }}
+ />
+ )}
</div>
- {modelCredential && (
- <ModelLoadBalancingConfigs {...{
- draftConfig,
- setDraftConfig,
- provider,
- currentCustomConfigurationModelFixedFields: {
- __model_name: model.model,
- __model_type: model.model_type,
- },
- configurationMethod: model.fetch_from,
- className: 'mt-2',
- modelCredential,
- onUpdate: handleUpdate,
- onRemove: handleUpdateWhenSwitchCredential,
- model: {
- model: model.model,
- model_type: model.model_type,
- },
- }}
- />
- )}
- </div>
- <div className="mt-6 flex items-center justify-between gap-2">
- <div>
- {!providerFormSchemaPredefined && (
- <Button onClick={() => openConfirmDelete(undefined, { model: model.model, model_type: model.model_type })} className="text-components-button-destructive-secondary-text">
- {t('modelProvider.auth.removeModel', { ns: 'common' })}
+ <div className="mt-6 flex items-center justify-between gap-2">
+ <div>
+ {!providerFormSchemaPredefined && (
+ <Button onClick={() => openConfirmDelete(undefined, { model: model.model, model_type: model.model_type })} className="text-components-button-destructive-secondary-text">
+ {t('modelProvider.auth.removeModel', { ns: 'common' })}
+ </Button>
+ )}
+ </div>
+ <div className="space-x-2">
+ <Button onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button
+ variant="primary"
+ onClick={handleSave}
+ disabled={loading
+ || (draftConfig?.enabled && (draftConfig?.configs.filter(config => config.enabled).length ?? 0) < 2)
+ || isLoading}
+ >
+ {t('operation.save', { ns: 'common' })}
</Button>
- )}
- </div>
- <div className="space-x-2">
- <Button onClick={onClose}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button
- variant="primary"
- onClick={handleSave}
- disabled={loading
- || (draftConfig?.enabled && (draftConfig?.configs.filter(config => config.enabled).length ?? 0) < 2)
- || isLoading}
- >
- {t('operation.save', { ns: 'common' })}
- </Button>
+ </div>
</div>
- </div>
- </>
- )}
- </Modal>
- <AlertDialog open={!!deleteModel} onOpenChange={open => !open && closeConfirmDelete()}>
- <AlertDialogContent>
- <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
- <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
- {t('modelProvider.confirmDelete', { ns: 'common' })}
- </AlertDialogTitle>
- </div>
- <AlertDialogActions>
- <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>
- <AlertDialogConfirmButton disabled={doingAction} onClick={handleDeleteModel}>
- {t('operation.confirm', { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogActions>
- </AlertDialogContent>
- </AlertDialog>
+ </>
+ )}
+ <AlertDialog open={!!deleteModel} onOpenChange={open => !open && closeConfirmDelete()}>
+ <AlertDialogContent>
+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
+ {t('modelProvider.confirmDelete', { ns: 'common' })}
+ </AlertDialogTitle>
+ </div>
+ <AlertDialogActions>
+ <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>
+ <AlertDialogConfirmButton disabled={doingAction} onClick={handleDeleteModel}>
+ {t('operation.confirm', { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
+ </DialogContent>
+ </Dialog>
</>
)
}
diff --git a/web/app/components/header/nav/__tests__/index.spec.tsx b/web/app/components/header/nav/__tests__/index.spec.tsx
index 6f9b4489816..1e456296f79 100644
--- a/web/app/components/header/nav/__tests__/index.spec.tsx
+++ b/web/app/components/header/nav/__tests__/index.spec.tsx
@@ -9,7 +9,6 @@ import {
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
-import { use } from 'react'
import { vi } from 'vitest'
import { useStore as useAppStore } from '@/app/components/app/store'
import { useAppContext } from '@/context/app-context'
@@ -17,59 +16,6 @@ import { useRouter, useSelectedLayoutSegment } from '@/next/navigation'
import { AppModeEnum } from '@/types/app'
import Nav from '../index'
-vi.mock('@headlessui/react', () => {
- type MenuContextValue = { open: boolean, setOpen: (open: boolean) => void }
- const MenuContext = React.createContext<MenuContextValue | null>(null)
-
- const Menu = ({ children }: { children: React.ReactNode | ((props: { open: boolean }) => React.ReactNode) }) => {
- const [open, setOpen] = React.useState(false)
- const value = React.useMemo(() => ({ open, setOpen }), [open])
- return (
- <MenuContext value={value}>
- {typeof children === 'function' ? children({ open }) : children}
- </MenuContext>
- )
- }
-
- const MenuButton = ({ onClick, children, ...props }: { onClick?: () => void, children?: React.ReactNode }) => {
- const context = use(MenuContext)
- const handleClick = () => {
- context?.setOpen(!context.open)
- onClick?.()
- }
- return (
- <button type="button" aria-expanded={context?.open ?? false} onClick={handleClick} {...props}>
- {children}
- </button>
- )
- }
-
- const MenuItems = ({ as: Component = 'div', role, children, ...props }: { as?: React.ElementType, role?: string, children: React.ReactNode }) => {
- const context = use(MenuContext)
- if (!context?.open)
- return null
- return (
- <Component role={role ?? 'menu'} {...props}>
- {children}
- </Component>
- )
- }
-
- const MenuItem = ({ as: Component = 'div', role, children, ...props }: { as?: React.ElementType, role?: string, children: React.ReactNode }) => (
- <Component role={role ?? 'menuitem'} {...props}>
- {children}
- </Component>
- )
-
- return {
- Menu,
- MenuButton,
- MenuItems,
- MenuItem,
- Transition: ({ show = true, children }: { show?: boolean, children: React.ReactNode }) => (show ? <>{children}</> : null),
- }
-})
-
// Mock next/navigation
vi.mock('@/next/navigation', () => ({
useSelectedLayoutSegment: vi.fn(),
diff --git a/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx b/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx
index 32de0691dd5..aaabe456132 100644
--- a/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx
+++ b/web/app/components/header/nav/nav-selector/__tests__/index.spec.tsx
@@ -2,7 +2,6 @@ import type { INavSelectorProps, NavItem } from '../index'
import type { AppContextValue } from '@/context/app-context'
import { act, fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import * as React from 'react'
import { vi } from 'vitest'
import { useStore as useAppStore } from '@/app/components/app/store'
import { useAppContext } from '@/context/app-context'
@@ -10,59 +9,6 @@ import { useRouter } from '@/next/navigation'
import { AppModeEnum } from '@/types/app'
import NavSelector from '../index'
-vi.mock('@headlessui/react', () => {
- type MenuContextValue = { open: boolean, setOpen: (open: boolean) => void }
- const MenuContext = React.createContext<MenuContextValue | null>(null)
-
- const Menu = ({ children }: { children: React.ReactNode | ((props: { open: boolean }) => React.ReactNode) }) => {
- const [open, setOpen] = React.useState(false)
- const value = React.useMemo(() => ({ open, setOpen }), [open])
- return (
- <MenuContext.Provider value={value}>
- {typeof children === 'function' ? children({ open }) : children}
- </MenuContext.Provider>
- )
- }
-
- const MenuButton = ({ onClick, children, ...props }: { onClick?: () => void, children?: React.ReactNode }) => {
- const context = React.useContext(MenuContext)
- const handleClick = () => {
- context?.setOpen(!context.open)
- onClick?.()
- }
- return (
- <button type="button" aria-expanded={context?.open ?? false} onClick={handleClick} {...props}>
- {children}
- </button>
- )
- }
-
- const MenuItems = ({ as: Component = 'div', role, children, ...props }: { as?: React.ElementType, role?: string, children: React.ReactNode }) => {
- const context = React.useContext(MenuContext)
- if (!context?.open)
- return null
- return (
- <Component role={role ?? 'menu'} {...props}>
- {children}
- </Component>
- )
- }
-
- const MenuItem = ({ as: Component = 'div', role, children, ...props }: { as?: React.ElementType, role?: string, children: React.ReactNode }) => (
- <Component role={role ?? 'menuitem'} {...props}>
- {children}
- </Component>
- )
-
- return {
- Menu,
- MenuButton,
- MenuItems,
- MenuItem,
- Transition: ({ show = true, children }: { show?: boolean, children: React.ReactNode }) => (show ? <>{children}</> : null),
- }
-})
-
// Mock next/navigation
vi.mock('@/next/navigation', () => ({
useRouter: vi.fn(),
diff --git a/web/app/components/plugins/install-plugin/install-bundle/index.tsx b/web/app/components/plugins/install-plugin/install-bundle/index.tsx
index 6d2b476c51b..1cf2202dae0 100644
--- a/web/app/components/plugins/install-plugin/install-bundle/index.tsx
+++ b/web/app/components/plugins/install-plugin/install-bundle/index.tsx
@@ -2,10 +2,10 @@
import type { FC } from 'react'
import type { Dependency } from '../../types'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogCloseButton, DialogContent } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import { InstallStep } from '../../types'
import useHideLogic from '../hooks/use-hide-logic'
import ReadyToInstall from './ready-to-install'
@@ -50,26 +50,31 @@ const InstallBundle: FC<Props> = ({
}, [step, t])
return (
- <Modal
- isShow={true}
- onClose={foldAnimInto}
- className={cn(modalClassName, 'shadows-shadow-xl flex min-w-[560px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0')}
- closable
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ foldAnimInto()
+ }}
>
- <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
- <div className="self-stretch title-2xl-semi-bold text-text-primary">
- {getTitle()}
+ <DialogContent className={cn('relative w-full max-w-[480px] overflow-hidden! text-left align-middle', cn(modalClassName, 'shadows-shadow-xl flex min-w-[560px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0'))}>
+ <DialogCloseButton data-testid="modal-close-button" />
+
+ <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
+ <div className="self-stretch title-2xl-semi-bold text-text-primary">
+ {getTitle()}
+ </div>
</div>
- </div>
- <ReadyToInstall
- step={step}
- onStepChange={setStep}
- onStartToInstall={handleStartToInstall}
- setIsInstalling={setIsInstalling}
- allPlugins={fromDSLPayload}
- onClose={onClose}
- />
- </Modal>
+ <ReadyToInstall
+ step={step}
+ onStepChange={setStep}
+ onStartToInstall={handleStartToInstall}
+ setIsInstalling={setIsInstalling}
+ allPlugins={fromDSLPayload}
+ onClose={onClose}
+ />
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/plugins/install-plugin/install-from-github/index.tsx b/web/app/components/plugins/install-plugin/install-from-github/index.tsx
index 4e2c97ab0b4..ca2b28d2eff 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/index.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/index.tsx
@@ -3,11 +3,11 @@
import type { PluginDeclaration, UpdateFromGitHubPayload } from '../../types'
import type { InstallState } from '@/app/components/plugins/types'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogCloseButton, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
import { InstallStepFromGitHub } from '../../types'
import Installed from '../base/installed'
@@ -160,74 +160,80 @@ const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({ updatePayload, on
}
return (
- <Modal
- isShow={true}
- onClose={foldAnimInto}
- className={cn(modalClassName, `shadows-shadow-xl flex min-w-[560px] flex-col items-start rounded-2xl border-[0.5px]
- border-components-panel-border bg-components-panel-bg p-0`)}
- closable
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ foldAnimInto()
+ }}
>
- <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
- <div className="flex grow flex-col items-start gap-1">
- <div className="self-stretch title-2xl-semi-bold text-text-primary">
- {getTitle()}
- </div>
- <div className="self-stretch system-xs-regular text-text-tertiary">
- {!([InstallStepFromGitHub.uploadFailed, InstallStepFromGitHub.installed, InstallStepFromGitHub.installFailed].includes(state.step)) && t('installFromGitHub.installNote', { ns: 'plugin' })}
+ <DialogContent className={cn('w-[560px] max-w-none! overflow-hidden! text-left align-middle', cn(modalClassName, `shadows-shadow-xl flex min-w-[560px] flex-col items-start rounded-2xl border-[0.5px]
+ border-components-panel-border bg-components-panel-bg p-0`))}
+ >
+ <DialogCloseButton data-testid="modal-close-button" />
+
+ <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
+ <div className="flex grow flex-col items-start gap-1">
+ <div className="self-stretch title-2xl-semi-bold text-text-primary">
+ {getTitle()}
+ </div>
+ <div className="self-stretch system-xs-regular text-text-tertiary">
+ {!([InstallStepFromGitHub.uploadFailed, InstallStepFromGitHub.installed, InstallStepFromGitHub.installFailed].includes(state.step)) && t('installFromGitHub.installNote', { ns: 'plugin' })}
+ </div>
</div>
</div>
- </div>
- {([InstallStepFromGitHub.uploadFailed, InstallStepFromGitHub.installed, InstallStepFromGitHub.installFailed].includes(state.step))
- ? (
- <Installed
- payload={manifest}
- isFailed={[InstallStepFromGitHub.uploadFailed, InstallStepFromGitHub.installFailed].includes(state.step)}
- errMsg={errorMsg}
- onCancel={onClose}
- />
- )
- : (
- <div className={`flex flex-col items-start justify-center self-stretch px-6 py-3 ${state.step === InstallStepFromGitHub.installed ? 'gap-2' : 'gap-4'}`}>
- {state.step === InstallStepFromGitHub.setUrl && (
- <SetURL
- repoUrl={state.repoUrl}
- onChange={value => setState(prevState => ({ ...prevState, repoUrl: value }))}
- onNext={handleUrlSubmit}
- onCancel={onClose}
- />
- )}
- {state.step === InstallStepFromGitHub.selectPackage && (
- <SelectPackage
- updatePayload={updatePayload!}
- repoUrl={state.repoUrl}
- selectedVersion={state.selectedVersion}
- versions={versions}
- onSelectVersion={item => setState(prevState => ({ ...prevState, selectedVersion: String(item.value) }))}
- selectedPackage={state.selectedPackage}
- packages={packages}
- onSelectPackage={item => setState(prevState => ({ ...prevState, selectedPackage: String(item.value) }))}
- onUploaded={handleUploaded}
- onFailed={handleUploadFail}
- onBack={handleBack}
- />
- )}
- {state.step === InstallStepFromGitHub.readyToInstall && (
- <Loaded
- updatePayload={updatePayload!}
- uniqueIdentifier={uniqueIdentifier!}
- payload={manifest as any}
- repoUrl={state.repoUrl}
- selectedVersion={state.selectedVersion}
- selectedPackage={state.selectedPackage}
- onBack={handleBack}
- onStartToInstall={handleStartToInstall}
- onInstalled={handleInstalled}
- onFailed={handleFailed}
- />
- )}
- </div>
- )}
- </Modal>
+ {([InstallStepFromGitHub.uploadFailed, InstallStepFromGitHub.installed, InstallStepFromGitHub.installFailed].includes(state.step))
+ ? (
+ <Installed
+ payload={manifest}
+ isFailed={[InstallStepFromGitHub.uploadFailed, InstallStepFromGitHub.installFailed].includes(state.step)}
+ errMsg={errorMsg}
+ onCancel={onClose}
+ />
+ )
+ : (
+ <div className={`flex flex-col items-start justify-center self-stretch px-6 py-3 ${state.step === InstallStepFromGitHub.installed ? 'gap-2' : 'gap-4'}`}>
+ {state.step === InstallStepFromGitHub.setUrl && (
+ <SetURL
+ repoUrl={state.repoUrl}
+ onChange={value => setState(prevState => ({ ...prevState, repoUrl: value }))}
+ onNext={handleUrlSubmit}
+ onCancel={onClose}
+ />
+ )}
+ {state.step === InstallStepFromGitHub.selectPackage && (
+ <SelectPackage
+ updatePayload={updatePayload!}
+ repoUrl={state.repoUrl}
+ selectedVersion={state.selectedVersion}
+ versions={versions}
+ onSelectVersion={item => setState(prevState => ({ ...prevState, selectedVersion: String(item.value) }))}
+ selectedPackage={state.selectedPackage}
+ packages={packages}
+ onSelectPackage={item => setState(prevState => ({ ...prevState, selectedPackage: String(item.value) }))}
+ onUploaded={handleUploaded}
+ onFailed={handleUploadFail}
+ onBack={handleBack}
+ />
+ )}
+ {state.step === InstallStepFromGitHub.readyToInstall && (
+ <Loaded
+ updatePayload={updatePayload!}
+ uniqueIdentifier={uniqueIdentifier!}
+ payload={manifest as any}
+ repoUrl={state.repoUrl}
+ selectedVersion={state.selectedVersion}
+ selectedPackage={state.selectedPackage}
+ onBack={handleBack}
+ onStartToInstall={handleStartToInstall}
+ onInstalled={handleInstalled}
+ onFailed={handleFailed}
+ />
+ )}
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/plugins/install-plugin/install-from-local-package/index.tsx b/web/app/components/plugins/install-plugin/install-from-local-package/index.tsx
index 94504acd986..e7696d455ae 100644
--- a/web/app/components/plugins/install-plugin/install-from-local-package/index.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-local-package/index.tsx
@@ -2,10 +2,10 @@
import type { Dependency, PluginDeclaration } from '../../types'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogCloseButton, DialogContent } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
import { InstallStep } from '../../types'
import useHideLogic from '../hooks/use-hide-logic'
@@ -86,52 +86,57 @@ const InstallFromLocalPackage: React.FC<InstallFromLocalPackageProps> = ({
}, [])
return (
- <Modal
- isShow={true}
- onClose={foldAnimInto}
- className={cn(modalClassName, 'shadows-shadow-xl flex min-w-[560px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0')}
- closable
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ foldAnimInto()
+ }}
>
- <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
- <div className="self-stretch title-2xl-semi-bold text-text-primary">
- {getTitle()}
+ <DialogContent className={cn('w-[560px] max-w-none! overflow-hidden! text-left align-middle', cn(modalClassName, 'shadows-shadow-xl flex min-w-[560px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0'))}>
+ <DialogCloseButton data-testid="modal-close-button" />
+
+ <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
+ <div className="self-stretch title-2xl-semi-bold text-text-primary">
+ {getTitle()}
+ </div>
</div>
- </div>
- {step === InstallStep.uploading && (
- <Uploading
- isBundle={isBundle}
- file={file}
- onCancel={onClose}
- onPackageUploaded={handlePackageUploaded}
- onBundleUploaded={handleBundleUploaded}
- onFailed={handleUploadFail}
- />
- )}
- {isBundle
- ? (
- <ReadyToInstallBundle
- step={step}
- onStepChange={setStep}
- onStartToInstall={handleStartToInstall}
- setIsInstalling={setIsInstalling}
- onClose={onClose}
- allPlugins={dependencies}
- />
- )
- : (
- <ReadyToInstallPackage
- step={step}
- onStepChange={setStep}
- onStartToInstall={handleStartToInstall}
- setIsInstalling={setIsInstalling}
- onClose={onClose}
- uniqueIdentifier={uniqueIdentifier}
- manifest={manifest}
- errorMsg={errorMsg}
- onError={setErrorMsg}
- />
- )}
- </Modal>
+ {step === InstallStep.uploading && (
+ <Uploading
+ isBundle={isBundle}
+ file={file}
+ onCancel={onClose}
+ onPackageUploaded={handlePackageUploaded}
+ onBundleUploaded={handleBundleUploaded}
+ onFailed={handleUploadFail}
+ />
+ )}
+ {isBundle
+ ? (
+ <ReadyToInstallBundle
+ step={step}
+ onStepChange={setStep}
+ onStartToInstall={handleStartToInstall}
+ setIsInstalling={setIsInstalling}
+ onClose={onClose}
+ allPlugins={dependencies}
+ />
+ )
+ : (
+ <ReadyToInstallPackage
+ step={step}
+ onStepChange={setStep}
+ onStartToInstall={handleStartToInstall}
+ setIsInstalling={setIsInstalling}
+ onClose={onClose}
+ uniqueIdentifier={uniqueIdentifier}
+ manifest={manifest}
+ errorMsg={errorMsg}
+ onError={setErrorMsg}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/plugins/install-plugin/install-from-local-package/steps/__tests__/uploading.spec.tsx b/web/app/components/plugins/install-plugin/install-from-local-package/steps/__tests__/uploading.spec.tsx
index aace5dcbe91..674d6a451c2 100644
--- a/web/app/components/plugins/install-plugin/install-from-local-package/steps/__tests__/uploading.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-local-package/steps/__tests__/uploading.spec.tsx
@@ -161,11 +161,9 @@ describe('Uploading', () => {
})
})
- // NOTE: The uploadFile API has an unconventional contract where it always rejects.
- // Success vs failure is determined by whether response.message exists:
- // - If response.message exists → treated as failure (calls onFailed)
- // - If response.message is absent → treated as success (calls onPackageUploaded/onBundleUploaded)
- // This explains why we use mockRejectedValue for "success" scenarios below.
+ // NOTE: Some upload endpoints have historically returned successful plugin upload
+ // payloads through rejected XHR objects, so the component accepts both resolved
+ // responses and rejected responses without an error message.
it('should call onPackageUploaded when upload rejects without error message (success case)', async () => {
const mockResult = {
@@ -193,6 +191,30 @@ describe('Uploading', () => {
})
})
+ it('should call onPackageUploaded when upload resolves with package response', async () => {
+ const mockResult = {
+ unique_identifier: 'test-uid',
+ manifest: createMockManifest(),
+ }
+ mockUploadFile.mockResolvedValue(mockResult)
+
+ const onPackageUploaded = vi.fn()
+ render(
+ <Uploading
+ {...defaultProps}
+ isBundle={false}
+ onPackageUploaded={onPackageUploaded}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(onPackageUploaded).toHaveBeenCalledWith({
+ uniqueIdentifier: mockResult.unique_identifier,
+ manifest: mockResult.manifest,
+ })
+ })
+ })
+
it('should call onBundleUploaded when upload rejects without error message (success case)', async () => {
const mockDependencies = createMockDependencies()
mockUploadFile.mockRejectedValue({
@@ -212,6 +234,24 @@ describe('Uploading', () => {
expect(onBundleUploaded).toHaveBeenCalledWith(mockDependencies)
})
})
+
+ it('should call onBundleUploaded when upload resolves with bundle response', async () => {
+ const mockDependencies = createMockDependencies()
+ mockUploadFile.mockResolvedValue(mockDependencies)
+
+ const onBundleUploaded = vi.fn()
+ render(
+ <Uploading
+ {...defaultProps}
+ isBundle
+ onBundleUploaded={onBundleUploaded}
+ />,
+ )
+
+ await waitFor(() => {
+ expect(onBundleUploaded).toHaveBeenCalledWith(mockDependencies)
+ })
+ })
})
// ================================
@@ -260,35 +300,48 @@ describe('Uploading', () => {
// Edge Cases Tests
// ================================
describe('Edge Cases', () => {
- it('should handle empty response gracefully', async () => {
+ it('should fail gracefully when upload response is empty', async () => {
mockUploadFile.mockRejectedValue({
response: {},
})
const onPackageUploaded = vi.fn()
- render(<Uploading {...defaultProps} onPackageUploaded={onPackageUploaded} />)
+ const onFailed = vi.fn()
+ render(<Uploading {...defaultProps} onPackageUploaded={onPackageUploaded} onFailed={onFailed} />)
await waitFor(() => {
- expect(onPackageUploaded).toHaveBeenCalledWith({
- uniqueIdentifier: undefined,
- manifest: undefined,
- })
+ expect(onPackageUploaded).not.toHaveBeenCalled()
+ expect(onFailed).toHaveBeenCalledWith('plugin.installModal.uploadFailed')
})
})
- it('should handle response with only unique_identifier', async () => {
+ it('should fail gracefully when upload response has no manifest', async () => {
mockUploadFile.mockRejectedValue({
response: { unique_identifier: 'only-uid' },
})
const onPackageUploaded = vi.fn()
- render(<Uploading {...defaultProps} onPackageUploaded={onPackageUploaded} />)
+ const onFailed = vi.fn()
+ render(<Uploading {...defaultProps} onPackageUploaded={onPackageUploaded} onFailed={onFailed} />)
await waitFor(() => {
- expect(onPackageUploaded).toHaveBeenCalledWith({
- uniqueIdentifier: 'only-uid',
- manifest: undefined,
- })
+ expect(onPackageUploaded).not.toHaveBeenCalled()
+ expect(onFailed).toHaveBeenCalledWith('plugin.installModal.uploadFailed')
+ })
+ })
+
+ it('should fail gracefully when upload response is null', async () => {
+ mockUploadFile.mockRejectedValue({
+ response: null,
+ })
+
+ const onPackageUploaded = vi.fn()
+ const onFailed = vi.fn()
+ render(<Uploading {...defaultProps} onPackageUploaded={onPackageUploaded} onFailed={onFailed} />)
+
+ await waitFor(() => {
+ expect(onPackageUploaded).not.toHaveBeenCalled()
+ expect(onFailed).toHaveBeenCalledWith('plugin.installModal.uploadFailed')
})
})
diff --git a/web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx b/web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx
index e7c3b4cd0f6..ea90975ec5c 100644
--- a/web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-local-package/steps/uploading.tsx
@@ -1,8 +1,7 @@
'use client'
import type { FC } from 'react'
-import type { Dependency, PluginDeclaration } from '../../../types'
+import type { Dependency, Plugin, PluginDeclaration } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
-import { RiLoader2Line } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { uploadFile } from '@/service/plugins'
@@ -10,6 +9,40 @@ import Card from '../../../card'
const i18nPrefix = 'installModal'
+type PackageUploadResponse = {
+ unique_identifier: string
+ manifest: PluginDeclaration
+}
+
+type UploadFailureResponse = {
+ message?: string
+}
+
+function isObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null
+}
+
+function isPackageUploadResponse(value: unknown): value is PackageUploadResponse {
+ if (!isObject(value))
+ return false
+
+ return typeof value.unique_identifier === 'string' && isObject(value.manifest)
+}
+
+function getRejectedResponse(error: unknown): unknown {
+ if (!isObject(error) || !('response' in error))
+ return undefined
+
+ return error.response
+}
+
+function getUploadFailureMessage(response: unknown): string | undefined {
+ if (!isObject(response))
+ return undefined
+
+ return (response as UploadFailureResponse).message
+}
+
type Props = {
isBundle: boolean
file: File
@@ -32,36 +65,50 @@ const Uploading: FC<Props> = ({
}) => {
const { t } = useTranslation()
const fileName = file.name
- const handleUpload = async () => {
+ const handleUploadedResponse = React.useCallback((response: unknown) => {
+ if (isBundle) {
+ if (Array.isArray(response)) {
+ onBundleUploaded(response as Dependency[])
+ return
+ }
+ onFailed(t(`${i18nPrefix}.uploadFailed`, { ns: 'plugin' }))
+ return
+ }
+
+ if (!isPackageUploadResponse(response)) {
+ onFailed(t(`${i18nPrefix}.uploadFailed`, { ns: 'plugin' }))
+ return
+ }
+
+ onPackageUploaded({
+ uniqueIdentifier: response.unique_identifier,
+ manifest: response.manifest,
+ })
+ }, [isBundle, onBundleUploaded, onFailed, onPackageUploaded, t])
+
+ const handleUpload = React.useCallback(async () => {
try {
- await uploadFile(file, isBundle)
+ handleUploadedResponse(await uploadFile(file, isBundle))
}
- catch (e: any) {
- if (e.response?.message) {
- onFailed(e.response?.message)
- }
- else { // Why it would into this branch?
- const res = e.response
- if (isBundle) {
- onBundleUploaded(res)
- return
- }
- onPackageUploaded({
- uniqueIdentifier: res.unique_identifier,
- manifest: res.manifest,
- })
+ catch (error: unknown) {
+ const response = getRejectedResponse(error)
+ const message = getUploadFailureMessage(response)
+ if (message) {
+ onFailed(message)
+ return
}
+ handleUploadedResponse(response)
}
- }
+ }, [file, handleUploadedResponse, isBundle, onFailed])
React.useEffect(() => {
handleUpload()
- }, [])
+ }, [handleUpload])
return (
<>
<div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">
<div className="flex items-center gap-1 self-stretch">
- <RiLoader2Line className="h-4 w-4 animate-spin-slow text-text-accent" />
+ <span className="i-ri-loader-2-line h-4 w-4 animate-spin-slow text-text-accent" />
<div className="system-md-regular text-text-secondary">
{t(`${i18nPrefix}.uploadingPackage`, {
ns: 'plugin',
@@ -72,7 +119,7 @@ const Uploading: FC<Props> = ({
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
<Card
className="w-full"
- payload={{ name: fileName } as any}
+ payload={{ name: fileName } as Plugin}
isLoading
loadingFileName={fileName}
installed={false}
diff --git a/web/app/components/plugins/install-plugin/install-from-marketplace/index.tsx b/web/app/components/plugins/install-plugin/install-from-marketplace/index.tsx
index 128b49fcae5..f2bcc14fda1 100644
--- a/web/app/components/plugins/install-plugin/install-from-marketplace/index.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-marketplace/index.tsx
@@ -2,10 +2,10 @@
import type { Dependency, Plugin, PluginManifestInMarket } from '../../types'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogCloseButton, DialogContent } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import { InstallStep } from '../../types'
import Installed from '../base/installed'
import useHideLogic from '../hooks/use-hide-logic'
@@ -70,60 +70,64 @@ const InstallFromMarketplace: React.FC<InstallFromMarketplaceProps> = ({
}, [setIsInstalling])
return (
- <Modal
- isShow={true}
- onClose={foldAnimInto}
- wrapperClassName="z-9999"
- className={cn(modalClassName, 'shadows-shadow-xl flex min-w-[560px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0')}
- closable
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ foldAnimInto()
+ }}
>
- <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
- <div className="self-stretch title-2xl-semi-bold text-text-primary">
- {getTitle()}
+ <DialogContent className={cn('w-[560px] max-w-none! overflow-hidden! text-left align-middle', cn(modalClassName, 'shadows-shadow-xl flex min-w-[560px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg p-0'))}>
+ <DialogCloseButton data-testid="modal-close-button" />
+
+ <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
+ <div className="self-stretch title-2xl-semi-bold text-text-primary">
+ {getTitle()}
+ </div>
</div>
- </div>
- {
- isBundle
- ? (
- <ReadyToInstallBundle
- step={step}
- onStepChange={setStep}
- onStartToInstall={handleStartToInstall}
- setIsInstalling={setIsInstalling}
- onClose={onClose}
- allPlugins={dependencies!}
- isFromMarketPlace
- />
- )
- : (
- <>
- {
- step === InstallStep.readyToInstall && (
- <Install
- uniqueIdentifier={uniqueIdentifier}
- payload={manifest!}
- onCancel={onClose}
- onInstalled={handleInstalled}
- onFailed={handleFailed}
- onStartToInstall={handleStartToInstall}
- />
- )
- }
- {
- [InstallStep.installed, InstallStep.installFailed].includes(step) && (
- <Installed
- payload={manifest!}
- isMarketPayload
- isFailed={step === InstallStep.installFailed}
- errMsg={errorMsg}
- onCancel={onSuccess}
- />
- )
- }
- </>
- )
- }
- </Modal>
+ {
+ isBundle
+ ? (
+ <ReadyToInstallBundle
+ step={step}
+ onStepChange={setStep}
+ onStartToInstall={handleStartToInstall}
+ setIsInstalling={setIsInstalling}
+ onClose={onClose}
+ allPlugins={dependencies!}
+ isFromMarketPlace
+ />
+ )
+ : (
+ <>
+ {
+ step === InstallStep.readyToInstall && (
+ <Install
+ uniqueIdentifier={uniqueIdentifier}
+ payload={manifest!}
+ onCancel={onClose}
+ onInstalled={handleInstalled}
+ onFailed={handleFailed}
+ onStartToInstall={handleStartToInstall}
+ />
+ )
+ }
+ {
+ [InstallStep.installed, InstallStep.installFailed].includes(step) && (
+ <Installed
+ payload={manifest!}
+ isMarketPayload
+ isFailed={step === InstallStep.installFailed}
+ errMsg={errorMsg}
+ onCancel={onSuccess}
+ />
+ )
+ }
+ </>
+ )
+ }
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/schema-modal.spec.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/schema-modal.spec.tsx
index e8a2ee83187..b2debdb10fd 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/schema-modal.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/schema-modal.spec.tsx
@@ -2,14 +2,11 @@ import { fireEvent, render, screen } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import SchemaModal from '../schema-modal'
-vi.mock('@/app/components/base/modal', () => ({
- default: ({
- children,
- isShow,
- }: {
- children: React.ReactNode
- isShow: boolean
- }) => isShow ? <div data-testid="modal">{children}</div> : null,
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ children, open }: { children: React.ReactNode, open?: boolean }) =>
+ open === false ? null : <>{children}</>,
+ DialogContent: ({ children }: { children: React.ReactNode }) => <div data-testid="modal">{children}</div>,
+ DialogTitle: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}))
vi.mock('@/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor', () => ({
diff --git a/web/app/components/plugins/plugin-mutation-model/index.tsx b/web/app/components/plugins/plugin-mutation-model/index.tsx
index 96a60fd938f..339ec9edb5d 100644
--- a/web/app/components/plugins/plugin-mutation-model/index.tsx
+++ b/web/app/components/plugins/plugin-mutation-model/index.tsx
@@ -2,9 +2,9 @@ import type { UseMutationResult } from '@tanstack/react-query'
import type { FC, ReactNode } from 'react'
import type { Plugin } from '../types'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { memo } from 'react'
-import Modal from '@/app/components/base/modal'
import Card from '@/app/components/plugins/card'
type Props = {
@@ -33,45 +33,52 @@ const PluginMutationModal: FC<Props> = ({
modalBottomLeft,
}: Props) => {
return (
- <Modal
- isShow={true}
- onClose={onCancel}
- className="min-w-[560px]"
- closable
- title={modelTitle}
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
>
- <div className="mt-3 mb-2 system-md-regular text-text-secondary">
- {description}
- </div>
- <div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
- <Card
- installed={mutation.isSuccess}
- payload={plugin}
- className="w-full"
- titleLeft={cardTitleLeft}
- />
- </div>
- <div className="flex items-center gap-2 self-stretch pt-5">
- <div>
- {modalBottomLeft}
+ <DialogContent className="w-full min-w-[560px] overflow-hidden! border-none text-left align-middle">
+ <DialogCloseButton data-testid="modal-close-button" />
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {modelTitle}
+ </DialogTitle>
+
+ <div className="mt-3 mb-2 system-md-regular text-text-secondary">
+ {description}
+ </div>
+ <div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
+ <Card
+ installed={mutation.isSuccess}
+ payload={plugin}
+ className="w-full"
+ titleLeft={cardTitleLeft}
+ />
</div>
- <div className="ml-auto flex gap-2">
- {!mutation.isPending && (
- <Button onClick={onCancel}>
- {cancelButtonText}
+ <div className="flex items-center gap-2 self-stretch pt-5">
+ <div>
+ {modalBottomLeft}
+ </div>
+ <div className="ml-auto flex gap-2">
+ {!mutation.isPending && (
+ <Button onClick={onCancel}>
+ {cancelButtonText}
+ </Button>
+ )}
+ <Button
+ variant="primary"
+ loading={mutation.isPending}
+ onClick={mutate}
+ disabled={mutation.isPending}
+ >
+ {confirmButtonText}
</Button>
- )}
- <Button
- variant="primary"
- loading={mutation.isPending}
- onClick={mutate}
- disabled={mutation.isPending}
- >
- {confirmButtonText}
- </Button>
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/plugins/plugin-page/__tests__/plugin-info.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/plugin-info.spec.tsx
index e95f4686f81..54818e4d02a 100644
--- a/web/app/components/plugins/plugin-page/__tests__/plugin-info.spec.tsx
+++ b/web/app/components/plugins/plugin-page/__tests__/plugin-info.spec.tsx
@@ -2,17 +2,19 @@ import { render, screen } from '@testing-library/react'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
-vi.mock('../../../base/modal', () => ({
- default: ({ children, title, isShow }: { children: React.ReactNode, title: string, isShow: boolean }) => (
- isShow
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ children, open }: { children: React.ReactNode, open?: boolean }) => (
+ open !== false
? (
<div data-testid="modal">
- <div data-testid="modal-title">{title}</div>
{children}
</div>
)
: null
),
+ DialogContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
+ DialogTitle: ({ children }: { children: React.ReactNode }) => <div data-testid="modal-title">{children}</div>,
+ DialogCloseButton: () => <button type="button">Close</button>,
}))
vi.mock('../../base/key-value-item', () => ({
diff --git a/web/app/components/plugins/plugin-page/plugin-info.tsx b/web/app/components/plugins/plugin-page/plugin-info.tsx
index 0638bd66a2e..29a137afca6 100644
--- a/web/app/components/plugins/plugin-page/plugin-info.tsx
+++ b/web/app/components/plugins/plugin-page/plugin-info.tsx
@@ -1,8 +1,8 @@
'use client'
import type { FC } from 'react'
+import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '../../base/modal'
import KeyValueItem from '../base/key-value-item'
import { convertRepoToUrl } from '../install-plugin/utils'
@@ -23,19 +23,26 @@ const PlugInfo: FC<Props> = ({
const { t } = useTranslation()
const labelWidthClassName = 'w-[96px]'
return (
- <Modal
- title={t(`${i18nPrefix}.title`, { ns: 'plugin' })}
- className="w-[480px]"
- isShow
- onClose={onHide}
- closable
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
>
- <div className="mt-5 space-y-3">
- {repository && <KeyValueItem label={t(`${i18nPrefix}.repository`, { ns: 'plugin' })} labelWidthClassName={labelWidthClassName} value={`${convertRepoToUrl(repository)}`} valueMaxWidthClassName="max-w-[190px]" />}
- {release && <KeyValueItem label={t(`${i18nPrefix}.release`, { ns: 'plugin' })} labelWidthClassName={labelWidthClassName} value={release} />}
- {packageName && <KeyValueItem label={t(`${i18nPrefix}.packageName`, { ns: 'plugin' })} labelWidthClassName={labelWidthClassName} value={packageName} />}
- </div>
- </Modal>
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden! border-none text-left align-middle">
+ <DialogCloseButton data-testid="modal-close-button" />
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(`${i18nPrefix}.title`, { ns: 'plugin' })}
+ </DialogTitle>
+
+ <div className="mt-5 space-y-3">
+ {repository && <KeyValueItem label={t(`${i18nPrefix}.repository`, { ns: 'plugin' })} labelWidthClassName={labelWidthClassName} value={`${convertRepoToUrl(repository)}`} valueMaxWidthClassName="max-w-[190px]" />}
+ {release && <KeyValueItem label={t(`${i18nPrefix}.release`, { ns: 'plugin' })} labelWidthClassName={labelWidthClassName} value={release} />}
+ {packageName && <KeyValueItem label={t(`${i18nPrefix}.packageName`, { ns: 'plugin' })} labelWidthClassName={labelWidthClassName} value={packageName} />}
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(PlugInfo)
diff --git a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx b/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
index 95a9910038b..f1959e81192 100644
--- a/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/reference-setting-modal/__tests__/index.spec.tsx
@@ -14,28 +14,25 @@ const mockSystemFeatures = { enable_marketplace: true }
const render = (ui: ReactElement) =>
renderWithSystemFeatures(ui, { systemFeatures: mockSystemFeatures })
-// Mock Modal component
-vi.mock('@/app/components/base/modal', () => ({
- default: ({ children, isShow, onClose, closable, className }: {
+let mockDialogOnOpenChange: ((open: boolean) => void) | undefined
+
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ children, open, onOpenChange }: {
children: React.ReactNode
- isShow: boolean
- onClose: () => void
- closable?: boolean
- className?: string
+ open?: boolean
+ onOpenChange?: (open: boolean) => void
}) => {
- if (!isShow)
- return null
- return (
- <div data-testid="modal" className={className}>
- {closable && (
- <button data-testid="modal-close" onClick={onClose}>
- Close
- </button>
- )}
- {children}
- </div>
- )
+ mockDialogOnOpenChange = onOpenChange
+ return open === false ? null : <>{children}</>
},
+ DialogContent: ({ children, className }: { children: React.ReactNode, className?: string }) => (
+ <div data-testid="modal" className={className}>{children}</div>
+ ),
+ DialogCloseButton: () => (
+ <button data-testid="modal-close" onClick={() => mockDialogOnOpenChange?.(false)}>
+ Close
+ </button>
+ ),
}))
// Mock OptionCard component
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/index.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/index.tsx
index d7d6fcd35f3..5710eb7a661 100644
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/index.tsx
+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/index.tsx
@@ -143,7 +143,6 @@ const AutoUpdateSetting: FC<Props> = ({
timezone={timezone}
onChange={v => handleChange('upgrade_time_of_day')(convertLocalSecondsToUTCDaySeconds(dayjsToTimeOfDay(v), timezone!))}
onClear={() => handleChange('upgrade_time_of_day')(convertLocalSecondsToUTCDaySeconds(0, timezone!))}
- popupClassName="z-99"
title={t(`${i18nPrefix}.updateTime`, { ns: 'plugin' })}
minuteFilter={minuteFilter}
renderTrigger={renderTimePickerTrigger}
diff --git a/web/app/components/plugins/reference-setting-modal/index.tsx b/web/app/components/plugins/reference-setting-modal/index.tsx
index b93713bdd8e..9bc0aaf7d60 100644
--- a/web/app/components/plugins/reference-setting-modal/index.tsx
+++ b/web/app/components/plugins/reference-setting-modal/index.tsx
@@ -3,11 +3,11 @@ import type { FC } from 'react'
import type { AutoUpdateConfig } from './auto-update-setting/types'
import type { Permissions, ReferenceSetting } from '@/app/components/plugins/types'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogCloseButton, DialogContent } from '@langgenius/dify-ui/dialog'
import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import { PermissionType } from '@/app/components/plugins/types'
import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card'
import { systemFeaturesQueryOptions } from '@/service/system-features'
@@ -53,59 +53,64 @@ const PluginSettingModal: FC<Props> = ({
}, [onHide, onSave, tempAutoUpdateConfig, tempPrivilege])
return (
- <Modal
- isShow
- onClose={onHide}
- closable
- className="w-[620px] max-w-[620px] p-0!"
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
>
- <div className="shadows-shadow-xl flex w-full flex-col items-start rounded-2xl border border-components-panel-border bg-components-panel-bg">
- <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
- <span className="self-stretch title-2xl-semi-bold text-text-primary">{t(`${i18nPrefix}.title`, { ns: 'plugin' })}</span>
- </div>
- <div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">
- {[
- { title: t(`${i18nPrefix}.whoCanInstall`, { ns: 'plugin' }), key: 'install_permission', value: tempPrivilege?.install_permission || PermissionType.noOne },
- { title: t(`${i18nPrefix}.whoCanDebug`, { ns: 'plugin' }), key: 'debug_permission', value: tempPrivilege?.debug_permission || PermissionType.noOne },
- ].map(({ title, key, value }) => (
- <div key={key} className="flex flex-col items-start gap-1 self-stretch">
- <Label label={title} />
- <div className="flex w-full items-start justify-between gap-2">
- {[PermissionType.everyone, PermissionType.admin, PermissionType.noOne].map(option => (
- <OptionCard
- key={option}
- title={t(`${i18nPrefix}.${option}`, { ns: 'plugin' })}
- onSelect={() => handlePrivilegeChange(key)(option)}
- selected={value === option}
- className="flex-1"
- />
- ))}
+ <DialogContent className="w-[620px] max-w-[620px] overflow-hidden! border-none p-0! text-left align-middle">
+ <DialogCloseButton data-testid="modal-close-button" />
+
+ <div className="shadows-shadow-xl flex w-full flex-col items-start rounded-2xl border border-components-panel-border bg-components-panel-bg">
+ <div className="flex items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
+ <span className="self-stretch title-2xl-semi-bold text-text-primary">{t(`${i18nPrefix}.title`, { ns: 'plugin' })}</span>
+ </div>
+ <div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">
+ {[
+ { title: t(`${i18nPrefix}.whoCanInstall`, { ns: 'plugin' }), key: 'install_permission', value: tempPrivilege?.install_permission || PermissionType.noOne },
+ { title: t(`${i18nPrefix}.whoCanDebug`, { ns: 'plugin' }), key: 'debug_permission', value: tempPrivilege?.debug_permission || PermissionType.noOne },
+ ].map(({ title, key, value }) => (
+ <div key={key} className="flex flex-col items-start gap-1 self-stretch">
+ <Label label={title} />
+ <div className="flex w-full items-start justify-between gap-2">
+ {[PermissionType.everyone, PermissionType.admin, PermissionType.noOne].map(option => (
+ <OptionCard
+ key={option}
+ title={t(`${i18nPrefix}.${option}`, { ns: 'plugin' })}
+ onSelect={() => handlePrivilegeChange(key)(option)}
+ selected={value === option}
+ className="flex-1"
+ />
+ ))}
+ </div>
</div>
- </div>
- ))}
- </div>
- {
- enable_marketplace && (
- <AutoUpdateSetting payload={tempAutoUpdateConfig} onChange={setTempAutoUpdateConfig} />
- )
- }
- <div className="flex h-[76px] items-center justify-end gap-2 self-stretch p-6 pt-5">
- <Button
- className="min-w-[72px]"
- onClick={onHide}
- >
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button
- className="min-w-[72px]"
- variant="primary"
- onClick={handleSave}
- >
- {t('operation.save', { ns: 'common' })}
- </Button>
+ ))}
+ </div>
+ {
+ enable_marketplace && (
+ <AutoUpdateSetting payload={tempAutoUpdateConfig} onChange={setTempAutoUpdateConfig} />
+ )
+ }
+ <div className="flex h-[76px] items-center justify-end gap-2 self-stretch p-6 pt-5">
+ <Button
+ className="min-w-[72px]"
+ onClick={onHide}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ className="min-w-[72px]"
+ variant="primary"
+ onClick={handleSave}
+ >
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/rag-pipeline/components/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/index.spec.tsx
index 0eec89b8b8d..30b503899e0 100644
--- a/web/app/components/rag-pipeline/components/__tests__/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/index.spec.tsx
@@ -420,7 +420,7 @@ function getDescriptionTextarea() {
}
// Helper to find the AppIcon span in PublishAsKnowledgePipelineModal
-// HeadlessUI Dialog renders via portal to document.body, so we search the full document
+// The modal renders via portal to document.body, so we search the full document.
function getAppIcon() {
const emoji = document.querySelector('em-emoji')
return emoji?.closest('span') as HTMLElement
@@ -687,7 +687,7 @@ describe('PublishAsKnowledgePipelineModal', () => {
render(<PublishAsKnowledgePipelineModal {...defaultProps} />)
// Real AppIcon renders an em-emoji custom element inside a span
- // HeadlessUI Dialog renders via portal, so search the full document
+ // The modal renders via portal, so search the full document.
expect(document.querySelector('em-emoji')).toBeInTheDocument()
})
@@ -845,7 +845,7 @@ describe('PublishAsKnowledgePipelineModal', () => {
const { rerender } = render(<PublishAsKnowledgePipelineModal {...defaultProps} />)
rerender(<PublishAsKnowledgePipelineModal {...defaultProps} />)
- // HeadlessUI Dialog renders via portal, so search the full document
+ // The modal renders via portal, so search the full document.
expect(document.querySelector('em-emoji')).toBeInTheDocument()
})
})
diff --git a/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx
index 7a99b7ab903..e1a4af0410b 100644
--- a/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx
@@ -17,9 +17,12 @@ vi.mock('@/app/components/workflow/store', () => ({
}),
}))
-vi.mock('@/app/components/base/modal', () => ({
- default: ({ children, isShow }: { children: React.ReactNode, isShow: boolean }) =>
- isShow ? <div data-testid="modal">{children}</div> : null,
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ children, open }: { children: React.ReactNode, open?: boolean }) =>
+ open === false ? null : <>{children}</>,
+ DialogContent: ({ children, className }: { children: React.ReactNode, className?: string }) => (
+ <div data-testid="modal" className={className}>{children}</div>
+ ),
}))
vi.mock('@langgenius/dify-ui/button', () => ({
diff --git a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
index d31a06f4213..815b21ba981 100644
--- a/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/update-dsl-modal.spec.tsx
@@ -121,18 +121,14 @@ vi.mock('@langgenius/dify-ui/button', () => ({
),
}))
-vi.mock('@/app/components/base/modal', () => ({
- default: ({ children, isShow, _onClose, className }: PropsWithChildren<{
- isShow: boolean
- _onClose: () => void
- className?: string
- }>) => isShow
- ? (
- <div data-testid="modal" className={className}>
- {children}
- </div>
- )
- : null,
+vi.mock('@langgenius/dify-ui/dialog', () => ({
+ Dialog: ({ children, open }: PropsWithChildren<{ open?: boolean }>) =>
+ open === false ? null : <>{children}</>,
+ DialogContent: ({ children, className }: PropsWithChildren<{ className?: string }>) => (
+ <div data-testid="modal" className={className}>
+ {children}
+ </div>
+ ),
}))
vi.mock('@/app/components/workflow/constants', () => ({
diff --git a/web/app/components/rag-pipeline/components/__tests__/version-mismatch-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/version-mismatch-modal.spec.tsx
index 56ed88e2ae8..b4b29fd0a87 100644
--- a/web/app/components/rag-pipeline/components/__tests__/version-mismatch-modal.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/version-mismatch-modal.spec.tsx
@@ -31,13 +31,13 @@ describe('VersionMismatchModal', () => {
it('should render dialog when isShow is true', () => {
render(<VersionMismatchModal {...defaultProps} />)
- expect(screen.getByRole('dialog')).toBeInTheDocument()
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
})
it('should not render dialog when isShow is false', () => {
render(<VersionMismatchModal {...defaultProps} isShow={false} />)
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
})
it('should render error title', () => {
diff --git a/web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx b/web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx
index faa71f0f4e8..eeb6337847e 100644
--- a/web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx
+++ b/web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx
@@ -2,14 +2,13 @@
import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
import type { IconInfo } from '@/models/datasets'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { RiCloseLine } from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import AppIconPicker from '@/app/components/base/app-icon-picker'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import Textarea from '@/app/components/base/textarea'
import { useWorkflowStore } from '@/app/components/workflow/store'
@@ -77,77 +76,76 @@ const PublishAsKnowledgePipelineModal = ({
return (
<>
- <Modal
- isShow
- onClose={noop}
- className="relative w-[520px]! p-0!"
- >
- <div className="relative flex items-center p-6 pr-14 pb-3 title-2xl-semi-bold text-text-primary">
- {t('common.publishAs', { ns: 'pipeline' })}
- <div
- data-testid="publish-modal-close-btn"
- className="absolute top-5 right-5 flex h-8 w-8 cursor-pointer items-center justify-center"
- onClick={onCancel}
- >
- <RiCloseLine className="h-4 w-4 text-text-tertiary" />
+ <Dialog open>
+ <DialogContent className="relative w-full max-w-[480px]! overflow-hidden! border-none p-0! text-left align-middle">
+
+ <div className="relative flex items-center p-6 pr-14 pb-3 title-2xl-semi-bold text-text-primary">
+ {t('common.publishAs', { ns: 'pipeline' })}
+ <div
+ data-testid="publish-modal-close-btn"
+ className="absolute top-5 right-5 flex h-8 w-8 cursor-pointer items-center justify-center"
+ onClick={onCancel}
+ >
+ <RiCloseLine className="h-4 w-4 text-text-tertiary" />
+ </div>
</div>
- </div>
- <div className="px-6 py-3">
- <div className="mb-5 flex">
- <div className="mr-3 grow">
+ <div className="px-6 py-3">
+ <div className="mb-5 flex">
+ <div className="mr-3 grow">
+ <div className="mb-1 flex h-6 items-center system-sm-medium text-text-secondary">
+ {t('common.publishAsPipeline.name', { ns: 'pipeline' })}
+ </div>
+ <Input
+ value={pipelineName}
+ onChange={e => setPipelineName(e.target.value)}
+ placeholder={t('common.publishAsPipeline.namePlaceholder', { ns: 'pipeline' }) || ''}
+ />
+ </div>
+ <AppIcon
+ size="xxl"
+ onClick={() => { setShowAppIconPicker(true) }}
+ className="mt-2 shrink-0 cursor-pointer"
+ iconType={pipelineIcon?.icon_type}
+ icon={pipelineIcon?.icon}
+ background={pipelineIcon?.icon_background}
+ imageUrl={pipelineIcon?.icon_url}
+ />
+ </div>
+ <div>
<div className="mb-1 flex h-6 items-center system-sm-medium text-text-secondary">
- {t('common.publishAsPipeline.name', { ns: 'pipeline' })}
+ {t('common.publishAsPipeline.description', { ns: 'pipeline' })}
</div>
- <Input
- value={pipelineName}
- onChange={e => setPipelineName(e.target.value)}
- placeholder={t('common.publishAsPipeline.namePlaceholder', { ns: 'pipeline' }) || ''}
+ <Textarea
+ className="resize-none"
+ placeholder={t('common.publishAsPipeline.descriptionPlaceholder', { ns: 'pipeline' }) || ''}
+ value={description}
+ onChange={e => setDescription(e.target.value)}
/>
</div>
- <AppIcon
- size="xxl"
- onClick={() => { setShowAppIconPicker(true) }}
- className="mt-2 shrink-0 cursor-pointer"
- iconType={pipelineIcon?.icon_type}
- icon={pipelineIcon?.icon}
- background={pipelineIcon?.icon_background}
- imageUrl={pipelineIcon?.icon_url}
- />
</div>
- <div>
- <div className="mb-1 flex h-6 items-center system-sm-medium text-text-secondary">
- {t('common.publishAsPipeline.description', { ns: 'pipeline' })}
- </div>
- <Textarea
- className="resize-none"
- placeholder={t('common.publishAsPipeline.descriptionPlaceholder', { ns: 'pipeline' }) || ''}
- value={description}
- onChange={e => setDescription(e.target.value)}
- />
+ <div className="flex items-center justify-end px-6 py-5">
+ <Button
+ className="mr-2"
+ onClick={onCancel}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </Button>
+ <Button
+ disabled={!pipelineName?.trim() || confirmDisabled}
+ variant="primary"
+ onClick={() => handleConfirm()}
+ >
+ {t('common.publish', { ns: 'workflow' })}
+ </Button>
</div>
- </div>
- <div className="flex items-center justify-end px-6 py-5">
- <Button
- className="mr-2"
- onClick={onCancel}
- >
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button
- disabled={!pipelineName?.trim() || confirmDisabled}
- variant="primary"
- onClick={() => handleConfirm()}
- >
- {t('common.publish', { ns: 'workflow' })}
- </Button>
- </div>
- </Modal>
- {showAppIconPicker && (
- <AppIconPicker
- onSelect={handleSelectIcon}
- onClose={handleCloseIconPicker}
- />
- )}
+ {showAppIconPicker && (
+ <AppIconPicker
+ onSelect={handleSelectIcon}
+ onClose={handleCloseIconPicker}
+ />
+ )}
+ </DialogContent>
+ </Dialog>
</>
)
}
diff --git a/web/app/components/rag-pipeline/components/update-dsl-modal.tsx b/web/app/components/rag-pipeline/components/update-dsl-modal.tsx
index 742c29a6da2..da75e03b5ca 100644
--- a/web/app/components/rag-pipeline/components/update-dsl-modal.tsx
+++ b/web/app/components/rag-pipeline/components/update-dsl-modal.tsx
@@ -1,6 +1,7 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import {
RiAlertFill,
RiCloseLine,
@@ -9,7 +10,6 @@ import {
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import Uploader from '@/app/components/app/create-from-dsl-modal/uploader'
-import Modal from '@/app/components/base/modal'
import { useUpdateDSLModal } from '../hooks/use-update-dsl-modal'
import VersionMismatchModal from './version-mismatch-modal'
@@ -39,66 +39,71 @@ const UpdateDSLModal = ({
return (
<>
- <Modal
- className="w-[520px] rounded-2xl p-6"
- isShow={show}
- onClose={onCancel}
+ <Dialog
+ open={show}
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
>
- <div className="mb-3 flex items-center justify-between">
- <div className="title-2xl-semi-bold text-text-primary">{t('common.importDSL', { ns: 'workflow' })}</div>
- <div className="flex h-[22px] w-[22px] cursor-pointer items-center justify-center" onClick={onCancel}>
- <RiCloseLine className="h-[18px] w-[18px] text-text-tertiary" />
- </div>
- </div>
- <div className="relative mb-2 flex grow gap-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-xs">
- <div className="absolute top-0 left-0 h-full w-full bg-toast-warning-bg opacity-40" />
- <div className="flex items-start justify-center p-1">
- <RiAlertFill className="h-4 w-4 shrink-0 text-text-warning-secondary" />
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden! rounded-2xl border-none p-6 text-left align-middle">
+
+ <div className="mb-3 flex items-center justify-between">
+ <div className="title-2xl-semi-bold text-text-primary">{t('common.importDSL', { ns: 'workflow' })}</div>
+ <div className="flex h-[22px] w-[22px] cursor-pointer items-center justify-center" onClick={onCancel}>
+ <RiCloseLine className="h-[18px] w-[18px] text-text-tertiary" />
+ </div>
</div>
- <div className="flex grow flex-col items-start gap-0.5 py-1">
- <div className="system-xs-medium whitespace-pre-line text-text-primary">{t('common.importDSLTip', { ns: 'workflow' })}</div>
- <div className="flex items-start gap-1 self-stretch pt-1 pb-0.5">
- <Button
- size="small"
- variant="secondary"
- className="z-1000"
- onClick={onBackup}
- >
- <RiFileDownloadLine className="h-3.5 w-3.5 text-components-button-secondary-text" />
- <div className="flex items-center justify-center gap-1 px-[3px]">
- {t('common.backupCurrentDraft', { ns: 'workflow' })}
- </div>
- </Button>
+ <div className="relative mb-2 flex grow gap-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-xs">
+ <div className="absolute top-0 left-0 h-full w-full bg-toast-warning-bg opacity-40" />
+ <div className="flex items-start justify-center p-1">
+ <RiAlertFill className="h-4 w-4 shrink-0 text-text-warning-secondary" />
+ </div>
+ <div className="flex grow flex-col items-start gap-0.5 py-1">
+ <div className="system-xs-medium whitespace-pre-line text-text-primary">{t('common.importDSLTip', { ns: 'workflow' })}</div>
+ <div className="flex items-start gap-1 self-stretch pt-1 pb-0.5">
+ <Button
+ size="small"
+ variant="secondary"
+ className="z-1000"
+ onClick={onBackup}
+ >
+ <RiFileDownloadLine className="h-3.5 w-3.5 text-components-button-secondary-text" />
+ <div className="flex items-center justify-center gap-1 px-[3px]">
+ {t('common.backupCurrentDraft', { ns: 'workflow' })}
+ </div>
+ </Button>
+ </div>
</div>
</div>
- </div>
- <div>
- <div className="pt-2 system-md-semibold text-text-primary">
- {t('common.chooseDSL', { ns: 'workflow' })}
+ <div>
+ <div className="pt-2 system-md-semibold text-text-primary">
+ {t('common.chooseDSL', { ns: 'workflow' })}
+ </div>
+ <div className="flex w-full flex-col items-start justify-center gap-4 self-stretch py-4">
+ <Uploader
+ file={currentFile}
+ updateFile={handleFile}
+ className="mt-0! w-full"
+ accept=".pipeline"
+ displayName="PIPELINE"
+ />
+ </div>
</div>
- <div className="flex w-full flex-col items-start justify-center gap-4 self-stretch py-4">
- <Uploader
- file={currentFile}
- updateFile={handleFile}
- className="mt-0! w-full"
- accept=".pipeline"
- displayName="PIPELINE"
- />
+ <div className="flex items-center justify-end gap-2 self-stretch pt-5">
+ <Button onClick={onCancel}>{t('newApp.Cancel', { ns: 'app' })}</Button>
+ <Button
+ disabled={!currentFile || loading}
+ variant="primary"
+ tone="destructive"
+ onClick={handleImport}
+ loading={loading}
+ >
+ {t('common.overwriteAndImport', { ns: 'workflow' })}
+ </Button>
</div>
- </div>
- <div className="flex items-center justify-end gap-2 self-stretch pt-5">
- <Button onClick={onCancel}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button
- disabled={!currentFile || loading}
- variant="primary"
- tone="destructive"
- onClick={handleImport}
- loading={loading}
- >
- {t('common.overwriteAndImport', { ns: 'workflow' })}
- </Button>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
<VersionMismatchModal
isShow={showErrorModal}
versions={versions}
diff --git a/web/app/components/rag-pipeline/components/version-mismatch-modal.tsx b/web/app/components/rag-pipeline/components/version-mismatch-modal.tsx
index dc50e972e97..221757de02e 100644
--- a/web/app/components/rag-pipeline/components/version-mismatch-modal.tsx
+++ b/web/app/components/rag-pipeline/components/version-mismatch-modal.tsx
@@ -1,7 +1,14 @@
import type { MouseEventHandler } from 'react'
-import { Button } from '@langgenius/dify-ui/button'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
type VersionMismatchModalProps = {
isShow: boolean
@@ -22,32 +29,36 @@ const VersionMismatchModal = ({
const { t } = useTranslation()
return (
- <Modal
- isShow={isShow}
- onClose={onClose}
- className="w-[480px]"
+ <AlertDialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className="flex flex-col items-start gap-2 self-stretch pb-4">
- <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>
- <div className="flex grow flex-col system-md-regular text-text-secondary">
- <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
- <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
- <br />
- <div>
- {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
- <span className="system-md-medium">{versions?.importedVersion}</span>
- </div>
- <div>
- {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
- <span className="system-md-medium">{versions?.systemVersion}</span>
- </div>
+ <AlertDialogContent className="w-[480px] max-w-none! overflow-hidden! border-none p-6 text-left align-middle shadow-xl">
+ <div className="flex flex-col items-start gap-2 self-stretch pb-4">
+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</AlertDialogTitle>
+ <AlertDialogDescription render={<div />} className="flex grow flex-col system-md-regular text-text-secondary">
+ <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
+ <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
+ <br />
+ <div>
+ {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
+ <span className="system-md-medium">{versions?.importedVersion}</span>
+ </div>
+ <div>
+ {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
+ <span className="system-md-medium">{versions?.systemVersion}</span>
+ </div>
+ </AlertDialogDescription>
</div>
- </div>
- <div className="flex items-start justify-end gap-2 self-stretch pt-6">
- <Button variant="secondary" onClick={onClose}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button variant="primary" tone="destructive" onClick={onConfirm}>{t('newApp.Confirm', { ns: 'app' })}</Button>
- </div>
- </Modal>
+ <AlertDialogActions className="items-start p-0 pt-6">
+ <AlertDialogCancelButton variant="secondary">{t('newApp.Cancel', { ns: 'app' })}</AlertDialogCancelButton>
+ <AlertDialogConfirmButton onClick={onConfirm}>{t('newApp.Confirm', { ns: 'app' })}</AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
)
}
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
index 2449bcc6056..6876df90141 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-update-dsl-modal.spec.ts
@@ -340,6 +340,7 @@ describe('useUpdateDSLModal', () => {
id: 'import-id',
status: DSLImportStatus.FAILED,
pipeline_id: 'test-pipeline-id',
+ error: 'Missing rag_pipeline data in YAML content',
})
const { result } = renderUpdateDSLModal()
@@ -351,7 +352,10 @@ describe('useUpdateDSLModal', () => {
await (result.current.handleImport as unknown as AsyncFn)()
})
- expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))
+ expect(toastMocks.call).toHaveBeenCalledWith({
+ type: 'error',
+ message: 'Missing rag_pipeline data in YAML content',
+ })
})
it('should notify error when importDSL throws', async () => {
@@ -369,6 +373,29 @@ describe('useUpdateDSLModal', () => {
expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))
})
+ it('should notify response error when importDSL rejects with a response body', async () => {
+ mockImportDSL.mockRejectedValue(new Response(JSON.stringify({
+ error: 'Missing rag_pipeline data in YAML content',
+ }), {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ }))
+
+ const { result } = renderUpdateDSLModal()
+ act(() => {
+ result.current.handleFile(createFile())
+ })
+
+ await act(async () => {
+ await (result.current.handleImport as unknown as AsyncFn)()
+ })
+
+ expect(toastMocks.call).toHaveBeenCalledWith({
+ type: 'error',
+ message: 'Missing rag_pipeline data in YAML content',
+ })
+ })
+
it('should notify error when pipeline_id is missing on success', async () => {
mockImportDSL.mockResolvedValue({
id: 'import-id',
@@ -468,6 +495,7 @@ describe('useUpdateDSLModal', () => {
mockImportDSLConfirm.mockResolvedValue({
status: DSLImportStatus.FAILED,
pipeline_id: 'test-pipeline-id',
+ error: 'Import information expired or does not exist',
})
const { result } = renderUpdateDSLModal()
@@ -477,7 +505,10 @@ describe('useUpdateDSLModal', () => {
await (result.current.onUpdateDSLConfirm as unknown as AsyncFn)()
})
- expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))
+ expect(toastMocks.call).toHaveBeenCalledWith({
+ type: 'error',
+ message: 'Import information expired or does not exist',
+ })
})
it('should notify error when confirm throws exception', async () => {
@@ -493,6 +524,27 @@ describe('useUpdateDSLModal', () => {
expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }))
})
+ it('should notify response error when confirm rejects with a response body', async () => {
+ mockImportDSLConfirm.mockRejectedValue(new Response(JSON.stringify({
+ error: 'Import information expired or does not exist',
+ }), {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' },
+ }))
+
+ const { result } = renderUpdateDSLModal()
+ await setupPendingState(result)
+
+ await act(async () => {
+ await (result.current.onUpdateDSLConfirm as unknown as AsyncFn)()
+ })
+
+ expect(toastMocks.call).toHaveBeenCalledWith({
+ type: 'error',
+ message: 'Import information expired or does not exist',
+ })
+ })
+
it('should notify error when confirm succeeds but pipeline_id is missing', async () => {
mockImportDSLConfirm.mockResolvedValue({
status: DSLImportStatus.COMPLETED,
diff --git a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
index 7271279996b..0d12a0a8818 100644
--- a/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
+++ b/web/app/components/rag-pipeline/hooks/use-update-dsl-modal.ts
@@ -15,11 +15,36 @@ type VersionInfo = {
importedVersion: string
systemVersion: string
}
+type ImportErrorResponse = {
+ message?: unknown
+ error?: unknown
+}
type UseUpdateDSLModalParams = {
onCancel: () => void
onImport?: () => void
}
const isCompletedStatus = (status: DSLImportStatus): boolean => status === DSLImportStatus.COMPLETED || status === DSLImportStatus.COMPLETED_WITH_WARNINGS
+const getNonEmptyString = (value: unknown): string | undefined => {
+ if (typeof value !== 'string')
+ return undefined
+
+ const trimmedValue = value.trim()
+ return trimmedValue || undefined
+}
+const getImportErrorMessage = async (error: unknown): Promise<string | undefined> => {
+ if (error instanceof Response && !error.bodyUsed) {
+ try {
+ const errorData = await error.clone().json() as ImportErrorResponse
+ return getNonEmptyString(errorData.message) ?? getNonEmptyString(errorData.error)
+ }
+ catch {}
+ }
+
+ if (error instanceof Error)
+ return getNonEmptyString(error.message)
+
+ return undefined
+}
export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParams) => {
const { t } = useTranslation()
const { eventEmitter } = useEventEmitterContextContext()
@@ -52,9 +77,9 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam
if (!file)
setFileContent('')
}
- const notifyError = useCallback(() => {
+ const notifyError = useCallback((message?: string) => {
setLoading(false)
- toast.error(t('common.importFailure', { ns: 'workflow' }))
+ toast.error(message || t('common.importFailure', { ns: 'workflow' }))
}, [t])
const updateWorkflow = useCallback(async (pipelineId: string) => {
const { graph, hash, rag_pipeline_variables } = await fetchWorkflowDraft(`/rag/pipelines/${pipelineId}/workflows/draft`)
@@ -117,10 +142,10 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam
else if (status === DSLImportStatus.PENDING)
showVersionMismatch(id, imported_dsl_version, current_dsl_version)
else
- notifyError()
+ notifyError(response.error)
}
- catch {
- notifyError()
+ catch (error) {
+ notifyError(await getImportErrorMessage(error))
}
isCreatingRef.current = false
}, [currentFile, fileContent, workflowStore, importDSL, completeImport, showVersionMismatch, notifyError])
@@ -128,16 +153,16 @@ export const useUpdateDSLModal = ({ onCancel, onImport }: UseUpdateDSLModalParam
if (!importId)
return
try {
- const { status, pipeline_id } = await importDSLConfirm(importId)
+ const { status, pipeline_id, error } = await importDSLConfirm(importId)
if (status === DSLImportStatus.COMPLETED) {
await completeImport(pipeline_id)
return
}
if (status === DSLImportStatus.FAILED)
- notifyError()
+ notifyError(error)
}
- catch {
- notifyError()
+ catch (error) {
+ notifyError(await getImportErrorMessage(error))
}
}, [importId, importDSLConfirm, completeImport, notifyError])
return {
diff --git a/web/app/components/share/text-generation/info-modal.tsx b/web/app/components/share/text-generation/info-modal.tsx
index 29471548ef9..f3b2bef5ade 100644
--- a/web/app/components/share/text-generation/info-modal.tsx
+++ b/web/app/components/share/text-generation/info-modal.tsx
@@ -1,8 +1,8 @@
import type { SiteInfo } from '@/models/share'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogCloseButton, DialogContent } from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import AppIcon from '@/app/components/base/app-icon'
-import Modal from '@/app/components/base/modal'
import { appDefaultIconBackground } from '@/config'
type Props = {
@@ -17,37 +17,42 @@ const InfoModal = ({
data,
}: Props) => {
return (
- <Modal
- isShow={isShow}
- onClose={onClose}
- className="max-w-[400px] min-w-[400px] p-0!"
- closable
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className={cn('flex flex-col items-center gap-4 px-4 pt-10 pb-8')}>
- <AppIcon
- size="xxl"
- iconType={data?.icon_type}
- icon={data?.icon}
- background={data?.icon_background || appDefaultIconBackground}
- imageUrl={data?.icon_url}
- />
- <div className="system-xl-semibold text-text-secondary">{data?.title}</div>
- <div className="system-xs-regular text-text-tertiary">
- {/* copyright */}
- {data?.copyright && (
- <div>
- ©
- {(new Date()).getFullYear()}
- {' '}
- {data?.copyright}
- </div>
- )}
- {data?.custom_disclaimer && (
- <div className="mt-2">{data.custom_disclaimer}</div>
- )}
+ <DialogContent className="w-full max-w-[400px] min-w-[400px] overflow-hidden! border-none p-0! text-left align-middle">
+ <DialogCloseButton data-testid="modal-close-button" />
+
+ <div className={cn('flex flex-col items-center gap-4 px-4 pt-10 pb-8')}>
+ <AppIcon
+ size="xxl"
+ iconType={data?.icon_type}
+ icon={data?.icon}
+ background={data?.icon_background || appDefaultIconBackground}
+ imageUrl={data?.icon_url}
+ />
+ <div className="system-xl-semibold text-text-secondary">{data?.title}</div>
+ <div className="system-xs-regular text-text-tertiary">
+ {/* copyright */}
+ {data?.copyright && (
+ <div>
+ ©
+ {(new Date()).getFullYear()}
+ {' '}
+ {data?.copyright}
+ </div>
+ )}
+ {data?.custom_disclaimer && (
+ <div className="mt-2">{data.custom_disclaimer}</div>
+ )}
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/tools/mcp/__tests__/mcp-server-modal.spec.tsx b/web/app/components/tools/mcp/__tests__/mcp-server-modal.spec.tsx
index 9029ee56a24..c496dd9adf6 100644
--- a/web/app/components/tools/mcp/__tests__/mcp-server-modal.spec.tsx
+++ b/web/app/components/tools/mcp/__tests__/mcp-server-modal.spec.tsx
@@ -3,9 +3,12 @@ import type { MCPServerDetail } from '@/app/components/tools/types'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as React from 'react'
-import { describe, expect, it, vi } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import MCPServerModal from '../mcp-server-modal'
+const mockGetSocket = vi.hoisted(() => vi.fn())
+const mockSocketEmit = vi.hoisted(() => vi.fn())
+
// Mock the services
vi.mock('@/service/use-tools', () => ({
useCreateMCPServer: () => ({
@@ -19,6 +22,12 @@ vi.mock('@/service/use-tools', () => ({
useInvalidateMCPServerDetail: () => vi.fn(),
}))
+vi.mock('@/app/components/workflow/collaboration/core/websocket-manager', () => ({
+ webSocketClient: {
+ getSocket: mockGetSocket,
+ },
+}))
+
describe('MCPServerModal', () => {
const createWrapper = () => {
const queryClient = new QueryClient({
@@ -38,6 +47,11 @@ describe('MCPServerModal', () => {
onHide: vi.fn(),
}
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockGetSocket.mockReturnValue(null)
+ })
+
describe('Rendering', () => {
it('should render without crashing', () => {
render(<MCPServerModal {...defaultProps} />, { wrapper: createWrapper() })
@@ -168,6 +182,15 @@ describe('MCPServerModal', () => {
}
})
+ it('should call onHide when the dialog requests close', () => {
+ const onHide = vi.fn()
+ render(<MCPServerModal {...defaultProps} onHide={onHide} />, { wrapper: createWrapper() })
+
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ expect(onHide).toHaveBeenCalledTimes(1)
+ })
+
it('should disable confirm button when description is empty', () => {
render(<MCPServerModal {...defaultProps} />, { wrapper: createWrapper() })
@@ -346,6 +369,48 @@ describe('MCPServerModal', () => {
})
})
+ it('should ignore parameters without variables when rendering and submitting', async () => {
+ const onHide = vi.fn()
+ const latestParams = [
+ { label: 'Missing variable', type: 'string' },
+ ]
+
+ render(
+ <MCPServerModal {...defaultProps} latestParams={latestParams} onHide={onHide} />,
+ { wrapper: createWrapper() },
+ )
+
+ expect(screen.queryByText('Missing variable')).not.toBeInTheDocument()
+
+ fireEvent.change(screen.getByPlaceholderText('tools.mcp.server.modal.descriptionPlaceholder'), {
+ target: { value: 'Test description' },
+ })
+ fireEvent.click(screen.getByText('tools.mcp.server.modal.confirm'))
+
+ await waitFor(() => {
+ expect(onHide).toHaveBeenCalled()
+ })
+ })
+
+ it('should emit a created update when socket exists', async () => {
+ const onHide = vi.fn()
+ mockGetSocket.mockReturnValue({ emit: mockSocketEmit })
+
+ render(<MCPServerModal {...defaultProps} onHide={onHide} />, { wrapper: createWrapper() })
+
+ fireEvent.change(screen.getByPlaceholderText('tools.mcp.server.modal.descriptionPlaceholder'), {
+ target: { value: 'Test description' },
+ })
+ fireEvent.click(screen.getByText('tools.mcp.server.modal.confirm'))
+
+ await waitFor(() => {
+ expect(mockSocketEmit).toHaveBeenCalledWith('collaboration_event', expect.objectContaining({
+ type: 'mcp_server_update',
+ data: expect.objectContaining({ action: 'created' }),
+ }))
+ })
+ })
+
it('should handle empty description submission', async () => {
const onHide = vi.fn()
render(<MCPServerModal {...defaultProps} onHide={onHide} />, { wrapper: createWrapper() })
diff --git a/web/app/components/tools/mcp/mcp-server-modal.tsx b/web/app/components/tools/mcp/mcp-server-modal.tsx
index ab4a5c36f4d..cfb33f38399 100644
--- a/web/app/components/tools/mcp/mcp-server-modal.tsx
+++ b/web/app/components/tools/mcp/mcp-server-modal.tsx
@@ -3,12 +3,11 @@ import type {
MCPServerDetail,
} from '@/app/components/tools/types'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { RiCloseLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import Divider from '@/app/components/base/divider'
-import Modal from '@/app/components/base/modal'
import Textarea from '@/app/components/base/textarea'
import MCPServerParamItem from '@/app/components/tools/mcp/mcp-server-param-item'
import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'
@@ -20,11 +19,19 @@ import {
type ModalProps = {
appID: string
- latestParams?: any[]
+ latestParams?: MCPServerParam[]
data?: MCPServerDetail
show: boolean
onHide: () => void
- appInfo?: any
+ appInfo?: {
+ description?: string
+ }
+}
+
+type MCPServerParam = {
+ variable?: string
+ label?: string
+ type?: string
}
const MCPServerModal = ({
@@ -42,7 +49,7 @@ const MCPServerModal = ({
const defaultDescription = data?.description || appInfo?.description || ''
const [description, setDescription] = React.useState(defaultDescription)
- const [params, setParams] = React.useState(data?.parameters || {})
+ const [params, setParams] = React.useState<Record<string, string>>(data?.parameters || {})
const handleParamChange = (variable: string, value: string) => {
setParams(prev => ({
@@ -52,10 +59,14 @@ const MCPServerModal = ({
}
const getParamValue = () => {
- const res = {} as any
- latestParams.map((param) => {
- res[param.variable] = params[param.variable]
- return param
+ const res: Record<string, string> = {}
+ latestParams.forEach((param) => {
+ if (!param.variable)
+ return
+
+ const value = params[param.variable]
+ if (value !== undefined)
+ res[param.variable] = value
})
return res
}
@@ -78,7 +89,11 @@ const MCPServerModal = ({
const submit = async () => {
if (!data) {
- const payload: any = {
+ const payload: {
+ appID: string
+ description?: string
+ parameters: Record<string, string>
+ } = {
appID,
parameters: getParamValue(),
}
@@ -92,13 +107,18 @@ const MCPServerModal = ({
onHide()
}
else {
- const payload: any = {
+ const payload: {
+ appID: string
+ id: string
+ description: string
+ parameters: Record<string, string>
+ } = {
appID,
id: data.id,
parameters: getParamValue(),
+ description,
}
- payload.description = description
await updateMCPServer(payload)
invalidateMCPServerDetail(appID)
emitMcpServerUpdate('updated')
@@ -107,56 +127,67 @@ const MCPServerModal = ({
}
return (
- <Modal
- isShow={show}
- onClose={onHide}
- className={cn('relative max-w-[520px]! p-0!')}
+ <Dialog
+ open={show}
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
>
- <div className="absolute top-5 right-5 z-10 cursor-pointer p-1.5" onClick={onHide}>
- <RiCloseLine className="h-5 w-5 text-text-tertiary" />
- </div>
- <div className="relative p-6 pb-3 title-2xl-semi-bold text-xl text-text-primary">
- {!data ? t('mcp.server.modal.addTitle', { ns: 'tools' }) : t('mcp.server.modal.editTitle', { ns: 'tools' })}
- </div>
- <div className="space-y-5 px-6 py-3">
- <div className="space-y-0.5">
- <div className="flex h-6 items-center gap-1">
- <div className="system-sm-medium text-text-secondary">{t('mcp.server.modal.description', { ns: 'tools' })}</div>
- <div className="system-xs-regular text-text-destructive-secondary">*</div>
- </div>
- <Textarea
- className="h-[96px] resize-none"
- value={description}
- placeholder={t('mcp.server.modal.descriptionPlaceholder', { ns: 'tools' })}
- onChange={e => setDescription(e.target.value)}
- >
- </Textarea>
+ <DialogContent className="w-[calc(100vw-2rem)] max-w-[520px]! overflow-hidden! border-none p-0! text-left align-middle transition-all duration-100 ease-in">
+ <div className="absolute top-5 right-5 z-10 cursor-pointer p-1.5" onClick={onHide}>
+ <RiCloseLine className="h-5 w-5 text-text-tertiary" />
</div>
- {latestParams.length > 0 && (
- <div>
- <div className="mb-1 flex items-center gap-2">
- <div className="shrink-0 system-xs-medium-uppercase text-text-primary">{t('mcp.server.modal.parameters', { ns: 'tools' })}</div>
- <Divider type="horizontal" className="m-0! h-px! grow bg-divider-subtle" />
- </div>
- <div className="mb-2 body-xs-regular text-text-tertiary">{t('mcp.server.modal.parametersTip', { ns: 'tools' })}</div>
- <div className="space-y-3">
- {latestParams.map(paramItem => (
- <MCPServerParamItem
- key={paramItem.variable}
- data={paramItem}
- value={params[paramItem.variable] || ''}
- onChange={value => handleParamChange(paramItem.variable, value)}
- />
- ))}
+ <div className="relative p-6 pb-3 title-2xl-semi-bold text-xl text-text-primary">
+ {!data ? t('mcp.server.modal.addTitle', { ns: 'tools' }) : t('mcp.server.modal.editTitle', { ns: 'tools' })}
+ </div>
+ <div className="space-y-5 px-6 py-3">
+ <div className="space-y-0.5">
+ <div className="flex h-6 items-center gap-1">
+ <div className="system-sm-medium text-text-secondary">{t('mcp.server.modal.description', { ns: 'tools' })}</div>
+ <div className="system-xs-regular text-text-destructive-secondary">*</div>
</div>
+ <Textarea
+ className="h-[96px] resize-none"
+ value={description}
+ placeholder={t('mcp.server.modal.descriptionPlaceholder', { ns: 'tools' })}
+ onChange={e => setDescription(e.target.value)}
+ >
+ </Textarea>
</div>
- )}
- </div>
- <div className="flex flex-row-reverse p-6 pt-5">
- <Button disabled={!description || creating || updating} className="ml-2" variant="primary" onClick={submit}>{data ? t('mcp.modal.save', { ns: 'tools' }) : t('mcp.server.modal.confirm', { ns: 'tools' })}</Button>
- <Button onClick={onHide}>{t('mcp.modal.cancel', { ns: 'tools' })}</Button>
- </div>
- </Modal>
+ {latestParams.length > 0 && (
+ <div>
+ <div className="mb-1 flex items-center gap-2">
+ <div className="shrink-0 system-xs-medium-uppercase text-text-primary">{t('mcp.server.modal.parameters', { ns: 'tools' })}</div>
+ <Divider type="horizontal" className="m-0! h-px! grow bg-divider-subtle" />
+ </div>
+ <div className="mb-2 body-xs-regular text-text-tertiary">{t('mcp.server.modal.parametersTip', { ns: 'tools' })}</div>
+ <div className="space-y-3">
+ {latestParams.map((paramItem) => {
+ if (!paramItem.variable)
+ return null
+
+ const { variable } = paramItem
+
+ return (
+ <MCPServerParamItem
+ key={variable}
+ data={paramItem}
+ value={params[variable] || ''}
+ onChange={value => handleParamChange(variable, value)}
+ />
+ )
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="flex flex-row-reverse p-6 pt-5">
+ <Button disabled={!description || creating || updating} className="ml-2" variant="primary" onClick={submit}>{data ? t('mcp.modal.save', { ns: 'tools' }) : t('mcp.server.modal.confirm', { ns: 'tools' })}</Button>
+ <Button onClick={onHide}>{t('mcp.modal.cancel', { ns: 'tools' })}</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/tools/mcp/modal.tsx b/web/app/components/tools/mcp/modal.tsx
index 165535127da..79179ae3dc7 100644
--- a/web/app/components/tools/mcp/modal.tsx
+++ b/web/app/components/tools/mcp/modal.tsx
@@ -4,17 +4,15 @@ import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import type { AppIconType } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import { RiCloseLine, RiEditLine } from '@remixicon/react'
import { useHover } from 'ahooks'
-import { noop } from 'es-toolkit/function'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import AppIconPicker from '@/app/components/base/app-icon-picker'
import { Mcp } from '@/app/components/base/icons/src/vender/other'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import TabSlider from '@/app/components/base/tab-slider'
import { MCPAuthMethod } from '@/app/components/tools/types'
import { shouldUseMcpIconForAppIcon } from '@/utils/mcp'
@@ -281,18 +279,16 @@ const MCPModal: FC<DuplicateAppModalProps> = ({
const formKey = data?.id ?? 'create'
return (
- <Modal
- isShow={show}
- onClose={noop}
- className={cn('relative max-w-[520px]!', 'p-6')}
- >
- <MCPModalContent
- key={formKey}
- data={data}
- onConfirm={onConfirm}
- onHide={onHide}
- />
- </Modal>
+ <Dialog open={show}>
+ <DialogContent className="w-full max-w-[520px]! overflow-hidden! border-none p-6 text-left align-middle">
+ <MCPModalContent
+ key={formKey}
+ data={data}
+ onConfirm={onConfirm}
+ onHide={onHide}
+ />
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx b/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx
index 241cd7d762b..684c700648a 100644
--- a/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx
+++ b/web/app/components/workflow/__tests__/update-dsl-modal.spec.tsx
@@ -126,6 +126,15 @@ describe('UpdateDSLModal', () => {
expect(defaultProps.onBackup).toHaveBeenCalledTimes(1)
})
+ it('should call cancel handler when the import dialog requests close', () => {
+ const onCancel = vi.fn()
+ renderModal({ ...defaultProps, onCancel })
+
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ expect(onCancel).toHaveBeenCalledTimes(1)
+ })
+
it('should import a valid file and emit workflow update payload', async () => {
renderModal()
@@ -228,6 +237,32 @@ describe('UpdateDSLModal', () => {
})
})
+ it('should close the pending modal when dialog requests close', async () => {
+ mockImportDSL.mockResolvedValue({
+ id: 'import-8',
+ status: DSLImportStatus.PENDING,
+ imported_dsl_version: '1.0.0',
+ current_dsl_version: '2.0.0',
+ })
+
+ renderModal()
+
+ fireEvent.change(screen.getByTestId('dsl-file-input'), {
+ target: { files: [new File(['workflow'], 'workflow.yml', { type: 'text/yaml' })] },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'workflow.common.overwriteAndImport' }))
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'app.newApp.Confirm' })).toBeInTheDocument()
+ })
+
+ fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
+
+ await waitFor(() => {
+ expect(screen.queryByRole('button', { name: 'app.newApp.Confirm' })).not.toBeInTheDocument()
+ })
+ })
+
it('should show an error when the selected file content is invalid for the current app mode', async () => {
class InvalidDSLFileReader extends MockFileReader {
override readAsText(_file: Blob) {
diff --git a/web/app/components/workflow/header/online-users.tsx b/web/app/components/workflow/header/online-users.tsx
index 17e1de3feb5..93e9d1fa852 100644
--- a/web/app/components/workflow/header/online-users.tsx
+++ b/web/app/components/workflow/header/online-users.tsx
@@ -189,7 +189,6 @@ const OnlineUsers = () => {
placement="bottom-start"
sideOffset={8}
alignOffset={-48}
- className="z-[9999]"
popupClassName={cn(
'mt-1.5 flex max-h-[200px] w-[240px] flex-col overflow-y-auto',
'rounded-xl border-[0.5px] border-components-panel-border',
diff --git a/web/app/components/workflow/nodes/http/components/authorization/index.tsx b/web/app/components/workflow/nodes/http/components/authorization/index.tsx
index b72e52911d0..684f943d5f2 100644
--- a/web/app/components/workflow/nodes/http/components/authorization/index.tsx
+++ b/web/app/components/workflow/nodes/http/components/authorization/index.tsx
@@ -4,12 +4,12 @@ import type { Authorization as AuthorizationPayloadType } from '../../types'
import type { Var } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { produce } from 'immer'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import BaseInput from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import Input from '@/app/components/workflow/nodes/_base/components/input-support-select-var'
import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'
import { VarType } from '@/app/components/workflow/types'
@@ -115,70 +115,78 @@ const Authorization: FC<Props> = ({
onHide()
}, [tempPayload, onChange, onHide])
return (
- <Modal
- title={t(`${i18nPrefix}.authorization`, { ns: 'workflow' })}
- isShow={isShow}
- onClose={onHide}
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
>
- <div>
- <div className="space-y-2">
- <Field title={t(`${i18nPrefix}.authorizationType`, { ns: 'workflow' })}>
- <RadioGroup
- options={[
- { value: AuthorizationType.none, label: t(`${i18nPrefix}.no-auth`, { ns: 'workflow' }) },
- { value: AuthorizationType.apiKey, label: t(`${i18nPrefix}.api-key`, { ns: 'workflow' }) },
- ]}
- value={tempPayload.type}
- onChange={handleAuthTypeChange}
- />
- </Field>
+ <DialogContent className="overflow-hidden! border-none text-left align-middle">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(`${i18nPrefix}.authorization`, { ns: 'workflow' })}
+ </DialogTitle>
- {tempPayload.type === AuthorizationType.apiKey && (
- <>
- <Field title={t(`${i18nPrefix}.auth-type`, { ns: 'workflow' })}>
- <RadioGroup
- options={[
- { value: APIType.basic, label: t(`${i18nPrefix}.basic`, { ns: 'workflow' }) },
- { value: APIType.bearer, label: t(`${i18nPrefix}.bearer`, { ns: 'workflow' }) },
- { value: APIType.custom, label: t(`${i18nPrefix}.custom`, { ns: 'workflow' }) },
- ]}
- value={tempPayload.config?.type || APIType.basic}
- onChange={handleAuthAPITypeChange}
- />
- </Field>
- {tempPayload.config?.type === APIType.custom && (
- <Field title={t(`${i18nPrefix}.header`, { ns: 'workflow' })} isRequired>
- <BaseInput
- value={tempPayload.config?.header || ''}
- onChange={handleAPIKeyOrHeaderChange('header')}
+ <div>
+ <div className="space-y-2">
+ <Field title={t(`${i18nPrefix}.authorizationType`, { ns: 'workflow' })}>
+ <RadioGroup
+ options={[
+ { value: AuthorizationType.none, label: t(`${i18nPrefix}.no-auth`, { ns: 'workflow' }) },
+ { value: AuthorizationType.apiKey, label: t(`${i18nPrefix}.api-key`, { ns: 'workflow' }) },
+ ]}
+ value={tempPayload.type}
+ onChange={handleAuthTypeChange}
+ />
+ </Field>
+
+ {tempPayload.type === AuthorizationType.apiKey && (
+ <>
+ <Field title={t(`${i18nPrefix}.auth-type`, { ns: 'workflow' })}>
+ <RadioGroup
+ options={[
+ { value: APIType.basic, label: t(`${i18nPrefix}.basic`, { ns: 'workflow' }) },
+ { value: APIType.bearer, label: t(`${i18nPrefix}.bearer`, { ns: 'workflow' }) },
+ { value: APIType.custom, label: t(`${i18nPrefix}.custom`, { ns: 'workflow' }) },
+ ]}
+ value={tempPayload.config?.type || APIType.basic}
+ onChange={handleAuthAPITypeChange}
/>
</Field>
- )}
+ {tempPayload.config?.type === APIType.custom && (
+ <Field title={t(`${i18nPrefix}.header`, { ns: 'workflow' })} isRequired>
+ <BaseInput
+ value={tempPayload.config?.header || ''}
+ onChange={handleAPIKeyOrHeaderChange('header')}
+ />
+ </Field>
+ )}
- <Field title={t(`${i18nPrefix}.api-key-title`, { ns: 'workflow' })} isRequired>
- <div className="flex">
- <Input
- instanceId="http-api-key"
- className={cn(isFocus ? 'border-components-input-border-active bg-components-input-bg-active shadow-xs' : 'border-components-input-border-hover bg-components-input-bg-normal', 'w-0 grow rounded-lg border px-3 py-[6px]')}
- value={tempPayload.config?.api_key || ''}
- onChange={handleAPIKeyChange}
- nodesOutputVars={availableVars}
- availableNodes={availableNodesWithParent}
- onFocusChange={setIsFocus}
- placeholder={' '}
- placeholderClassName="leading-[21px]!"
- />
- </div>
- </Field>
- </>
- )}
- </div>
- <div className="mt-6 flex justify-end space-x-2">
- <Button onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button variant="primary" onClick={handleConfirm}>{t('operation.save', { ns: 'common' })}</Button>
+ <Field title={t(`${i18nPrefix}.api-key-title`, { ns: 'workflow' })} isRequired>
+ <div className="flex">
+ <Input
+ instanceId="http-api-key"
+ className={cn(isFocus ? 'border-components-input-border-active bg-components-input-bg-active shadow-xs' : 'border-components-input-border-hover bg-components-input-bg-normal', 'w-0 grow rounded-lg border px-3 py-[6px]')}
+ value={tempPayload.config?.api_key || ''}
+ onChange={handleAPIKeyChange}
+ nodesOutputVars={availableVars}
+ availableNodes={availableNodesWithParent}
+ onFocusChange={setIsFocus}
+ placeholder={' '}
+ placeholderClassName="leading-[21px]!"
+ />
+ </div>
+ </Field>
+ </>
+ )}
+ </div>
+ <div className="mt-6 flex justify-end space-x-2">
+ <Button onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button variant="primary" onClick={handleConfirm}>{t('operation.save', { ns: 'common' })}</Button>
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
export default React.memo(Authorization)
diff --git a/web/app/components/workflow/nodes/http/components/curl-panel.tsx b/web/app/components/workflow/nodes/http/components/curl-panel.tsx
index 8ba5fb36a90..87dc2a34270 100644
--- a/web/app/components/workflow/nodes/http/components/curl-panel.tsx
+++ b/web/app/components/workflow/nodes/http/components/curl-panel.tsx
@@ -2,11 +2,11 @@
import type { FC } from 'react'
import type { HttpNodeType } from '../types'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import Textarea from '@/app/components/base/textarea'
import { useNodesInteractions } from '@/app/components/workflow/hooks'
import { parseCurl } from './curl-parser'
@@ -42,28 +42,35 @@ const CurlPanel: FC<Props> = ({ nodeId, isShow, onHide, handleCurlImport }) => {
}, [onHide, nodeId, inputString, handleNodeSelect, handleCurlImport])
return (
- <Modal
- title={t('nodes.http.curl.title', { ns: 'workflow' })}
- isShow={isShow}
- onClose={onHide}
- className="w-[400px]! max-w-[400px]! p-4!"
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onHide()
+ }}
>
- <div>
- <Textarea
- value={inputString}
- className="my-3 h-40 w-full grow"
- onChange={e => setInputString(e.target.value)}
- placeholder={t('nodes.http.curl.placeholder', { ns: 'workflow' })!}
- />
- </div>
- <div className="mt-4 flex justify-end space-x-2">
- <Button className="w-[95px]!" onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button className="w-[95px]!" variant="primary" onClick={handleSave}>
- {' '}
- {t('operation.save', { ns: 'common' })}
- </Button>
- </div>
- </Modal>
+ <DialogContent className="w-[400px]! max-w-[400px]! overflow-hidden! border-none p-4! text-left align-middle">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t('nodes.http.curl.title', { ns: 'workflow' })}
+ </DialogTitle>
+
+ <div>
+ <Textarea
+ value={inputString}
+ className="my-3 h-40 w-full grow"
+ onChange={e => setInputString(e.target.value)}
+ placeholder={t('nodes.http.curl.placeholder', { ns: 'workflow' })!}
+ />
+ </div>
+ <div className="mt-4 flex justify-end space-x-2">
+ <Button className="w-[95px]!" onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button className="w-[95px]!" variant="primary" onClick={handleSave}>
+ {' '}
+ {t('operation.save', { ns: 'common' })}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/index.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/index.tsx
index fa5166a06f9..f4445fd54da 100644
--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/index.tsx
+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/index.tsx
@@ -1,5 +1,5 @@
import type { SchemaRoot } from '../../types'
-import Modal from '../../../../../base/modal'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { JsonSchemaConfig } from './json-schema-config'
type JsonSchemaConfigModalProps = {
@@ -16,16 +16,21 @@ export function JsonSchemaConfigModal({
onClose,
}: JsonSchemaConfigModalProps) {
return (
- <Modal
- isShow={isShow}
- onClose={onClose}
- className="h-[800px] max-w-[960px] p-0"
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <JsonSchemaConfig
- defaultSchema={defaultSchema}
- onSave={onSave}
- onClose={onClose}
- />
- </Modal>
+ <DialogContent className="h-[800px] max-h-none w-full max-w-[960px] overflow-hidden! border-none p-0 text-left align-middle">
+
+ <JsonSchemaConfig
+ defaultSchema={defaultSchema}
+ onSave={onSave}
+ onClose={onClose}
+ />
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
index f63d9a0d506..2c5de939644 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/__tests__/integration.spec.tsx
@@ -110,24 +110,23 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/model-param
),
}))
-vi.mock('@/app/components/base/modal', () => ({
+vi.mock('@langgenius/dify-ui/dialog', () => ({
__esModule: true,
- default: ({
+ Dialog: ({
children,
- isShow,
- title,
+ open,
}: {
children: ReactNode
- isShow?: boolean
- title?: ReactNode
- }) => isShow
+ open?: boolean
+ }) => open !== false
? (
<div data-testid="base-modal">
- <div>{title}</div>
{children}
</div>
)
: null,
+ DialogContent: ({ children }: { children: ReactNode }) => <>{children}</>,
+ DialogTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}))
vi.mock('@/app/components/workflow/nodes/_base/components/collapse', () => ({
diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx
index ddded68989d..122ee169410 100644
--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx
+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx
@@ -3,6 +3,7 @@ import type { FC } from 'react'
import type { Param } from '../../types'
import type { MoreInfo } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger } from '@langgenius/dify-ui/select'
import { Switch } from '@langgenius/dify-ui/switch'
import { toast } from '@langgenius/dify-ui/toast'
@@ -13,7 +14,6 @@ import { useTranslation } from 'react-i18next'
import Field from '@/app/components/app/configuration/config-var/config-modal/field'
import ConfigSelect from '@/app/components/app/configuration/config-var/config-select'
import Input from '@/app/components/base/input'
-import Modal from '@/app/components/base/modal'
import Textarea from '@/app/components/base/textarea'
import { ChangeType } from '@/app/components/workflow/types'
import { checkKeys } from '@/utils/var'
@@ -124,64 +124,71 @@ const AddExtractParameter: FC<Props> = ({
</div>
)}
{isShowModal && (
- <Modal
- title={t(`${i18nPrefix}.addExtractParameter`, { ns: 'workflow' })}
- isShow
- onClose={hideModal}
- className="w-[400px]! max-w-[400px]! p-4!"
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ hideModal()
+ }}
>
- <div>
- <div className="space-y-2">
- <Field title={t(`${i18nPrefix}.addExtractParameterContent.name`, { ns: 'workflow' })}>
- <Input
- value={param.name}
- onChange={e => handleParamChange('name')(e.target.value)}
- placeholder={t(`${i18nPrefix}.addExtractParameterContent.namePlaceholder`, { ns: 'workflow' })!}
- />
- </Field>
- <Field title={t(`${i18nPrefix}.addExtractParameterContent.type`, { ns: 'workflow' })}>
- <Select
- value={param.type}
- onValueChange={value => value && handleParamChange('type')(value)}
- >
- <SelectTrigger className="w-full capitalize">
- {param.type}
- </SelectTrigger>
- <SelectContent>
- {TYPES.map(type => (
- <SelectItem key={type} value={type} className="capitalize">
- <SelectItemText className="capitalize">{type}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Field>
- {param.type === ParamType.select && (
- <Field title={t('variableConfig.options', { ns: 'appDebug' })}>
- <ConfigSelect options={param.options || []} onChange={handleParamChange('options')} />
+ <DialogContent className="w-[400px]! max-w-[400px]! overflow-hidden! border-none p-4! text-left align-middle">
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(`${i18nPrefix}.addExtractParameter`, { ns: 'workflow' })}
+ </DialogTitle>
+
+ <div>
+ <div className="space-y-2">
+ <Field title={t(`${i18nPrefix}.addExtractParameterContent.name`, { ns: 'workflow' })}>
+ <Input
+ value={param.name}
+ onChange={e => handleParamChange('name')(e.target.value)}
+ placeholder={t(`${i18nPrefix}.addExtractParameterContent.namePlaceholder`, { ns: 'workflow' })!}
+ />
</Field>
- )}
- <Field title={t(`${i18nPrefix}.addExtractParameterContent.description`, { ns: 'workflow' })}>
- <Textarea
- value={param.description}
- onChange={e => handleParamChange('description')(e.target.value)}
- placeholder={t(`${i18nPrefix}.addExtractParameterContent.descriptionPlaceholder`, { ns: 'workflow' })!}
- />
- </Field>
- <Field title={t(`${i18nPrefix}.addExtractParameterContent.required`, { ns: 'workflow' })}>
- <>
- <div className="mb-1.5 text-xs leading-[18px] font-normal text-text-tertiary">{t(`${i18nPrefix}.addExtractParameterContent.requiredContent`, { ns: 'workflow' })}</div>
- <Switch size="lg" checked={param.required ?? false} onCheckedChange={handleParamChange('required')} />
- </>
- </Field>
- </div>
- <div className="mt-4 flex justify-end space-x-2">
- <Button className="w-[95px]!" onClick={hideModal}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button className="w-[95px]!" variant="primary" onClick={handleSave}>{isAdd ? t('operation.add', { ns: 'common' }) : t('operation.save', { ns: 'common' })}</Button>
+ <Field title={t(`${i18nPrefix}.addExtractParameterContent.type`, { ns: 'workflow' })}>
+ <Select
+ value={param.type}
+ onValueChange={value => value && handleParamChange('type')(value)}
+ >
+ <SelectTrigger className="w-full capitalize">
+ {param.type}
+ </SelectTrigger>
+ <SelectContent>
+ {TYPES.map(type => (
+ <SelectItem key={type} value={type} className="capitalize">
+ <SelectItemText className="capitalize">{type}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ {param.type === ParamType.select && (
+ <Field title={t('variableConfig.options', { ns: 'appDebug' })}>
+ <ConfigSelect options={param.options || []} onChange={handleParamChange('options')} />
+ </Field>
+ )}
+ <Field title={t(`${i18nPrefix}.addExtractParameterContent.description`, { ns: 'workflow' })}>
+ <Textarea
+ value={param.description}
+ onChange={e => handleParamChange('description')(e.target.value)}
+ placeholder={t(`${i18nPrefix}.addExtractParameterContent.descriptionPlaceholder`, { ns: 'workflow' })!}
+ />
+ </Field>
+ <Field title={t(`${i18nPrefix}.addExtractParameterContent.required`, { ns: 'workflow' })}>
+ <>
+ <div className="mb-1.5 text-xs leading-[18px] font-normal text-text-tertiary">{t(`${i18nPrefix}.addExtractParameterContent.requiredContent`, { ns: 'workflow' })}</div>
+ <Switch size="lg" checked={param.required ?? false} onCheckedChange={handleParamChange('required')} />
+ </>
+ </Field>
+ </div>
+ <div className="mt-4 flex justify-end space-x-2">
+ <Button className="w-[95px]!" onClick={hideModal}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button className="w-[95px]!" variant="primary" onClick={handleSave}>{isAdd ? t('operation.add', { ns: 'common' }) : t('operation.save', { ns: 'common' })}</Button>
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)}
</div>
)
diff --git a/web/app/components/workflow/nodes/tool/components/__tests__/input-var-list.spec.tsx b/web/app/components/workflow/nodes/tool/components/__tests__/input-var-list.spec.tsx
index 11d7d33295a..87ee0447ff2 100644
--- a/web/app/components/workflow/nodes/tool/components/__tests__/input-var-list.spec.tsx
+++ b/web/app/components/workflow/nodes/tool/components/__tests__/input-var-list.spec.tsx
@@ -1,7 +1,7 @@
import type { ToolVarInputs } from '../../types'
import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { App } from '@/types/app'
-import { screen } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { createMockProviderContextValue } from '@/__mocks__/provider-context'
@@ -479,20 +479,23 @@ describe('InputVarList', () => {
},
})
- await user.click(screen.getByRole('combobox', { name: 'app.appSelector.label' }))
- await user.type(screen.getByPlaceholderText('Topic'), 'weather')
+ const topicInput = await screen.findByPlaceholderText('Topic')
+ await user.type(topicInput, 'weather')
- expect(onChange).toHaveBeenLastCalledWith({
- assistant: {
- app_id: 'app-1',
- inputs: { topic: 'weather' },
- files: [],
- },
- model: {
- credential_id: 'credential-1',
- },
+ await waitFor(() => {
+ expect(onChange).toHaveBeenLastCalledWith({
+ assistant: {
+ app_id: 'app-1',
+ inputs: { topic: 'weather' },
+ files: [],
+ },
+ model: {
+ credential_id: 'credential-1',
+ },
+ })
})
+ await user.click(screen.getByRole('button', { name: 'app.appSelector.label' }))
await user.click(screen.getByText('workflow:errorMsg.configureModel'))
await user.click(await screen.findByRole('combobox', { name: 'plugin.detailPanel.configureModel' }))
await user.click(await screen.findByRole('option', { name: /GPT-4o/i }))
diff --git a/web/app/components/workflow/operator/index.tsx b/web/app/components/workflow/operator/index.tsx
index 5797983e44b..97fc4378b92 100644
--- a/web/app/components/workflow/operator/index.tsx
+++ b/web/app/components/workflow/operator/index.tsx
@@ -92,7 +92,7 @@ const Operator = ({ handleUndo, handleRedo }: OperatorProps) => {
return (
<div
ref={bottomPanelRef}
- className="absolute right-0 bottom-0 left-0 z-[60] px-1"
+ className="absolute right-0 bottom-0 left-0 z-10 px-1"
style={
{
width: bottomPanelWidth,
diff --git a/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx b/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx
index 573d3e56421..689b2fe0b32 100644
--- a/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx
@@ -3,10 +3,10 @@ import type {
ConversationVariable,
} from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { RiCloseLine } from '@remixicon/react'
import { useMount } from 'ahooks'
import copy from 'copy-to-clipboard'
-import { noop } from 'es-toolkit/function'
import { capitalize } from 'es-toolkit/string'
import * as React from 'react'
import { useCallback } from 'react'
@@ -16,7 +16,6 @@ import {
CopyCheck,
} from '@/app/components/base/icons/src/vender/line/files'
import { BubbleX } from '@/app/components/base/icons/src/vender/line/others'
-import Modal from '@/app/components/base/modal'
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
@@ -76,87 +75,86 @@ const ConversationVariableModal = ({
})
return (
- <Modal
- isShow
- onClose={noop}
- className={cn('h-[640px] w-[920px] max-w-[920px] p-0')}
- >
- <div className="absolute top-4 right-4 cursor-pointer p-2" onClick={onHide}>
- <RiCloseLine className="h-4 w-4 text-text-tertiary" />
- </div>
- <div className="flex h-full w-full">
- {/* LEFT */}
- <div className="flex h-full w-[224px] shrink-0 flex-col border-r border-divider-burn bg-background-sidenav-bg">
- <div className="shrink-0 pt-5 pr-4 pb-3 pl-5 system-xl-semibold text-text-primary">{t('chatVariable.panelTitle', { ns: 'workflow' })}</div>
- <div className="grow overflow-y-auto px-3 py-2">
- {varList.map(chatVar => (
- <div key={chatVar.id} className={cn('group mb-0.5 flex cursor-pointer items-center rounded-lg p-2 hover:bg-state-base-hover', currentVar.id === chatVar.id && 'bg-state-base-hover')} onClick={() => setCurrentVar(chatVar)}>
- <BubbleX className={cn('mr-1 h-4 w-4 shrink-0 text-text-tertiary group-hover:text-util-colors-teal-teal-700', currentVar.id === chatVar.id && 'text-util-colors-teal-teal-700')} />
- <div title={chatVar.name} className={cn('truncate system-sm-medium text-text-tertiary group-hover:text-util-colors-teal-teal-700', currentVar.id === chatVar.id && 'text-util-colors-teal-teal-700')}>{chatVar.name}</div>
- </div>
- ))}
- </div>
+ <Dialog open>
+ <DialogContent className={cn('max-h-none w-full overflow-hidden! border-none text-left align-middle', cn('h-[640px] w-[920px] max-w-[920px] p-0'))}>
+
+ <div className="absolute top-4 right-4 cursor-pointer p-2" onClick={onHide}>
+ <RiCloseLine className="h-4 w-4 text-text-tertiary" />
</div>
- {/* RIGHT */}
- <div className="flex h-full w-0 grow flex-col bg-components-panel-bg">
- <div className="shrink-0 p-4 pb-2">
- <div className="flex items-center gap-1 py-1">
- <div className="system-xl-semibold text-text-primary">{currentVar.name}</div>
- <div className="system-xs-medium text-text-tertiary">{capitalize(currentVar.value_type)}</div>
+ <div className="flex h-full w-full">
+ {/* LEFT */}
+ <div className="flex h-full w-[224px] shrink-0 flex-col border-r border-divider-burn bg-background-sidenav-bg">
+ <div className="shrink-0 pt-5 pr-4 pb-3 pl-5 system-xl-semibold text-text-primary">{t('chatVariable.panelTitle', { ns: 'workflow' })}</div>
+ <div className="grow overflow-y-auto px-3 py-2">
+ {varList.map(chatVar => (
+ <div key={chatVar.id} className={cn('group mb-0.5 flex cursor-pointer items-center rounded-lg p-2 hover:bg-state-base-hover', currentVar.id === chatVar.id && 'bg-state-base-hover')} onClick={() => setCurrentVar(chatVar)}>
+ <BubbleX className={cn('mr-1 h-4 w-4 shrink-0 text-text-tertiary group-hover:text-util-colors-teal-teal-700', currentVar.id === chatVar.id && 'text-util-colors-teal-teal-700')} />
+ <div title={chatVar.name} className={cn('truncate system-sm-medium text-text-tertiary group-hover:text-util-colors-teal-teal-700', currentVar.id === chatVar.id && 'text-util-colors-teal-teal-700')}>{chatVar.name}</div>
+ </div>
+ ))}
</div>
</div>
- <div className="flex h-0 grow flex-col p-4 pt-2">
- <div className="mb-2 flex shrink-0 items-center gap-2">
- <div className="shrink-0 system-xs-medium-uppercase text-text-tertiary">{t('chatVariable.storedContent', { ns: 'workflow' }).toLocaleUpperCase()}</div>
- <div
- className="h-px grow"
- style={{
- background: 'linear-gradient(to right, rgba(16, 24, 40, 0.08) 0%, rgba(255, 255, 255) 100%)',
- }}
- >
+ {/* RIGHT */}
+ <div className="flex h-full w-0 grow flex-col bg-components-panel-bg">
+ <div className="shrink-0 p-4 pb-2">
+ <div className="flex items-center gap-1 py-1">
+ <div className="system-xl-semibold text-text-primary">{currentVar.name}</div>
+ <div className="system-xs-medium text-text-tertiary">{capitalize(currentVar.value_type)}</div>
</div>
- {!!latestValueTimestampMap[currentVar.id] && (
- <div className="shrink-0 system-xs-regular text-text-tertiary">
- {t('chatVariable.updatedAt', { ns: 'workflow' })}
- {formatTime(latestValueTimestampMap[currentVar.id]!, t('dateTimeFormat', { ns: 'appLog' }) as string)}
- </div>
- )}
</div>
- <div className="grow overflow-y-auto">
- {currentVar.value_type !== ChatVarType.Number && currentVar.value_type !== ChatVarType.String && (
- <div className="flex h-full flex-col rounded-lg bg-components-input-bg-normal px-2 pb-2">
- <div className="flex h-7 shrink-0 items-center justify-between pt-1 pr-2 pl-3">
- <div className="system-xs-semibold text-text-secondary">JSON</div>
- <div className="flex items-center p-1">
- {!isCopied
- ? (
- <Copy className="h-4 w-4 cursor-pointer text-text-tertiary" onClick={handleCopy} />
- )
- : (
- <CopyCheck className="h-4 w-4 text-text-tertiary" />
- )}
- </div>
+ <div className="flex h-0 grow flex-col p-4 pt-2">
+ <div className="mb-2 flex shrink-0 items-center gap-2">
+ <div className="shrink-0 system-xs-medium-uppercase text-text-tertiary">{t('chatVariable.storedContent', { ns: 'workflow' }).toLocaleUpperCase()}</div>
+ <div
+ className="h-px grow"
+ style={{
+ background: 'linear-gradient(to right, rgba(16, 24, 40, 0.08) 0%, rgba(255, 255, 255) 100%)',
+ }}
+ >
+ </div>
+ {!!latestValueTimestampMap[currentVar.id] && (
+ <div className="shrink-0 system-xs-regular text-text-tertiary">
+ {t('chatVariable.updatedAt', { ns: 'workflow' })}
+ {formatTime(latestValueTimestampMap[currentVar.id]!, t('dateTimeFormat', { ns: 'appLog' }) as string)}
</div>
- <div className="grow pl-4">
- <CodeEditor
- readOnly
- noWrapper
- isExpand
- language={CodeLanguage.json}
- value={latestValueMap[currentVar.id] || ''}
- isJSONStringifyBeauty
- />
+ )}
+ </div>
+ <div className="grow overflow-y-auto">
+ {currentVar.value_type !== ChatVarType.Number && currentVar.value_type !== ChatVarType.String && (
+ <div className="flex h-full flex-col rounded-lg bg-components-input-bg-normal px-2 pb-2">
+ <div className="flex h-7 shrink-0 items-center justify-between pt-1 pr-2 pl-3">
+ <div className="system-xs-semibold text-text-secondary">JSON</div>
+ <div className="flex items-center p-1">
+ {!isCopied
+ ? (
+ <Copy className="h-4 w-4 cursor-pointer text-text-tertiary" onClick={handleCopy} />
+ )
+ : (
+ <CopyCheck className="h-4 w-4 text-text-tertiary" />
+ )}
+ </div>
+ </div>
+ <div className="grow pl-4">
+ <CodeEditor
+ readOnly
+ noWrapper
+ isExpand
+ language={CodeLanguage.json}
+ value={latestValueMap[currentVar.id] || ''}
+ isJSONStringifyBeauty
+ />
+ </div>
</div>
- </div>
- )}
- {(currentVar.value_type === ChatVarType.Number || currentVar.value_type === ChatVarType.String) && (
- <div className="h-full overflow-x-hidden overflow-y-auto rounded-lg bg-components-input-bg-normal px-4 py-3 system-md-regular text-components-input-text-filled">{latestValueMap[currentVar.id] || ''}</div>
- )}
+ )}
+ {(currentVar.value_type === ChatVarType.Number || currentVar.value_type === ChatVarType.String) && (
+ <div className="h-full overflow-x-hidden overflow-y-auto rounded-lg bg-components-input-bg-normal px-4 py-3 system-md-regular text-components-input-text-filled">{latestValueMap[currentVar.id] || ''}</div>
+ )}
+ </div>
</div>
</div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx b/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx
index 8299ff2b300..bd0c9934c32 100644
--- a/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/action-menu/index.tsx
@@ -33,7 +33,8 @@ const ActionMenu: FC<ActionMenuProps> = (props: ActionMenuProps) => {
onOpenChange={setOpen}
>
<DropdownMenuTrigger
- render={<Button size="small" className="px-1" onClick={e => e.stopPropagation()} />}
+ nativeButton={false}
+ render={<Button nativeButton={false} size="small" className="px-1" onClick={e => e.stopPropagation()} />}
>
<RiMoreFill className="h-4 w-4" />
</DropdownMenuTrigger>
diff --git a/web/app/components/workflow/panel/version-history-panel/delete-confirm-modal.tsx b/web/app/components/workflow/panel/version-history-panel/delete-confirm-modal.tsx
index 1f7948c41b7..b2057ae54cd 100644
--- a/web/app/components/workflow/panel/version-history-panel/delete-confirm-modal.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/delete-confirm-modal.tsx
@@ -1,9 +1,16 @@
import type { FC } from 'react'
import type { VersionHistory } from '@/types/workflow'
-import { Button } from '@langgenius/dify-ui/button'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
type DeleteConfirmModalProps = {
isOpen: boolean
@@ -21,24 +28,36 @@ const DeleteConfirmModal: FC<DeleteConfirmModalProps> = ({
const { t } = useTranslation()
return (
- <Modal className="p-0" isShow={isOpen} onClose={onClose}>
- <div className="flex flex-col gap-y-2 p-6 pb-4">
- <div className="title-2xl-semi-bold text-text-primary">
- {`${t('operation.delete', { ns: 'common' })} ${versionInfo.marked_name || t('versionHistory.defaultName', { ns: 'workflow' })}`}
+ <AlertDialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
+ >
+ <AlertDialogContent className="overflow-hidden! border-none text-left align-middle shadow-xl">
+ <div className="flex flex-col gap-y-2 p-6 pb-4">
+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">
+ {`${t('operation.delete', { ns: 'common' })} ${versionInfo.marked_name || t('versionHistory.defaultName', { ns: 'workflow' })}`}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="system-md-regular text-text-secondary">
+ {t('versionHistory.deletionTip', { ns: 'workflow' })}
+ </AlertDialogDescription>
</div>
- <p className="system-md-regular text-text-secondary">
- {t('versionHistory.deletionTip', { ns: 'workflow' })}
- </p>
- </div>
- <div className="flex items-center justify-end gap-x-2 p-6">
- <Button onClick={onClose}>
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button variant="primary" tone="destructive" onClick={onDelete.bind(null, versionInfo.id)}>
- {t('operation.delete', { ns: 'common' })}
- </Button>
- </div>
- </Modal>
+ <AlertDialogActions>
+ <AlertDialogCancelButton
+ nativeButton={false}
+ variant="secondary"
+ closeProps={{ nativeButton: false }}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton nativeButton={false} onClick={onDelete.bind(null, versionInfo.id)}>
+ {t('operation.delete', { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
)
}
diff --git a/web/app/components/workflow/panel/version-history-panel/empty.tsx b/web/app/components/workflow/panel/version-history-panel/empty.tsx
index 21751234d71..844b53412e1 100644
--- a/web/app/components/workflow/panel/version-history-panel/empty.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/empty.tsx
@@ -22,7 +22,7 @@ const Empty: FC<EmptyProps> = ({
{t('versionHistory.filter.empty', { ns: 'workflow' })}
</div>
<div className="flex justify-center">
- <Button size="small" onClick={onResetFilter}>
+ <Button nativeButton={false} size="small" onClick={onResetFilter}>
{t('versionHistory.filter.reset', { ns: 'workflow' })}
</Button>
</div>
diff --git a/web/app/components/workflow/panel/version-history-panel/filter/index.tsx b/web/app/components/workflow/panel/version-history-panel/filter/index.tsx
index bb94e3727ae..e2277b3fb12 100644
--- a/web/app/components/workflow/panel/version-history-panel/filter/index.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/filter/index.tsx
@@ -42,6 +42,7 @@ const Filter: FC<FilterProps> = ({
onOpenChange={setOpen}
>
<PopoverTrigger
+ nativeButton={false}
render={(
<div
className={cn(
diff --git a/web/app/components/workflow/panel/version-history-panel/restore-confirm-modal.tsx b/web/app/components/workflow/panel/version-history-panel/restore-confirm-modal.tsx
index 9fc2c25742c..b001224c088 100644
--- a/web/app/components/workflow/panel/version-history-panel/restore-confirm-modal.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/restore-confirm-modal.tsx
@@ -1,9 +1,16 @@
import type { FC } from 'react'
import type { VersionHistory } from '@/types/workflow'
-import { Button } from '@langgenius/dify-ui/button'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
type RestoreConfirmModalProps = {
isOpen: boolean
@@ -21,24 +28,36 @@ const RestoreConfirmModal: FC<RestoreConfirmModalProps> = ({
const { t } = useTranslation()
return (
- <Modal className="p-0" isShow={isOpen} onClose={onClose}>
- <div className="flex flex-col gap-y-2 p-6 pb-4">
- <div className="title-2xl-semi-bold text-text-primary">
- {`${t('common.restore', { ns: 'workflow' })} ${versionInfo.marked_name || t('versionHistory.defaultName', { ns: 'workflow' })}`}
+ <AlertDialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
+ >
+ <AlertDialogContent className="overflow-hidden! border-none text-left align-middle shadow-xl">
+ <div className="flex flex-col gap-y-2 p-6 pb-4">
+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">
+ {`${t('common.restore', { ns: 'workflow' })} ${versionInfo.marked_name || t('versionHistory.defaultName', { ns: 'workflow' })}`}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="system-md-regular text-text-secondary">
+ {t('versionHistory.restorationTip', { ns: 'workflow' })}
+ </AlertDialogDescription>
</div>
- <p className="system-md-regular text-text-secondary">
- {t('versionHistory.restorationTip', { ns: 'workflow' })}
- </p>
- </div>
- <div className="flex items-center justify-end gap-x-2 p-6">
- <Button onClick={onClose}>
- {t('operation.cancel', { ns: 'common' })}
- </Button>
- <Button variant="primary" onClick={onRestore.bind(null, versionInfo)}>
- {t('common.restore', { ns: 'workflow' })}
- </Button>
- </div>
- </Modal>
+ <AlertDialogActions>
+ <AlertDialogCancelButton
+ nativeButton={false}
+ variant="secondary"
+ closeProps={{ nativeButton: false }}
+ >
+ {t('operation.cancel', { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton nativeButton={false} tone="default" onClick={onRestore.bind(null, versionInfo)}>
+ {t('common.restore', { ns: 'workflow' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
)
}
diff --git a/web/app/components/workflow/update-dsl-modal.tsx b/web/app/components/workflow/update-dsl-modal.tsx
index 549dee487fd..c5cb9cc62d7 100644
--- a/web/app/components/workflow/update-dsl-modal.tsx
+++ b/web/app/components/workflow/update-dsl-modal.tsx
@@ -2,6 +2,7 @@
import type { MouseEventHandler } from 'react'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { toast } from '@langgenius/dify-ui/toast'
import {
RiAlertFill,
@@ -17,7 +18,6 @@ import {
import { useTranslation } from 'react-i18next'
import Uploader from '@/app/components/app/create-from-dsl-modal/uploader'
import { useStore as useAppStore } from '@/app/components/app/store'
-import Modal from '@/app/components/base/modal'
import { usePluginDependencies } from '@/app/components/workflow/plugin-dependency/hooks'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import {
@@ -199,90 +199,100 @@ const UpdateDSLModal = ({
return (
<>
- <Modal
- className="w-[520px] rounded-2xl p-6"
- isShow={show}
- onClose={onCancel}
+ <Dialog
+ open={show}
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
+ }}
>
- <div className="mb-3 flex items-center justify-between">
- <div className="title-2xl-semi-bold text-text-primary">{t('importApp', { ns: 'app' })}</div>
- <div className="flex h-[22px] w-[22px] cursor-pointer items-center justify-center" onClick={onCancel}>
- <RiCloseLine className="h-[18px] w-[18px] text-text-tertiary" />
- </div>
- </div>
- <div className="relative mb-2 flex grow gap-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-xs">
- <div className="absolute top-0 left-0 h-full w-full bg-toast-warning-bg opacity-40" />
- <div className="flex items-start justify-center p-1">
- <RiAlertFill className="h-4 w-4 shrink-0 text-text-warning-secondary" />
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden! rounded-2xl border-none p-6 text-left align-middle">
+
+ <div className="mb-3 flex items-center justify-between">
+ <div className="title-2xl-semi-bold text-text-primary">{t('importApp', { ns: 'app' })}</div>
+ <div className="flex h-[22px] w-[22px] cursor-pointer items-center justify-center" onClick={onCancel}>
+ <RiCloseLine className="h-[18px] w-[18px] text-text-tertiary" />
+ </div>
</div>
- <div className="flex grow flex-col items-start gap-0.5 py-1">
- <div className="system-xs-medium whitespace-pre-line text-text-primary">{t('common.importDSLTip', { ns: 'workflow' })}</div>
- <div className="flex items-start gap-1 self-stretch pt-1 pb-0.5">
- <Button
- size="small"
- variant="secondary"
- className="z-1000"
- onClick={onBackup}
- >
- <RiFileDownloadLine className="h-3.5 w-3.5 text-components-button-secondary-text" />
- <div className="flex items-center justify-center gap-1 px-[3px]">
- {t('common.backupCurrentDraft', { ns: 'workflow' })}
- </div>
- </Button>
+ <div className="relative mb-2 flex grow gap-0.5 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-xs">
+ <div className="absolute top-0 left-0 h-full w-full bg-toast-warning-bg opacity-40" />
+ <div className="flex items-start justify-center p-1">
+ <RiAlertFill className="h-4 w-4 shrink-0 text-text-warning-secondary" />
+ </div>
+ <div className="flex grow flex-col items-start gap-0.5 py-1">
+ <div className="system-xs-medium whitespace-pre-line text-text-primary">{t('common.importDSLTip', { ns: 'workflow' })}</div>
+ <div className="flex items-start gap-1 self-stretch pt-1 pb-0.5">
+ <Button
+ size="small"
+ variant="secondary"
+ className="z-1000"
+ onClick={onBackup}
+ >
+ <RiFileDownloadLine className="h-3.5 w-3.5 text-components-button-secondary-text" />
+ <div className="flex items-center justify-center gap-1 px-[3px]">
+ {t('common.backupCurrentDraft', { ns: 'workflow' })}
+ </div>
+ </Button>
+ </div>
</div>
</div>
- </div>
- <div>
- <div className="pt-2 system-md-semibold text-text-primary">
- {t('common.chooseDSL', { ns: 'workflow' })}
+ <div>
+ <div className="pt-2 system-md-semibold text-text-primary">
+ {t('common.chooseDSL', { ns: 'workflow' })}
+ </div>
+ <div className="flex w-full flex-col items-start justify-center gap-4 self-stretch py-4">
+ <Uploader
+ file={currentFile}
+ updateFile={handleFile}
+ className="mt-0! w-full"
+ />
+ </div>
</div>
- <div className="flex w-full flex-col items-start justify-center gap-4 self-stretch py-4">
- <Uploader
- file={currentFile}
- updateFile={handleFile}
- className="mt-0! w-full"
- />
+ <div className="flex items-center justify-end gap-2 self-stretch pt-5">
+ <Button onClick={onCancel}>{t('newApp.Cancel', { ns: 'app' })}</Button>
+ <Button
+ disabled={!currentFile || loading}
+ variant="primary"
+ tone="destructive"
+ onClick={handleImport}
+ loading={loading}
+ >
+ {t('common.overwriteAndImport', { ns: 'workflow' })}
+ </Button>
</div>
- </div>
- <div className="flex items-center justify-end gap-2 self-stretch pt-5">
- <Button onClick={onCancel}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button
- disabled={!currentFile || loading}
- variant="primary"
- tone="destructive"
- onClick={handleImport}
- loading={loading}
- >
- {t('common.overwriteAndImport', { ns: 'workflow' })}
- </Button>
- </div>
- </Modal>
- <Modal
- isShow={showErrorModal}
- onClose={() => setShowErrorModal(false)}
- className="w-[480px]"
+ </DialogContent>
+ </Dialog>
+ <Dialog
+ open={showErrorModal}
+ onOpenChange={(open) => {
+ if (!open)
+ setShowErrorModal(false)
+ }}
>
- <div className="flex flex-col items-start gap-2 self-stretch pb-4">
- <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>
- <div className="flex grow flex-col system-md-regular text-text-secondary">
- <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
- <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
- <br />
- <div>
- {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
- <span className="system-md-medium">{versions?.importedVersion}</span>
- </div>
- <div>
- {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
- <span className="system-md-medium">{versions?.systemVersion}</span>
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden! border-none text-left align-middle">
+
+ <div className="flex flex-col items-start gap-2 self-stretch pb-4">
+ <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>
+ <div className="flex grow flex-col system-md-regular text-text-secondary">
+ <div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div>
+ <div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div>
+ <br />
+ <div>
+ {t('newApp.appCreateDSLErrorPart3', { ns: 'app' })}
+ <span className="system-md-medium">{versions?.importedVersion}</span>
+ </div>
+ <div>
+ {t('newApp.appCreateDSLErrorPart4', { ns: 'app' })}
+ <span className="system-md-medium">{versions?.systemVersion}</span>
+ </div>
</div>
</div>
- </div>
- <div className="flex items-start justify-end gap-2 self-stretch pt-6">
- <Button variant="secondary" onClick={() => setShowErrorModal(false)}>{t('newApp.Cancel', { ns: 'app' })}</Button>
- <Button variant="primary" tone="destructive" onClick={onUpdateDSLConfirm}>{t('newApp.Confirm', { ns: 'app' })}</Button>
- </div>
- </Modal>
+ <div className="flex items-start justify-end gap-2 self-stretch pt-6">
+ <Button variant="secondary" onClick={() => setShowErrorModal(false)}>{t('newApp.Cancel', { ns: 'app' })}</Button>
+ <Button variant="primary" tone="destructive" onClick={onUpdateDSLConfirm}>{t('newApp.Confirm', { ns: 'app' })}</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
</>
)
}
diff --git a/web/app/education-apply/expire-notice-modal.tsx b/web/app/education-apply/expire-notice-modal.tsx
index e54afaecde3..5e07bf0fb10 100644
--- a/web/app/education-apply/expire-notice-modal.tsx
+++ b/web/app/education-apply/expire-notice-modal.tsx
@@ -1,9 +1,9 @@
'use client'
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { RiExternalLinkLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
-import Modal from '@/app/components/base/modal'
import { useDocLink } from '@/context/i18n'
import { useModalContextSelector } from '@/context/modal-context'
import useTimestamp from '@/hooks/use-timestamp'
@@ -41,63 +41,70 @@ const ExpireNoticeModal: React.FC<Props> = ({ expireAt, expired, onClose }) => {
}
return (
- <Modal
- isShow
- onClose={onClose}
- title={expired ? t(`${i18nPrefix}.expired.title`, { ns: 'education' }) : t(`${i18nPrefix}.isAboutToExpire.title`, { ns: 'education', date: formatTime(expireAt, t(`${i18nPrefix}.dateFormat`, { ns: 'education' }) as string), interpolation: { escapeValue: false } })}
- closable
- className="max-w-[600px]"
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open)
+ onClose()
+ }}
>
- <div className="mt-5 space-y-5 body-md-regular text-text-secondary">
- <div>
- {expired
- ? (
- <>
- <div>{t(`${i18nPrefix}.expired.summary.line1`, { ns: 'education' })}</div>
- <div>{t(`${i18nPrefix}.expired.summary.line2`, { ns: 'education' })}</div>
- </>
- )
- : t(`${i18nPrefix}.isAboutToExpire.summary`, { ns: 'education' })}
- </div>
- <div>
- <strong className="block title-md-semi-bold">{t(`${i18nPrefix}.stillInEducation.title`, { ns: 'education' })}</strong>
- {t(`${i18nPrefix}.stillInEducation.${expired ? 'expired' : 'isAboutToExpire'}`, { ns: 'education' })}
- </div>
- <div>
- <strong className="block title-md-semi-bold">{t(`${i18nPrefix}.alreadyGraduated.title`, { ns: 'education' })}</strong>
- {t(`${i18nPrefix}.alreadyGraduated.${expired ? 'expired' : 'isAboutToExpire'}`, { ns: 'education' })}
+ <DialogContent className="w-full max-w-[600px] overflow-hidden! border-none text-left align-middle">
+ <DialogCloseButton data-testid="modal-close-button" />
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {expired ? t(`${i18nPrefix}.expired.title`, { ns: 'education' }) : t(`${i18nPrefix}.isAboutToExpire.title`, { ns: 'education', date: formatTime(expireAt, t(`${i18nPrefix}.dateFormat`, { ns: 'education' }) as string), interpolation: { escapeValue: false } })}
+ </DialogTitle>
+
+ <div className="mt-5 space-y-5 body-md-regular text-text-secondary">
+ <div>
+ {expired
+ ? (
+ <>
+ <div>{t(`${i18nPrefix}.expired.summary.line1`, { ns: 'education' })}</div>
+ <div>{t(`${i18nPrefix}.expired.summary.line2`, { ns: 'education' })}</div>
+ </>
+ )
+ : t(`${i18nPrefix}.isAboutToExpire.summary`, { ns: 'education' })}
+ </div>
+ <div>
+ <strong className="block title-md-semi-bold">{t(`${i18nPrefix}.stillInEducation.title`, { ns: 'education' })}</strong>
+ {t(`${i18nPrefix}.stillInEducation.${expired ? 'expired' : 'isAboutToExpire'}`, { ns: 'education' })}
+ </div>
+ <div>
+ <strong className="block title-md-semi-bold">{t(`${i18nPrefix}.alreadyGraduated.title`, { ns: 'education' })}</strong>
+ {t(`${i18nPrefix}.alreadyGraduated.${expired ? 'expired' : 'isAboutToExpire'}`, { ns: 'education' })}
+ </div>
</div>
- </div>
- <div className="mt-7 flex items-center justify-between space-x-2">
- <Link className="flex items-center space-x-1 system-xs-regular text-text-accent" href={eduDocLink} target="_blank" rel="noopener noreferrer">
- <div>{t('learn', { ns: 'education' })}</div>
- <RiExternalLinkLine className="size-3" />
- </Link>
- <div className="flex space-x-2">
- {expired
- ? (
- <Button
- onClick={() => {
- onClose()
- setShowPricingModal()
- }}
- className="flex items-center space-x-1"
- >
- <SparklesSoftAccent className="size-4" />
- <div className="text-components-button-secondary-accent-text">{t(`${i18nPrefix}.action.upgrade`, { ns: 'education' })}</div>
- </Button>
- )
- : (
- <Button onClick={onClose}>
- {t(`${i18nPrefix}.action.dismiss`, { ns: 'education' })}
- </Button>
- )}
- <Button variant="primary" onClick={handleConfirm}>
- {t(`${i18nPrefix}.action.reVerify`, { ns: 'education' })}
- </Button>
+ <div className="mt-7 flex items-center justify-between space-x-2">
+ <Link className="flex items-center space-x-1 system-xs-regular text-text-accent" href={eduDocLink} target="_blank" rel="noopener noreferrer">
+ <div>{t('learn', { ns: 'education' })}</div>
+ <RiExternalLinkLine className="size-3" />
+ </Link>
+ <div className="flex space-x-2">
+ {expired
+ ? (
+ <Button
+ onClick={() => {
+ onClose()
+ setShowPricingModal()
+ }}
+ className="flex items-center space-x-1"
+ >
+ <SparklesSoftAccent className="size-4" />
+ <div className="text-components-button-secondary-accent-text">{t(`${i18nPrefix}.action.upgrade`, { ns: 'education' })}</div>
+ </Button>
+ )
+ : (
+ <Button onClick={onClose}>
+ {t(`${i18nPrefix}.action.dismiss`, { ns: 'education' })}
+ </Button>
+ )}
+ <Button variant="primary" onClick={handleConfirm}>
+ {t(`${i18nPrefix}.action.reVerify`, { ns: 'education' })}
+ </Button>
+ </div>
</div>
- </div>
- </Modal>
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/app/education-apply/verify-state-modal.tsx b/web/app/education-apply/verify-state-modal.tsx
index 9103e94f364..ac10f2319e8 100644
--- a/web/app/education-apply/verify-state-modal.tsx
+++ b/web/app/education-apply/verify-state-modal.tsx
@@ -1,10 +1,9 @@
import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import {
RiExternalLinkLine,
} from '@remixicon/react'
import * as React from 'react'
-import { useCallback, useEffect, useRef, useState } from 'react'
-import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
@@ -34,61 +33,25 @@ function Confirm({
}: IConfirm) {
const { t } = useTranslation()
const docLink = useDocLink()
- const dialogRef = useRef<HTMLDivElement>(null)
- const [isVisible, setIsVisible] = useState(isShow)
const eduDocLink = docLink('/use-dify/workspace/subscription-management#dify-for-education')
const handleClick = () => {
window.open(eduDocLink, '_blank', 'noopener,noreferrer')
}
- useEffect(() => {
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.key === 'Escape')
- onCancel()
- }
-
- document.addEventListener('keydown', handleKeyDown)
- return () => {
- document.removeEventListener('keydown', handleKeyDown)
- }
- }, [onCancel])
-
- const handleClickOutside = useCallback((event: MouseEvent) => {
- if (maskClosable && dialogRef.current && !dialogRef.current.contains(event.target as Node))
- onCancel()
- }, [maskClosable, onCancel])
-
- useEffect(() => {
- document.addEventListener('mousedown', handleClickOutside)
- return () => {
- document.removeEventListener('mousedown', handleClickOutside)
- }
- }, [handleClickOutside])
-
- useEffect(() => {
- const timer = setTimeout(() => {
- setIsVisible(isShow)
- }, isShow ? 0 : 200)
-
- return () => clearTimeout(timer)
- }, [isShow])
-
- if (!isVisible)
- return null
-
- return createPortal(
- <div
- className="fixed inset-0 z-10000000 flex items-center justify-center bg-background-overlay"
- onClick={(e) => {
- e.preventDefault()
- e.stopPropagation()
+ return (
+ <Dialog
+ open={isShow}
+ onOpenChange={(open) => {
+ if (!open)
+ onCancel()
}}
+ disablePointerDismissal={!maskClosable}
>
- <div ref={dialogRef} className="relative w-full max-w-[481px] overflow-hidden">
+ <DialogContent className="w-full max-w-[481px]! overflow-hidden! border-none bg-transparent p-0! shadow-none">
<div className="shadows-shadow-lg flex max-w-full flex-col items-start rounded-2xl border-[0.5px] border-solid border-components-panel-border bg-components-panel-bg">
<div className="flex flex-col items-start gap-2 self-stretch pt-6 pr-6 pb-4 pl-6">
- <div className="title-2xl-semi-bold text-text-primary">{title}</div>
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">{title}</DialogTitle>
<div className="w-full system-md-regular text-text-tertiary">{content}</div>
</div>
{email && (
@@ -109,9 +72,8 @@ function Confirm({
<Button variant="primary" className={confirmText ? 'min-w-20!' : 'w-20!'} onClick={onConfirm}>{confirmText || t('operation.ok', { ns: 'common' })}</Button>
</div>
</div>
- </div>
- </div>,
- document.body,
+ </DialogContent>
+ </Dialog>
)
}
diff --git a/web/eslint.constants.mjs b/web/eslint.constants.mjs
index eb85d5d9021..bd8254b6fb8 100644
--- a/web/eslint.constants.mjs
+++ b/web/eslint.constants.mjs
@@ -39,9 +39,19 @@ const BASE_UI_RESTRICTED_IMPORT_PATTERNS = [
},
]
+const FLOATING_UI_RESTRICTED_IMPORT_PATTERNS = [
+ {
+ group: [
+ '@floating-ui/*',
+ ],
+ message: 'Do not import Floating UI directly in web. Use @langgenius/dify-ui/* primitives instead.',
+ },
+]
+
export const WEB_RESTRICTED_IMPORT_PATTERNS = [
...NEXT_PLATFORM_RESTRICTED_IMPORT_PATTERNS,
...BASE_UI_RESTRICTED_IMPORT_PATTERNS,
+ ...FLOATING_UI_RESTRICTED_IMPORT_PATTERNS,
]
export const OVERLAY_RESTRICTED_IMPORT_PATTERNS = [
diff --git a/web/models/pipeline.ts b/web/models/pipeline.ts
index e75ee7569a1..30389ab5e0b 100644
--- a/web/models/pipeline.ts
+++ b/web/models/pipeline.ts
@@ -89,6 +89,7 @@ export type ImportPipelineDSLResponse = {
dataset_id: string
current_dsl_version: string
imported_dsl_version: string
+ error?: string
}
export type ImportPipelineDSLConfirmResponse = {
diff --git a/web/package.json b/web/package.json
index 0dd9dfbde58..df1ceed01f0 100644
--- a/web/package.json
+++ b/web/package.json
@@ -54,7 +54,6 @@
"@emoji-mart/data": "catalog:",
"@floating-ui/react": "catalog:",
"@formatjs/intl-localematcher": "catalog:",
- "@headlessui/react": "catalog:",
"@heroicons/react": "catalog:",
"@lexical/code": "catalog:",
"@lexical/link": "catalog:",
diff --git a/web/service/__tests__/use-pipeline.spec.tsx b/web/service/__tests__/use-pipeline.spec.tsx
new file mode 100644
index 00000000000..411d29ac6a6
--- /dev/null
+++ b/web/service/__tests__/use-pipeline.spec.tsx
@@ -0,0 +1,81 @@
+import type { ReactNode } from 'react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, renderHook } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { DSLImportMode, DSLImportStatus } from '@/models/app'
+import { post } from '../base'
+import { useImportPipelineDSL, useImportPipelineDSLConfirm } from '../use-pipeline'
+
+vi.mock('../base', () => ({
+ post: vi.fn(),
+ get: vi.fn(),
+ patch: vi.fn(),
+ del: vi.fn(),
+}))
+
+const createWrapper = () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ })
+
+ return ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ {children}
+ </QueryClientProvider>
+ )
+}
+
+describe('use-pipeline imports', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(post).mockResolvedValue({
+ id: 'import-id',
+ status: DSLImportStatus.COMPLETED,
+ pipeline_id: 'pipeline-id',
+ dataset_id: 'dataset-id',
+ current_dsl_version: '0.1.0',
+ imported_dsl_version: '0.1.0',
+ })
+ })
+
+ it('should import pipeline DSL silently so callers can own error toasts', async () => {
+ const { result } = renderHook(
+ () => useImportPipelineDSL(),
+ { wrapper: createWrapper() },
+ )
+ const request = {
+ mode: DSLImportMode.YAML_CONTENT,
+ yaml_content: 'rag_pipeline: {}',
+ }
+
+ await act(async () => {
+ await result.current.mutateAsync(request)
+ })
+
+ expect(post).toHaveBeenCalledWith(
+ '/rag/pipelines/imports',
+ { body: request },
+ { silent: true },
+ )
+ })
+
+ it('should confirm pipeline DSL import silently so callers can own error toasts', async () => {
+ const { result } = renderHook(
+ () => useImportPipelineDSLConfirm(),
+ { wrapper: createWrapper() },
+ )
+
+ await act(async () => {
+ await result.current.mutateAsync('import-id')
+ })
+
+ expect(post).toHaveBeenCalledWith(
+ '/rag/pipelines/imports/import-id/confirm',
+ {},
+ { silent: true },
+ )
+ })
+})
diff --git a/web/service/use-pipeline.ts b/web/service/use-pipeline.ts
index 6efb5bb8c65..7e1bd9711f2 100644
--- a/web/service/use-pipeline.ts
+++ b/web/service/use-pipeline.ts
@@ -113,7 +113,7 @@ export const useImportPipelineDSL = (
return useMutation({
mutationKey: [NAME_SPACE, 'dsl-import'],
mutationFn: (request: ImportPipelineDSLRequest) => {
- return post<ImportPipelineDSLResponse>('/rag/pipelines/imports', { body: request })
+ return post<ImportPipelineDSLResponse>('/rag/pipelines/imports', { body: request }, { silent: true })
},
...mutationOptions,
})
@@ -125,7 +125,7 @@ export const useImportPipelineDSLConfirm = (
return useMutation({
mutationKey: [NAME_SPACE, 'dsl-import-confirm'],
mutationFn: (importId: string) => {
- return post<ImportPipelineDSLConfirmResponse>(`/rag/pipelines/imports/${importId}/confirm`)
+ return post<ImportPipelineDSLConfirmResponse>(`/rag/pipelines/imports/${importId}/confirm`, {}, { silent: true })
},
...mutationOptions,
})
diff --git a/web/vitest.setup.ts b/web/vitest.setup.ts
index 6211fcd2f4f..99d264113e8 100644
--- a/web/vitest.setup.ts
+++ b/web/vitest.setup.ts
@@ -1,46 +1,26 @@
import * as jestDomMatchers from '@testing-library/jest-dom/matchers'
import { act, cleanup } from '@testing-library/react'
import * as React from 'react'
-import '@testing-library/jest-dom/vitest'
+import { afterEach, beforeEach, expect, vi } from 'vitest'
import 'vitest-canvas-mock'
-expect.extend(jestDomMatchers)
-
-// Suppress act() warnings from @headlessui/react internal Transition component
-// These warnings are caused by Headless UI's internal async state updates, not our code
-const originalConsoleError = console.error
-console.error = (...args: unknown[]) => {
- // Check all arguments for the Headless UI TransitionRootFn act warning
- const fullMessage = args.map(arg => (typeof arg === 'string' ? arg : '')).join(' ')
- if (fullMessage.includes('TransitionRootFn') && fullMessage.includes('not wrapped in act'))
- return
- originalConsoleError.apply(console, args)
+if (typeof expect.extend === 'function') {
+ expect.extend(jestDomMatchers)
}
-// Fix for @headlessui/react compatibility with happy-dom
-// headlessui tries to override focus properties which may be read-only in happy-dom
+(
+ globalThis as typeof globalThis & {
+ BASE_UI_ANIMATIONS_DISABLED: boolean
+ }
+).BASE_UI_ANIMATIONS_DISABLED = true
+
+// Base UI waits for element animations while closing overlays.
if (typeof window !== 'undefined') {
- // Provide a minimal animations API polyfill before @headlessui/react boots
if (typeof Element !== 'undefined' && !Element.prototype.getAnimations)
Element.prototype.getAnimations = () => []
if (!document.getAnimations)
document.getAnimations = () => []
-
- const ensureWritable = (target: object, prop: string) => {
- const descriptor = Object.getOwnPropertyDescriptor(target, prop)
- if (descriptor && !descriptor.writable) {
- const original = descriptor.value ?? descriptor.get?.call(target)
- Object.defineProperty(target, prop, {
- value: typeof original === 'function' ? original : vi.fn(),
- writable: true,
- configurable: true,
- })
- }
- }
-
- ensureWritable(window, 'focus')
- ensureWritable(HTMLElement.prototype, 'focus')
}
if (typeof globalThis.ResizeObserver === 'undefined') {