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): align hotkeys with command ownership (#42974)

yyh414cce2f7018
diff --git a/.agents/skills/how-to-write-component/references/interactions.md b/.agents/skills/how-to-write-component/references/interactions.md
index 6559b134258..d90f5a05640 100644
--- a/.agents/skills/how-to-write-component/references/interactions.md
+++ b/.agents/skills/how-to-write-component/references/interactions.md
@@ -10,13 +10,8 @@ Read this document when a change involves application hotkeys, focus, dialogs, m
## Keyboard Commands
-- Distinguish application commands from widget-local keyboard semantics. Use `@tanstack/react-hotkeys` for application commands; keep menu navigation, dialog Escape handling, editor behavior, and ARIA widget keys in their local primitive or owner.
-- Use `useHotkey` or `useHotkeys` for registered commands. When an existing `onKeyDown` intentionally owns the command, use `matchesKeyboardEvent` rather than duplicating modifier parsing or adding another global listener.
-- Keep registration and keycap or menu display derived from one canonical command. Distinguish registered commands, held keys, and display-only accelerators.
-- Keep a single-owner command beside its component. Create a feature-local hotkey module only when several production files share it; tests alone do not justify extraction.
-- Make availability and scope explicit with `enabled`, `ignoreInputs`, and `target`. Put a target ref on the actual behavior owner rather than creating wrapper DOM solely for hotkey scope.
-- Preserve existing `preventDefault` and propagation behavior when migrating command APIs.
-- Test observable command behavior, disabled and input scope, target scope, and the registration/display contract at the owning feature boundary.
+- Keep widget navigation, dialog dismissal, and editor commands in their local primitive or owner.
+- For Web application commands, follow [Keyboard commands] for TanStack registration, typed bindings, targets, event consumption, display, and verification. Do not recreate that policy in a wrapper or a second command framework.
## Secondary Surfaces
@@ -28,4 +23,5 @@ Read this document when a change involves application hotkeys, focus, dialogs, m
- Prefer primitive-owned open state unless another owner must observe or coordinate it. Analytics callbacks and local cleanup alone do not require a controlled root.
[overlay contract]: ../../../../packages/dify-ui/docs/overlays.md
+[Keyboard commands]: ../../../../web/docs/hotkeys.md
[state ownership]: state.md
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index fe5c18bc626..fb53b55192d 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -192,11 +192,6 @@
"count": 9
}
},
- "web/app/components/app/app-publisher/__tests__/sections.spec.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/app/app-publisher/__tests__/version-info-modal.spec.tsx": {
"typescript/no-explicit-any": {
"count": 3
@@ -1329,14 +1324,6 @@
"count": 1
}
},
- "web/app/components/base/prompt-editor/plugins/hitl-input-block/tag-label.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/base/prompt-editor/plugins/last-run-block/component.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
@@ -3689,14 +3676,6 @@
"count": 1
}
},
- "web/app/components/workflow/note-node/note-editor/toolbar/operator.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
- }
- },
"web/app/components/workflow/operator/hooks.ts": {
"typescript/no-explicit-any": {
"count": 1
diff --git a/packages/dify-ui/src/kbd/index.stories.tsx b/packages/dify-ui/src/kbd/index.stories.tsx
index 0ba16e3a0ef..1736f80e58e 100644
--- a/packages/dify-ui/src/kbd/index.stories.tsx
+++ b/packages/dify-ui/src/kbd/index.stories.tsx
@@ -1,5 +1,5 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
-import type { FormatDisplayOptions, RegisterableHotkey } from '@tanstack/react-hotkeys'
+import type { DisplayHotkey, FormatDisplayOptions } from '@tanstack/react-hotkeys'
import { formatForDisplay } from '@tanstack/react-hotkeys'
import { Kbd, KbdGroup } from '.'
import {
@@ -43,29 +43,17 @@ const meta = {
export default meta
type Story = StoryObj<typeof meta>
-const displayKeys = (
- hotkey: RegisterableHotkey | (string & {}),
- platform: FormatDisplayOptions['platform'] = 'mac',
-) => {
- if (typeof hotkey !== 'string') return [formatForDisplay(hotkey, { platform })]
-
- return hotkey
- .split('+')
- .filter(Boolean)
- .map((key) => formatForDisplay(key, { platform }))
-}
-
const HotkeyKbdGroup = ({
hotkey,
color = 'gray',
platform = 'mac',
}: {
- hotkey: RegisterableHotkey | (string & {})
+ hotkey: DisplayHotkey
color?: 'gray' | 'white'
platform?: FormatDisplayOptions['platform']
}) => (
<KbdGroup>
- {displayKeys(hotkey, platform).map((key, index) => (
+ {formatForDisplay(hotkey, { platform, parts: true }).map((key, index) => (
// oxlint-disable-next-line react/no-array-index-key -- Repeated display keys are static, ordered tokens with no component state.
<Kbd key={`${key}-${index}`} color={color}>
{key}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b3b956a8bb9..2fd73bc1f03 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -327,8 +327,8 @@ catalogs:
specifier: 1.33.5
version: 1.33.5
'@tanstack/react-hotkeys':
- specifier: 0.10.0
- version: 0.10.0
+ specifier: 0.12.0
+ version: 0.12.0
'@tanstack/react-query':
specifier: 5.103.1
version: 5.103.1
@@ -1159,7 +1159,7 @@ importers:
'@tanstack/react-hotkeys':
specifier: 'catalog:'
'@tanstack/react-virtual':
specifier: 'catalog:'
@@ -1469,7 +1469,7 @@ importers:
'@tanstack/react-hotkeys':
specifier: 'catalog:'
'@tanstack/react-query':
specifier: 'catalog:'
version: 5.103.1([email protected])
@@ -4661,9 +4661,9 @@ packages:
'@tanstack/[email protected]':
resolution: {integrity: sha512-3dfx9MBP0aq5sXKteikG629X9oviptrQj0IFRk9YGcb+lB7Kv5x8S17oOSk1wUWgjQZ4xVJEMbKwOAODymocgA==}
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-vqH7X9nb0MTJ/O08++dB5bP9jgj4+BIPOUu/U+6myG86lDsirZSVSobpq5UQpE7nBuk62i8eIYeOhd+OMl/UrA==}
- engines: {node: '>=18'}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-gmvA+09xK/Q+gmC6WtZ2DfAOdkLgTMaEQSGvbMbcSD/PNrTpsDK5v9E7JfavhgkWDxtHoJ+FIYoS6Y5HWSE1Sg==}
+ engines: {node: '>=20'}
'@tanstack/[email protected]':
resolution: {integrity: sha512-y/xtNPNt/YeyoVxE/JCx+T7yjEzpezmbb+toK8DDD1P4m7Kzs5YR956+7OKexG3f8aXgC3rLZl7b1V+yNUSy5w==}
@@ -4681,9 +4681,9 @@ packages:
'@tanstack/react-start':
optional: true
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-GwOSndI5j3qBVYTmgP1mYyRTnlxb2MS17cwGlsavSxMQPSnmDf+m3LzMIpRMs+3zzQMjg3cYhHsFYizYlFI2tw==}
- engines: {node: '>=18'}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-sKCuPMpJ46sH/Aexs2Zj4h6d/Ch4A1awIzjTD1CbKgTwb18DwRmtB/zTJ4D4QeQdV6BowzdSw3ztz3GBLoN1jA==}
+ engines: {node: '>=20'}
peerDependencies:
react: '>=16.8'
react-dom: '>=16.8'
@@ -4693,8 +4693,8 @@ packages:
peerDependencies:
react: ^18 || ^19
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-tX4YXh3PDkmpvGQWkWqKpzs/MSqbtuwY9dWdWhtV9Q50PmO+jOkUKIWIX4G85dwt7lxdHLXsiaEKPdKmC8F41w==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-HaIGKI3YLmjBYIvy5DFDY23oNaYZIsTZfngey07Uh5iLVJgM3bIGCnZeOFOqzjFld9JHWcaHJnasD/bKoGKwJQ==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
@@ -4705,8 +4705,8 @@ packages:
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
- '@tanstack/[email protected]':
- resolution: {integrity: sha512-WlzzCt3xi0G6pCAJu1U+2jiECwabETDpQDi3hfkFZvJii9AuZqEKbOiVarX1/bWhTNjU486yQtJCCasi/0q+Cw==}
+ '@tanstack/[email protected]':
+ resolution: {integrity: sha512-mzTOBhypOuDJAy/D8n2MfUZ1HFkXnmSETviRyhqEC8LUE7/IZQExOTxMANj3KjTofYTkFNpBY67qaVrT41YccA==}
'@tanstack/[email protected]':
resolution: {integrity: sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==}
@@ -12160,11 +12160,11 @@ snapshots:
dependencies:
'@tanstack/devtools-event-client': 0.4.4
'@tanstack/pacer-lite': 0.1.1
- '@tanstack/store': 0.11.0
+ '@tanstack/store': 0.11.1
- '@tanstack/[email protected]':
+ '@tanstack/[email protected]':
dependencies:
- '@tanstack/store': 0.11.0
+ '@tanstack/store': 0.11.1
'@tanstack/[email protected]': {}
@@ -12173,15 +12173,15 @@ snapshots:
dependencies:
'@tanstack/form-core': 1.33.5
- '@tanstack/react-store': 0.11.0([email protected]([email protected]))([email protected])
+ '@tanstack/react-store': 0.11.1([email protected]([email protected]))([email protected])
react: 19.3.0
transitivePeerDependencies:
- react-dom
dependencies:
- '@tanstack/hotkeys': 0.8.0
- '@tanstack/react-store': 0.11.0([email protected]([email protected]))([email protected])
+ '@tanstack/hotkeys': 0.10.0
+ '@tanstack/react-store': 0.11.1([email protected]([email protected]))([email protected])
react: 19.3.0
react-dom: 19.3.0([email protected])
@@ -12190,9 +12190,9 @@ snapshots:
'@tanstack/query-core': 5.103.1
react: 19.3.0
dependencies:
- '@tanstack/store': 0.11.0
+ '@tanstack/store': 0.11.1
react: 19.3.0
react-dom: 19.3.0([email protected])
use-sync-external-store: 1.6.0([email protected])
@@ -12203,7 +12203,7 @@ snapshots:
react: 19.3.0
react-dom: 19.3.0([email protected])
- '@tanstack/[email protected]': {}
+ '@tanstack/[email protected]': {}
'@tanstack/[email protected]': {}
@@ -17844,7 +17844,7 @@ time:
'@tanstack/[email protected]': '2026-08-11T12:45:38.255Z'
'@tanstack/[email protected]': '2026-09-16T15:01:04.863Z'
'@tanstack/[email protected]': '2026-08-11T12:45:38.642Z'
- '@tanstack/[email protected]': '2026-04-25T12:28:06.989Z'
+ '@tanstack/[email protected]': '2026-09-24T18:29:12.070Z'
'@tanstack/[email protected]': '2026-09-16T15:01:15.056Z'
'@tanstack/[email protected]': '2026-09-14T10:22:44.535Z'
'@testing-library/[email protected]': '2026-09-13T18:08:36.116Z'
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 10a9948279a..a4a0317bc7b 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -121,7 +121,7 @@ catalog:
'@tanstack/form-core': 1.33.5
'@tanstack/query-core': 5.103.1
'@tanstack/react-form': 1.33.5
- '@tanstack/react-hotkeys': 0.10.0
+ '@tanstack/react-hotkeys': 0.12.0
'@tanstack/react-query': 5.103.1
'@tanstack/react-virtual': 3.14.13
'@testing-library/dom': 10.4.2
diff --git a/web/AGENTS.md b/web/AGENTS.md
index 7dfce633dae..bc4e8987aaa 100644
--- a/web/AGENTS.md
+++ b/web/AGENTS.md
@@ -16,6 +16,7 @@ Web owns application-specific requirements and consumes shared architecture guid
- Reuse the Web `SearchInput` composite when its search, clear, and IME contract matches the feature; otherwise follow the canonical [Input Group contract].
- Give save and submit flows a real form boundary with visible labels and accessible errors. Use Dify UI `Form` when its structured submission and validation contract is the owner; otherwise use a native form. Follow the canonical [form contract].
- Follow the canonical [Button contract] and [IconButton contract] for action semantics, loading, accessible names, and primitive composition. Do not add a Web wrapper that hides those contracts.
+- Follow [Keyboard commands] for hotkey ownership, targets, event consumption, typed bindings, and keycap display. Keep widget and editor keyboard semantics in their local owners.
- Follow [Accessible names and descriptions] when choosing or changing visible labels, ARIA naming, descriptions, or visually hidden text. Web owns localization and feature-specific status announcements; do not redefine the Dify UI naming contract locally.
- Follow the [Dify UI overlay contract] for primitive selection, portals, focus, and layering. Use `@langgenius/dify-ui/infotip` for an info glyph that opens explanatory content. Do not introduce a generic Web wrapper that recreates Dify UI overlay behavior.
- For custom SVG icons, follow `../packages/iconify-collections/README.md`; do not add generated React icons under `app/components/base/icons/src/`.
@@ -37,6 +38,7 @@ This block is written and re-added by `next dev` — verify at `node_modules/nex
[Dify UI package index]: ../packages/dify-ui/README.md
[IconButton contract]: ../packages/dify-ui/src/icon-button/README.md
[Input Group contract]: ../packages/dify-ui/src/input-group/README.md
+[Keyboard commands]: docs/hotkeys.md
[Page landmarks]: docs/landmarks.md
[Truncated Text Disclosure]: docs/truncated-text-disclosure.md
[form contract]: ../packages/dify-ui/docs/forms.md
diff --git a/web/app/components/app-sidebar/app-detail-top.tsx b/web/app/components/app-sidebar/app-detail-top.tsx
index 52ee85c0f49..121e327ff3a 100644
--- a/web/app/components/app-sidebar/app-detail-top.tsx
+++ b/web/app/components/app-sidebar/app-detail-top.tsx
@@ -91,8 +91,8 @@ export function AppDetailTop({ expand = true, onToggle }: AppDetailTopProps) {
<TooltipContent placement="bottom" className="flex items-center gap-1">
<span className="px-0.5">{t(($) => $['gotoAnything.quickAction'], { ns: 'app' })}</span>
<KbdGroup>
- {GOTO_ANYTHING_HOTKEY.split('+').map((key) => (
- <Kbd key={key}>{formatForDisplay(key)}</Kbd>
+ {formatForDisplay(GOTO_ANYTHING_HOTKEY, { parts: true }).map((key) => (
+ <Kbd key={key}>{key}</Kbd>
))}
</KbdGroup>
</TooltipContent>
diff --git a/web/app/components/app-sidebar/dataset-detail-top.tsx b/web/app/components/app-sidebar/dataset-detail-top.tsx
index 45e4d3acef7..58dc247fd35 100644
--- a/web/app/components/app-sidebar/dataset-detail-top.tsx
+++ b/web/app/components/app-sidebar/dataset-detail-top.tsx
@@ -94,8 +94,8 @@ export function DatasetDetailTop({ expand = true, onToggle }: DatasetDetailTopPr
<TooltipContent placement="bottom" className="flex items-center gap-1">
<span className="px-0.5">{t(($) => $['gotoAnything.quickAction'], { ns: 'app' })}</span>
<KbdGroup>
- {GOTO_ANYTHING_HOTKEY.split('+').map((key) => (
- <Kbd key={key}>{formatForDisplay(key)}</Kbd>
+ {formatForDisplay(GOTO_ANYTHING_HOTKEY, { parts: true }).map((key) => (
+ <Kbd key={key}>{key}</Kbd>
))}
</KbdGroup>
</TooltipContent>
diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
index 481dd218c45..57e3daf7abe 100644
--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
@@ -43,10 +43,6 @@ const sectionProps = vi.hoisted(() => ({
summary: null as null | Record<string, any>,
actions: null as null | Record<string, any>,
}))
-const hotkeyMocks = vi.hoisted(() => ({
- hotkeys: [] as string[],
- handlers: [] as Array<(event: { preventDefault: () => void }) => void>,
-}))
const collaborationMocks = vi.hoisted(() => ({
handler: undefined as
| ((update: {
@@ -61,13 +57,6 @@ const collaborationMocks = vi.hoisted(() => ({
let mockAppDetail: Record<string, any> | null = null
let mockWorkspacePermissionKeys: string[] = ['tool.manage']
-vi.mock('@tanstack/react-hotkeys', () => ({
- useHotkey: (hotkey: string, handler: (event: { preventDefault: () => void }) => void) => {
- hotkeyMocks.hotkeys.push(hotkey)
- hotkeyMocks.handlers.push(handler)
- },
-}))
-
vi.mock('@/app/components/app/store', () => ({
useStore: (selector: (state: { appDetail: Record<string, any> | null }) => unknown) =>
selector({ appDetail: mockAppDetail }),
@@ -255,8 +244,6 @@ vi.mock('../built-in-publisher/actions-section', () => ({
describe('AppPublisher', () => {
beforeEach(() => {
vi.clearAllMocks()
- hotkeyMocks.hotkeys.length = 0
- hotkeyMocks.handlers.length = 0
collaborationMocks.handler = undefined
sectionProps.summary = null
sectionProps.actions = null
@@ -938,36 +925,7 @@ describe('AppPublisher', () => {
expect(mockOnToggle).not.toHaveBeenCalled()
})
- it('should keep keyboard publishing available in multiple model mode', async () => {
- const preventDefault = vi.fn()
- mockOnPublish.mockResolvedValue(undefined)
-
- render(
- <AppPublisher
- debugWithMultipleModel
- multipleModelConfigs={[
- {
- id: 'model-1',
- model: 'gpt-4o',
- provider: 'openai',
- parameters: {},
- },
- ]}
- publishedAt={Date.now()}
- onPublish={mockOnPublish}
- />,
- )
-
- hotkeyMocks.handlers[0]!({ preventDefault })
-
- await waitFor(() => {
- expect(preventDefault).toHaveBeenCalled()
- expect(mockOnPublish).toHaveBeenCalledTimes(1)
- })
- })
-
it('should keep the popover open when restore and publish fail', async () => {
- const preventDefault = vi.fn()
const onRestore = vi.fn().mockRejectedValue(new Error('restore failed'))
mockOnPublish.mockRejectedValueOnce(new Error('publish failed'))
@@ -975,15 +933,10 @@ describe('AppPublisher', () => {
<AppPublisher publishedAt={Date.now()} onPublish={mockOnPublish} onRestore={onRestore} />,
)
- hotkeyMocks.handlers[0]!({ preventDefault })
-
- await waitFor(() => {
- expect(preventDefault).toHaveBeenCalled()
- expect(mockOnPublish).toHaveBeenCalledTimes(1)
- })
- expect(mockTrackEvent).not.toHaveBeenCalled()
-
fireEvent.click(screen.getByText(/(?:^|\.)common\.publish(?=$|:)/))
+ fireEvent.click(screen.getByText('publisher-summary-publish'))
+ await waitFor(() => expect(mockOnPublish).toHaveBeenCalledTimes(1))
+ expect(mockTrackEvent).not.toHaveBeenCalled()
fireEvent.click(screen.getByText('publisher-summary-restore'))
await waitFor(() => {
diff --git a/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx b/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx
index 5f3a9d7ffd5..84066d87d5c 100644
--- a/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/publisher-panel.spec.tsx
@@ -1,6 +1,8 @@
-import { render, screen } from '@testing-library/react'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { act, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
+import { AppModeEnum } from '@/types/app'
import { PublisherPanel } from '../publisher-content/publisher-panel'
vi.mock('../environment-deployment-flow', () => ({
@@ -18,8 +20,16 @@ vi.mock('../environment-deployment-flow', () => ({
),
}))
-function PublisherPanelHarness() {
- const [open, setOpen] = useState(true)
+function PublisherPanelHarness({
+ initialOpen = true,
+ onPublish = vi.fn(),
+ showBuiltInPublisher = false,
+}: {
+ initialOpen?: boolean
+ onPublish?: () => Promise<void>
+ showBuiltInPublisher?: boolean
+}) {
+ const [open, setOpen] = useState(initialOpen)
return (
<>
@@ -27,19 +37,22 @@ function PublisherPanelHarness() {
<PublisherPanel
builtInPublisher={{
actions: {
- appDetail: null,
- appURL: '',
+ appDetail: { id: 'app-1', mode: AppModeEnum.CHAT },
+ appURL: 'https://example.com/app',
canViewAccessPoint: false,
disabledFunctionButton: false,
+ publishedAt: 1_710_000_000_000,
workflowToolIsLoading: false,
onConfigureWorkflowTool: vi.fn(),
},
summary: {
formatTimeFromNow: () => '',
- handlePublish: vi.fn(),
+ handlePublish: onPublish,
handleRestore: vi.fn(),
isChatApp: false,
+ isPublishing: false,
published: false,
+ publishedAt: 1_710_000_000_000,
upgradeHighlightStyle: {},
},
}}
@@ -56,7 +69,7 @@ function PublisherPanelHarness() {
}}
environmentPublisherKey="staging"
open={open}
- showBuiltInPublisher={false}
+ showBuiltInPublisher={showBuiltInPublisher}
workflowLaunch={{
hiddenVariables: [],
open: false,
@@ -70,6 +83,35 @@ function PublisherPanelHarness() {
}
describe('PublisherPanel', () => {
+ it('publishes from the actions section on first open and reopen, but not while closed', async () => {
+ const user = userEvent.setup()
+ const onPublish = vi.fn().mockResolvedValue(undefined)
+ const modifier = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ const shortcut = `{${modifier}>}{Shift>}P{/Shift}{/${modifier}}`
+ render(<PublisherPanelHarness initialOpen={false} onPublish={onPublish} showBuiltInPublisher />)
+ const trigger = screen.getByRole('button', { name: /common\.publish\b/ })
+
+ for (let opened = 1; opened <= 2; opened++) {
+ await user.click(trigger)
+ const openWebApp = screen.getByRole('link', { name: /common\.openWebApp\b/ })
+ act(() => openWebApp.focus())
+ expect(openWebApp).toHaveFocus()
+ expect(screen.getByRole('button', { name: /common\.publishUpdate\b/ })).toBeEnabled()
+ await user.keyboard(shortcut)
+ expect(onPublish).toHaveBeenCalledTimes(opened)
+
+ await user.click(trigger)
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('link', { name: /common\.openWebApp\b/ }),
+ ).not.toBeInTheDocument(),
+ )
+ expect(trigger).toHaveFocus()
+ await user.keyboard(shortcut)
+ expect(onPublish).toHaveBeenCalledTimes(opened)
+ }
+ })
+
it('keeps the publisher open after an outside press when dismissal is prevented', async () => {
const user = userEvent.setup()
render(<PublisherPanelHarness />)
diff --git a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx b/web/app/components/app/app-publisher/__tests__/sections.spec.tsx
index 208905ce50c..41a67ac335a 100644
--- a/web/app/components/app/app-publisher/__tests__/sections.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/sections.spec.tsx
@@ -1,12 +1,17 @@
+import type { ComponentProps } from 'react'
import type { VersionHistory } from '@/types/workflow'
-import { fireEvent, screen, within } from '@testing-library/react'
+import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
+import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { useRef } from 'react'
+import { expectLoadingButton } from '@/test/button'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { render as renderWithConsoleState } from '@/test/console/render'
import { AppModeEnum } from '@/types/app'
import { PublisherActionsSection } from '../built-in-publisher/actions-section'
import { PublisherSummarySection } from '../built-in-publisher/summary-section'
+import { usePublishController } from '../publisher-content/use-publish-controller'
vi.mock('../publish-with-multiple-model', () => ({
default: ({
@@ -48,18 +53,226 @@ const createVersionInfo = (overrides: Partial<VersionHistory> = {}): VersionHist
...overrides,
})
+function PublisherPopup({
+ defaultOpen = false,
+ ...props
+}: Partial<Omit<ComponentProps<typeof PublisherSummarySection>, 'keyboardTarget'>> & {
+ defaultOpen?: boolean
+}) {
+ const popupRef = useRef<HTMLDivElement>(null)
+ return (
+ <Popover defaultOpen={defaultOpen}>
+ <PopoverTrigger>Open publisher</PopoverTrigger>
+ <PopoverContent ref={popupRef}>
+ <PublisherSummarySection
+ keyboardTarget={popupRef}
+ formatTimeFromNow={() => 'just now'}
+ handlePublish={vi.fn().mockResolvedValue(undefined)}
+ handleRestore={vi.fn().mockResolvedValue(undefined)}
+ isChatApp={false}
+ isPublishing={false}
+ published={false}
+ upgradeHighlightStyle={{}}
+ {...props}
+ />
+ </PopoverContent>
+ </Popover>
+ )
+}
+
+function PublishingPopup({ onPublish }: { onPublish: () => Promise<void> }) {
+ const publish = usePublishController({
+ appMode: AppModeEnum.CHAT,
+ supportsMultiEnvironment: false,
+ onClose: () => {},
+ onPublish,
+ })
+ return (
+ <PublisherPopup
+ handlePublish={publish.handlePublish}
+ published={publish.published}
+ isPublishing={publish.isPublishing}
+ />
+ )
+}
+
+function publishFrom(target: HTMLElement, options: KeyboardEventInit = {}) {
+ const event = new KeyboardEvent('keydown', {
+ key: 'P',
+ ctrlKey: true,
+ shiftKey: true,
+ bubbles: true,
+ cancelable: true,
+ ...options,
+ })
+ fireEvent(target, event)
+ fireEvent.keyUp(target, { key: 'P', ctrlKey: true, shiftKey: true })
+ return event
+}
+
describe('app-publisher sections', () => {
+ it('publishes only from its open built-in popup and unregisters when the popup closes', async () => {
+ const user = userEvent.setup()
+ const handlePublish = vi.fn().mockResolvedValue(undefined)
+ render(<PublisherPopup handlePublish={handlePublish} />)
+ expect(publishFrom(document.body).defaultPrevented).toBe(false)
+ expect(handlePublish).not.toHaveBeenCalled()
+
+ await user.click(screen.getByRole('button', { name: 'Open publisher' }))
+ const button = screen.getByRole('button', { name: /common\.publish\b/ })
+ expect(publishFrom(document.body).defaultPrevented).toBe(false)
+ await act(async () => {
+ expect(publishFrom(button).defaultPrevented).toBe(true)
+ })
+ expect(handlePublish).toHaveBeenCalledTimes(1)
+
+ await user.click(screen.getByRole('button', { name: 'Open publisher' }))
+ expect(publishFrom(document.body).defaultPrevented).toBe(false)
+ expect(handlePublish).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([{ publishDisabled: true }, { published: true }])(
+ 'shares the disabled state between the publish button and shortcut: %o',
+ async (props) => {
+ const user = userEvent.setup()
+ const handlePublish = vi.fn().mockResolvedValue(undefined)
+ render(<PublisherPopup {...props} handlePublish={handlePublish} />)
+ await user.click(screen.getByRole('button', { name: 'Open publisher' }))
+ const button = screen.getByRole('button', { name: /common\.publish/ })
+ expect(button).toBeDisabled()
+ expect(publishFrom(button).defaultPrevented).toBe(false)
+ await user.click(button)
+ expect(handlePublish).not.toHaveBeenCalled()
+ },
+ )
+
+ it('consumes held publish keys and allows publishing again after release', async () => {
+ const user = userEvent.setup()
+ const handlePublish = vi.fn().mockResolvedValue(undefined)
+ render(<PublisherPopup handlePublish={handlePublish} />)
+ await user.click(screen.getByRole('button', { name: 'Open publisher' }))
+ const button = screen.getByRole('button', { name: /common\.publish\b/ })
+ const keyOptions = {
+ key: 'P',
+ ctrlKey: true,
+ shiftKey: true,
+ bubbles: true,
+ cancelable: true,
+ }
+ const keyDown = new KeyboardEvent('keydown', keyOptions)
+ const repeatedKeyDown = new KeyboardEvent('keydown', { ...keyOptions, repeat: true })
+
+ fireEvent(button, keyDown)
+ fireEvent(button, repeatedKeyDown)
+ expect(keyDown.defaultPrevented).toBe(true)
+ expect(repeatedKeyDown.defaultPrevented).toBe(true)
+ expect(handlePublish).toHaveBeenCalledTimes(1)
+
+ fireEvent.keyUp(button, keyOptions)
+ publishFrom(button)
+ expect(handlePublish).toHaveBeenCalledTimes(2)
+ })
+
+ it('prevents a second publish while the shared publish action is pending', async () => {
+ const user = userEvent.setup()
+ let resolvePublish: () => void = () => {}
+ const handlePublish = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolvePublish = resolve
+ }),
+ )
+ render(<PublishingPopup onPublish={handlePublish} />)
+ await user.click(screen.getByRole('button', { name: 'Open publisher' }))
+ const button = screen.getByRole('button', { name: /common\.publish\b/ })
+ publishFrom(button)
+ expectLoadingButton(button)
+ publishFrom(button)
+ await user.click(button)
+ expect(handlePublish).toHaveBeenCalledTimes(1)
+ await act(async () => resolvePublish())
+ await waitFor(() =>
+ expect(screen.getByRole('button', { name: /common\.published\b/ })).toBeDisabled(),
+ )
+ })
+
+ it('keeps a pending publication locked when its popup closes and reopens', async () => {
+ const user = userEvent.setup()
+ let resolvePublish: () => void = () => {}
+ const onPublish = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolvePublish = resolve
+ }),
+ )
+ render(<PublishingPopup onPublish={onPublish} />)
+ const trigger = screen.getByRole('button', { name: 'Open publisher' })
+ await user.click(trigger)
+ publishFrom(screen.getByRole('button', { name: /common\.publish\b/ }))
+ expect(onPublish).toHaveBeenCalledOnce()
+ await user.click(trigger)
+ await waitFor(() =>
+ expect(screen.queryByRole('button', { name: /common\.publish\b/ })).not.toBeInTheDocument(),
+ )
+ await user.click(trigger)
+ const reopenedButton = screen.getByRole('button', { name: /common\.publish\b/ })
+ expectLoadingButton(reopenedButton)
+ publishFrom(reopenedButton)
+ await user.click(reopenedButton)
+ expect(onPublish).toHaveBeenCalledOnce()
+ await act(async () => resolvePublish())
+ expect(screen.getByRole('button', { name: /common\.published\b/ })).toBeDisabled()
+ })
+
+ it('allows a retry after the publication fails', async () => {
+ const user = userEvent.setup()
+ let rejectPublish: (error: Error) => void = () => {}
+ const onPublish = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>((_resolve, reject) => {
+ rejectPublish = reject
+ }),
+ )
+ .mockResolvedValue(undefined)
+ render(<PublishingPopup onPublish={onPublish} />)
+ await user.click(screen.getByRole('button', { name: 'Open publisher' }))
+ const button = screen.getByRole('button', { name: /common\.publish\b/ })
+ await user.click(button)
+ expectLoadingButton(button)
+ await act(async () => rejectPublish(new Error('Publication failed')))
+ expect(button).not.toHaveAttribute('aria-disabled', 'true')
+ await user.click(button)
+ expect(onPublish).toHaveBeenCalledTimes(2)
+ expect(screen.getByRole('button', { name: /common\.published\b/ })).toBeDisabled()
+ })
+
+ it('keeps multiple-model publication behind the model selection action', async () => {
+ const user = userEvent.setup()
+ const handlePublish = vi.fn().mockResolvedValue(undefined)
+ render(<PublisherPopup debugWithMultipleModel handlePublish={handlePublish} />)
+ await user.click(screen.getByRole('button', { name: 'Open publisher' }))
+ const modelButton = screen.getByRole('button', { name: 'publish-multiple-model' })
+ expect(publishFrom(modelButton).defaultPrevented).toBe(false)
+ expect(handlePublish).not.toHaveBeenCalled()
+ await user.click(modelButton)
+ expect(handlePublish).toHaveBeenCalledWith({ model: 'gpt-4o' })
+ })
+
it('should render restore controls for published chat apps', () => {
const handleRestore = vi.fn()
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel={false}
draftUpdatedAt={Date.now()}
formatTimeFromNow={() => '3 minutes ago'}
handlePublish={vi.fn()}
handleRestore={handleRestore}
isChatApp
+ isPublishing={false}
multipleModelConfigs={[]}
publishDisabled={false}
published={false}
@@ -79,13 +292,15 @@ describe('app-publisher sections', () => {
const handleRestore = vi.fn()
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel={false}
draftUpdatedAt={Date.now()}
formatTimeFromNow={() => '3 minutes ago'}
handlePublish={vi.fn()}
handleRestore={handleRestore}
isChatApp
+ isPublishing={false}
multipleModelConfigs={[]}
publishDisabled={false}
published
@@ -107,13 +322,15 @@ describe('app-publisher sections', () => {
it('should render the initial publish action when the draft has not been published yet', () => {
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel={false}
draftUpdatedAt={Date.now()}
formatTimeFromNow={() => '1 minute ago'}
handlePublish={vi.fn()}
handleRestore={vi.fn()}
isChatApp={false}
+ isPublishing={false}
multipleModelConfigs={[]}
publishDisabled={false}
published={false}
@@ -133,13 +350,15 @@ describe('app-publisher sections', () => {
const onEditVersion = vi.fn()
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel={false}
draftUpdatedAt={1_710_000_000_000}
formatTimeFromNow={() => '17 days ago'}
handlePublish={vi.fn()}
handleRestore={vi.fn()}
isChatApp={false}
+ isPublishing={false}
isWorkflowApp
multipleModelConfigs={[]}
onEditVersion={onEditVersion}
@@ -169,13 +388,15 @@ describe('app-publisher sections', () => {
const onEditVersion = vi.fn()
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel={false}
draftUpdatedAt={1_710_000_200_000}
formatTimeFromNow={() => '2 minutes ago'}
handlePublish={vi.fn()}
handleRestore={vi.fn()}
isChatApp={false}
+ isPublishing={false}
isWorkflowApp
multipleModelConfigs={[]}
onEditVersion={onEditVersion}
@@ -206,13 +427,15 @@ describe('app-publisher sections', () => {
it('should keep non-workflow apps free of workflow version details and saved time', () => {
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel={false}
draftUpdatedAt={1_710_000_200_000}
formatTimeFromNow={() => '2 minutes ago'}
handlePublish={vi.fn()}
handleRestore={vi.fn()}
isChatApp
+ isPublishing={false}
isWorkflowApp={false}
multipleModelConfigs={[]}
publishDisabled={false}
@@ -234,14 +457,16 @@ describe('app-publisher sections', () => {
const handlePublish = vi.fn()
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel
draftUpdatedAt={Date.now()}
formatTimeFromNow={() => '1 minute ago'}
handlePublish={handlePublish}
handleRestore={vi.fn()}
isChatApp={false}
- multipleModelConfigs={[{ id: '1' } as any]}
+ isPublishing={false}
+ multipleModelConfigs={[]}
publishDisabled={false}
published={false}
publishedAt={Date.now()}
@@ -257,14 +482,16 @@ describe('app-publisher sections', () => {
it('should disable multiple-model publishing when publishing is unavailable', () => {
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel
draftUpdatedAt={Date.now()}
formatTimeFromNow={() => '1 minute ago'}
handlePublish={vi.fn()}
handleRestore={vi.fn()}
isChatApp={false}
- multipleModelConfigs={[{ id: '1' } as any]}
+ isPublishing={false}
+ multipleModelConfigs={[]}
publishDisabled
published={false}
publishedAt={Date.now()}
@@ -278,13 +505,15 @@ describe('app-publisher sections', () => {
it('should render the upgrade hint when the start node limit is exceeded', () => {
render(
- <PublisherSummarySection
+ <PublisherPopup
+ defaultOpen
debugWithMultipleModel={false}
draftUpdatedAt={Date.now()}
formatTimeFromNow={() => '1 minute ago'}
handlePublish={vi.fn()}
handleRestore={vi.fn()}
isChatApp={false}
+ isPublishing={false}
multipleModelConfigs={[]}
publishDisabled={false}
published={false}
diff --git a/web/app/components/app/app-publisher/built-in-publisher/index.tsx b/web/app/components/app/app-publisher/built-in-publisher/index.tsx
index a9875f22c37..9f1e9c17a37 100644
--- a/web/app/components/app/app-publisher/built-in-publisher/index.tsx
+++ b/web/app/components/app/app-publisher/built-in-publisher/index.tsx
@@ -4,13 +4,14 @@ import { PublisherSummarySection } from './summary-section'
type BuiltInPublisherProps = {
actions: ComponentProps<typeof PublisherActionsSection>
- summary: ComponentProps<typeof PublisherSummarySection>
+ keyboardTarget: ComponentProps<typeof PublisherSummarySection>['keyboardTarget']
+ summary: Omit<ComponentProps<typeof PublisherSummarySection>, 'keyboardTarget'>
}
-export function BuiltInPublisher({ actions, summary }: BuiltInPublisherProps) {
+export function BuiltInPublisher({ actions, keyboardTarget, summary }: BuiltInPublisherProps) {
return (
<>
- <PublisherSummarySection {...summary} />
+ <PublisherSummarySection {...summary} keyboardTarget={keyboardTarget} />
<PublisherActionsSection {...actions} />
</>
)
diff --git a/web/app/components/app/app-publisher/built-in-publisher/summary-section.tsx b/web/app/components/app/app-publisher/built-in-publisher/summary-section.tsx
index 03d68f709c1..d7d099383e7 100644
--- a/web/app/components/app/app-publisher/built-in-publisher/summary-section.tsx
+++ b/web/app/components/app/app-publisher/built-in-publisher/summary-section.tsx
@@ -1,11 +1,11 @@
import type { WorkflowResponse } from '@dify/contracts/api/console/apps/types.gen'
-import type { CSSProperties, ReactNode } from 'react'
+import type { CSSProperties, ReactNode, RefObject } from 'react'
import type { ModelAndParameter } from '../../configuration/debug/types'
import type { AppPublisherProps } from '../types'
import type { PublishWorkflowParams } from '@/types/workflow'
import { Button } from '@langgenius/dify-ui/button'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
-import { formatForDisplay } from '@tanstack/react-hotkeys'
+import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
import { useTranslation } from 'react-i18next'
import UpgradeBtn from '@/app/components/billing/upgrade-btn'
import { getWorkflowVersionName } from '@/app/components/workflow/utils/version'
@@ -34,6 +34,8 @@ type PublisherSummarySectionProps = Pick<
handleRestore: () => Promise<void>
environmentTabs?: ReactNode
isChatApp: boolean
+ isPublishing: boolean
+ keyboardTarget: RefObject<HTMLDivElement | null>
isWorkflowApp?: boolean
onEditVersion?: () => void
published: boolean
@@ -49,6 +51,8 @@ export function PublisherSummarySection({
handlePublish,
handleRestore,
isChatApp,
+ isPublishing,
+ keyboardTarget,
isWorkflowApp = false,
multipleModelConfigs = [],
onEditVersion,
@@ -73,6 +77,18 @@ export function PublisherSummarySection({
? t(($) => $['common.publishUpdate'], { ns: 'workflow' })
: t(($) => $['common.publish'], { ns: 'workflow' })
+ function requestPublish(params?: ModelAndParameter | PublishWorkflowParams) {
+ if (publishButtonDisabled || isPublishing) return
+ return handlePublish(params)
+ }
+
+ useHotkey(APP_PUBLISH_HOTKEY, () => void requestPublish(), {
+ target: keyboardTarget,
+ enabled: !publishButtonDisabled && !isPublishing && !debugWithMultipleModel,
+ ignoreInputs: false,
+ requireReset: true,
+ })
+
return (
<div className="flex flex-col gap-3 p-4">
{environmentTabs}
@@ -176,17 +192,18 @@ export function PublisherSummarySection({
<div className="flex w-full flex-col">
{debugWithMultipleModel ? (
<PublishWithMultipleModel
- disabled={publishButtonDisabled}
+ disabled={publishButtonDisabled || isPublishing}
multipleModelConfigs={multipleModelConfigs}
- onSelect={(item) => handlePublish(item)}
+ onSelect={(item) => requestPublish(item)}
/>
) : (
<>
<Button
variant="primary"
className="w-full"
- onClick={() => handlePublish()}
+ onClick={() => void requestPublish()}
disabled={publishButtonDisabled}
+ loading={isPublishing}
>
{publishDisabled ? (
publishButtonLabel
@@ -194,9 +211,9 @@ export function PublisherSummarySection({
<span className="flex items-center gap-1">
<span>{publishButtonLabel}</span>
<KbdGroup aria-hidden>
- {APP_PUBLISH_HOTKEY.split('+').map((key) => (
+ {formatForDisplay(APP_PUBLISH_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white" disabled={publishButtonDisabled}>
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
diff --git a/web/app/components/app/app-publisher/publisher-content/index.tsx b/web/app/components/app/app-publisher/publisher-content/index.tsx
index 68b01dc6d88..68e2e9661a2 100644
--- a/web/app/components/app/app-publisher/publisher-content/index.tsx
+++ b/web/app/components/app/app-publisher/publisher-content/index.tsx
@@ -95,7 +95,6 @@ export function PublisherContent({
onClose: closePublisher,
onPublish,
onRestore,
- publishDisabled,
publishedAt,
supportsMultiEnvironment,
})
@@ -202,6 +201,7 @@ export function PublisherContent({
handlePublish: publish.handlePublish,
handleRestore: publish.handleRestore,
isChatApp: publish.isChatApp,
+ isPublishing: publish.isPublishing,
isWorkflowApp: publish.isWorkflowApp,
multipleModelConfigs,
onEditVersion: versionInfo.openEditor,
diff --git a/web/app/components/app/app-publisher/publisher-content/publisher-panel/index.tsx b/web/app/components/app/app-publisher/publisher-content/publisher-panel/index.tsx
index 07cef773d02..07003c91b09 100644
--- a/web/app/components/app/app-publisher/publisher-content/publisher-panel/index.tsx
+++ b/web/app/components/app/app-publisher/publisher-content/publisher-panel/index.tsx
@@ -3,14 +3,14 @@ import type { ComponentProps } from 'react'
import type { AppPublisherProps } from '../../types'
import { Button } from '@langgenius/dify-ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
-import { useState } from 'react'
+import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { WorkflowLaunchDialog } from '@/app/components/app/overview/workflow-launch-dialog'
import { BuiltInPublisher } from '../../built-in-publisher'
import { PublisherEnvironmentFlow } from '../../environment-deployment-flow'
type PublisherPanelProps = Pick<AppPublisherProps, 'crossAxisOffset' | 'disabled'> & {
- builtInPublisher: ComponentProps<typeof BuiltInPublisher>
+ builtInPublisher: Omit<ComponentProps<typeof BuiltInPublisher>, 'keyboardTarget'>
environmentPublisher: Omit<
ComponentProps<typeof PublisherEnvironmentFlow>,
'onConfigurationOpenChange'
@@ -33,6 +33,7 @@ export function PublisherPanel({
showBuiltInPublisher,
workflowLaunch,
}: PublisherPanelProps) {
+ const popupRef = useRef<HTMLDivElement>(null)
const { t } = useTranslation(['workflow'])
const [deploymentConfigurationOpen, setDeploymentConfigurationOpen] = useState(false)
const handleOpenChange: NonNullable<PopoverProps['onOpenChange']> = (nextOpen, eventDetails) => {
@@ -58,6 +59,7 @@ export function PublisherPanel({
}
/>
<PopoverContent
+ ref={popupRef}
placement="bottom-end"
sideOffset={4}
alignOffset={crossAxisOffset}
@@ -65,7 +67,7 @@ export function PublisherPanel({
>
<div className="flex max-h-[calc(100dvh-32px)] w-88 flex-col overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl shadow-shadow-shadow-5">
{showBuiltInPublisher ? (
- <BuiltInPublisher {...builtInPublisher} />
+ <BuiltInPublisher {...builtInPublisher} keyboardTarget={popupRef} />
) : (
<PublisherEnvironmentFlow
key={environmentPublisherKey}
diff --git a/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts b/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts
index 6f7052cd4b0..2801e0d0c98 100644
--- a/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts
+++ b/web/app/components/app/app-publisher/publisher-content/use-publish-controller.ts
@@ -5,9 +5,8 @@ import type {
AppPublisherPublishParams,
} from '../types'
import type { CollaborationUpdate } from '@/app/components/workflow/collaboration/types/collaboration'
-import { useHotkey } from '@tanstack/react-hotkeys'
import { useQueryClient } from '@tanstack/react-query'
-import { use, useEffect, useState } from 'react'
+import { use, useEffect, useRef, useState } from 'react'
import { trackEvent } from '@/app/components/base/amplitude'
import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'
import { webSocketClient } from '@/app/components/workflow/collaboration/core/websocket-manager'
@@ -19,11 +18,10 @@ import {
appWorkflowVersionsInfiniteQueryOptions,
} from '@/service/workflow-queries'
import { AppModeEnum } from '@/types/app'
-import { APP_PUBLISH_HOTKEY } from '../hotkeys'
type UsePublishControllerParams = Pick<
AppPublisherProps,
- 'onPublish' | 'onRestore' | 'publishDisabled' | 'publishedAt'
+ 'onPublish' | 'onRestore' | 'publishedAt'
> & {
appId?: string
appMode?: AppModeEnum
@@ -58,11 +56,12 @@ export function usePublishController({
onClose,
onPublish,
onRestore,
- publishDisabled = false,
publishedAt,
supportsMultiEnvironment,
}: UsePublishControllerParams) {
const [published, setPublished] = useState(false)
+ const [isPublishing, setIsPublishing] = useState(false)
+ const publishingRef = useRef(false)
const queryClient = useQueryClient()
const workflowStore = use(WorkflowContext)
const invalidateAppWorkflow = useInvalidateAppWorkflow()
@@ -121,11 +120,17 @@ export function usePublishController({
}
async function handlePublish(params?: AppPublisherPublishParams) {
+ if (publishingRef.current) return
+ publishingRef.current = true
+ setIsPublishing(true)
try {
await publishApp(params)
} catch (error) {
console.warn('[app-publisher] publish failed', error)
setPublished(false)
+ } finally {
+ publishingRef.current = false
+ setIsPublishing(false)
}
}
@@ -140,12 +145,6 @@ export function usePublishController({
} catch {}
}
- useHotkey(APP_PUBLISH_HOTKEY, (event) => {
- event.preventDefault()
- if (publishDisabled || published) return
- void handlePublish()
- })
-
useEffect(() => {
if (!appId) return
@@ -176,6 +175,7 @@ export function usePublishController({
handleRestore,
hasPublishedVersion,
isChatApp,
+ isPublishing,
isPublishedWorkflowError,
isPublishedWorkflowLoading,
isPublishedWorkflowSuccess,
diff --git a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx
index c27f08220d0..b87c1cfceff 100644
--- a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx
@@ -11,9 +11,6 @@ import { getRedirection } from '@/utils/app-redirection'
import { trackCreateApp } from '@/utils/create-app-tracking'
import CreateAppModal from '../index'
-const ahooksMocks = vi.hoisted(() => ({
- keyPressHandlers: [] as Array<() => void>,
-}))
const mockConsoleState = vi.hoisted(() => ({
userProfile: { id: 'user-1' },
workspacePermissionKeys: ['app.create_and_management'] as string[],
@@ -30,12 +27,6 @@ vi.mock('ahooks', () => ({
},
useHover: () => false,
}))
-vi.mock('@tanstack/react-hotkeys', () => ({
- formatForDisplay: (key: string) => key,
- useHotkey: (_hotkey: string, handler: () => void) => {
- ahooksMocks.keyPressHandlers.push(handler)
- },
-}))
vi.mock('@/next/navigation', () => ({
useRouter: vi.fn(),
useParams: () => ({}),
@@ -138,7 +129,6 @@ function render(ui: ReactElement) {
describe('CreateAppModal', () => {
beforeEach(() => {
vi.clearAllMocks()
- ahooksMocks.keyPressHandlers.length = 0
mockUseRouter.mockReturnValue({ push: mockPush } as unknown as ReturnType<typeof useRouter>)
appQuota = { size: 0, limit: 1 }
mockConsoleStateReader.mockReturnValue({
@@ -281,7 +271,9 @@ describe('CreateAppModal', () => {
target: { value: 'Created from shortcut' },
})
- ahooksMocks.keyPressHandlers.at(-1)?.()
+ const nameInput = screen.getByPlaceholderText('app.newApp.appNamePlaceholder')
+ fireEvent.keyDown(nameInput, { key: 'Enter', code: 'Enter', ctrlKey: true })
+ fireEvent.keyUp(nameInput, { key: 'Enter', code: 'Enter', ctrlKey: true })
await waitFor(() => {
expect(mockCreateApp).toHaveBeenCalledWith({
@@ -295,12 +287,15 @@ describe('CreateAppModal', () => {
})
})
- it('shows validation feedback when the keyboard shortcut runs without a name', () => {
+ it('keeps creation unavailable from both the button and shortcut without a name', () => {
renderModal()
- ahooksMocks.keyPressHandlers.at(-1)?.()
+ const nameInput = screen.getByPlaceholderText('app.newApp.appNamePlaceholder')
+ fireEvent.keyDown(nameInput, { key: 'Enter', code: 'Enter', ctrlKey: true })
+ fireEvent.keyUp(nameInput, { key: 'Enter', code: 'Enter', ctrlKey: true })
- expect(mockToastError).toHaveBeenCalledWith('app.newApp.nameNotEmpty')
+ expect(screen.getByRole('button', { name: /app\.newApp\.Create/ })).toBeDisabled()
+ expect(mockToastError).not.toHaveBeenCalled()
expect(mockCreateApp).not.toHaveBeenCalled()
})
@@ -320,7 +315,9 @@ describe('CreateAppModal', () => {
expect(screen.queryByPlaceholderText('app.iconPicker.search')).not.toBeInTheDocument()
- ahooksMocks.keyPressHandlers.at(-1)?.()
+ const nameInput = screen.getByPlaceholderText('app.newApp.appNamePlaceholder')
+ fireEvent.keyDown(nameInput, { key: 'Enter', code: 'Enter', ctrlKey: true })
+ fireEvent.keyUp(nameInput, { key: 'Enter', code: 'Enter', ctrlKey: true })
expect(mockCreateApp).not.toHaveBeenCalled()
})
diff --git a/web/app/components/app/create-app-modal/index.tsx b/web/app/components/app/create-app-modal/index.tsx
index 62dca0354a5..62905ae78d3 100644
--- a/web/app/components/app/create-app-modal/index.tsx
+++ b/web/app/components/app/create-app-modal/index.tsx
@@ -52,6 +52,7 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP
const { t } = useTranslation(['app'])
const { push } = useRouter()
const nameInputId = useId()
+ const contentRef = useRef<HTMLDivElement>(null)
const [appMode, setAppMode] = useState<AppModeEnum>(defaultAppMode || AppModeEnum.ADVANCED_CHAT)
const [appIcon, setAppIcon] = useState<AppIconSelection>({
@@ -165,19 +166,30 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP
])
const { run: handleCreateApp } = useDebounceFn(onCreate, { wait: 300 })
+ const createDisabled = isAppQuotaUnavailable || isAppsFull || !canCreateApp || !name.trim()
useHotkey(
CREATE_APP_HOTKEY,
- () => {
- if (isAppQuotaUnavailable || isAppsFull || !canCreateApp) return
+ (event) => {
+ if (event.defaultPrevented || event.isComposing) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
handleCreateApp()
},
{
+ target: contentRef,
+ enabled: !createDisabled && !isCreating && !showAppIconPicker,
ignoreInputs: false,
+ preventDefault: false,
+ stopPropagation: false,
},
)
return (
<>
- <div className="flex h-full justify-center overflow-x-hidden overflow-y-auto">
+ <div
+ ref={contentRef}
+ className="flex h-full justify-center overflow-x-hidden overflow-y-auto"
+ >
<div className="flex flex-1 shrink-0 justify-end">
<div className="px-10">
<div className="h-6 w-full 2xl:h-34.75" />
@@ -371,16 +383,16 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP
<div className="flex gap-2">
<Button onClick={onClose}>{t(($) => $['newApp.Cancel'], { ns: 'app' })}</Button>
<Button
- disabled={isAppQuotaUnavailable || !canCreateApp || isAppsFull || !name}
+ disabled={createDisabled}
loading={isCreating}
variant="primary"
onClick={handleCreateApp}
>
<span>{t(($) => $['newApp.Create'], { ns: 'app' })}</span>
<KbdGroup>
- {CREATE_APP_HOTKEY.split('+').map((key) => (
+ {formatForDisplay(CREATE_APP_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white">
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
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 3fff68ffa61..83aa1ed7009 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
@@ -22,9 +22,6 @@ const toastMocks = vi.hoisted(() => ({
error: vi.fn(),
warning: vi.fn(),
}))
-const hotkeyMocks = vi.hoisted(() => ({
- handlers: new Map<string, { handler: () => void; options?: { enabled?: boolean } }>(),
-}))
let appCount = 0
let appLimit = 10
let mockWorkspacePermissionKeys: string[] = ['app.create_and_management']
@@ -35,28 +32,6 @@ vi.mock('ahooks', () => ({
}),
}))
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (hotkey: string, handler: () => void, options?: { enabled?: boolean }) => {
- hotkeyMocks.handlers.set(hotkey, { handler, options })
- },
- }
-})
-
-const triggerHotkey = (hotkey: string) => {
- const registration = hotkeyMocks.handlers.get(hotkey)
- if (registration?.options?.enabled === false) return
- registration?.handler()
-}
-
-vi.mock('@/next/navigation', () => ({
- useRouter: () => ({
- push: mockPush,
- }),
-}))
-
vi.mock('@/utils/create-app-tracking', () => ({
trackCreateApp: (...args: unknown[]) => mockTrackCreateApp(...args),
}))
@@ -151,10 +126,20 @@ function render(ui: ReactElement) {
})
}
+vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: mockPush }) }))
+
+function submitWithKeyboard() {
+ const target =
+ screen.queryByRole('textbox') ??
+ screen.queryByRole('button', { name: /operation\.create/i }) ??
+ document.body
+ fireEvent.keyDown(target, { key: 'Enter', ctrlKey: true })
+ fireEvent.keyUp(target, { key: 'Enter', ctrlKey: true })
+}
+
describe('CreateFromDSLModal', () => {
beforeEach(() => {
vi.clearAllMocks()
- hotkeyMocks.handlers.clear()
appCount = 0
appLimit = 10
mockWorkspacePermissionKeys = ['app.create_and_management']
@@ -243,7 +228,7 @@ describe('CreateFromDSLModal', () => {
const handleClose = vi.fn()
render(<CreateFromDSLModal show onClose={handleClose} />)
- triggerHotkey('Mod+Enter')
+ submitWithKeyboard()
expect(mockImportDSL).not.toHaveBeenCalled()
await act(async () => {
@@ -524,7 +509,7 @@ describe('CreateFromDSLModal', () => {
expect(getCreateButton())!.toBeDisabled()
})
- triggerHotkey('Mod+Enter')
+ submitWithKeyboard()
expect(mockImportDSL).not.toHaveBeenCalled()
})
@@ -879,7 +864,13 @@ describe('CreateFromDSLModal', () => {
/>,
)
- triggerHotkey('Mod+Enter')
+ fireEvent.keyDown(document.body, { key: 'Enter', ctrlKey: true })
+ fireEvent.keyUp(document.body, { key: 'Enter', ctrlKey: true })
+ const input = screen.getByRole('textbox')
+ fireEvent.keyDown(input, { key: 'Enter', ctrlKey: true, isComposing: true })
+ fireEvent.keyUp(input, { key: 'Enter', ctrlKey: true })
+ expect(mockImportDSL).not.toHaveBeenCalled()
+ submitWithKeyboard()
await waitFor(() => {
expect(mockImportDSL).toHaveBeenCalledWith({
@@ -924,7 +915,7 @@ describe('CreateFromDSLModal', () => {
expect(screen.getByText('apps-full')).toBeInTheDocument()
expect(getCreateButton()).toBeDisabled()
await user.click(getCreateButton())
- triggerHotkey('Mod+Enter')
+ submitWithKeyboard()
expect(mockImportDSL).not.toHaveBeenCalled()
})
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 3023ed06d0b..69a51dfa250 100644
--- a/web/app/components/app/create-from-dsl-modal/index.tsx
+++ b/web/app/components/app/create-from-dsl-modal/index.tsx
@@ -17,7 +17,7 @@ import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { Tabs, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'
-import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
+import { formatForDisplay, matchesKeyboardEvent } from '@tanstack/react-hotkeys'
import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useRef, useState } from 'react'
@@ -94,7 +94,6 @@ function CreateFromDSLModal({
}: CreateFromDSLModalProps) {
const { push } = useRouter()
const { t } = useTranslation(['app', 'common'])
- const formRef = useRef<HTMLFormElement>(null)
const browseButtonRef = useRef<HTMLButtonElement>(null)
const [currentFile, setCurrentFile] = useState<File | undefined>(droppedFile)
const [currentTab, setCurrentTab] = useState(activeTab)
@@ -291,11 +290,6 @@ function CreateFromDSLModal({
isAppsFull ||
(currentTab === CreateFromDSLModalTab.FROM_FILE && !currentFile)
- useHotkey(CREATE_FROM_DSL_HOTKEY, () => formRef.current?.requestSubmit(), {
- enabled: show && !createDisabled && !isImporting && !pendingImport,
- ignoreInputs: false,
- })
-
return (
<>
<Dialog
@@ -325,7 +319,27 @@ function CreateFromDSLModal({
<span aria-hidden className="i-ri-close-line size-5 text-text-tertiary" />
</IconButton>
</div>
- <Form<ImportFormValues> ref={formRef} onFormSubmit={handleSubmit}>
+ <Form<ImportFormValues>
+ onFormSubmit={handleSubmit}
+ onKeyDown={(event) => {
+ if (
+ !show ||
+ createDisabled ||
+ isImporting ||
+ !!pendingImport ||
+ event.defaultPrevented ||
+ event.nativeEvent.isComposing ||
+ !(event.target instanceof Node) ||
+ !event.currentTarget.contains(event.target) ||
+ !matchesKeyboardEvent(event.nativeEvent, CREATE_FROM_DSL_HOTKEY)
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ event.currentTarget.requestSubmit()
+ }}
+ >
<Tabs value={currentTab} onValueChange={handleTabChange}>
<TabsList className="h-9 gap-6 border-b border-divider-subtle px-6">
<TabsTab
@@ -394,9 +408,9 @@ function CreateFromDSLModal({
>
<span>{t(($) => $['operation.create'], { ns: 'common' })}</span>
<KbdGroup>
- {CREATE_FROM_DSL_HOTKEY.split('+').map((key) => (
+ {formatForDisplay(CREATE_FROM_DSL_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white">
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
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 db348701284..b950b0b34ad 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
@@ -65,6 +65,7 @@ describe('PdfPreview', () => {
it('should render the pdf preview portal with overlay and loading indicator', () => {
render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
+ expect(screen.getByRole('dialog', { name: 'workflow.common.preview' })).toBeInTheDocument()
expect(document.querySelector('[tabindex="-1"]')).toBeInTheDocument()
expect(getScaleContainer()).not.toHaveAttribute('aria-label')
expect(screen.getByTestId('pdf-loader')).toBeInTheDocument()
@@ -110,7 +111,7 @@ describe('PdfPreview', () => {
it('should zoom in when ArrowUp key is pressed', () => {
render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
- fireEvent.keyDown(document, { key: 'ArrowUp', code: 'ArrowUp' })
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'ArrowUp', code: 'ArrowUp' })
expect(getScaleContainer().getAttribute('style')).toContain('scale(1.2)')
})
@@ -118,7 +119,7 @@ describe('PdfPreview', () => {
it('should zoom out when ArrowDown key is pressed', () => {
render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
- fireEvent.keyDown(document, { key: 'ArrowDown', code: 'ArrowDown' })
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'ArrowDown', code: 'ArrowDown' })
expect(getScaleContainer().getAttribute('style')).toMatch(/scale\(0\.8333/)
})
diff --git a/web/app/components/base/file-uploader/pdf-preview.tsx b/web/app/components/base/file-uploader/pdf-preview.tsx
index 9cee1c577f9..e662158d1a2 100644
--- a/web/app/components/base/file-uploader/pdf-preview.tsx
+++ b/web/app/components/base/file-uploader/pdf-preview.tsx
@@ -1,10 +1,9 @@
-import type { FC } from 'react'
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
+import { Dialog, DialogBackdrop, DialogPopup, DialogPortal } from '@langgenius/dify-ui/dialog'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { RiCloseLine, RiZoomInLine, RiZoomOutLine } from '@remixicon/react'
import { useHotkey } from '@tanstack/react-hotkeys'
import { noop } from 'es-toolkit/function'
-import { useState } from 'react'
+import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
@@ -16,8 +15,9 @@ type PdfPreviewProps = {
onCancel: () => void
}
-const PdfPreview: FC<PdfPreviewProps> = ({ url, onCancel }) => {
- const { t } = useTranslation(['common'])
+function PdfPreviewContent({ url, onCancel }: PdfPreviewProps) {
+ const previewRef = useRef<HTMLDivElement>(null)
+ const { t } = useTranslation(['common', 'workflow'])
const media = useBreakpoints()
const [scale, setScale] = useState(1)
const [position, setPosition] = useState({ x: 0, y: 0 })
@@ -38,24 +38,52 @@ const PdfPreview: FC<PdfPreviewProps> = ({ url, onCancel }) => {
})
}
- useHotkey('ArrowUp', zoomIn)
- useHotkey('ArrowDown', zoomOut)
+ useHotkey(
+ 'ArrowUp',
+ (event) => {
+ if (event.defaultPrevented || event.isComposing) return
+ event.preventDefault()
+ event.stopPropagation()
+ zoomIn()
+ },
+ {
+ target: previewRef,
+ enabled: true,
+ ignoreInputs: true,
+ requireReset: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
+ useHotkey(
+ 'ArrowDown',
+ (event) => {
+ if (event.defaultPrevented || event.isComposing) return
+ event.preventDefault()
+ event.stopPropagation()
+ zoomOut()
+ },
+ {
+ target: previewRef,
+ enabled: true,
+ ignoreInputs: true,
+ requireReset: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
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
- >
- <DialogContent
- className={`inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 shadow-none! ${!isMobile ? 'p-8!' : 'p-0!'}`}
- backdropProps={{ className: 'bg-transparent!' }}
+ <>
+ <DialogBackdrop className="bg-transparent!" />
+ <DialogPopup
+ ref={previewRef}
+ aria-label={t(($) => $['common.preview'], { ns: 'workflow' })}
+ className={`fixed inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 shadow-none! ${!isMobile ? 'p-8!' : 'p-0!'}`}
>
<div
tabIndex={-1}
@@ -134,7 +162,23 @@ const PdfPreview: FC<PdfPreviewProps> = ({ url, onCancel }) => {
/>
<TooltipContent>{cancelLabel}</TooltipContent>
</Tooltip>
- </DialogContent>
+ </DialogPopup>
+ </>
+ )
+}
+
+function PdfPreview(props: PdfPreviewProps) {
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) props.onCancel()
+ }}
+ disablePointerDismissal
+ >
+ <DialogPortal>
+ <PdfPreviewContent {...props} />
+ </DialogPortal>
</Dialog>
)
}
diff --git a/web/app/components/base/image-uploader/__tests__/image-preview.browser.spec.tsx b/web/app/components/base/image-uploader/__tests__/image-preview.browser.spec.tsx
new file mode 100644
index 00000000000..38c26141884
--- /dev/null
+++ b/web/app/components/base/image-uploader/__tests__/image-preview.browser.spec.tsx
@@ -0,0 +1,65 @@
+import { useState } from 'react'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import ImagePreview from '../image-preview'
+
+const imageUrl = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100"><rect width="200" height="100" fill="teal" /></svg>')}`
+
+it('keeps the portalled preview fullscreen and owns arrows only while open', async () => {
+ // Real layout and native initial focus prove the popup/content split retains the preview boundary.
+ const onNext = vi.fn()
+ const onCancel = vi.fn()
+
+ function PreviewHost() {
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ Open preview
+ </button>
+ {open && (
+ <ImagePreview
+ url={imageUrl}
+ title="Local preview"
+ onNext={onNext}
+ onCancel={() => {
+ onCancel()
+ setOpen(false)
+ }}
+ />
+ )}
+ </>
+ )
+ }
+
+ await page.viewport(960, 640)
+ const screen = await render(<PreviewHost />)
+ await screen.getByRole('button', { name: 'Open preview' }).click()
+ const dialog = screen.getByRole('dialog', { name: 'Local preview' })
+ await expect.element(dialog).toBeVisible()
+ await expect.poll(() => dialog.element().contains(document.activeElement)).toBe(true)
+ const bounds = dialog.element().getBoundingClientRect()
+ expect(bounds.x).toBeCloseTo(0)
+ expect(bounds.y).toBeCloseTo(0)
+ expect(bounds.width).toBeCloseTo(960)
+ expect(bounds.height).toBeCloseTo(640)
+
+ const image = dialog.getByRole('img', { name: 'Local preview' })
+ await expect.poll(() => image.element().getBoundingClientRect().width).toBeGreaterThan(0)
+ const initialWidth = image.element().getBoundingClientRect().width
+ await userEvent.keyboard('{ArrowRight>3/}')
+ expect(onNext).toHaveBeenCalledOnce()
+ await userEvent.keyboard('{ArrowRight}')
+ expect(onNext).toHaveBeenCalledTimes(2)
+ await userEvent.keyboard('{ArrowUp>3/}')
+ await expect
+ .poll(() => image.element().getBoundingClientRect().width)
+ .toBeCloseTo(initialWidth * 1.2 ** 3)
+
+ await userEvent.keyboard('{Escape}')
+ await expect.element(dialog).not.toBeInTheDocument()
+ expect(onCancel).toHaveBeenCalledOnce()
+ await userEvent.keyboard('{ArrowRight}{ArrowUp}')
+ expect(onNext).toHaveBeenCalledTimes(2)
+ expect(onCancel).toHaveBeenCalledOnce()
+})
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 d04e3f73951..aa96bcd6dac 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
@@ -111,6 +111,7 @@ describe('ImagePreview', () => {
const overlay = getOverlay()
expect(overlay).toBeInTheDocument()
+ expect(screen.getByRole('dialog', { name: 'Preview Image' })).toBeInTheDocument()
expect(screen.getByTestId('image-preview-container')).not.toHaveAttribute('aria-label')
expect(overlay.closest('[data-base-ui-portal]')?.parentElement).toBe(document.body)
expect(screen.getByRole('img', { name: 'Preview Image' })).toHaveAttribute(
@@ -119,6 +120,12 @@ describe('ImagePreview', () => {
)
})
+ it.each(['', ' '])('names the dialog when the image title is %j', (title) => {
+ render(<ImagePreview url={dataImage} title={title} onCancel={vi.fn()} />)
+
+ expect(screen.getByRole('dialog', { name: 'workflow.common.preview' })).toBeInTheDocument()
+ })
+
it('should convert plain base64 string into data image src', () => {
render(<ImagePreview url={base64Image} title="Preview Image" onCancel={vi.fn()} />)
@@ -142,14 +149,34 @@ describe('ImagePreview', () => {
)
fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
- fireEvent.keyDown(document, { key: 'ArrowLeft', code: 'ArrowLeft' })
- fireEvent.keyDown(document, { key: 'ArrowRight', code: 'ArrowRight' })
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'ArrowLeft', code: 'ArrowLeft' })
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'ArrowRight', code: 'ArrowRight' })
expect(onCancel).toHaveBeenCalledTimes(1)
expect(onPrev).toHaveBeenCalledTimes(1)
expect(onNext).toHaveBeenCalledTimes(1)
})
+ it('leaves outside arrows and unavailable image navigation unclaimed', () => {
+ render(
+ <ImagePreview url="https://example.com/image.png" title="Preview" onCancel={vi.fn()} />,
+ )
+ const outside = new KeyboardEvent('keydown', {
+ key: 'ArrowUp',
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(document.body, outside)
+ expect(outside.defaultPrevented).toBe(false)
+ const unavailable = new KeyboardEvent('keydown', {
+ key: 'ArrowRight',
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(screen.getByRole('dialog'), unavailable)
+ expect(unavailable.defaultPrevented).toBe(false)
+ })
+
it('should zoom in and out from keyboard up/down hotkeys', async () => {
render(
<ImagePreview
@@ -160,12 +187,12 @@ describe('ImagePreview', () => {
)
const image = screen.getByRole('img', { name: 'Preview Image' })
- fireEvent.keyDown(document, { key: 'ArrowUp', code: 'ArrowUp' })
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'ArrowUp', code: 'ArrowUp' })
await waitFor(() => {
expect(image).toHaveStyle({ transform: 'scale(1.2) translate(0px, 0px)' })
})
- fireEvent.keyDown(document, { key: 'ArrowDown', code: 'ArrowDown' })
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'ArrowDown', code: 'ArrowDown' })
await waitFor(() => {
expect(image).toHaveStyle({ transform: 'scale(1) translate(0px, 0px)' })
})
diff --git a/web/app/components/base/image-uploader/image-preview.tsx b/web/app/components/base/image-uploader/image-preview.tsx
index b95ea920509..f4dc00a6313 100644
--- a/web/app/components/base/image-uploader/image-preview.tsx
+++ b/web/app/components/base/image-uploader/image-preview.tsx
@@ -1,5 +1,4 @@
-import type { FC } from 'react'
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
+import { Dialog, DialogBackdrop, DialogPopup, DialogPortal } from '@langgenius/dify-ui/dialog'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useHotkey } from '@tanstack/react-hotkeys'
import { noop } from 'es-toolkit/function'
@@ -50,8 +49,9 @@ const fetchImageAsPng = async (url: string): Promise<Blob> => {
}
}
-const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onNext }) => {
- const { t } = useTranslation(['common'])
+function ImagePreviewContent({ url, title, onCancel, onPrev, onNext }: ImagePreviewProps) {
+ const previewRef = useRef<HTMLDivElement>(null)
+ const { t } = useTranslation(['common', 'workflow'])
const [scale, setScale] = useState(1)
const [position, setPosition] = useState({ x: 0, y: 0 })
const [isDragging, setIsDragging] = useState(false)
@@ -184,10 +184,18 @@ const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onN
}
}, [handleMouseUp])
- useHotkey('ArrowUp', zoomIn)
- useHotkey('ArrowDown', zoomOut)
- useHotkey('ArrowLeft', onPrev || noop)
- useHotkey('ArrowRight', onNext || noop)
+ useHotkey('ArrowUp', zoomIn, { target: previewRef })
+ useHotkey('ArrowDown', zoomOut, { target: previewRef })
+ useHotkey('ArrowLeft', () => onPrev?.(), {
+ target: previewRef,
+ enabled: !!onPrev,
+ requireReset: true,
+ })
+ useHotkey('ArrowRight', () => onNext?.(), {
+ target: previewRef,
+ enabled: !!onNext,
+ requireReset: true,
+ })
const copyImageLabel = t(($) => $['operation.copyImage'], { ns: 'common' })
const zoomOutLabel = t(($) => $['operation.zoomOut'], { ns: 'common' })
@@ -197,16 +205,12 @@ const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onN
const cancelLabel = t(($) => $['operation.cancel'], { ns: 'common' })
return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onCancel()
- }}
- disablePointerDismissal
- >
- <DialogContent
- className="image-preview-container inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
- backdropProps={{ className: 'bg-transparent!' }}
+ <>
+ <DialogBackdrop className="bg-transparent!" />
+ <DialogPopup
+ ref={previewRef}
+ aria-label={title.trim() || t(($) => $['common.preview'], { ns: 'workflow' })}
+ className="image-preview-container fixed inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
>
<div
data-testid="image-preview-container"
@@ -327,7 +331,23 @@ const ImagePreview: FC<ImagePreviewProps> = ({ url, title, onCancel, onPrev, onN
/>
<TooltipContent>{cancelLabel}</TooltipContent>
</Tooltip>
- </DialogContent>
+ </DialogPopup>
+ </>
+ )
+}
+
+function ImagePreview(props: ImagePreviewProps) {
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) props.onCancel()
+ }}
+ disablePointerDismissal
+ >
+ <DialogPortal>
+ <ImagePreviewContent {...props} />
+ </DialogPortal>
</Dialog>
)
}
diff --git a/web/app/components/base/prompt-editor/__tests__/index.spec.tsx b/web/app/components/base/prompt-editor/__tests__/index.spec.tsx
index c17b609a553..48c2ff4145c 100644
--- a/web/app/components/base/prompt-editor/__tests__/index.spec.tsx
+++ b/web/app/components/base/prompt-editor/__tests__/index.spec.tsx
@@ -32,6 +32,12 @@ const mocks = vi.hoisted(() => {
commandHandlers.set(command, handler)
return vi.fn()
}),
+ registerRootListener: vi.fn(
+ (listener: (root: HTMLElement | null, previousRoot: HTMLElement | null) => void) => {
+ listener(rootElement, null)
+ return () => listener(null, rootElement)
+ },
+ ),
registerUpdateListener: vi.fn(() => vi.fn()),
registerNodeTransform: vi.fn(() => vi.fn()),
dispatchCommand: vi.fn(),
@@ -325,7 +331,7 @@ describe('PromptEditor', () => {
<PromptEditor
shortcutPopups={[
{
- hotkey: ['mod', '/'],
+ hotkey: 'Mod+/',
Popup,
},
]}
@@ -354,8 +360,8 @@ describe('PromptEditor', () => {
render(
<PromptEditor
shortcutPopups={[
- { hotkey: 'ctrl+a', Popup: PopupA },
- { hotkey: 'ctrl+b', Popup: PopupB },
+ { hotkey: 'Control+A', Popup: PopupA },
+ { hotkey: 'Control+B', Popup: PopupB },
]}
/>,
)
diff --git a/web/app/components/base/prompt-editor/__tests__/prompt-editor-content.spec.tsx b/web/app/components/base/prompt-editor/__tests__/prompt-editor-content.spec.tsx
index e9568d0b318..f8afcf024a5 100644
--- a/web/app/components/base/prompt-editor/__tests__/prompt-editor-content.spec.tsx
+++ b/web/app/components/base/prompt-editor/__tests__/prompt-editor-content.spec.tsx
@@ -438,7 +438,7 @@ describe('PromptEditorContent', () => {
const { container } = render(
<PromptEditorContentHarness
captures={captures}
- shortcutPopups={[{ hotkey: 'ctrl+/', Popup }]}
+ shortcutPopups={[{ hotkey: 'Control+/', Popup }]}
initialText="seed prompt"
floatingAnchorElem={document.createElement('div')}
onEditorChange={onEditorChange}
@@ -479,7 +479,7 @@ describe('PromptEditorContent', () => {
editable.focus()
setSelectionOnEditable(editable)
- fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ fireEvent.keyDown(editable, { key: '/', ctrlKey: true })
const insertButton = await screen.findByRole('button', { name: 'Insert shortcut' })
fireEvent.click(insertButton)
diff --git a/web/app/components/base/prompt-editor/index.tsx b/web/app/components/base/prompt-editor/index.tsx
index f893022912e..43e6efb428b 100644
--- a/web/app/components/base/prompt-editor/index.tsx
+++ b/web/app/components/base/prompt-editor/index.tsx
@@ -1,10 +1,10 @@
'use client'
import type { InitialConfigType } from '@lexical/react/LexicalComposer'
+import type { Hotkey } from '@tanstack/react-hotkeys'
import type { EditorState } from 'lexical'
import type { FC } from 'react'
import type {
- Hotkey,
ShortcutPopupDisplayMode,
ShortcutPopupInsertHandler,
} from './plugins/shortcuts-popup-plugin'
diff --git a/web/app/components/base/prompt-editor/plugins/component-picker-block/__tests__/index.spec.tsx b/web/app/components/base/prompt-editor/plugins/component-picker-block/__tests__/index.spec.tsx
index 190dbaaca6a..bcba6c235a6 100644
--- a/web/app/components/base/prompt-editor/plugins/component-picker-block/__tests__/index.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/component-picker-block/__tests__/index.spec.tsx
@@ -719,12 +719,12 @@ describe('ComponentPicker (component-picker-block/index.tsx)', () => {
expect(firstItem).toHaveAttribute('data-selected', 'true')
expect(secondItem).toHaveAttribute('data-selected', 'false')
- fireEvent.keyDown(document, { key: 'ArrowDown' })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_TEST_ID), { key: 'ArrowDown' })
expect(firstItem).toHaveAttribute('data-selected', 'false')
expect(secondItem).toHaveAttribute('data-selected', 'true')
- fireEvent.keyDown(document, { key: 'Enter' })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_TEST_ID), { key: 'Enter' })
expect(dispatchSpy).toHaveBeenCalledWith(INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND, [
'node-1',
diff --git a/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx b/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
index 6ae8698b930..a10d8adfbf3 100644
--- a/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
+++ b/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx
@@ -82,6 +82,8 @@ const ComponentPicker = ({
],
})
const [editor] = useLexicalComposerContext()
+ const [keyboardTarget, setKeyboardTarget] = useState<HTMLElement | null>(null)
+ useEffect(() => editor.registerRootListener(setKeyboardTarget), [editor])
const triggerMatchRef = useRef<MenuTextMatch | null>(null)
const baseCheckForTriggerMatch = useBasicTypeaheadTriggerMatch(triggerString, {
minLength: 0,
@@ -254,7 +256,9 @@ const ComponentPicker = ({
{workflowVariableBlock?.show && (
<div className="p-1">
<VarReferenceVars
- hideSearch={triggerString === '/'}
+ {...(triggerString === '/'
+ ? { hideSearch: true, keyboardTarget }
+ : { hideSearch: false })}
searchText={triggerString === '/' ? effectiveQueryString || '' : undefined}
searchBoxClassName="mt-1"
vars={workflowVariableOptions}
@@ -348,6 +352,7 @@ const ComponentPicker = ({
handleClose,
currentBlock?.generatorType,
handleSelectWorkflowVariable,
+ keyboardTarget,
queryString,
triggerString,
workflowVariableBlock?.showManageInputField,
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field-keyboard.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field-keyboard.spec.tsx
new file mode 100644
index 00000000000..300e8554f93
--- /dev/null
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field-keyboard.spec.tsx
@@ -0,0 +1,61 @@
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { TransferMethod } from '@/types/app'
+import InputField from '../input-field'
+
+vi.mock('@/service/use-common', () => ({
+ useFileUploadConfig: () => ({ data: undefined }),
+}))
+
+it('lets the extension input commit its tag before the field shortcut saves', async () => {
+ const user = userEvent.setup()
+ const onSave = vi.fn()
+ const modifier = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ const shortcut = `{${modifier}>}{Enter}{/${modifier}}`
+
+ function Host() {
+ const [open, setOpen] = useState(true)
+ return (
+ open && (
+ <InputField
+ nodeId="file-input"
+ isEdit={false}
+ payload={{
+ type: InputVarType.singleFile,
+ output_variable_name: 'upload',
+ allowed_file_types: [SupportUploadFileTypes.custom],
+ allowed_file_extensions: ['.pdf'],
+ allowed_file_upload_methods: [TransferMethod.local_file],
+ }}
+ onChange={(value) => {
+ onSave(value)
+ setOpen(false)
+ }}
+ onCancel={() => setOpen(false)}
+ />
+ )
+ )
+ }
+
+ render(<Host />)
+ const extensionInput = screen.getByRole('textbox', {
+ name: 'appDebug.variableConfig.file.custom.name',
+ })
+ await user.type(extensionInput, '.md')
+ await user.keyboard(shortcut)
+
+ expect(onSave).not.toHaveBeenCalled()
+ expect(screen.getByText('.md')).toBeInTheDocument()
+ expect(extensionInput).toHaveValue('')
+
+ await user.click(screen.getByRole('textbox', { name: /saveResponseAs/ }))
+ await user.keyboard(shortcut)
+
+ expect(onSave).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ allowed_file_extensions: ['.pdf', '.md'] }),
+ )
+ expect(extensionInput).not.toBeInTheDocument()
+})
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
index 4fc32d7db7c..312c33235fa 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/input-field.spec.tsx
@@ -1,8 +1,5 @@
-import type {
- FormInputItem,
- ParagraphFormInput,
-} from '@/app/components/workflow/nodes/human-input/types'
-import { render, screen } from '@testing-library/react'
+import type { ParagraphFormInput } from '@/app/components/workflow/nodes/human-input/types'
+import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { InputVarType, SupportUploadFileTypes, VarType } from '@/app/components/workflow/types'
import { TransferMethod } from '@/types/app'
@@ -82,6 +79,26 @@ describe('InputField', () => {
fileUploadSettingMaxLength = 4
})
+ it('saves only from the field surface and ignores composition', () => {
+ const onChange = vi.fn()
+ render(
+ <InputField
+ nodeId="node-scope"
+ isEdit={false}
+ payload={createPayload()}
+ onChange={onChange}
+ onCancel={vi.fn()}
+ />,
+ )
+ fireEvent.keyDown(document.body, { key: 'Enter', ctrlKey: true })
+ const input = screen.getByRole('textbox', { name: /saveResponseAs/ })
+ fireEvent.keyDown(input, { key: 'Enter', ctrlKey: true, isComposing: true })
+ expect(onChange).not.toHaveBeenCalled()
+ fireEvent.keyUp(input, { key: 'Enter', ctrlKey: true })
+ fireEvent.keyDown(input, { key: 'Enter', ctrlKey: true })
+ expect(onChange).toHaveBeenCalledTimes(1)
+ })
+
it('should keep the header and actions visible while the field content scrolls internally', () => {
const { container } = render(
<InputField
@@ -283,7 +300,7 @@ describe('InputField', () => {
default: {
type: 'constant',
selector: [],
- value: '',
+ value: 'initial',
},
})}
onChange={onChange}
@@ -291,9 +308,9 @@ describe('InputField', () => {
/>,
)
- await user.keyboard('{Tab}')
- const inputs = screen.getAllByRole('textbox')
- await user.type(inputs[1]!, 'constant-default')
+ const input = screen.getByRole('textbox', { name: /staticContent/ })
+ await user.clear(input)
+ await user.type(input, 'constant-default')
await user.keyboard('{Control>}{Enter}{/Control}')
expect(onChange).toHaveBeenCalledTimes(1)
@@ -407,42 +424,6 @@ describe('InputField', () => {
})
})
- it('should initialize default config when missing and selector is selected', async () => {
- const user = userEvent.setup()
- const onChange = vi.fn()
- const payloadWithoutDefault = {
- ...createPayload(),
- default: undefined,
- } as unknown as FormInputItem
-
- render(
- <InputField
- nodeId="node-6"
- isEdit={false}
- payload={payloadWithoutDefault}
- onChange={onChange}
- onCancel={vi.fn()}
- />,
- )
-
- await user.keyboard('{Tab}')
- await user.click(
- screen.getByText(/workflowHumanInput\.nodes\.humanInput\.insertInputField\.useVarInstead/i),
- )
- await user.click(
- screen.getByRole('button', {
- name: /workflowHumanInput\.nodes\.humanInput\.insertInputField\.insert/i,
- }),
- )
-
- expect(onChange).toHaveBeenCalledTimes(1)
- expect(onChange.mock.calls[0]![0].default).toEqual({
- type: 'variable',
- selector: [],
- value: '',
- })
- })
-
it('should switch to select payload when field type changes', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/pre-populate.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/pre-populate.spec.tsx
index 55067dcd278..cb20b7e5d2d 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/pre-populate.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/pre-populate.spec.tsx
@@ -68,7 +68,7 @@ describe('PrePopulate', () => {
vi.clearAllMocks()
})
- it('should show placeholder initially and switch out of placeholder on Tab key', async () => {
+ it('keeps Tab navigation native and opens static content on activation', async () => {
const user = userEvent.setup()
renderWithI18n(<PrePopulate nodeId="node-1" isVariable={false} value="" />)
@@ -76,8 +76,10 @@ describe('PrePopulate', () => {
await user.keyboard('{Tab}')
- expect(screen.queryByText('Static Content')).not.toBeInTheDocument()
- expect(screen.getByRole('textbox'))!.toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Static Content' })).toHaveFocus()
+ expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
+ await user.keyboard('{Enter}')
+ expect(screen.getByRole('textbox')).toHaveFocus()
})
it('should update constant value and toggle to variable mode when type switch is clicked', async () => {
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 58433731e19..cd4fe8ea5e6 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
@@ -1,3 +1,4 @@
+import type { Hotkey } from '@tanstack/react-hotkeys'
import type { Item as TypeSelectItem } from '@/app/components/app/configuration/config-var/config-modal/type-select'
import type {
FormInputItem,
@@ -9,10 +10,10 @@ import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Input } from '@langgenius/dify-ui/input'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
-import { formatForDisplay } from '@tanstack/react-hotkeys'
+import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
import { produce } from 'immer'
import * as React from 'react'
-import { useCallback, useEffect, useMemo, useState } from 'react'
+import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import TypeSelector from '@/app/components/app/configuration/config-var/config-modal/type-select'
import ConfigSelect from '@/app/components/app/configuration/config-var/config-select'
@@ -30,6 +31,8 @@ import { InputVarType, VarType } from '@/app/components/workflow/types'
import PrePopulate from './pre-populate'
import TypeSwitch from './type-switch'
+const SAVE_HOTKEY = 'Mod+Enter' satisfies Hotkey
+
const i18nPrefix = 'nodes.humanInput.insertInputField'
type InputFieldProps = {
@@ -48,6 +51,7 @@ const InputField: React.FC<InputFieldProps> = ({
onChange,
onCancel,
}) => {
+ const rootRef = useRef<HTMLDivElement>(null)
const outputVariableNameInputId = React.useId()
const { t } = useTranslation(['appDebug', 'common', 'workflow', 'workflowHumanInput'])
const [tempPayload, setTempPayload] = useState<FormInputItem>(
@@ -202,21 +206,35 @@ const InputField: React.FC<InputFieldProps> = ({
})
}, [])
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
- e.preventDefault()
- handleSave()
- }
- }
- window.addEventListener('keydown', handleKeyDown)
- return () => {
- window.removeEventListener('keydown', handleKeyDown)
- }
- }, [handleSave])
+ // Let child React handlers commit their input before claiming the field shortcut.
+ useHotkey(
+ SAVE_HOTKEY,
+ (event) => {
+ if (
+ event.defaultPrevented ||
+ event.isComposing ||
+ !(event.target instanceof Node) ||
+ !rootRef.current?.contains(event.target)
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ handleSave()
+ },
+ {
+ enabled: nameValid,
+ ignoreInputs: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
return (
- <div className="flex max-h-(--shortcut-popup-max-height,80dvh) w-93 flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-[5px]">
+ <div
+ ref={rootRef}
+ className="flex max-h-(--shortcut-popup-max-height,80dvh) w-93 flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-[5px]"
+ >
<div className="shrink-0 p-3 pb-2">
<div className="system-md-semibold text-text-primary">
{t(($) => $[`${i18nPrefix}.title`], { ns: 'workflowHumanInput' })}
@@ -353,9 +371,9 @@ const InputField: React.FC<InputFieldProps> = ({
<Button className="flex" variant="primary" disabled={!nameValid} onClick={handleSave}>
<span>{t(($) => $[`${i18nPrefix}.insert`], { ns: 'workflowHumanInput' })}</span>
<KbdGroup>
- {['Mod', 'Enter'].map((key) => (
+ {formatForDisplay(SAVE_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white">
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx
index c713fafca39..1ebea04f321 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/pre-populate.tsx
@@ -4,7 +4,7 @@ import type { ValueSelector, Var } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { Textarea } from '@langgenius/dify-ui/textarea'
import * as React from 'react'
-import { useCallback, useEffect, useState } from 'react'
+import { useCallback, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
import { VarType } from '@/app/components/workflow/types'
@@ -100,19 +100,6 @@ const PrePopulate: FC<Props> = ({
const isShowPlaceholder =
!onPlaceholderClicked && (isVariable ? !valueSelector || valueSelector.length === 0 : !value)
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Tab' && !onPlaceholderClicked) {
- e.preventDefault()
- setOnPlaceholderClicked(true)
- }
- }
- window.addEventListener('keydown', handleKeyDown)
- return () => {
- window.removeEventListener('keydown', handleKeyDown)
- }
- }, [onPlaceholderClicked, setOnPlaceholderClicked])
-
if (isShowPlaceholder)
return <Placeholder varPickerProps={varPickerProps} onTypeClick={handleTypeChange} />
diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/tag-label.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/tag-label.tsx
index 44b3032a486..53fce932cde 100644
--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/tag-label.tsx
+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/tag-label.tsx
@@ -13,17 +13,19 @@ type Props = Readonly<{
const TagLabel: FC<Props> = ({ type, children, className, onClick }) => {
const iconClassName =
type === 'edit' ? 'i-ri-edit-line' : 'i-custom-vender-solid-development-variable-02'
+ const Component = onClick ? 'button' : 'span'
return (
- <div
+ <Component
+ type={onClick ? 'button' : undefined}
className={cn(
- 'inline-flex h-5 cursor-pointer items-center space-x-1 rounded-md bg-components-button-secondary-bg px-1 text-text-accent',
+ 'inline-flex h-5 cursor-pointer items-center space-x-1 rounded-md bg-components-button-secondary-bg px-1 text-text-accent focus-visible:outline-2 focus-visible:outline-state-accent-solid',
className,
)}
onClick={onClick}
>
<span aria-hidden className={cn(iconClassName, 'size-3.5')} />
- <div className="system-xs-medium">{children}</div>
- </div>
+ <span className="system-xs-medium">{children}</span>
+ </Component>
)
}
export default React.memo(TagLabel)
diff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx b/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx
index 3dacb9cb534..e2d0931c76a 100644
--- a/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx
+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx
@@ -41,7 +41,7 @@ describe('RosterReferenceBlockNode', () => {
<RosterReferenceBlockComponent text="[§tool-all:tavily/tavily:tavily§]" />,
)
- const token = screen.getByTitle('tavily')
+ const token = screen.getByText('tavily').closest<HTMLElement>('[contenteditable="false"]')!
expect(token).toHaveAttribute('contenteditable', 'false')
expect(token).toHaveAttribute('data-roster-reference-kind', 'tool-all')
expect(token).toHaveAttribute('data-roster-reference-id', 'tavily/tavily')
@@ -63,7 +63,7 @@ describe('RosterReferenceBlockNode', () => {
</RosterReferenceBlockContext>,
)
- const token = screen.getByTitle('Playwright does not exist')
+ const token = screen.getByText('Playwright').closest<HTMLElement>('[contenteditable="false"]')!
expect(token).toHaveAttribute('data-roster-reference-warning', 'true')
expect(token).toHaveClass('border-components-badge-status-light-warning-halo')
expect(token).toHaveClass('bg-state-warning-hover')
@@ -71,7 +71,7 @@ describe('RosterReferenceBlockNode', () => {
expect(token.querySelector('.i-ri-alert-fill')).toBeInTheDocument()
await user.hover(token)
- expect(await screen.findByText('Playwright does not exist')).toBeInTheDocument()
+ expect(await screen.findByText('Playwright does not exist')).toBeVisible()
})
it('should expose DecoratorNode behavior and preserve raw text content', () => {
diff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx b/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx
index e3558e77df7..8ee1061270d 100644
--- a/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx
+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx
@@ -40,7 +40,6 @@ const RosterReferenceBlockComponent = ({ text }: RosterReferenceBlockComponentPr
data-roster-reference-kind={token.kind}
data-roster-reference-id={token.id}
data-roster-reference-warning={warning ? true : undefined}
- title={warning ?? token.label}
className={cn(
'inline-flex min-w-4.5 items-center gap-0.5 overflow-hidden rounded-[5px] border py-px pr-1 pl-px align-middle shadow-xs shadow-shadow-shadow-3',
warning
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 6575219eacc..a917bccfa94 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,8 +1,10 @@
+import type { Hotkey } from '@tanstack/react-hotkeys'
import type { ShortcutPopupDisplayMode, ShortcutPopupInsertHandler } from '../index'
import { LexicalComposer } from '@lexical/react/LexicalComposer'
import { ContentEditable } from '@lexical/react/LexicalContentEditable'
import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'
+import { detectPlatform } from '@tanstack/react-hotkeys'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { createCommand } from 'lexical'
import * as React from 'react'
@@ -51,7 +53,7 @@ const CONTENT_EDITABLE_ID = 'ce'
type MinimalEditorProps = {
withContainer?: boolean
- hotkey?: string | string[] | string[][] | ((e: KeyboardEvent) => boolean)
+ hotkey?: Hotkey
displayMode?: ShortcutPopupDisplayMode
children?:
| React.ReactNode
@@ -109,12 +111,12 @@ const MinimalEditor: React.FC<MinimalEditorProps> = ({
function focusAndTriggerHotkey(
key: string,
modifiers: Partial<Record<'ctrlKey' | 'metaKey' | 'altKey' | 'shiftKey', boolean>> = {
- ctrlKey: true,
+ ...(detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }),
},
) {
const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
ce.focus()
- fireEvent.keyDown(document, { key, ...modifiers })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_ID), { key, ...modifiers })
}
describe('ShortcutsPopupPlugin', () => {
@@ -134,7 +136,10 @@ describe('ShortcutsPopupPlugin', () => {
it('does not open when editor is not focused', async () => {
render(<MinimalEditor />)
- fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_ID), {
+ key: '/',
+ ...(detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }),
+ })
await waitFor(() => {
expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
})
@@ -145,7 +150,7 @@ describe('ShortcutsPopupPlugin', () => {
focusAndTriggerHotkey('/')
expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- fireEvent.keyDown(document, { key: 'Escape' })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_ID), { key: 'Escape' })
await waitFor(() => {
expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
})
@@ -156,7 +161,10 @@ describe('ShortcutsPopupPlugin', () => {
const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
ce.focus()
- fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_ID), {
+ key: '/',
+ ...(detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }),
+ })
expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
fireEvent.mouseDown(ce)
@@ -170,7 +178,10 @@ describe('ShortcutsPopupPlugin', () => {
const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
ce.focus()
- fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_ID), {
+ key: '/',
+ ...(detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }),
+ })
expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
const portal = document.createElement('div')
@@ -270,162 +281,28 @@ describe('ShortcutsPopupPlugin', () => {
}
})
- // ─── matchHotkey: string hotkey ───
- it('matches a string hotkey like "mod+/"', async () => {
- render(<MinimalEditor hotkey="mod+/" />)
- focusAndTriggerHotkey('/', { metaKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('matches ctrl+/ when hotkey is "mod+/" (mod matches ctrl or meta)', async () => {
- render(<MinimalEditor hotkey="mod+/" />)
- focusAndTriggerHotkey('/', { ctrlKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- // ─── matchHotkey: string[] hotkey ───
- it('matches when hotkey is a string array like ["mod", "/"]', async () => {
- render(<MinimalEditor hotkey={['mod', '/']} />)
- focusAndTriggerHotkey('/', { ctrlKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- // ─── matchHotkey: string[][] (nested) hotkey ───
- it('matches when hotkey is a nested array (any combo matches)', async () => {
- render(
- <MinimalEditor
- hotkey={[
- ['ctrl', 'k'],
- ['meta', 'j'],
- ]}
- />,
- )
- focusAndTriggerHotkey('k', { ctrlKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('matches the second combo in a nested array', async () => {
- render(
- <MinimalEditor
- hotkey={[
- ['ctrl', 'k'],
- ['meta', 'j'],
- ]}
- />,
- )
- focusAndTriggerHotkey('j', { metaKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
+ it('does not open for an extra modifier or composing input', () => {
+ render(<MinimalEditor />)
+ const editor = screen.getByTestId(CONTENT_EDITABLE_ID)
+ editor.focus()
+ const modifier = detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }
+ fireEvent.keyDown(editor, { key: '/', ...modifier, altKey: true })
+ fireEvent.keyDown(editor, { key: '/', ...modifier, isComposing: true })
+ expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
})
- it('does not match nested array when no combo matches', async () => {
+ it('closes only from its editor or popup, leaving unrelated Escape alone', async () => {
render(
- <MinimalEditor
- hotkey={[
- ['ctrl', 'k'],
- ['meta', 'j'],
- ]}
- />,
+ <MinimalEditor displayMode="workflow-panel-adjacent-center">
+ <button type="button">Popup action</button>
+ </MinimalEditor>,
)
- focusAndTriggerHotkey('x', { ctrlKey: true })
- await waitFor(() => {
- expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
- })
- })
-
- // ─── matchHotkey: function hotkey ───
- it('matches when hotkey is a custom function returning true', async () => {
- const customMatcher = (e: KeyboardEvent) => e.key === 'F1'
- render(<MinimalEditor hotkey={customMatcher} />)
- focusAndTriggerHotkey('F1', {})
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('does not match when custom function returns false', async () => {
- const customMatcher = (e: KeyboardEvent) => e.key === 'F1'
- render(<MinimalEditor hotkey={customMatcher} />)
- focusAndTriggerHotkey('F2', {})
- await waitFor(() => {
- expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
- })
- })
-
- // ─── matchHotkey: modifier aliases ───
- it('matches meta/cmd/command aliases', async () => {
- render(<MinimalEditor hotkey="cmd+k" />)
- focusAndTriggerHotkey('k', { metaKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('matches "command" alias for meta', async () => {
- render(<MinimalEditor hotkey="command+k" />)
- focusAndTriggerHotkey('k', { metaKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('does not match meta alias when meta is not pressed', async () => {
- render(<MinimalEditor hotkey="cmd+k" />)
- focusAndTriggerHotkey('k', {})
- await waitFor(() => {
- expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
- })
- })
-
- it('matches alt/option alias', async () => {
- render(<MinimalEditor hotkey="alt+a" />)
- focusAndTriggerHotkey('a', { altKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('does not match alt alias when alt is not pressed', async () => {
- render(<MinimalEditor hotkey="alt+a" />)
- focusAndTriggerHotkey('a', {})
- await waitFor(() => {
- expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
- })
- })
-
- it('matches shift alias', async () => {
- render(<MinimalEditor hotkey="shift+s" />)
- focusAndTriggerHotkey('s', { shiftKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('does not match shift alias when shift is not pressed', async () => {
- render(<MinimalEditor hotkey="shift+s" />)
- focusAndTriggerHotkey('s', {})
- await waitFor(() => {
- expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
- })
- })
-
- it('matches ctrl alias', async () => {
- render(<MinimalEditor hotkey="ctrl+b" />)
- focusAndTriggerHotkey('b', { ctrlKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('does not match ctrl alias when ctrl is not pressed', async () => {
- render(<MinimalEditor hotkey="ctrl+b" />)
- focusAndTriggerHotkey('b', {})
- await waitFor(() => {
- expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
- })
- })
-
- // ─── matchHotkey: space key normalization ───
- it('normalizes space key to "space" for matching', async () => {
- render(<MinimalEditor hotkey="ctrl+space" />)
- focusAndTriggerHotkey(' ', { ctrlKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- // ─── matchHotkey: key mismatch ───
- it('does not match when expected key does not match pressed key', async () => {
- render(<MinimalEditor hotkey="ctrl+z" />)
- focusAndTriggerHotkey('x', { ctrlKey: true })
- await waitFor(() => {
- expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
- })
+ focusAndTriggerHotkey('/')
+ const popupAction = await screen.findByRole('button', { name: 'Popup action' })
+ fireEvent.keyDown(document.body, { key: 'Escape' })
+ expect(popupAction).toBeInTheDocument()
+ fireEvent.keyDown(popupAction, { key: 'Escape' })
+ expect(screen.queryByRole('button', { name: 'Popup action' })).not.toBeInTheDocument()
})
// ─── Children rendering ───
@@ -535,7 +412,7 @@ describe('ShortcutsPopupPlugin', () => {
focusAndTriggerHotkey('/')
await screen.findByText(SHORTCUTS_EMPTY_CONTENT)
- fireEvent.keyDown(document, { key: 'Escape' })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_ID), { key: 'Escape' })
await waitFor(() => {
expect(onClose).toHaveBeenCalledTimes(1)
})
@@ -577,7 +454,7 @@ describe('ShortcutsPopupPlugin', () => {
})
Object.defineProperty(escEvent, 'preventDefault', { value: preventDefaultSpy })
Object.defineProperty(escEvent, 'stopPropagation', { value: stopPropagationSpy })
- document.dispatchEvent(escEvent)
+ screen.getByTestId(CONTENT_EDITABLE_ID).dispatchEvent(escEvent)
await waitFor(() => {
expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
@@ -640,27 +517,6 @@ describe('ShortcutsPopupPlugin', () => {
Range.prototype.getBoundingClientRect = originalGetBoundingClientRect
})
- // ─── Combined modifier hotkeys ───
- it('matches hotkey with multiple modifiers: ctrl+shift+k', async () => {
- render(<MinimalEditor hotkey="ctrl+shift+k" />)
- focusAndTriggerHotkey('k', { ctrlKey: true, shiftKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('matches "option" alias for alt', async () => {
- render(<MinimalEditor hotkey="option+o" />)
- focusAndTriggerHotkey('o', { altKey: true })
- expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
- })
-
- it('does not match mod hotkey when neither ctrl nor meta is pressed', async () => {
- render(<MinimalEditor hotkey="mod+k" />)
- focusAndTriggerHotkey('k', {})
- await waitFor(() => {
- expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
- })
- })
-
// ─── Line 195: lastSelectionRef fallback when no domSelection range ───
it('opens via lastSelectionRef fallback when getSelection returns no ranges', async () => {
// First, focus and type so lastSelectionRef is populated
@@ -669,7 +525,7 @@ describe('ShortcutsPopupPlugin', () => {
// First open works normally
expect(await screen.findByText(SHORTCUTS_EMPTY_CONTENT)).toBeInTheDocument()
// Close it
- fireEvent.keyDown(document, { key: 'Escape' })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_ID), { key: 'Escape' })
await waitFor(() => {
expect(screen.queryByText(SHORTCUTS_EMPTY_CONTENT)).not.toBeInTheDocument()
})
@@ -684,20 +540,6 @@ describe('ShortcutsPopupPlugin', () => {
window.getSelection = originalGetSelection
})
- // ─── Line 101: expectedKey is null (modifier-only hotkey like "ctrl") ───
- it('opens when hotkey is a modifier-only string (no key part)', async () => {
- render(<MinimalEditor hotkey="ctrl" />)
- const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
- ce.focus()
- // Fire ctrl alone — matchCombo with no expectedKey should return true
- fireEvent.keyDown(document, { key: 'Control', ctrlKey: true })
- // Either opens or not, what matters is the branch executes without error
- await waitFor(() => {
- // Component either shows popup or not (implementation may open)
- expect(document.body).toBeInTheDocument()
- })
- })
-
// ─── Line 199: null range when both domSelection and lastSelectionRef are null ───
it('does not crash when openPortal is called with null range', async () => {
render(<MinimalEditor />)
@@ -707,7 +549,10 @@ describe('ShortcutsPopupPlugin', () => {
const ce = screen.getByTestId(CONTENT_EDITABLE_ID)
ce.focus()
- fireEvent.keyDown(document, { key: '/', ctrlKey: true })
+ fireEvent.keyDown(screen.getByTestId(CONTENT_EDITABLE_ID), {
+ key: '/',
+ ...(detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }),
+ })
// No crash expected, popup may still open but without position reference
expect(document.body).toBeInTheDocument()
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 b5b72c39063..594dd2d1801 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
@@ -1,8 +1,10 @@
+import type { Hotkey } from '@tanstack/react-hotkeys'
import type { LexicalCommand } from 'lexical'
import type { CSSProperties } from 'react'
import { autoUpdate, flip, offset, shift, size, useFloating } from '@floating-ui/react'
import { cn } from '@langgenius/dify-ui/cn'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
+import { matchesKeyboardEvent } from '@tanstack/react-hotkeys'
import { $getSelection, $isRangeSelection } from 'lexical'
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import { createPortal } from 'react-dom'
@@ -14,13 +16,6 @@ export type ShortcutPopupInsertHandler = <Payload>(
) => void
export type ShortcutPopupDisplayMode = 'selection' | 'workflow-panel-adjacent-center'
-// Hotkey can be:
-// - string: 'mod+/'
-// - string[]: ['mod', '/']
-// - string[][]: [['mod', '/'], ['mod', 'shift', '/']] (any combo matches)
-// - function: custom matcher
-export type Hotkey = string | string[] | string[][] | ((e: KeyboardEvent) => boolean)
-
type ShortcutPopupPluginProps = {
hotkey?: Hotkey
children?:
@@ -99,87 +94,8 @@ function subscribeWorkflowPanelAdjacentPlacement(callback: () => void) {
}
}
-const META_ALIASES = new Set(['meta', 'cmd', 'command'])
-const CTRL_ALIASES = new Set(['ctrl'])
-const ALT_ALIASES = new Set(['alt', 'option'])
-const SHIFT_ALIASES = new Set(['shift'])
-
-function matchHotkey(event: KeyboardEvent, hotkey?: Hotkey) {
- /* v8 ignore next 2 -- plugin always provides a default hotkey ('mod+/'); undefined hotkey is not reachable via public props flow. @preserve */
- if (!hotkey) return false
-
- if (typeof hotkey === 'function') return hotkey(event)
-
- const matchCombo = (tokens: string[]) => {
- const parts = tokens.map((t) => t.toLowerCase().trim()).filter(Boolean)
- let expectedKey: string | null = null
-
- let needMod = false
- let needCtrl = false
- let needMeta = false
- let needAlt = false
- let needShift = false
-
- for (const p of parts) {
- if (p === 'mod') {
- needMod = true
- continue
- }
- if (CTRL_ALIASES.has(p)) {
- needCtrl = true
- continue
- }
- if (META_ALIASES.has(p)) {
- needMeta = true
- continue
- }
- if (ALT_ALIASES.has(p)) {
- needAlt = true
- continue
- }
- if (SHIFT_ALIASES.has(p)) {
- needShift = true
- continue
- }
- expectedKey = p
- }
-
- if (needMod && !(event.metaKey || event.ctrlKey)) return false
- if (needCtrl && !event.ctrlKey) return false
- if (needMeta && !event.metaKey) return false
- if (needAlt && !event.altKey) return false
- if (needShift && !event.shiftKey) return false
-
- if (expectedKey) {
- const k = event.key.toLowerCase()
- const normalized = k === ' ' ? 'space' : k
- if (normalized !== expectedKey) return false
- }
-
- return true
- }
-
- if (Array.isArray(hotkey)) {
- const isNested = hotkey.length > 0 && Array.isArray((hotkey as unknown[])[0])
- if (isNested) {
- const combos = hotkey as string[][]
- return combos.some((tokens) => matchCombo(tokens))
- } else {
- const tokens = hotkey as string[]
- return matchCombo(tokens)
- }
- }
-
- const tokensFromString = hotkey
- .toLowerCase()
- .split('+')
- .map((t) => t.trim())
- .filter(Boolean)
- return matchCombo(tokensFromString)
-}
-
export default function ShortcutsPopupPlugin({
- hotkey = 'mod+/',
+ hotkey = 'Mod+/',
children,
className,
container,
@@ -303,6 +219,9 @@ export default function ShortcutsPopupPlugin({
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.defaultPrevented || event.isComposing || event.repeat) return
+ if (!isEditorFocused()) return
+
if (open && event.key === 'Escape') {
event.stopPropagation()
event.preventDefault()
@@ -310,17 +229,18 @@ export default function ShortcutsPopupPlugin({
return
}
- if (!isEditorFocused()) return
-
- if (matchHotkey(event, hotkey)) {
+ if (matchesKeyboardEvent(event, hotkey)) {
event.preventDefault()
+ event.stopPropagation()
openPortal()
}
}
- document.addEventListener('keydown', handleKeyDown, true)
- return () => document.removeEventListener('keydown', handleKeyDown, true)
- }, [hotkey, open, isEditorFocused, openPortal, closePortal])
+ return editor.registerRootListener((root, previousRoot) => {
+ previousRoot?.removeEventListener('keydown', handleKeyDown, true)
+ root?.addEventListener('keydown', handleKeyDown, true)
+ })
+ }, [editor, hotkey, open, isEditorFocused, openPortal, closePortal])
useEffect(() => {
if (!open) return
@@ -365,8 +285,17 @@ export default function ShortcutsPopupPlugin({
: {}
return createPortal(
+ // oxlint-disable-next-line jsx-a11y/no-static-element-interactions -- The popup delegates Escape dismissal after its nested widgets handle the event.
<div
data-testid="shortcuts-popup"
+ onKeyDown={(event) => {
+ if (event.defaultPrevented || event.nativeEvent.isComposing || event.key !== 'Escape')
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ closePortal()
+ editor.focus()
+ }}
ref={(node) => {
portalRef.current = node
if (!isFixedPanelAdjacent) refs.setFloating(node)
diff --git a/web/app/components/base/prompt-editor/prompt-editor-content.tsx b/web/app/components/base/prompt-editor/prompt-editor-content.tsx
index bfefdccaf12..9d824f4da7a 100644
--- a/web/app/components/base/prompt-editor/prompt-editor-content.tsx
+++ b/web/app/components/base/prompt-editor/prompt-editor-content.tsx
@@ -1,7 +1,7 @@
+import type { Hotkey } from '@tanstack/react-hotkeys'
import type { EditorState } from 'lexical'
import type { FC } from 'react'
import type {
- Hotkey,
ShortcutPopupDisplayMode,
ShortcutPopupInsertHandler,
} from './plugins/shortcuts-popup-plugin'
@@ -97,10 +97,9 @@ const getShortcutPopupKey = (
displayMode: ShortcutPopupDisplayMode | undefined,
Popup: React.ComponentType<{ onClose: () => void; onInsert: ShortcutPopupInsertHandler }>,
) => {
- const hotkeyKey = typeof hotkey === 'function' ? hotkey.name || 'custom' : JSON.stringify(hotkey)
const popupKey = Popup.displayName ?? Popup.name ?? 'Popup'
- return `${popupKey}:${displayMode ?? 'default'}:${hotkeyKey}`
+ return `${popupKey}:${displayMode ?? 'default'}:${hotkey}`
}
const PromptEditorContent: FC<PromptEditorContentProps> = ({
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 36fd5e781fc..3e484e02fe4 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
@@ -59,7 +59,7 @@ describe('ImagePreviewer', () => {
render(<ImagePreviewer images={images} onClose={vi.fn()} />)
- expect(screen.getByRole('dialog')).toBeInTheDocument()
+ expect(screen.getByRole('dialog', { name: 'image1.png' })).toBeInTheDocument()
expect(screen.getByRole('progressbar')).toBeInTheDocument()
expect(screen.getByText('Esc')).toBeInTheDocument()
})
@@ -71,12 +71,21 @@ describe('ImagePreviewer', () => {
'src',
'blob:mock-url',
)
+ expect(screen.getByRole('dialog', { name: 'image1.png' })).toBeInTheDocument()
expect(screen.getByText(/800.*600/)).toBeInTheDocument()
expect(screen.getByText('1.00 KB')).toBeInTheDocument()
expect(mockFetch).toHaveBeenCalledTimes(3)
expect(mockFetch.mock.calls.map(([url]) => url)).toEqual(images.map(({ url }) => url))
})
+ it('keeps a localized dialog name when the image name is empty', async () => {
+ render(<ImagePreviewer images={[{ ...images[0]!, name: '' }]} onClose={vi.fn()} />)
+
+ expect(screen.getByRole('dialog', { name: 'workflow.common.preview' })).toBeInTheDocument()
+ await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument())
+ expect(screen.getByRole('dialog', { name: 'workflow.common.preview' })).toBeInTheDocument()
+ })
+
it('starts from the requested image', async () => {
render(<ImagePreviewer images={images} initialIndex={1} onClose={vi.fn()} />)
@@ -94,6 +103,7 @@ describe('ImagePreviewer', () => {
await user.click(nextButton)
expect(screen.getByRole('img', { name: 'image2.png' })).toBeInTheDocument()
+ expect(screen.getByRole('dialog', { name: 'image2.png' })).toBeInTheDocument()
expect(previousButton).toBeEnabled()
await user.click(nextButton)
@@ -104,6 +114,28 @@ describe('ImagePreviewer', () => {
expect(screen.getByRole('img', { name: 'image2.png' })).toBeInTheDocument()
})
+ it('changes images once per held arrow and resumes navigation after reaching a boundary', async () => {
+ const user = userEvent.setup()
+ render(<ImagePreviewer images={images} onClose={vi.fn()} />)
+ await screen.findByRole('img', { name: 'image1.png' })
+ const { closeButton, nextButton } = getPreviewButtons()
+ expect(closeButton).toHaveFocus()
+
+ await user.keyboard('{ArrowRight>3/}')
+ expect(screen.getByRole('img', { name: 'image2.png' })).toBeInTheDocument()
+ await user.keyboard('{ArrowRight}')
+ expect(screen.getByRole('img', { name: 'image3.png' })).toBeInTheDocument()
+ expect(nextButton).toBeDisabled()
+
+ await user.keyboard('{ArrowRight>3/}')
+ expect(screen.getByRole('img', { name: 'image3.png' })).toBeInTheDocument()
+ await user.keyboard('{ArrowLeft}')
+ expect(screen.getByRole('img', { name: 'image2.png' })).toBeInTheDocument()
+ expect(nextButton).toBeEnabled()
+ await user.keyboard('{ArrowRight}')
+ expect(screen.getByRole('img', { name: 'image3.png' })).toBeInTheDocument()
+ })
+
it('disables both navigation buttons for a single image', async () => {
render(<ImagePreviewer images={[images[0]!]} onClose={vi.fn()} />)
await screen.findByRole('img', { name: 'image1.png' })
@@ -133,6 +165,7 @@ describe('ImagePreviewer', () => {
render(<ImagePreviewer images={images} onClose={vi.fn()} />)
expect(await screen.findByText(/Failed to load image/)).toHaveTextContent(images[0]!.url)
+ expect(screen.getByRole('dialog', { name: 'image1.png' })).toBeInTheDocument()
const retryButton = screen.getByRole('button', { name: 'common.operation.retry' })
await user.click(retryButton)
diff --git a/web/app/components/datasets/common/image-previewer/index.tsx b/web/app/components/datasets/common/image-previewer/index.tsx
index 679dfd7b80c..bcc468be1c6 100644
--- a/web/app/components/datasets/common/image-previewer/index.tsx
+++ b/web/app/components/datasets/common/image-previewer/index.tsx
@@ -1,4 +1,4 @@
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
+import { Dialog, DialogBackdrop, DialogPopup, DialogPortal } from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Kbd } from '@langgenius/dify-ui/kbd'
import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
@@ -28,8 +28,9 @@ type ImagePreviewerProps = {
onClose: () => void
}
-const ImagePreviewer = ({ images, initialIndex = 0, onClose }: ImagePreviewerProps) => {
- const { t } = useTranslation(['common'])
+function ImagePreviewerContent({ images, initialIndex = 0, onClose }: ImagePreviewerProps) {
+ const previewRef = useRef<HTMLDivElement>(null)
+ const { t } = useTranslation(['common', 'workflow'])
const [currentIndex, setCurrentIndex] = useState(initialIndex)
const [cachedImages, setCachedImages] = useState<Record<string, CachedImage>>(() => {
return images.reduce(
@@ -142,20 +143,24 @@ const ImagePreviewer = ({ images, initialIndex = 0, onClose }: ImagePreviewerPro
[fetchImage],
)
- useHotkey('ArrowLeft', prevImage)
- useHotkey('ArrowRight', nextImage)
+ useHotkey('ArrowLeft', prevImage, {
+ target: previewRef,
+ enabled: currentIndex > 0,
+ requireReset: true,
+ })
+ useHotkey('ArrowRight', nextImage, {
+ target: previewRef,
+ enabled: currentIndex < images.length - 1,
+ requireReset: true,
+ })
return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onClose()
- }}
- disablePointerDismissal
- >
- <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]"
- backdropProps={{ className: 'bg-transparent!' }}
+ <>
+ <DialogBackdrop className="bg-transparent!" />
+ <DialogPopup
+ ref={previewRef}
+ aria-label={currentImage!.name.trim() || t(($) => $['common.preview'], { ns: 'workflow' })}
+ className="image-previewer fixed 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]"
>
<div className="absolute top-6 right-6 z-10 flex cursor-pointer flex-col items-center gap-y-1">
<IconButton
@@ -221,7 +226,23 @@ const ImagePreviewer = ({ images, initialIndex = 0, onClose }: ImagePreviewerPro
>
<span aria-hidden className="i-ri-arrow-right-line size-5" />
</IconButton>
- </DialogContent>
+ </DialogPopup>
+ </>
+ )
+}
+
+function ImagePreviewer(props: ImagePreviewerProps) {
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) props.onClose()
+ }}
+ disablePointerDismissal
+ >
+ <DialogPortal>
+ <ImagePreviewerContent {...props} />
+ </DialogPortal>
</Dialog>
)
}
diff --git a/web/app/components/datasets/documents/detail/completed/child-segment-detail.tsx b/web/app/components/datasets/documents/detail/completed/child-segment-detail.tsx
index ee9a1b430a6..0b1da6413fc 100644
--- a/web/app/components/datasets/documents/detail/completed/child-segment-detail.tsx
+++ b/web/app/components/datasets/documents/detail/completed/child-segment-detail.tsx
@@ -34,6 +34,7 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({
onCancel,
docForm,
}) => {
+ const editorRef = React.useRef<HTMLDivElement>(null)
const { t } = useTranslation(['common', 'datasetDocuments'])
const canEdit = useDocumentContext((s) => s.canEdit)
const [content, setContent] = useState(childChunkInfo?.content || '')
@@ -69,7 +70,7 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({
}, [childChunkInfo?.updated_at])
return (
- <div className="flex h-full flex-col">
+ <div ref={editorRef} className="flex h-full flex-col">
<div
className={cn(
'flex items-center justify-between',
@@ -97,6 +98,7 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({
{canEdit && fullScreen && (
<>
<ActionButtons
+ target={editorRef}
handleCancel={handleCancel}
handleSave={handleSave}
loading={loading}
@@ -153,6 +155,7 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({
{canEdit && !fullScreen && (
<div className="flex items-center justify-end border-t border-t-divider-subtle p-4 pt-3">
<ActionButtons
+ target={editorRef}
handleCancel={handleCancel}
handleSave={handleSave}
loading={loading}
diff --git a/web/app/components/datasets/documents/detail/completed/common/__tests__/action-buttons.spec.tsx b/web/app/components/datasets/documents/detail/completed/common/__tests__/action-buttons.spec.tsx
index 5d74b905e0c..625e343d62a 100644
--- a/web/app/components/datasets/documents/detail/completed/common/__tests__/action-buttons.spec.tsx
+++ b/web/app/components/datasets/documents/detail/completed/common/__tests__/action-buttons.spec.tsx
@@ -1,380 +1,164 @@
+import type { ComponentProps } from 'react'
import { fireEvent, render, screen } from '@testing-library/react'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { useRef } from 'react'
import { ChunkingMode } from '@/models/datasets'
import { DocumentContext } from '../../../context'
import { ActionButtons } from '../action-buttons'
-const mockUseHotkey = vi.fn()
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (hotkey: string, callback: (e: KeyboardEvent) => void, options?: object) => {
- mockUseHotkey(hotkey, callback, options)
- },
- }
-})
-
-// Create wrapper component for providing context
-const createWrapper = (contextValue: {
- docForm?: ChunkingMode
- parentMode?: 'paragraph' | 'full-doc'
-}) => {
- return ({ children }: { children: React.ReactNode }) => (
- <DocumentContext.Provider value={contextValue}>{children}</DocumentContext.Provider>
+function Editor({
+ label = 'Chunk content',
+ ...props
+}: Omit<ComponentProps<typeof ActionButtons>, 'target'> & { label?: string }) {
+ const target = useRef<HTMLDivElement>(null)
+ return (
+ <div ref={target}>
+ <textarea aria-label={label} />
+ <ActionButtons {...props} target={target} />
+ </div>
)
}
-const getEscCallback = (): ((e: KeyboardEvent) => void) | undefined => {
- const escCall = mockUseHotkey.mock.calls.find((call) => call[0] === 'Escape')
- return escCall?.[1]
-}
-
-const getCtrlSCallback = (): ((e: KeyboardEvent) => void) | undefined => {
- const ctrlSCall = mockUseHotkey.mock.calls.find((call) => call[0] === 'Mod+S')
- return ctrlSCall?.[1]
+function pressKey(target: HTMLElement, key: string, options: KeyboardEventInit = {}) {
+ const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...options })
+ fireEvent(target, event)
+ fireEvent.keyUp(target, { key, ...options })
+ return event
}
describe('ActionButtons', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockUseHotkey.mockClear()
- })
-
- describe('Rendering', () => {
- it('should render cancel button', () => {
- render(<ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={false} />, {
- wrapper: createWrapper({}),
- })
-
- expect(screen.getByText(/operation\.cancel/i))!.toBeInTheDocument()
- })
-
- it('should render save button', () => {
- render(<ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={false} />, {
- wrapper: createWrapper({}),
- })
-
- expect(screen.getByText(/operation\.save/i))!.toBeInTheDocument()
- })
-
- it('should render ESC keyboard hint on cancel button', () => {
- render(<ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={false} />, {
- wrapper: createWrapper({}),
- })
-
- expect(screen.getByText('Esc'))!.toBeInTheDocument()
- })
-
- it('should render S keyboard hint on save button', () => {
- render(<ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={false} />, {
- wrapper: createWrapper({}),
- })
-
- expect(screen.getByText('S'))!.toBeInTheDocument()
- })
- })
-
- describe('User Interactions', () => {
- it('should call handleCancel when cancel button is clicked', () => {
- const mockHandleCancel = vi.fn()
- render(
- <ActionButtons handleCancel={mockHandleCancel} handleSave={vi.fn()} loading={false} />,
- { wrapper: createWrapper({}) },
- )
-
- const cancelButton = screen.getAllByRole('button')[0]
- fireEvent.click(cancelButton!)
-
- expect(mockHandleCancel).toHaveBeenCalledTimes(1)
- })
-
- it('should call handleSave when save button is clicked', () => {
- const mockHandleSave = vi.fn()
- render(<ActionButtons handleCancel={vi.fn()} handleSave={mockHandleSave} loading={false} />, {
- wrapper: createWrapper({}),
- })
-
- const buttons = screen.getAllByRole('button')
- const saveButton = buttons[buttons.length - 1] // Save button is last
- fireEvent.click(saveButton!)
-
- expect(mockHandleSave).toHaveBeenCalledTimes(1)
- })
-
- it('should disable save button when loading is true', () => {
- render(<ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={true} />, {
- wrapper: createWrapper({}),
- })
-
- const buttons = screen.getAllByRole('button')
- const saveButton = buttons[buttons.length - 1]
- expect(saveButton)!.toBeDisabled()
- })
+ it('saves and cancels through the same actions as the buttons inside its editor', () => {
+ const handleSave = vi.fn()
+ const handleCancel = vi.fn()
+ render(<Editor handleSave={handleSave} handleCancel={handleCancel} loading={false} />)
+ const input = screen.getByRole('textbox')
+ expect(pressKey(input, 's', { ctrlKey: true }).defaultPrevented).toBe(true)
+ expect(pressKey(input, 'Escape').defaultPrevented).toBe(true)
+ fireEvent.click(screen.getByRole('button', { name: /operation.save/ }))
+ fireEvent.click(screen.getByRole('button', { name: /operation.cancel/ }))
+ expect(handleSave).toHaveBeenCalledTimes(2)
+ expect(handleCancel).toHaveBeenCalledTimes(2)
})
- // Regeneration button tests
- describe('Regeneration Button', () => {
- it('should show regeneration button in parent-child paragraph mode for edit action', () => {
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={vi.fn()}
+ it('only handles shortcuts originating inside its own editor', () => {
+ const firstSave = vi.fn()
+ const secondSave = vi.fn()
+ const handleCancel = vi.fn()
+ render(
+ <>
+ <Editor
+ label="First chunk"
+ handleSave={firstSave}
+ handleCancel={handleCancel}
loading={false}
- actionType="edit"
- isChildChunk={false}
- showRegenerationButton={true}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- expect(screen.getByText(/operation\.saveAndRegenerate/i))!.toBeInTheDocument()
- })
-
- it('should not show regeneration button when isChildChunk is true', () => {
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={vi.fn()}
- loading={false}
- actionType="edit"
- isChildChunk={true}
- showRegenerationButton={true}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- expect(screen.queryByText(/operation\.saveAndRegenerate/i)).not.toBeInTheDocument()
- })
-
- it('should not show regeneration button when showRegenerationButton is false', () => {
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={vi.fn()}
+ />
+ <Editor
+ label="Second chunk"
+ handleSave={secondSave}
+ handleCancel={handleCancel}
loading={false}
- actionType="edit"
- isChildChunk={false}
- showRegenerationButton={false}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- expect(screen.queryByText(/operation\.saveAndRegenerate/i)).not.toBeInTheDocument()
- })
-
- it('should not show regeneration button when actionType is add', () => {
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={vi.fn()}
- loading={false}
- actionType="add"
- isChildChunk={false}
- showRegenerationButton={true}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- expect(screen.queryByText(/operation\.saveAndRegenerate/i)).not.toBeInTheDocument()
- })
-
- it('should call handleRegeneration when regeneration button is clicked', () => {
- const mockHandleRegeneration = vi.fn()
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={mockHandleRegeneration}
- loading={false}
- actionType="edit"
- isChildChunk={false}
- showRegenerationButton={true}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- const regenerationButton = screen.getByText(/operation\.saveAndRegenerate/i).closest('button')
- if (regenerationButton) fireEvent.click(regenerationButton)
-
- expect(mockHandleRegeneration).toHaveBeenCalledTimes(1)
- })
-
- it('should disable regeneration button when loading is true', () => {
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={vi.fn()}
- loading={true}
- actionType="edit"
- isChildChunk={false}
- showRegenerationButton={true}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- const regenerationButton = screen.getByText(/operation\.saveAndRegenerate/i).closest('button')
- expect(regenerationButton)!.toBeDisabled()
- })
+ />
+ <input aria-label="Outside editor" />
+ </>,
+ )
+ pressKey(screen.getByRole('textbox', { name: 'Second chunk' }), 's', { ctrlKey: true })
+ expect(
+ pressKey(screen.getByRole('textbox', { name: 'Outside editor' }), 'Escape').defaultPrevented,
+ ).toBe(false)
+ expect(secondSave).toHaveBeenCalledTimes(1)
+ expect(firstSave).not.toHaveBeenCalled()
+ expect(handleCancel).not.toHaveBeenCalled()
})
- // Default props tests
- describe('Default Props', () => {
- it('should use default actionType of edit', () => {
- // Arrange & Act - when not specifying actionType and other conditions are met
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={vi.fn()}
- loading={false}
- showRegenerationButton={true}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- // Assert - regeneration button should show with default actionType='edit'
- // Assert - regeneration button should show with default actionType='edit'
- expect(screen.getByText(/operation\.saveAndRegenerate/i))!.toBeInTheDocument()
- })
-
- it('should use default isChildChunk of false', () => {
- // Arrange & Act - when not specifying isChildChunk
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={vi.fn()}
- loading={false}
- actionType="edit"
- showRegenerationButton={true}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- // Assert - regeneration button should show with default isChildChunk=false
- // Assert - regeneration button should show with default isChildChunk=false
- expect(screen.getByText(/operation\.saveAndRegenerate/i))!.toBeInTheDocument()
- })
-
- it('should use default showRegenerationButton of true', () => {
- // Arrange & Act - when not specifying showRegenerationButton
- render(
- <ActionButtons
- handleCancel={vi.fn()}
- handleSave={vi.fn()}
- handleRegeneration={vi.fn()}
- loading={false}
- actionType="edit"
- isChildChunk={false}
- />,
- { wrapper: createWrapper({ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }) },
- )
-
- // Assert - regeneration button should show with default showRegenerationButton=true
- // Assert - regeneration button should show with default showRegenerationButton=true
- expect(screen.getByText(/operation\.saveAndRegenerate/i))!.toBeInTheDocument()
- })
+ it('disables saving from both the button and keyboard while loading', () => {
+ const handleSave = vi.fn()
+ render(<Editor handleSave={handleSave} handleCancel={vi.fn()} loading />)
+ expect(screen.getByRole('button', { name: /operation.save/ })).toBeDisabled()
+ expect(pressKey(screen.getByRole('textbox'), 's', { ctrlKey: true }).defaultPrevented).toBe(
+ false,
+ )
+ expect(handleSave).not.toHaveBeenCalled()
})
- describe('Edge Cases', () => {
- it('should handle missing context values gracefully', () => {
- // Arrange & Act & Assert - should not throw
- expect(() => {
- render(<ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={false} />, {
- wrapper: createWrapper({}),
- })
- }).not.toThrow()
- })
-
- it('should maintain structure when rerendered', () => {
- const { rerender } = render(
- <ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={false} />,
- { wrapper: createWrapper({}) },
- )
-
- rerender(
- <DocumentContext.Provider value={{}}>
- <ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={true} />
- </DocumentContext.Provider>,
- )
-
- expect(screen.getByText(/operation\.cancel/i))!.toBeInTheDocument()
- expect(screen.getByText(/operation\.save/i))!.toBeInTheDocument()
- })
+ it('ignores composing events and events claimed before they reach the editor', () => {
+ const handleSave = vi.fn()
+ const handleCancel = vi.fn()
+ render(<Editor handleSave={handleSave} handleCancel={handleCancel} loading={false} />)
+ const input = screen.getByRole('textbox')
+ pressKey(input, 's', { ctrlKey: true, isComposing: true })
+ input.addEventListener('keydown', (event) => event.preventDefault(), { once: true })
+ pressKey(input, 's', { ctrlKey: true })
+ expect(handleSave).not.toHaveBeenCalled()
+ expect(handleCancel).not.toHaveBeenCalled()
})
- describe('Keyboard Shortcuts', () => {
- it('should display ctrl key hint on save button', () => {
- render(<ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={false} />, {
- wrapper: createWrapper({}),
- })
-
- const kbdElements = document.querySelectorAll('kbd')
- expect(kbdElements.length).toBeGreaterThan(0)
- })
+ it('consumes repeated save keys without repeating the save action', () => {
+ const handleSave = vi.fn()
+ render(<Editor handleSave={handleSave} handleCancel={vi.fn()} loading={false} />)
+ const input = screen.getByRole('textbox')
+ fireEvent.keyDown(input, { key: 's', ctrlKey: true })
+ const repeatedSave = new KeyboardEvent('keydown', {
+ key: 's',
+ ctrlKey: true,
+ repeat: true,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(input, repeatedSave)
+ expect(repeatedSave.defaultPrevented).toBe(true)
+ expect(handleSave).toHaveBeenCalledTimes(1)
+ fireEvent.keyUp(input, { key: 's', ctrlKey: true })
+ pressKey(input, 's', { ctrlKey: true })
+ expect(handleSave).toHaveBeenCalledTimes(2)
+ })
- it('should call handleCancel and preventDefault when ESC key is pressed', () => {
- const mockHandleCancel = vi.fn()
- const mockPreventDefault = vi.fn()
+ it.each([
+ {
+ actionType: 'edit' as const,
+ isChildChunk: false,
+ showRegenerationButton: true,
+ visible: true,
+ },
+ {
+ actionType: 'add' as const,
+ isChildChunk: false,
+ showRegenerationButton: true,
+ visible: false,
+ },
+ {
+ actionType: 'edit' as const,
+ isChildChunk: true,
+ showRegenerationButton: true,
+ visible: false,
+ },
+ {
+ actionType: 'edit' as const,
+ isChildChunk: false,
+ showRegenerationButton: false,
+ visible: false,
+ },
+ ])(
+ 'offers regeneration only for eligible parent chunks: $actionType / $isChildChunk / $showRegenerationButton',
+ ({ visible, ...props }) => {
+ const handleRegeneration = vi.fn()
render(
- <ActionButtons handleCancel={mockHandleCancel} handleSave={vi.fn()} loading={false} />,
- { wrapper: createWrapper({}) },
+ <DocumentContext.Provider
+ value={{ docForm: ChunkingMode.parentChild, parentMode: 'paragraph' }}
+ >
+ <Editor
+ {...props}
+ handleSave={vi.fn()}
+ handleCancel={vi.fn()}
+ handleRegeneration={handleRegeneration}
+ loading={false}
+ />
+ </DocumentContext.Provider>,
)
-
- // Act - get the ESC callback and invoke it
- const escCallback = getEscCallback()
- expect(escCallback).toBeDefined()
- escCallback!({ preventDefault: mockPreventDefault } as unknown as KeyboardEvent)
-
- expect(mockPreventDefault).toHaveBeenCalledTimes(1)
- expect(mockHandleCancel).toHaveBeenCalledTimes(1)
- })
-
- it('should call handleSave and preventDefault when Ctrl+S is pressed and not loading', () => {
- const mockHandleSave = vi.fn()
- const mockPreventDefault = vi.fn()
- render(<ActionButtons handleCancel={vi.fn()} handleSave={mockHandleSave} loading={false} />, {
- wrapper: createWrapper({}),
- })
-
- // Act - get the Ctrl+S callback and invoke it
- const ctrlSCallback = getCtrlSCallback()
- expect(ctrlSCallback).toBeDefined()
- ctrlSCallback!({ preventDefault: mockPreventDefault } as unknown as KeyboardEvent)
-
- expect(mockPreventDefault).toHaveBeenCalledTimes(1)
- expect(mockHandleSave).toHaveBeenCalledTimes(1)
- })
-
- it('should not call handleSave when Ctrl+S is pressed while loading', () => {
- const mockHandleSave = vi.fn()
- const mockPreventDefault = vi.fn()
- render(<ActionButtons handleCancel={vi.fn()} handleSave={mockHandleSave} loading={true} />, {
- wrapper: createWrapper({}),
- })
-
- // Act - get the Ctrl+S callback and invoke it
- const ctrlSCallback = getCtrlSCallback()
- expect(ctrlSCallback).toBeDefined()
- ctrlSCallback!({ preventDefault: mockPreventDefault } as unknown as KeyboardEvent)
-
- expect(mockPreventDefault).toHaveBeenCalledTimes(1)
- expect(mockHandleSave).not.toHaveBeenCalled()
- })
-
- it('should register the Mod+S hotkey', () => {
- render(<ActionButtons handleCancel={vi.fn()} handleSave={vi.fn()} loading={false} />, {
- wrapper: createWrapper({}),
- })
-
- const ctrlSCall = mockUseHotkey.mock.calls.find((call) => call[0] === 'Mod+S')
- expect(ctrlSCall).toBeDefined()
- })
- })
+ const button = screen.queryByRole('button', { name: /operation.saveAndRegenerate/ })
+ expect(Boolean(button)).toBe(visible)
+ if (button) {
+ fireEvent.click(button)
+ expect(handleRegeneration).toHaveBeenCalledOnce()
+ }
+ },
+ )
})
diff --git a/web/app/components/datasets/documents/detail/completed/common/action-buttons.tsx b/web/app/components/datasets/documents/detail/completed/common/action-buttons.tsx
index 24f719b41cd..4dcdc2a9618 100644
--- a/web/app/components/datasets/documents/detail/completed/common/action-buttons.tsx
+++ b/web/app/components/datasets/documents/detail/completed/common/action-buttons.tsx
@@ -1,4 +1,5 @@
import type { Hotkey } from '@tanstack/react-hotkeys'
+import type { RefObject } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
@@ -10,6 +11,7 @@ const CANCEL_HOTKEY = 'Escape' satisfies Hotkey
const SAVE_HOTKEY = 'Mod+S' satisfies Hotkey
type ActionButtonsProps = {
+ target: RefObject<HTMLDivElement | null>
handleCancel: () => void
handleSave: () => void
loading: boolean
@@ -20,6 +22,7 @@ type ActionButtonsProps = {
}
export function ActionButtons({
+ target,
handleCancel,
handleSave,
loading,
@@ -32,16 +35,40 @@ export function ActionButtons({
const docForm = useDocumentContext((s) => s.docForm)
const parentMode = useDocumentContext((s) => s.parentMode)
- useHotkey(CANCEL_HOTKEY, (e) => {
- e.preventDefault()
- handleCancel()
- })
+ useHotkey(
+ CANCEL_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented || event.isComposing) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ handleCancel()
+ },
+ {
+ target,
+ ignoreInputs: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
- useHotkey(SAVE_HOTKEY, (e) => {
- e.preventDefault()
- if (loading) return
- handleSave()
- })
+ useHotkey(
+ SAVE_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ handleSave()
+ },
+ {
+ target,
+ enabled: !loading,
+ ignoreInputs: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
const isParentChildParagraphMode =
docForm === ChunkingMode.parentChild && parentMode === 'paragraph'
@@ -72,9 +99,9 @@ export function ActionButtons({
{t(($) => $['operation.save'], { ns: 'common' })}
</span>
<KbdGroup>
- {SAVE_HOTKEY.split('+').map((key) => (
+ {formatForDisplay(SAVE_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white">
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
diff --git a/web/app/components/datasets/documents/detail/completed/new-child-segment.tsx b/web/app/components/datasets/documents/detail/completed/new-child-segment.tsx
index b75eecb7e0a..ca125802639 100644
--- a/web/app/components/datasets/documents/detail/completed/new-child-segment.tsx
+++ b/web/app/components/datasets/documents/detail/completed/new-child-segment.tsx
@@ -3,7 +3,7 @@ import type { ChildChunkDetail, SegmentUpdater } from '@/models/datasets'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
import { RiCloseLine, RiExpandDiagonalLine } from '@remixicon/react'
-import { memo, useState } from 'react'
+import { memo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { ChunkingMode } from '@/models/datasets'
@@ -31,6 +31,7 @@ const NewChildSegmentModal: FC<NewChildSegmentModalProps> = ({
onSave,
viewNewlyAddedChildChunk,
}) => {
+ const editorRef = useRef<HTMLDivElement>(null)
const { t } = useTranslation(['common', 'datasetDocuments'])
const [content, setContent] = useState('')
const { datasetId, documentId } = useParams<{ datasetId: string; documentId: string }>()
@@ -91,7 +92,7 @@ const NewChildSegmentModal: FC<NewChildSegmentModalProps> = ({
const wordCountText = `${formatNumber(count)} ${t(($) => $['segment.characters'], { ns: 'datasetDocuments', count })}`
return (
- <div className="flex h-full flex-col">
+ <div ref={editorRef} className="flex h-full flex-col">
<div
className={cn(
'flex items-center justify-between',
@@ -115,6 +116,7 @@ const NewChildSegmentModal: FC<NewChildSegmentModalProps> = ({
<>
<AddAnother className="mr-3" checked={addAnother} onCheckedChange={setAddAnother} />
<ActionButtons
+ target={editorRef}
handleCancel={handleCancel.bind(null, 'esc')}
handleSave={handleSave}
loading={loading}
@@ -166,6 +168,7 @@ const NewChildSegmentModal: FC<NewChildSegmentModalProps> = ({
<div className="flex items-center justify-between border-t border-t-divider-subtle p-4 pt-3">
<AddAnother checked={addAnother} onCheckedChange={setAddAnother} />
<ActionButtons
+ target={editorRef}
handleCancel={handleCancel.bind(null, 'esc')}
handleSave={handleSave}
loading={loading}
diff --git a/web/app/components/datasets/documents/detail/completed/segment-detail.tsx b/web/app/components/datasets/documents/detail/completed/segment-detail.tsx
index 2ed000a005d..8a0c6715134 100644
--- a/web/app/components/datasets/documents/detail/completed/segment-detail.tsx
+++ b/web/app/components/datasets/documents/detail/completed/segment-detail.tsx
@@ -3,7 +3,7 @@ import type { SegmentDetailModel } from '@/models/datasets'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
import { RiCloseLine, RiCollapseDiagonalLine, RiExpandDiagonalLine } from '@remixicon/react'
-import { useCallback, useMemo, useState } from 'react'
+import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { v4 as uuid4 } from 'uuid'
import ImageUploaderInChunk from '@/app/components/datasets/common/image-uploader/image-uploader-in-chunk'
@@ -45,6 +45,7 @@ export function SegmentDetail({
isEditMode: requestedEditMode,
docForm,
}: ISegmentDetailProps) {
+ const editorRef = useRef<HTMLDivElement>(null)
const { t } = useTranslation(['common', 'datasetDocuments'])
const canEdit = useDocumentContext((s) => s.canEdit)
const isEditMode = requestedEditMode && canEdit
@@ -130,7 +131,7 @@ export function SegmentDetail({
const isECOIndexing = indexingTechnique === IndexingType.ECONOMICAL
return (
- <div className="flex h-full flex-col">
+ <div ref={editorRef} className="flex h-full flex-col">
<div
className={cn(
'flex shrink-0 items-center justify-between',
@@ -153,6 +154,7 @@ export function SegmentDetail({
{isEditMode && fullScreen && (
<>
<ActionButtons
+ target={editorRef}
handleCancel={handleCancel}
handleRegeneration={handleRegeneration}
handleSave={handleSave}
@@ -241,6 +243,7 @@ export function SegmentDetail({
{isEditMode && !fullScreen && (
<div className="flex items-center justify-end border-t border-t-divider-subtle p-4 pt-3">
<ActionButtons
+ target={editorRef}
handleCancel={handleCancel}
handleRegeneration={handleRegeneration}
handleSave={handleSave}
diff --git a/web/app/components/datasets/documents/detail/new-segment.tsx b/web/app/components/datasets/documents/detail/new-segment.tsx
index 4648fbd83a4..2f3f1c32716 100644
--- a/web/app/components/datasets/documents/detail/new-segment.tsx
+++ b/web/app/components/datasets/documents/detail/new-segment.tsx
@@ -4,7 +4,7 @@ import type { SegmentUpdater } from '@/models/datasets'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
import { RiCloseLine, RiExpandDiagonalLine } from '@remixicon/react'
-import { memo, useCallback, useState } from 'react'
+import { memo, useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import ImageUploaderInChunk from '@/app/components/datasets/common/image-uploader/image-uploader-in-chunk'
import { toast } from '@/app/notifications'
@@ -35,6 +35,7 @@ const NewSegmentModal: FC<NewSegmentModalProps> = ({
onSave,
viewNewlyAddedChunk,
}) => {
+ const editorRef = useRef<HTMLDivElement>(null)
const { t } = useTranslation(['common', 'datasetDocuments'])
const [question, setQuestion] = useState('')
const [answer, setAnswer] = useState('')
@@ -138,7 +139,7 @@ const NewSegmentModal: FC<NewSegmentModalProps> = ({
const isECOIndexing = indexingTechnique === IndexingType.ECONOMICAL
return (
- <div className="flex h-full flex-col">
+ <div ref={editorRef} className="flex h-full flex-col">
<div
className={cn(
'flex items-center justify-between',
@@ -160,6 +161,7 @@ const NewSegmentModal: FC<NewSegmentModalProps> = ({
<>
<AddAnother className="mr-3" checked={addAnother} onCheckedChange={setAddAnother} />
<ActionButtons
+ target={editorRef}
handleCancel={handleCancel.bind(null, 'esc')}
handleSave={handleSave}
loading={loading}
@@ -230,6 +232,7 @@ const NewSegmentModal: FC<NewSegmentModalProps> = ({
<div className="flex items-center justify-between border-t border-t-divider-subtle p-4 pt-3">
<AddAnother checked={addAnother} onCheckedChange={setAddAnother} />
<ActionButtons
+ target={editorRef}
handleCancel={handleCancel.bind(null, 'esc')}
handleSave={handleSave}
loading={loading}
diff --git a/web/app/components/detail-sidebar/__tests__/index.spec.tsx b/web/app/components/detail-sidebar/__tests__/index.spec.tsx
index 81e6fea7d15..b5dc5669a0b 100644
--- a/web/app/components/detail-sidebar/__tests__/index.spec.tsx
+++ b/web/app/components/detail-sidebar/__tests__/index.spec.tsx
@@ -116,7 +116,7 @@ describe('DetailSidebarFrame', () => {
describe.each(['mac', 'windows'] as const)('%s shortcut', (platform) => {
const modifiers = platform === 'mac' ? { metaKey: true } : { ctrlKey: true }
- it('toggles detail content outside editing fields', () => {
+ it('toggles detail content once per press outside editing fields', () => {
renderDetailSidebarFrame(null, platform)
fireEvent.keyDown(document.body, { key: 'b', ...modifiers })
@@ -124,12 +124,28 @@ describe('DetailSidebarFrame', () => {
expect(screen.getByTestId('detail-top')).toHaveAttribute('data-expand', 'false')
expect(Cookies.get(DETAIL_SIDEBAR_COOKIE_NAME)).toBe('collapse')
+ expect(fireEvent.keyDown(document.body, { key: 'b', repeat: true, ...modifiers })).toBe(false)
+
+ expect(screen.getByTestId('detail-top')).toHaveAttribute('data-expand', 'false')
+
+ fireEvent.keyUp(document.body, { key: 'b', ...modifiers })
fireEvent.keyDown(document.body, { key: 'b', ...modifiers })
expect(screen.getByTestId('detail-top')).toHaveAttribute('data-expand', 'true')
expect(Cookies.get(DETAIL_SIDEBAR_COOKIE_NAME)).toBe('expand')
})
+ it('leaves a consumed shortcut to its local owner', () => {
+ renderDetailSidebarFrame(null, platform)
+ const button = screen.getByRole('button', { name: 'Toggle' })
+ button.addEventListener('keydown', (event) => event.preventDefault(), { once: true })
+
+ fireEvent.keyDown(button, { key: 'b', ...modifiers })
+
+ expect(screen.getByRole('button', { name: 'account' })).toHaveTextContent('Expanded account')
+ expect(Cookies.get(DETAIL_SIDEBAR_COOKIE_NAME)).toBeUndefined()
+ })
+
it.each(['Note', 'Note text', 'Name', 'Description'])(
'leaves the shortcut to the %s editor',
(name) => {
diff --git a/web/app/components/detail-sidebar/index.tsx b/web/app/components/detail-sidebar/index.tsx
index 78a7b02b833..77bd9bc200d 100644
--- a/web/app/components/detail-sidebar/index.tsx
+++ b/web/app/components/detail-sidebar/index.tsx
@@ -110,10 +110,22 @@ export function DetailSidebarFrame({
}
}, [])
- useHotkey(DETAIL_SIDEBAR_TOGGLE_HOTKEY, handleToggleDetailNavigation, {
- ignoreInputs: true,
- preventDefault: true,
- })
+ useHotkey(
+ DETAIL_SIDEBAR_TOGGLE_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented) return
+
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ handleToggleDetailNavigation()
+ },
+ {
+ ignoreInputs: true,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
return (
<div
diff --git a/web/app/components/detail-sidebar/toggle-button.tsx b/web/app/components/detail-sidebar/toggle-button.tsx
index 7e35ff0e23b..b857892cd80 100644
--- a/web/app/components/detail-sidebar/toggle-button.tsx
+++ b/web/app/components/detail-sidebar/toggle-button.tsx
@@ -6,8 +6,6 @@ import { formatForDisplay } from '@tanstack/react-hotkeys'
import { useTranslation } from 'react-i18next'
import { DETAIL_SIDEBAR_TOGGLE_HOTKEY } from './hotkeys'
-const detailSidebarToggleShortcutKeys = DETAIL_SIDEBAR_TOGGLE_HOTKEY.split('+')
-
type DetailSidebarToggleButtonProps = {
expand: boolean
onToggle: () => void
@@ -45,8 +43,8 @@ export function DetailSidebarToggleButton({
<TooltipContent placement="right" className="flex items-center gap-1">
<span className="px-0.5">{label}</span>
<KbdGroup>
- {detailSidebarToggleShortcutKeys.map((key) => (
- <Kbd key={key}>{formatForDisplay(key)}</Kbd>
+ {formatForDisplay(DETAIL_SIDEBAR_TOGGLE_HOTKEY, { parts: true }).map((key) => (
+ <Kbd key={key}>{key}</Kbd>
))}
</KbdGroup>
</TooltipContent>
diff --git a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx
index 05383a24be0..7da46affed6 100644
--- a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx
+++ b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx
@@ -9,30 +9,6 @@ import { mockEmojiData } from '@/test/emoji-picker'
import { AppModeEnum } from '@/types/app'
import CreateAppModal from '../index'
-const hotkeyMocks = vi.hoisted(() => ({
- handlers: new Map<string, { handler: () => void; options?: { enabled?: boolean } }>(),
-}))
-
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (hotkey: string, handler: () => void, options?: { enabled?: boolean }) => {
- hotkeyMocks.handlers.set(hotkey, { handler, options })
- },
- }
-})
-
-const triggerHotkey = (hotkey: string) => {
- const registration = hotkeyMocks.handlers.get(hotkey)
- if (registration?.options?.enabled === false) return
- registration?.handler()
-}
-
-vi.mock('@/next/navigation', () => ({
- useParams: () => ({}),
-}))
-
let deploymentEdition: 'CLOUD' | 'COMMUNITY' = 'COMMUNITY'
let mockPlanType: CloudPlan = 'team'
let mockAppCount = 1
@@ -92,13 +68,20 @@ function render(ui: ReactElement) {
})
}
+vi.mock('@/next/navigation', () => ({ useParams: () => ({}) }))
+
+function submitWithKeyboard() {
+ const target = screen.queryByPlaceholderText('app.newApp.appNamePlaceholder') ?? document.body
+ fireEvent.keyDown(target, { key: 'Enter', ctrlKey: true })
+ fireEvent.keyUp(target, { key: 'Enter', ctrlKey: true })
+}
+
describe('CreateAppModal', () => {
beforeEach(() => {
vi.clearAllMocks()
deploymentEdition = 'COMMUNITY'
mockPlanType = 'team'
mockAppCount = 1
- hotkeyMocks.handlers.clear()
})
describe('Rendering', () => {
@@ -233,7 +216,7 @@ describe('CreateAppModal', () => {
it('should submit when Mod+Enter is pressed while visible', async () => {
const { onConfirm, onHide } = await setup()
- triggerHotkey('Mod+Enter')
+ submitWithKeyboard()
await act(async () => {
vi.advanceTimersByTime(300)
})
@@ -242,10 +225,34 @@ describe('CreateAppModal', () => {
expect(onHide).toHaveBeenCalledTimes(1)
})
+ it('does not submit while the visible confirmation action is disabled', async () => {
+ const { onConfirm, onHide } = await setup({ confirmDisabled: true })
+ expect(screen.getByRole('button', { name: /common\.operation\.create/ })).toBeDisabled()
+ submitWithKeyboard()
+ await act(async () => {
+ vi.advanceTimersByTime(300)
+ })
+ expect(onConfirm).not.toHaveBeenCalled()
+ expect(onHide).not.toHaveBeenCalled()
+ })
+
+ it('ignores shortcuts outside the dialog and during composition', async () => {
+ const { onConfirm } = await setup()
+ fireEvent.keyDown(document.body, { key: 'Enter', ctrlKey: true })
+ fireEvent.keyUp(document.body, { key: 'Enter', ctrlKey: true })
+ const input = screen.getByPlaceholderText('app.newApp.appNamePlaceholder')
+ fireEvent.keyDown(input, { key: 'Enter', ctrlKey: true, isComposing: true })
+ fireEvent.keyUp(input, { key: 'Enter', ctrlKey: true })
+ await act(async () => {
+ vi.advanceTimersByTime(300)
+ })
+ expect(onConfirm).not.toHaveBeenCalled()
+ })
+
it('should not submit when modal is hidden', async () => {
const { onConfirm, onHide } = await setup({ show: false })
- triggerHotkey('Mod+Enter')
+ submitWithKeyboard()
await act(async () => {
vi.advanceTimersByTime(300)
})
@@ -261,7 +268,7 @@ describe('CreateAppModal', () => {
const { onConfirm, onHide } = await setup({ isEditModal: false })
- triggerHotkey('Mod+Enter')
+ submitWithKeyboard()
await act(async () => {
vi.advanceTimersByTime(300)
})
@@ -277,7 +284,7 @@ describe('CreateAppModal', () => {
const { onConfirm, onHide } = await setup({ isEditModal: true })
- triggerHotkey('Mod+Enter')
+ submitWithKeyboard()
await act(async () => {
vi.advanceTimersByTime(300)
})
@@ -289,7 +296,7 @@ describe('CreateAppModal', () => {
it('should not submit when name is empty', async () => {
const { onConfirm, onHide } = await setup({ appName: ' ' })
- triggerHotkey('Mod+Enter')
+ submitWithKeyboard()
await act(async () => {
vi.advanceTimersByTime(300)
})
diff --git a/web/app/components/explore/create-app-modal/index.tsx b/web/app/components/explore/create-app-modal/index.tsx
index 112d28ee96f..321f5437da1 100644
--- a/web/app/components/explore/create-app-modal/index.tsx
+++ b/web/app/components/explore/create-app-modal/index.tsx
@@ -8,7 +8,7 @@ import { Input } from '@langgenius/dify-ui/input'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { Switch } from '@langgenius/dify-ui/switch'
import { Textarea } from '@langgenius/dify-ui/textarea'
-import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
+import { formatForDisplay, matchesKeyboardEvent } from '@tanstack/react-hotkeys'
import { useQuery } from '@tanstack/react-query'
import { useDebounceFn } from 'ahooks'
import { useAtomValue } from 'jotai'
@@ -106,7 +106,7 @@ const CreateAppModal = ({
appQuota.size >= appQuota.limit
const submit = useCallback(() => {
- if (!isEditModal && (isAppQuotaUnavailable || isAppsFull)) return
+ if (confirmDisabled || (!isEditModal && (isAppQuotaUnavailable || isAppsFull))) return
if (!name.trim()) {
toast(
t(($) => $['appCustomize.nameRequired'], { ns: 'explore' }),
@@ -129,6 +129,7 @@ const CreateAppModal = ({
onConfirm(payload)
onHide()
}, [
+ confirmDisabled,
isEditModal,
isAppQuotaUnavailable,
isAppsFull,
@@ -144,21 +145,33 @@ const CreateAppModal = ({
const { run: handleSubmit } = useDebounceFn(submit, { wait: 300 })
- useHotkey(
- SUBMIT_APP_HOTKEY,
- () => {
- handleSubmit()
- },
- {
- enabled: show && !isAppQuotaUnavailable && !(!isEditModal && isAppsFull) && !!name.trim(),
- ignoreInputs: false,
- },
- )
+ const submitDisabled =
+ isAppQuotaUnavailable || (!isEditModal && isAppsFull) || !name.trim() || !!confirmDisabled
return (
<>
<Dialog open={show} onOpenChange={(open) => !open && onHide()} disablePointerDismissal>
- <DialogContent backdropProps={{ forceRender: true }} className="px-8">
+ <DialogContent
+ onKeyDown={(event) => {
+ if (
+ !show ||
+ submitDisabled ||
+ showAppIconPicker ||
+ event.defaultPrevented ||
+ event.nativeEvent.isComposing ||
+ !(event.target instanceof Node) ||
+ !event.currentTarget.contains(event.target) ||
+ !matchesKeyboardEvent(event.nativeEvent, SUBMIT_APP_HOTKEY)
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ handleSubmit()
+ }}
+ backdropProps={{ forceRender: true }}
+ className="px-8"
+ >
<DialogClose
render={
<IconButton
@@ -274,12 +287,7 @@ const CreateAppModal = ({
</div>
<div className="flex flex-row-reverse">
<Button
- disabled={
- isAppQuotaUnavailable ||
- (!isEditModal && isAppsFull) ||
- !name.trim() ||
- confirmDisabled
- }
+ disabled={submitDisabled}
className="ml-2 w-24"
variant="primary"
onClick={handleSubmit}
@@ -290,9 +298,9 @@ const CreateAppModal = ({
: t(($) => $['operation.save'], { ns: 'common' })}
</span>
<KbdGroup>
- {SUBMIT_APP_HOTKEY.split('+').map((key) => (
+ {formatForDisplay(SUBMIT_APP_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white">
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
diff --git a/web/app/components/goto-anything/__tests__/index.spec.tsx b/web/app/components/goto-anything/__tests__/index.spec.tsx
index 2ce689e0a0c..e5a1fd2fc82 100644
--- a/web/app/components/goto-anything/__tests__/index.spec.tsx
+++ b/web/app/components/goto-anything/__tests__/index.spec.tsx
@@ -303,6 +303,21 @@ describe('GotoAnything', () => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
+ it('should leave a consumed shortcut to its local owner', () => {
+ renderGotoAnything(
+ <>
+ <button type="button" onKeyDown={(event) => event.preventDefault()}>
+ Local command
+ </button>
+ <GotoAnything />
+ </>,
+ )
+
+ triggerSearchShortcut(screen.getByRole('button', { name: 'Local command' }))
+
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
it.each(['shiftKey', 'altKey'] as const)('should ignore Mod+K with %s', (extraModifier) => {
renderGotoAnything(<GotoAnything />)
diff --git a/web/app/components/goto-anything/index.tsx b/web/app/components/goto-anything/index.tsx
index 910e681480c..4655d4c0651 100644
--- a/web/app/components/goto-anything/index.tsx
+++ b/web/app/components/goto-anything/index.tsx
@@ -540,8 +540,8 @@ export function GotoAnything() {
/>
</div>
<KbdGroup>
- {GOTO_ANYTHING_HOTKEY.split('+').map((key) => (
- <Kbd key={key}>{formatForDisplay(key)}</Kbd>
+ {formatForDisplay(GOTO_ANYTHING_HOTKEY, { parts: true }).map((key) => (
+ <Kbd key={key}>{key}</Kbd>
))}
</KbdGroup>
</AutocompleteInputGroup>
diff --git a/web/app/components/main-nav/components/search-button.tsx b/web/app/components/main-nav/components/search-button.tsx
index fdba9f6ac97..a488d3f8f9f 100644
--- a/web/app/components/main-nav/components/search-button.tsx
+++ b/web/app/components/main-nav/components/search-button.tsx
@@ -52,9 +52,10 @@ export function MainNavSearchButton({
className="h-4.5 min-w-0 shrink-0 rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary data-pending:invisible"
>
{displayPlatform !== null &&
- GOTO_ANYTHING_HOTKEY.split('+').map((key) => (
- <span key={key}>{formatForDisplay(key, { platform: displayPlatform })}</span>
- ))}
+ formatForDisplay(GOTO_ANYTHING_HOTKEY, {
+ platform: displayPlatform,
+ parts: true,
+ }).map((key) => <span key={key}>{key}</span>)}
</Kbd>
</DialogTrigger>
)
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-search.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-search.spec.tsx
new file mode 100644
index 00000000000..4c79ab185ad
--- /dev/null
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-search.spec.tsx
@@ -0,0 +1,61 @@
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import HomeSearch from '../home-search'
+
+const modifier = detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }
+
+describe('HomeSearch shortcut', () => {
+ it('focuses standalone search and leaves the console binding disabled', async () => {
+ const user = userEvent.setup()
+ const { rerender } = render(
+ <>
+ <button>Outside</button>
+ <HomeSearch>
+ <input aria-label="Marketplace search" />
+ </HomeSearch>
+ </>,
+ )
+ await user.click(screen.getByRole('button', { name: 'Outside' }))
+ fireEvent.keyDown(document.activeElement!, { key: 'k', ...modifier })
+ expect(screen.getByRole('textbox', { name: 'Marketplace search' })).toHaveFocus()
+ fireEvent.keyUp(document.activeElement!, { key: 'k', ...modifier })
+ rerender(
+ <>
+ <button>Outside</button>
+ <HomeSearch enableSearchShortcut={false}>
+ <input aria-label="Marketplace search" />
+ </HomeSearch>
+ </>,
+ )
+ await user.click(screen.getByRole('button', { name: 'Outside' }))
+ fireEvent.keyDown(document.activeElement!, { key: 'k', ...modifier })
+ expect(screen.getByRole('button', { name: 'Outside' })).toHaveFocus()
+ })
+
+ it('preserves input composition and shortcuts claimed by a nearer owner', async () => {
+ const user = userEvent.setup()
+ render(
+ <>
+ <input aria-label="Editor" onKeyDown={(event) => event.preventDefault()} />
+ <input aria-label="Description" />
+ <HomeSearch>
+ <input aria-label="Marketplace search" />
+ </HomeSearch>
+ </>,
+ )
+ const editor = screen.getByRole('textbox', { name: 'Editor' })
+ await user.click(editor)
+ fireEvent.keyDown(editor, { key: 'k', ...modifier })
+ expect(editor).toHaveFocus()
+ fireEvent.keyUp(editor, { key: 'k', ...modifier })
+
+ const description = screen.getByRole('textbox', { name: 'Description' })
+ await user.click(description)
+ expect(fireEvent.keyDown(description, { key: 'k', ...modifier, isComposing: true })).toBe(true)
+ expect(description).toHaveFocus()
+ fireEvent.keyUp(description, { key: 'k', ...modifier })
+ fireEvent.keyDown(description, { key: 'k', ...modifier })
+ expect(screen.getByRole('textbox', { name: 'Marketplace search' })).toHaveFocus()
+ })
+})
diff --git a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
index f66370a09c7..64fa3078f7d 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
@@ -1,6 +1,6 @@
import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { render, screen, waitFor, within } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
@@ -319,6 +319,8 @@ describe('MarketplaceSearchAutocomplete', () => {
await user.type(screen.getByRole('combobox'), 'search')
await user.hover(await screen.findByRole('option', { name: /Legal Research Agent/ }))
+ fireEvent.keyDown(screen.getByRole('combobox'), { key: 'Enter', isComposing: true })
+ expect(handleSubmit).not.toHaveBeenCalled()
await user.keyboard('{Enter}')
expect(handleSubmit).toHaveBeenCalledOnce()
diff --git a/web/app/components/plugins/marketplace/home/home-search.tsx b/web/app/components/plugins/marketplace/home/home-search.tsx
index 14990bc5418..76727505423 100644
--- a/web/app/components/plugins/marketplace/home/home-search.tsx
+++ b/web/app/components/plugins/marketplace/home/home-search.tsx
@@ -1,13 +1,17 @@
'use client'
+import type { Hotkey } from '@tanstack/react-hotkeys'
import type { ReactNode } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
+import { useHotkey } from '@tanstack/react-hotkeys'
import { useEffect, useRef } from 'react'
import { MARKETPLACE_CONTAINER_ID } from '../constants'
import EmbeddedMarketplaceSearch from './embedded-marketplace-search'
import styles from './home-sticky.module.css'
import { preserveStickySearchScroll } from './preserve-sticky-search-scroll'
+const SEARCH_HOTKEY = 'Mod+K' satisfies Hotkey
+
type HomeSearchProps = {
children?: ReactNode
/**
@@ -38,19 +42,23 @@ const HomeSearch = ({
return preserveStickySearchScroll(searchRoot, container)
}, [])
- useEffect(() => {
- if (!enableSearchShortcut) return
-
- const handleGlobalSearchShortcut = (event: KeyboardEvent) => {
- if (event.key.toLowerCase() !== 'k' || (!event.metaKey && !event.ctrlKey)) return
+ useHotkey(
+ SEARCH_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented) return
event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
searchRef.current?.querySelector('input')?.focus({ preventScroll: true })
- }
-
- document.addEventListener('keydown', handleGlobalSearchShortcut)
- return () => document.removeEventListener('keydown', handleGlobalSearchShortcut)
- }, [enableSearchShortcut])
+ },
+ {
+ enabled: enableSearchShortcut,
+ ignoreInputs: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
return (
<div
diff --git a/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx b/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
index 0ddb76d5f26..262df0be342 100644
--- a/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
+++ b/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
@@ -352,7 +352,13 @@ export function MarketplaceSearchAutocomplete({
size="large"
type="text"
onKeyDownCapture={(event) => {
- if (event.key !== 'Enter' || !inputName) return
+ if (
+ event.defaultPrevented ||
+ event.nativeEvent.isComposing ||
+ event.key !== 'Enter' ||
+ !inputName
+ )
+ return
if (keyboardHighlightedRef.current) return
event.preventDefault()
event.stopPropagation()
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx
index fc3f012cfd7..2492ce80d66 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/__tests__/run-mode.spec.tsx
@@ -6,37 +6,11 @@ const mockHandleWorkflowStartRunInWorkflow = vi.fn()
const mockHandleStopRun = vi.fn()
const mockSetIsPreparingDataSource = vi.fn()
const mockSetShowDebugAndPreviewPanel = vi.fn()
-const hotkeyRegistrations = vi.hoisted(
- () =>
- new Map<
- string,
- {
- callback: () => void
- options?: { enabled?: boolean; ignoreInputs?: boolean; preventDefault?: boolean }
- }
- >(),
-)
-
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (
- hotkey: string,
- callback: () => void,
- options?: { enabled?: boolean; ignoreInputs?: boolean; preventDefault?: boolean },
- ) => {
- hotkeyRegistrations.set(hotkey, { callback, options })
- },
- }
-})
let mockWorkflowRunningData: { task_id: string; result: { status: string } } | undefined
let mockIsPreparingDataSource = false
vi.mock('@/app/components/workflow/hooks/use-workflow-run', () => ({
- useWorkflowRun: () => ({
- handleStopRun: mockHandleStopRun,
- }),
+ useWorkflowRun: () => ({ handleStopRun: mockHandleStopRun }),
}))
vi.mock('@/app/components/workflow/hooks/use-workflow-start-run', () => ({
@@ -98,7 +72,6 @@ describe('RunMode', () => {
vi.clearAllMocks()
mockWorkflowRunningData = undefined
mockIsPreparingDataSource = false
- hotkeyRegistrations.clear()
})
describe('Idle state', () => {
@@ -137,15 +110,18 @@ describe('RunMode', () => {
it('should run through the enabled application shortcut', () => {
render(<RunMode />)
- const registration = hotkeyRegistrations.get('Alt+R')
- registration?.callback()
+ const event = new KeyboardEvent('keydown', {
+ key: 'r',
+ code: 'KeyR',
+ altKey: true,
+ bubbles: true,
+ })
+ // Happy DOM treats Alt as AltGraph; this event represents the plain Alt key.
+ vi.spyOn(event, 'getModifierState').mockImplementation((key) => key === 'Alt')
+ fireEvent(document.body, event)
+ fireEvent.keyUp(document.body, { key: 'r', code: 'KeyR', altKey: true })
expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalledOnce()
- expect(registration?.options).toEqual({
- enabled: true,
- ignoreInputs: true,
- preventDefault: true,
- })
})
})
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
index fbf6b367fbb..c2bd364bb11 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
@@ -1,6 +1,6 @@
import type { IconInfo } from '@/models/datasets'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { act, fireEvent, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
import * as React from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
@@ -19,31 +19,6 @@ vi.mock('@/features/system-features/state', async () => {
}
})
-const hotkeyHandlers = vi.hoisted(() => new Map<string, (event: KeyboardEvent) => void>())
-
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (hotkey: string, handler: (event: KeyboardEvent) => void) => {
- hotkeyHandlers.set(hotkey, handler)
- },
- }
-})
-
-const triggerHotkey = (hotkey: string) => {
- const handler = hotkeyHandlers.get(hotkey)
- if (!handler) return
-
- act(() => {
- handler({ preventDefault: vi.fn() } as unknown as KeyboardEvent)
- })
-}
-
-vi.mock('@/next/navigation', () => ({
- useParams: () => ({ datasetId: 'test-dataset-id' }),
-}))
-
vi.mock('@/next/link', () => ({
default: ({ children, ...props }: React.ComponentProps<'a'>) => <a {...props}>{children}</a>,
}))
@@ -247,10 +222,17 @@ function render(...args: Parameters<typeof renderWithoutPricing>) {
return renderWithoutPricing(...args)
}
+vi.mock('@/next/navigation', () => ({ useParams: () => ({ datasetId: 'test-dataset-id' }) }))
+
+function publishWithKeyboard() {
+ const target = screen.getByRole('button', { name: /workflow.common.publish(?:Update|ed)?/i })
+ fireEvent.keyDown(target, { key: 'P', ctrlKey: true, shiftKey: true })
+ fireEvent.keyUp(target, { key: 'P', ctrlKey: true, shiftKey: true })
+}
+
describe('publisher', () => {
beforeEach(() => {
vi.clearAllMocks()
- hotkeyHandlers.clear()
vi.spyOn(console, 'error').mockImplementation(() => {})
mockPublishedAt.mockReturnValue(null)
mockDraftUpdatedAt.mockReturnValue(1700000000)
@@ -900,7 +882,7 @@ describe('publisher', () => {
mockPublishWorkflow.mockResolvedValue({ created_at: 1700100000 })
renderWithQueryClient(<Popup />)
- triggerHotkey('Mod+Shift+P')
+ publishWithKeyboard()
await waitFor(() => {
expect(mockPublishWorkflow).toHaveBeenCalled()
@@ -923,7 +905,7 @@ describe('publisher', () => {
vi.clearAllMocks()
- triggerHotkey('Mod+Shift+P')
+ publishWithKeyboard()
expect(mockPublishWorkflow).not.toHaveBeenCalled()
})
@@ -932,7 +914,7 @@ describe('publisher', () => {
mockPublishedAt.mockReturnValue(null)
renderWithQueryClient(<Popup />)
- triggerHotkey('Mod+Shift+P')
+ publishWithKeyboard()
await waitFor(() => {
expect(screen.getByText('pipeline.common.confirmPublish')).toBeInTheDocument()
@@ -950,7 +932,7 @@ describe('publisher', () => {
)
renderWithQueryClient(<Popup />)
- triggerHotkey('Mod+Shift+P')
+ publishWithKeyboard()
await waitFor(() => {
const publishButton = screen.getByRole('button', {
@@ -959,7 +941,7 @@ describe('publisher', () => {
expect(publishButton).toBeDisabled()
})
- triggerHotkey('Mod+Shift+P')
+ publishWithKeyboard()
expect(mockPublishWorkflow).toHaveBeenCalledTimes(1)
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
index e1ab4f1f75f..9751eb4f44e 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
@@ -18,7 +18,7 @@ import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import { useAtomValue } from 'jotai'
import { useQueryState } from 'nuqs'
-import { useCallback, useState } from 'react'
+import { useCallback, useRef, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { trackEvent } from '@/app/components/base/amplitude'
import PremiumBadge from '@/app/components/base/premium-badge'
@@ -65,6 +65,7 @@ export function Popup({
isPublishingAsCustomizedPipeline = false,
onShowPublishAsKnowledgePipelineModal,
}: PopupProps) {
+ const popupRef = useRef<HTMLDivElement>(null)
const { t } = useTranslation(['billing', 'common', 'datasetPipeline', 'pipeline', 'workflow'])
const { data: deploymentEdition } = useSuspenseQuery({
...systemFeaturesQueryOptions(),
@@ -195,9 +196,10 @@ export function Popup({
],
)
useHotkey(RAG_PIPELINE_PUBLISH_HOTKEY, () => void handlePublish(), {
- enabled: !published && !publishing,
+ target: popupRef,
+ enabled: !published && !publishing && !confirmVisible,
ignoreInputs: true,
- preventDefault: true,
+ requireReset: true,
})
const handleClickPublishAsKnowledgePipeline = useCallback(() => {
if (isAllowPublishAsCustomKnowledgePipelineTemplate === undefined) return
@@ -217,6 +219,7 @@ export function Popup({
])
return (
<div
+ ref={popupRef}
className={cn(
'rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl shadow-shadow-shadow-5',
isAllowPublishAsCustomKnowledgePipelineTemplate ? 'w-90' : 'w-100',
@@ -253,9 +256,9 @@ export function Popup({
<div className="flex gap-1">
<span>{t(($) => $['common.publishUpdate'], { ns: 'workflow' })}</span>
<KbdGroup>
- {RAG_PIPELINE_PUBLISH_HOTKEY.split('+').map((key) => (
+ {formatForDisplay(RAG_PIPELINE_PUBLISH_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white">
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx
index 6efae336452..39c8a6f1329 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx
@@ -49,11 +49,22 @@ export function RunMode({ text }: RunModeProps) {
handleWorkflowStartRunInWorkflow()
}
- useHotkey(RAG_PIPELINE_RUN_HOTKEY, handleRun, {
- enabled: !isDisabled,
- ignoreInputs: true,
- preventDefault: true,
- })
+ useHotkey(
+ RAG_PIPELINE_RUN_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ handleRun()
+ },
+ {
+ stopPropagation: false,
+ enabled: !isDisabled,
+ ignoreInputs: true,
+ preventDefault: false,
+ },
+ )
if (!canRun) return null
@@ -91,8 +102,8 @@ export function RunMode({ text }: RunModeProps) {
)}
{!isDisabled && (
<KbdGroup>
- {RAG_PIPELINE_RUN_HOTKEY.split('+').map((key) => (
- <Kbd key={key}>{formatForDisplay(key)}</Kbd>
+ {formatForDisplay(RAG_PIPELINE_RUN_HOTKEY, { parts: true }).map((key) => (
+ <Kbd key={key}>{key}</Kbd>
))}
</KbdGroup>
)}
diff --git a/web/app/components/snippets/__tests__/create-snippet-dialog.spec.tsx b/web/app/components/snippets/__tests__/create-snippet-dialog.spec.tsx
index 88bd5b3533a..57248fcc7eb 100644
--- a/web/app/components/snippets/__tests__/create-snippet-dialog.spec.tsx
+++ b/web/app/components/snippets/__tests__/create-snippet-dialog.spec.tsx
@@ -1,46 +1,10 @@
import type { SnippetCanvasData, SnippetInputField } from '@/models/snippet'
-import { render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { PipelineInputVarType } from '@/models/pipeline'
import { expectLoadingButton } from '@/test/button'
import { CreateSnippetDialog } from '../create-snippet-dialog'
-let capturedKeyPressHandler: (() => void) | undefined
-let capturedHotkey: string | undefined
-let capturedHotkeyOptions:
- | {
- enabled?: boolean
- ignoreInputs?: boolean
- preventDefault?: boolean
- stopPropagation?: boolean
- target?: React.RefObject<HTMLElement | null>
- }
- | undefined
-
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (
- hotkey: string,
- handler: () => void,
- options?: {
- enabled?: boolean
- ignoreInputs?: boolean
- preventDefault?: boolean
- stopPropagation?: boolean
- target?: React.RefObject<HTMLElement | null>
- },
- ) => {
- capturedHotkey = hotkey
- capturedKeyPressHandler = () => {
- if (options?.enabled !== false) handler()
- }
- capturedHotkeyOptions = options
- },
- }
-})
-
const selectedGraph: SnippetCanvasData = {
nodes: [],
edges: [],
@@ -59,9 +23,6 @@ const inputFields: SnippetInputField[] = [
describe('CreateSnippetDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
- capturedKeyPressHandler = undefined
- capturedHotkey = undefined
- capturedHotkeyOptions = undefined
})
it('should submit trimmed snippet values with the selected graph and input fields', async () => {
@@ -177,7 +138,14 @@ describe('CreateSnippetDialog', () => {
/>,
)
- capturedKeyPressHandler?.()
+ fireEvent.keyDown(
+ screen.queryByRole('textbox', { name: 'workflow.snippet.nameLabel' }) ?? document.body,
+ { key: 'Enter', code: 'Enter', ctrlKey: true },
+ )
+ fireEvent.keyUp(
+ screen.queryByRole('textbox', { name: 'workflow.snippet.nameLabel' }) ?? document.body,
+ { key: 'Enter', code: 'Enter', ctrlKey: true },
+ )
expect(onConfirm).not.toHaveBeenCalled()
@@ -191,7 +159,14 @@ describe('CreateSnippetDialog', () => {
/>,
)
- capturedKeyPressHandler?.()
+ fireEvent.keyDown(
+ screen.queryByRole('textbox', { name: 'workflow.snippet.nameLabel' }) ?? document.body,
+ { key: 'Enter', code: 'Enter', ctrlKey: true },
+ )
+ fireEvent.keyUp(
+ screen.queryByRole('textbox', { name: 'workflow.snippet.nameLabel' }) ?? document.body,
+ { key: 'Enter', code: 'Enter', ctrlKey: true },
+ )
expect(onConfirm).not.toHaveBeenCalled()
@@ -204,21 +179,85 @@ describe('CreateSnippetDialog', () => {
/>,
)
- capturedKeyPressHandler?.()
+ fireEvent.keyDown(
+ screen.queryByRole('textbox', { name: 'workflow.snippet.nameLabel' }) ?? document.body,
+ { key: 'Enter', code: 'Enter', ctrlKey: true },
+ )
+ fireEvent.keyUp(
+ screen.queryByRole('textbox', { name: 'workflow.snippet.nameLabel' }) ?? document.body,
+ { key: 'Enter', code: 'Enter', ctrlKey: true },
+ )
expect(onConfirm).toHaveBeenCalledWith(
expect.objectContaining({
name: 'Keyboard snippet',
}),
)
- expect(capturedHotkeyOptions).toMatchObject({
- enabled: true,
- ignoreInputs: false,
- preventDefault: false,
- stopPropagation: false,
- })
- expect(capturedHotkeyOptions?.target?.current).toBe(screen.getByRole('dialog'))
- expect(capturedHotkey).toBe('Mod+Enter')
+ })
+
+ it('handles the first shortcut after opening and reopening its portal without a draft change', async () => {
+ const onConfirm = vi.fn()
+ const props = {
+ initialValue: { name: 'Portal snippet' },
+ onClose: vi.fn(),
+ onConfirm,
+ }
+ const { rerender } = render(<CreateSnippetDialog {...props} isOpen={false} />)
+ for (let opened = 1; opened <= 2; opened++) {
+ rerender(<CreateSnippetDialog {...props} isOpen />)
+ const input = await screen.findByRole('textbox', { name: 'workflow.snippet.nameLabel' })
+ const repeat = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ ctrlKey: true,
+ repeat: true,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(input, repeat)
+ expect(repeat.defaultPrevented).toBe(true)
+ expect(onConfirm).toHaveBeenCalledTimes(opened - 1)
+ fireEvent.keyDown(input, { key: 'Enter', ctrlKey: true })
+ fireEvent.keyUp(input, { key: 'Enter', ctrlKey: true })
+ expect(onConfirm).toHaveBeenCalledTimes(opened)
+ rerender(<CreateSnippetDialog {...props} isOpen={false} />)
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ fireEvent.keyDown(document.body, { key: 'Enter', ctrlKey: true })
+ expect(onConfirm).toHaveBeenCalledTimes(opened)
+ }
+ })
+
+ it('lets a child React handler claim the shortcut before the dialog action', () => {
+ const onConfirm = vi.fn()
+ render(
+ <CreateSnippetDialog
+ isOpen
+ initialValue={{ name: 'Nested control' }}
+ onClose={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+ const dialog = screen.getByRole('dialog')
+ const childContainer = document.createElement('div')
+ dialog.append(childContainer)
+ const childClaim = vi.fn((event: React.KeyboardEvent<HTMLButtonElement>) =>
+ event.preventDefault(),
+ )
+ const child = render(
+ <button type="button" onKeyDown={childClaim}>
+ Child action
+ </button>,
+ { container: childContainer },
+ )
+ const options = { key: 'Enter', ctrlKey: true }
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Child action' }), options)
+ expect(childClaim).toHaveBeenCalledOnce()
+ expect(onConfirm).not.toHaveBeenCalled()
+
+ child.rerender(<button type="button">Child action</button>)
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Child action' }), options)
+ expect(onConfirm).toHaveBeenCalledOnce()
+
+ child.unmount()
})
it('should disable form controls while submitting', () => {
diff --git a/web/app/components/snippets/components/snippet-detail-top.tsx b/web/app/components/snippets/components/snippet-detail-top.tsx
index fda8e9252a4..72b9be1c865 100644
--- a/web/app/components/snippets/components/snippet-detail-top.tsx
+++ b/web/app/components/snippets/components/snippet-detail-top.tsx
@@ -95,8 +95,8 @@ export function SnippetDetailTop({ expand = true, onToggle }: SnippetDetailTopPr
<TooltipContent placement="bottom" className="flex items-center gap-1">
<span className="px-0.5">{t(($) => $['gotoAnything.quickAction'], { ns: 'app' })}</span>
<KbdGroup>
- {GOTO_ANYTHING_HOTKEY.split('+').map((key) => (
- <Kbd key={key}>{formatForDisplay(key)}</Kbd>
+ {formatForDisplay(GOTO_ANYTHING_HOTKEY, { parts: true }).map((key) => (
+ <Kbd key={key}>{key}</Kbd>
))}
</KbdGroup>
</TooltipContent>
diff --git a/web/app/components/snippets/create-snippet-dialog.tsx b/web/app/components/snippets/create-snippet-dialog.tsx
index d9bcc877c2e..81196f7f1ca 100644
--- a/web/app/components/snippets/create-snippet-dialog.tsx
+++ b/web/app/components/snippets/create-snippet-dialog.tsx
@@ -13,7 +13,7 @@ import {
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
import { Textarea } from '@langgenius/dify-ui/textarea'
-import { useHotkey } from '@tanstack/react-hotkeys'
+import { matchesKeyboardEvent } from '@tanstack/react-hotkeys'
import { useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -63,7 +63,6 @@ export function CreateSnippetDialog({
const nameInputId = useId()
const descriptionInputId = useId()
const { t } = useTranslation(['common', 'workflow'])
- const popupRef = useRef<HTMLDivElement>(null)
const nameInputRef = useRef<HTMLInputElement>(null)
const [name, setName] = useState(initialValue?.name ?? '')
const [description, setDescription] = useState(initialValue?.description ?? '')
@@ -82,7 +81,7 @@ export function CreateSnippetDialog({
const trimmedName = name.trim()
const trimmedDescription = description.trim()
- if (!trimmedName) return
+ if (!trimmedName || isSubmitting) return
const payload = {
name: trimmedName,
@@ -94,21 +93,29 @@ export function CreateSnippetDialog({
onConfirm(payload)
}
- useHotkey(CREATE_SNIPPET_HOTKEY, handleConfirm, {
- enabled: isOpen && !isSubmitting,
- ignoreInputs: false,
- preventDefault: false,
- stopPropagation: false,
- target: popupRef,
- })
-
return (
<>
<Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
<DialogPortal>
<DialogBackdrop />
<DialogPopup
- ref={popupRef}
+ onKeyDown={(event) => {
+ if (
+ !isOpen ||
+ isSubmitting ||
+ !name.trim() ||
+ event.defaultPrevented ||
+ event.nativeEvent.isComposing ||
+ !(event.target instanceof Node) ||
+ !event.currentTarget.contains(event.target) ||
+ !matchesKeyboardEvent(event.nativeEvent, CREATE_SNIPPET_HOTKEY)
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ handleConfirm()
+ }}
initialFocus={nameInputRef}
className="fixed top-1/2 left-1/2 max-h-[80dvh] w-120 max-w-120 -translate-x-1/2 -translate-y-1/2 overflow-y-auto overscroll-contain p-0"
>
diff --git a/web/app/components/workflow/__tests__/edge-contextmenu.spec.tsx b/web/app/components/workflow/__tests__/edge-contextmenu.spec.tsx
index 879f93fce7a..8bf179d0043 100644
--- a/web/app/components/workflow/__tests__/edge-contextmenu.spec.tsx
+++ b/web/app/components/workflow/__tests__/edge-contextmenu.spec.tsx
@@ -1,8 +1,7 @@
import type { Edge, Node } from '../types'
import { ContextMenu } from '@langgenius/dify-ui/context-menu'
-import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { useEffect } from 'react'
import { useEdges, useNodes, useStoreApi } from 'reactflow'
import { createEdge, createNode } from '../__tests__/fixtures'
import { renderWorkflowFlowComponent } from '../__tests__/workflow-test-env'
@@ -90,24 +89,10 @@ const hooksStoreProps = {
}
const EdgeMenuHarness = () => {
- const { handleEdgeContextMenu, handleEdgeDelete } = useEdgesInteractions()
+ const { handleEdgeContextMenu } = useEdgesInteractions()
const edges = useEdges() as Edge[]
const reactFlowStore = useStoreApi()
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- if (e.key !== 'Delete' && e.key !== 'Backspace') return
-
- e.preventDefault()
- handleEdgeDelete()
- }
-
- document.addEventListener('keydown', handleKeyDown)
- return () => {
- document.removeEventListener('keydown', handleKeyDown)
- }
- }, [handleEdgeDelete])
-
return (
<div>
<RuntimeProbe />
@@ -283,6 +268,7 @@ describe('EdgeContextmenu', () => {
])(
'should delete the right-clicked edge with %s after switching from a selected node',
async (_, key) => {
+ const user = userEvent.setup()
renderEdgeMenu({
nodes: [
createNode({
@@ -304,7 +290,9 @@ describe('EdgeContextmenu', () => {
expect(await screen.findByRole('menu'))!.toBeInTheDocument()
- fireEvent.keyDown(document.body, { key })
+ const item = screen.getByRole('menuitem', { name: /common\.operation\.delete/i })
+ act(() => item.focus())
+ await user.keyboard(`{${key}}`)
await waitFor(() => {
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
@@ -318,6 +306,7 @@ describe('EdgeContextmenu', () => {
)
it('should keep bundled multi-selection nodes intact when delete runs after right-clicking an edge', async () => {
+ const user = userEvent.setup()
renderEdgeMenu({
nodes: [
createNode({
@@ -341,7 +330,9 @@ describe('EdgeContextmenu', () => {
expect(await screen.findByRole('menu'))!.toBeInTheDocument()
- fireEvent.keyDown(document.body, { key: 'Delete' })
+ const item = screen.getByRole('menuitem', { name: /common\.operation\.delete/i })
+ act(() => item.focus())
+ await user.keyboard('{Delete}')
await waitFor(() => {
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
diff --git a/web/app/components/workflow/__tests__/hotkeys.spec.ts b/web/app/components/workflow/__tests__/hotkeys.spec.ts
deleted file mode 100644
index cccde60f94d..00000000000
--- a/web/app/components/workflow/__tests__/hotkeys.spec.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { detectPlatform } from '@tanstack/react-hotkeys'
-import { shouldPreventWorkflowBrowserDefault } from '../hotkeys'
-
-const primaryModifier = detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }
-
-function createKeyboardEvent(key: string, modifiers: KeyboardEventInit = {}) {
- return new KeyboardEvent('keydown', { key, ...modifiers })
-}
-
-describe('workflow browser default hotkeys', () => {
- it.each(['d', 'z', 'y', 's'])('matches the exact Mod+%s browser guard', (key) => {
- expect(shouldPreventWorkflowBrowserDefault(createKeyboardEvent(key, primaryModifier))).toBe(
- true,
- )
- })
-
- it('matches the alternate redo hotkey', () => {
- expect(
- shouldPreventWorkflowBrowserDefault(
- createKeyboardEvent('z', { ...primaryModifier, shiftKey: true }),
- ),
- ).toBe(true)
- })
-
- it('does not match plain or over-modified keys', () => {
- expect(shouldPreventWorkflowBrowserDefault(createKeyboardEvent('s'))).toBe(false)
- expect(
- shouldPreventWorkflowBrowserDefault(
- createKeyboardEvent('s', { ...primaryModifier, shiftKey: true }),
- ),
- ).toBe(false)
- })
-})
diff --git a/web/app/components/workflow/__tests__/node-contextmenu.spec.tsx b/web/app/components/workflow/__tests__/node-contextmenu.spec.tsx
index 8c1753e6d45..bddd85f78bb 100644
--- a/web/app/components/workflow/__tests__/node-contextmenu.spec.tsx
+++ b/web/app/components/workflow/__tests__/node-contextmenu.spec.tsx
@@ -1,6 +1,9 @@
import type { Node } from '../types'
import { ContextMenu } from '@langgenius/dify-ui/context-menu'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { ReactFlowProvider } from 'reactflow'
import { NodeContextmenu } from '../node-contextmenu'
const mockUseNodes = vi.hoisted(() => vi.fn())
@@ -74,11 +77,24 @@ describe('NodeContextmenu', () => {
const renderNodeContextmenu = () =>
render(
- <ContextMenu open>
- <NodeContextmenu onClose={mockClose} />
- </ContextMenu>,
+ <ReactFlowProvider>
+ <ContextMenu open>
+ <NodeContextmenu onClose={mockClose} />
+ </ContextMenu>
+ </ReactFlowProvider>,
)
+ it.each(['c', 'd', 'Delete'])('runs %s from the node context menu owner', async (key) => {
+ const user = userEvent.setup()
+ contextMenuTarget = { type: 'node', nodeId: 'node-1' }
+ renderNodeContextmenu()
+ const item = screen.getByRole('menuitem', { name: /workflow.common.copy/ })
+ act(() => item.focus())
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await user.keyboard(key.length === 1 ? `{${mod}>}${key}{/${mod}}` : `{${key}}`)
+ expect(mockClose).toHaveBeenCalledTimes(1)
+ })
+
it('should stay hidden when the node menu is absent', () => {
renderNodeContextmenu()
diff --git a/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx b/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx
index 76c5d5f876f..7a418254010 100644
--- a/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx
+++ b/web/app/components/workflow/__tests__/panel-contextmenu.spec.tsx
@@ -1,5 +1,7 @@
import { ContextMenu } from '@langgenius/dify-ui/context-menu'
-import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { act, fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { withSelectorKey } from '@/test/i18n-mock'
import { FlowType } from '@/types/common'
import { fullWorkflowAccessControl } from '../hooks-store'
@@ -182,6 +184,26 @@ describe('PanelContextmenu', () => {
expect(mockClose).not.toHaveBeenCalled()
})
+ it.each([false, true])(
+ 'handles menu paste only when clipboard is available: %s',
+ async (hasClipboard) => {
+ const user = userEvent.setup()
+ renderPanelContextmenu({
+ initialStoreState: {
+ contextMenuTarget: { type: 'panel' },
+ clipboardElements: hasClipboard ? [createNode({ id: 'copied-node' })] : [],
+ },
+ hooksStoreProps: {},
+ })
+ const item = await screen.findByRole('menuitem', { name: /common.run/ })
+ act(() => item.focus())
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await user.keyboard(`{${mod}>}v{/${mod}}`)
+ expect(mockHandleNodesPaste).toHaveBeenCalledTimes(hasClipboard ? 1 : 0)
+ expect(mockClose).toHaveBeenCalledTimes(hasClipboard ? 1 : 0)
+ },
+ )
+
it('should render actions and execute enabled actions', async () => {
const { store } = renderPanelContextmenu({
initialStoreState: {
diff --git a/web/app/components/workflow/__tests__/selection-contextmenu.spec.tsx b/web/app/components/workflow/__tests__/selection-contextmenu.spec.tsx
index 105f9089f1c..4f1b75ed5d5 100644
--- a/web/app/components/workflow/__tests__/selection-contextmenu.spec.tsx
+++ b/web/app/components/workflow/__tests__/selection-contextmenu.spec.tsx
@@ -1,6 +1,8 @@
import type { Edge, Node } from '../types'
import { ContextMenu } from '@langgenius/dify-ui/context-menu'
+import { detectPlatform } from '@tanstack/react-hotkeys'
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { useEffect } from 'react'
import { useNodes } from 'reactflow'
import { PipelineInputVarType } from '@/models/pipeline'
@@ -159,6 +161,24 @@ describe('SelectionContextmenu', () => {
mockWorkspacePermissionKeys.value = ['snippets.create_and_modify']
})
+ it.each([
+ { key: 'c', action: mockHandleNodesCopy },
+ { key: 'd', action: mockHandleNodesDuplicate },
+ { key: 'Delete', action: mockHandleNodesDelete },
+ ])('runs $key for the menu selection and closes the menu', async ({ key, action }) => {
+ const user = userEvent.setup()
+ renderSelectionMenu({
+ nodes: [createNode({ id: 'n1', selected: true }), createNode({ id: 'n2', selected: true })],
+ initialStoreState: { contextMenuTarget: { type: 'selection' } },
+ })
+ const item = await screen.findByRole('menuitem', { name: /common.copy/ })
+ act(() => item.focus())
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await user.keyboard(key.length === 1 ? `{${mod}>}${key}{/${mod}}` : `{${key}}`)
+ expect(action).toHaveBeenCalledTimes(1)
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ })
+
it('should not render when selection context menu target is absent', () => {
renderSelectionMenu()
diff --git a/web/app/components/workflow/comment/__tests__/comment-close-focus.spec.tsx b/web/app/components/workflow/comment/__tests__/comment-close-focus.spec.tsx
index a8d11c527b9..05a6411ac35 100644
--- a/web/app/components/workflow/comment/__tests__/comment-close-focus.spec.tsx
+++ b/web/app/components/workflow/comment/__tests__/comment-close-focus.spec.tsx
@@ -201,6 +201,49 @@ describe('Comment keyboard focus lifecycle', () => {
},
)
+ it.each(['actions menu', 'mention suggestions'] as const)(
+ 'closes %s before the thread and restores its marker on the next Escape',
+ async (surface) => {
+ const user = userEvent.setup()
+ const { store } = renderCommentCanvas()
+ act(() => {
+ store
+ .getState()
+ .setMentionableUsersCache('app-1', [
+ { id: 'user-2', name: 'Bob', email: '[email protected]', avatar_url: null },
+ ])
+ })
+
+ await user.tab()
+ await user.keyboard('{Enter}')
+ const reply = await screen.findByRole('textbox')
+ await waitFor(() => expect(reply).toHaveFocus())
+
+ const commentActions = screen.getByRole('button', { name: /comments.aria.commentActions/ })
+ if (surface === 'actions menu') {
+ await user.click(commentActions)
+ expect(await screen.findByRole('menu')).toBeInTheDocument()
+ } else {
+ await user.type(reply, '@Bo')
+ expect(await screen.findByText('[email protected]')).toBeInTheDocument()
+ }
+
+ await user.keyboard('{Escape}')
+ await waitFor(() => {
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ expect(screen.queryByText('[email protected]')).not.toBeInTheDocument()
+ })
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ await waitFor(() => {
+ expect(surface === 'actions menu' ? commentActions : reply).toHaveFocus()
+ })
+
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(screen.getByRole('button', { name: /keyboard.openComment/ })).toHaveFocus()
+ },
+ )
+
it('restores the last viewed comment marker after navigating to another thread', async () => {
const user = userEvent.setup()
const otherComment: WorkflowCommentList = {
diff --git a/web/app/components/workflow/comment/__tests__/comment-thread-focus.spec.tsx b/web/app/components/workflow/comment/__tests__/comment-thread-focus.spec.tsx
index 342980130eb..69a86addfe2 100644
--- a/web/app/components/workflow/comment/__tests__/comment-thread-focus.spec.tsx
+++ b/web/app/components/workflow/comment/__tests__/comment-thread-focus.spec.tsx
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { renderWithAccountProfile } from '@/test/console/account-profile'
import { CommentIcon } from '../comment-icon'
+import { CommentInput } from '../comment-input'
import { CommentThread } from '../thread'
const storeState = vi.hoisted(() => ({
@@ -53,6 +54,7 @@ const createComment = (): WorkflowCommentDetail & WorkflowCommentList => ({
describe('Comment thread focus', () => {
beforeEach(() => {
vi.clearAllMocks()
+ storeState.mentionableUsersCache['app-1'] = []
vi.useFakeTimers({ shouldAdvanceTime: true })
})
@@ -60,6 +62,32 @@ describe('Comment thread focus', () => {
vi.useRealTimers()
})
+ it.each(['draft', 'thread'] as const)(
+ 'dismisses mentions before closing the %s',
+ async (kind) => {
+ const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
+ const onClose = vi.fn()
+ storeState.mentionableUsersCache['app-1'] = [
+ { id: 'user-2', name: 'Bob', email: '[email protected]', avatar_url: null },
+ ]
+ renderWithAccountProfile(
+ kind === 'draft' ? (
+ <CommentInput position={{ x: 0, y: 0 }} onSubmit={() => {}} onCancel={onClose} />
+ ) : (
+ <CommentThread comment={createComment()} onClose={onClose} onReply={() => {}} />
+ ),
+ )
+ await user.click(screen.getByRole('textbox'))
+ await user.type(screen.getByRole('textbox'), '@')
+ expect(screen.getByText('Bob')).toBeInTheDocument()
+ await user.keyboard('{Escape}')
+ expect(screen.queryByText('Bob')).not.toBeInTheDocument()
+ expect(onClose).not.toHaveBeenCalled()
+ await user.keyboard('{Escape}')
+ expect(onClose).toHaveBeenCalledTimes(1)
+ },
+ )
+
it('keeps focus on the marker after saving a keyboard move with its thread open', async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
const onPositionUpdate = vi.fn()
@@ -95,6 +123,7 @@ describe('Comment thread focus', () => {
await user.keyboard('{Enter}')
await act(() => vi.advanceTimersByTimeAsync(100))
expect(screen.getByRole('textbox')).toHaveFocus()
+ expect(screen.getByRole('dialog')).not.toHaveAttribute('aria-modal', 'true')
act(() => marker.focus())
await user.keyboard('{ArrowRight}')
diff --git a/web/app/components/workflow/comment/comment-input.spec.tsx b/web/app/components/workflow/comment/comment-input.spec.tsx
index c85ccce73a0..a7858fcb0fe 100644
--- a/web/app/components/workflow/comment/comment-input.spec.tsx
+++ b/web/app/components/workflow/comment/comment-input.spec.tsx
@@ -125,6 +125,8 @@ describe('CommentInput', () => {
render(<CommentInput position={{ x: 0, y: 0 }} onSubmit={vi.fn()} onCancel={onCancel} />)
fireEvent.keyDown(document, { key: 'Escape' })
+ expect(onCancel).not.toHaveBeenCalled()
+ fireEvent.keyDown(screen.getByTestId('mention-input'), { key: 'Escape' })
expect(onCancel).toHaveBeenCalledTimes(1)
})
diff --git a/web/app/components/workflow/comment/comment-input.tsx b/web/app/components/workflow/comment/comment-input.tsx
index 96e1579ef5c..b213ba1d7ad 100644
--- a/web/app/components/workflow/comment/comment-input.tsx
+++ b/web/app/components/workflow/comment/comment-input.tsx
@@ -54,21 +54,6 @@ export const CommentInput: FC<CommentInputProps> = memo(
endHandler: undefined,
})
- useEffect(() => {
- const handleGlobalKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape') {
- e.preventDefault()
- e.stopPropagation()
- onCancel()
- }
- }
-
- document.addEventListener('keydown', handleGlobalKeyDown, true)
- return () => {
- document.removeEventListener('keydown', handleGlobalKeyDown, true)
- }
- }, [onCancel])
-
const handleMentionSubmit = useCallback(
(content: string, mentionedUserIds: string[]) => {
onSubmit(content, mentionedUserIds)
@@ -146,13 +131,22 @@ export const CommentInput: FC<CommentInputProps> = memo(
)
return (
+ // oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The comment surface handles bubbling Escape after its child editor handles mentions.
<div
className={cn('absolute z-40 w-96', disabled && 'pointer-events-none opacity-80')}
style={{
left: position.x,
top: position.y,
}}
+ role="group"
data-comment-input
+ onKeyDown={(event) => {
+ if (event.defaultPrevented || event.nativeEvent.isComposing || event.key !== 'Escape')
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ onCancel()
+ }}
>
<div className="flex items-center gap-3">
<IconButton
diff --git a/web/app/components/workflow/comment/placement-preview.spec.tsx b/web/app/components/workflow/comment/placement-preview.spec.tsx
new file mode 100644
index 00000000000..aa45ea15116
--- /dev/null
+++ b/web/app/components/workflow/comment/placement-preview.spec.tsx
@@ -0,0 +1,68 @@
+import { HotkeysProvider } from '@tanstack/react-hotkeys'
+import { act, fireEvent, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { renderWorkflowComponent } from '../__tests__/workflow-test-env'
+import { CommentPlacementPreview } from './placement-preview'
+
+vi.mock('next/navigation', () => ({ useParams: () => ({ appId: 'app-1' }) }))
+
+function renderPlacement(placing = true) {
+ const onCancel = vi.fn()
+ const result = renderWorkflowComponent(
+ <HotkeysProvider>
+ <button>Canvas action</button>
+ <button onKeyDown={(event) => event.preventDefault()}>Local escape owner</button>
+ <input aria-label="Node input" />
+ <CommentPlacementPreview onSubmit={vi.fn()} onCancel={onCancel} />
+ </HotkeysProvider>,
+ { initialStoreState: { isCommentPlacing: placing, mentionableUsersCache: { 'app-1': [] } } },
+ )
+ return { ...result, onCancel }
+}
+
+it('cancels pending placement from the canvas without focusing the disabled preview', async () => {
+ const user = userEvent.setup()
+ const { onCancel } = renderPlacement()
+ await user.click(screen.getByRole('button', { name: 'Canvas action' }))
+ const owner = screen.getByRole('button', { name: 'Canvas action' })
+ for (const repeat of [false, true, true]) {
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ repeat,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(owner, event)
+ expect(event.defaultPrevented).toBe(true)
+ }
+ fireEvent.keyUp(owner, { key: 'Escape' })
+ expect(onCancel).toHaveBeenCalledTimes(1)
+})
+
+it('leaves claimed, composing, and input Escape with their local owner', async () => {
+ const user = userEvent.setup()
+ const { onCancel } = renderPlacement()
+ await user.click(screen.getByRole('button', { name: 'Local escape owner' }))
+ await user.keyboard('{Escape}')
+ await user.click(screen.getByRole('textbox', { name: 'Node input' }))
+ await user.keyboard('{Escape}')
+ const canvasAction = screen.getByRole('button', { name: 'Canvas action' })
+ fireEvent.keyDown(canvasAction, { key: 'Escape', isComposing: true })
+ fireEvent.keyUp(canvasAction, { key: 'Escape' })
+ expect(onCancel).not.toHaveBeenCalled()
+})
+
+it('stops owning Escape when inactive or once the editable draft is placed', async () => {
+ const user = userEvent.setup()
+ const { store, onCancel } = renderPlacement(false)
+ await user.click(screen.getByRole('button', { name: 'Canvas action' }))
+ await user.keyboard('{Escape}')
+ act(() =>
+ store.setState({
+ isCommentPlacing: true,
+ pendingComment: { pageX: 0, pageY: 0, elementX: 0, elementY: 0 },
+ }),
+ )
+ await user.keyboard('{Escape}')
+ expect(onCancel).not.toHaveBeenCalled()
+})
diff --git a/web/app/components/workflow/comment/placement-preview.tsx b/web/app/components/workflow/comment/placement-preview.tsx
new file mode 100644
index 00000000000..5fc20cd3b61
--- /dev/null
+++ b/web/app/components/workflow/comment/placement-preview.tsx
@@ -0,0 +1,45 @@
+import { useHotkey } from '@tanstack/react-hotkeys'
+import { useStore } from '../store/workflow'
+import { CommentInput } from './comment-input'
+
+export function CommentPlacementPreview({
+ onSubmit,
+ onCancel,
+}: {
+ onSubmit: (content: string, mentionedUserIds: string[]) => void
+ onCancel: () => void
+}) {
+ const isCommentPlacing = useStore((state) => state.isCommentPlacing)
+ const pendingComment = useStore((state) => state.pendingComment)
+ const mousePosition = useStore((state) => state.mousePosition)
+ const placing = isCommentPlacing && !pendingComment
+
+ useHotkey(
+ 'Escape',
+ (event) => {
+ if (event.defaultPrevented || event.isComposing) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ onCancel()
+ },
+ {
+ enabled: placing,
+ ignoreInputs: true,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
+
+ if (!placing) return null
+
+ return (
+ <CommentInput
+ position={{ x: mousePosition.elementX, y: mousePosition.elementY }}
+ onSubmit={onSubmit}
+ onCancel={onCancel}
+ autoFocus={false}
+ disabled
+ />
+ )
+}
diff --git a/web/app/components/workflow/comment/thread.spec.tsx b/web/app/components/workflow/comment/thread.spec.tsx
index 3ce23a9d886..478e11e51c9 100644
--- a/web/app/components/workflow/comment/thread.spec.tsx
+++ b/web/app/components/workflow/comment/thread.spec.tsx
@@ -161,6 +161,8 @@ describe('CommentThread', () => {
fireEvent.click(screen.getByLabelText('workflowComments.comments.aria.closeComment'))
fireEvent.keyDown(document, { key: 'Escape' })
+ expect(onClose).toHaveBeenCalledTimes(1)
+ fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' })
expect(onDelete).toHaveBeenCalledTimes(1)
expect(onResolve).toHaveBeenCalledTimes(1)
diff --git a/web/app/components/workflow/comment/thread.tsx b/web/app/components/workflow/comment/thread.tsx
index 992f1fae2ad..53ec2235a89 100644
--- a/web/app/components/workflow/comment/thread.tsx
+++ b/web/app/components/workflow/comment/thread.tsx
@@ -201,7 +201,6 @@ export const CommentThread: FC<CommentThreadProps> = memo(
// Focus management refs
const replyInputRef = useRef<HTMLTextAreaElement>(null)
- const threadRef = useRef<HTMLDivElement>(null)
// Get mentionable users from store
const mentionUsersFromStore = useStore((state) =>
@@ -248,26 +247,6 @@ export const CommentThread: FC<CommentThreadProps> = memo(
return () => clearTimeout(timer)
}, [comment.id, editingReply.id, isCommentEditing, canReply])
- // P2: Handle Esc key to close thread
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- // Don't intercept if actively editing a reply
- if (editingReply.id || isCommentEditing) return
-
- // Don't intercept if mention dropdown is open (let MentionInput handle it)
- if (document.querySelector('[data-mention-dropdown]')) return
-
- if (e.key === 'Escape') {
- e.preventDefault()
- e.stopPropagation()
- onClose()
- }
- }
-
- document.addEventListener('keydown', handleKeyDown, true)
- return () => document.removeEventListener('keydown', handleKeyDown, true)
- }, [onClose, editingReply.id, isCommentEditing])
-
const handleReplySubmit = useCallback(
async (content: string, mentionedUserIds: string[]) => {
if (!onReply || replySubmitting) return
@@ -448,11 +427,18 @@ export const CommentThread: FC<CommentThreadProps> = memo(
onMouseEnter={() => setCommentPreviewHovering(true)}
onMouseLeave={() => setCommentPreviewHovering(false)}
>
+ {/* oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The thread handles bubbling Escape after its child editor and menus have handled it. */}
<div
- ref={threadRef}
+ onKeyDown={(event) => {
+ if (event.defaultPrevented || event.nativeEvent.isComposing || event.key !== 'Escape')
+ return
+ if (editingReply.id || isCommentEditing) return
+ event.preventDefault()
+ event.stopPropagation()
+ onClose()
+ }}
className="relative flex h-90 flex-col overflow-hidden rounded-2xl border border-components-panel-border bg-components-panel-bg shadow-xl"
role="dialog"
- aria-modal="true"
aria-labelledby="comment-thread-title"
>
<div className="flex items-center justify-between rounded-t-2xl border-b border-components-panel-border bg-components-panel-bg-blur px-4 py-3">
diff --git a/web/app/components/workflow/edge-contextmenu.tsx b/web/app/components/workflow/edge-contextmenu.tsx
index 87d7378fe4f..9039f5ae1f6 100644
--- a/web/app/components/workflow/edge-contextmenu.tsx
+++ b/web/app/components/workflow/edge-contextmenu.tsx
@@ -2,6 +2,8 @@ import { ContextMenuContent, ContextMenuItem } from '@langgenius/dify-ui/context
import { useTranslation } from 'react-i18next'
import { useEdges } from 'reactflow'
import { useEdgesInteractions } from './hooks/use-edges-interactions'
+import { useNodesReadOnly } from './hooks/use-workflow'
+import { handleWorkflowMenuKeyDown } from './shortcuts/handle-workflow-menu-key-down'
import { ShortcutKbd } from './shortcuts/shortcut-kbd'
import { useStore } from './store'
@@ -10,20 +12,30 @@ export function EdgeContextmenu({ onClose }: { onClose: () => void }) {
const contextMenuTarget = useStore((s) => s.contextMenuTarget)
const edgeId = contextMenuTarget?.type === 'edge' ? contextMenuTarget.edgeId : undefined
const { handleEdgeDeleteById } = useEdgesInteractions()
+ const { getNodesReadOnly } = useNodesReadOnly()
const edges = useEdges()
const currentEdgeExists = !edgeId || edges.some((edge) => edge.id === edgeId)
if (!edgeId || !currentEdgeExists) return null
+ const deleteEdge = () => {
+ handleEdgeDeleteById(edgeId)
+ onClose()
+ }
+
return (
- <ContextMenuContent className="rounded-lg" sideOffset={4}>
+ <ContextMenuContent
+ className="rounded-lg"
+ sideOffset={4}
+ onKeyDown={(event) => {
+ if (getNodesReadOnly()) return
+ handleWorkflowMenuKeyDown(event, [['workflow.delete', deleteEdge]])
+ }}
+ >
<ContextMenuItem
variant="destructive"
className="justify-between gap-4 px-3"
- onClick={() => {
- handleEdgeDeleteById(edgeId)
- onClose()
- }}
+ onClick={deleteEdge}
>
<span>{t(($) => $['operation.delete'], { ns: 'common' })}</span>
<ShortcutKbd shortcut="workflow.delete" />
diff --git a/web/app/components/workflow/header/__tests__/run-mode.spec.tsx b/web/app/components/workflow/header/__tests__/run-mode.spec.tsx
index fe67929d905..498aad823da 100644
--- a/web/app/components/workflow/header/__tests__/run-mode.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/run-mode.spec.tsx
@@ -1,6 +1,7 @@
import type { ReactNode } from 'react'
import type { TestRunMenuRef } from '../test-run-menu'
import { fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
import RunMode from '../run-mode'
@@ -14,16 +15,7 @@ const mockHandleWorkflowRunAllTriggersInWorkflow = vi.fn()
const mockHandleStopRun = vi.fn()
const mockNotify = vi.fn()
const mockTrackEvent = vi.fn()
-const hotkeyRegistrations = vi.hoisted(
- () =>
- new Map<
- string,
- {
- callback: () => void
- options?: { ignoreInputs?: boolean }
- }
- >(),
-)
+const mockToggleMenu = vi.fn()
let mockWarningNodes: Array<{ id: string }> = []
let mockWorkflowRunningData:
@@ -85,16 +77,6 @@ vi.mock('@/app/components/workflow/hooks-store', () => ({
}),
}))
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (hotkey: string, callback: () => void, options?: { ignoreInputs?: boolean }) => {
- hotkeyRegistrations.set(hotkey, { callback, options })
- },
- }
-})
-
vi.mock('../../hooks/use-dynamic-test-run-options', () => ({
useDynamicTestRunOptions: () => mockDynamicOptions,
}))
@@ -134,7 +116,7 @@ vi.mock('../test-run-menu', async (importOriginal) => {
ref?: React.Ref<TestRunMenuRef>
}) => {
React.useImperativeHandle(ref, () => ({
- toggle: vi.fn(),
+ toggle: mockToggleMenu,
}))
return (
<div>
@@ -159,7 +141,6 @@ describe('RunMode', () => {
mockWorkflowRunningData = undefined
mockIsListening = false
mockCanRun = true
- hotkeyRegistrations.clear()
mockDynamicOptions = [{ type: TriggerType.UserInput, nodeId: 'start-node' }]
})
@@ -212,12 +193,33 @@ describe('RunMode', () => {
expect(screen.getByText(/listening/i))!.toBeInTheDocument()
})
- it('should register the test run menu shortcut as a page command outside text inputs', () => {
- render(<RunMode />)
-
- expect(hotkeyRegistrations.get('Alt+R')?.options).toEqual(
- expect.objectContaining({ ignoreInputs: true }),
+ it('opens the test run menu from the page but not an input, handled key, or disabled trigger', async () => {
+ const user = userEvent.setup()
+ const { rerender } = render(
+ <>
+ <RunMode />
+ <input aria-label="Prompt" />
+ <button onKeyDown={(event) => event.preventDefault()}>Local control</button>
+ </>,
)
+ const runKeyEvents: KeyboardEvent[] = []
+ const recordRunKeys = (event: KeyboardEvent) => {
+ if (event.key === 'r') runKeyEvents.push(event)
+ }
+ document.addEventListener('keydown', recordRunKeys)
+ await user.keyboard('{Alt>}{r>3/}{/Alt}')
+ document.removeEventListener('keydown', recordRunKeys)
+ expect(runKeyEvents).toHaveLength(3)
+ expect(runKeyEvents.every((event) => event.defaultPrevented)).toBe(true)
+ expect(mockToggleMenu).toHaveBeenCalledTimes(1)
+ await user.click(screen.getByRole('textbox', { name: 'Prompt' }))
+ await user.keyboard('{Alt>}r{/Alt}')
+ await user.click(screen.getByRole('button', { name: 'Local control' }))
+ await user.keyboard('{Alt>}r{/Alt}')
+ expect(mockToggleMenu).toHaveBeenCalledTimes(1)
+ rerender(<RunMode disabled />)
+ await user.keyboard('{Alt>}r{/Alt}')
+ expect(mockToggleMenu).toHaveBeenCalledTimes(1)
})
it('should keep the run trigger visible and disabled when workflow run permission is denied', () => {
diff --git a/web/app/components/workflow/header/__tests__/test-run-menu-helpers.spec.tsx b/web/app/components/workflow/header/__tests__/test-run-menu-helpers.spec.tsx
index de2e8c94238..c5cf8963cc9 100644
--- a/web/app/components/workflow/header/__tests__/test-run-menu-helpers.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/test-run-menu-helpers.spec.tsx
@@ -1,14 +1,9 @@
import type { TriggerOption } from '../test-run-menu'
import { DropdownMenu, DropdownMenuContent } from '@langgenius/dify-ui/dropdown-menu'
-import { fireEvent, render, renderHook, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { TriggerType } from '../test-run-menu'
-import {
- getNormalizedShortcutKey,
- OptionRow,
- SingleOptionTrigger,
- useShortcutMenu,
-} from '../test-run-menu-helpers'
+import { getNormalizedShortcutKey, OptionRow, SingleOptionTrigger } from '../test-run-menu-helpers'
const createOption = (overrides: Partial<TriggerOption> = {}): TriggerOption => ({
id: 'user-input',
@@ -47,42 +42,6 @@ describe('test-run-menu helpers', () => {
expect(onSelect).toHaveBeenCalledWith(option)
})
- it('should handle shortcut key presses only when the menu is open and the event is eligible', () => {
- const handleSelect = vi.fn()
- const option = createOption({ id: 'run-all', type: TriggerType.All, name: 'Run All' })
-
- const { rerender, unmount } = renderHook(
- ({ open }) =>
- useShortcutMenu({
- open,
- shortcutMappings: [{ option, shortcutKey: '~' }],
- handleSelect,
- }),
- {
- initialProps: { open: true },
- },
- )
-
- fireEvent.keyDown(window, { key: '`' })
- fireEvent.keyDown(window, { key: '`', altKey: true })
- fireEvent.keyDown(window, { key: '`', repeat: true })
-
- const preventedEvent = new KeyboardEvent('keydown', { key: '`', cancelable: true })
- preventedEvent.preventDefault()
- window.dispatchEvent(preventedEvent)
-
- expect(handleSelect).toHaveBeenCalledTimes(1)
- expect(handleSelect).toHaveBeenCalledWith(option)
-
- rerender({ open: false })
- fireEvent.keyDown(window, { key: '`' })
- expect(handleSelect).toHaveBeenCalledTimes(1)
-
- unmount()
- fireEvent.keyDown(window, { key: '`' })
- expect(handleSelect).toHaveBeenCalledTimes(1)
- })
-
it('should run single options for element and non-element children unless the click is prevented', async () => {
const user = userEvent.setup()
const runSoleOption = vi.fn()
diff --git a/web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx b/web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx
index cfbd49b1cb7..2eaf5319ad1 100644
--- a/web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/test-run-menu.spec.tsx
@@ -79,11 +79,36 @@ describe('TestRunMenu', () => {
})
expect(screen.getByText('~')).toBeInTheDocument()
- fireEvent.keyDown(window, { key: '0' })
+ fireEvent.keyDown(screen.getByRole('menu'), { key: '0' })
expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'run-all' }))
})
+ it('keeps menu accelerators local and ignores composition and modified keys', async () => {
+ const user = userEvent.setup()
+ const onSelect = vi.fn()
+ render(
+ <TestRunMenu
+ options={{
+ userInput: createOption(),
+ triggers: [createOption({ id: 'trigger', name: 'Webhook', type: TriggerType.Webhook })],
+ }}
+ onSelect={onSelect}
+ >
+ <button>Open menu</button>
+ </TestRunMenu>,
+ )
+ await user.click(screen.getByRole('button', { name: 'Open menu' }))
+ const menu = screen.getByRole('menu')
+ fireEvent.keyDown(document.body, { key: '0' })
+ fireEvent.keyDown(menu, { key: '0', isComposing: true })
+ fireEvent.keyDown(menu, { key: '0', ctrlKey: true })
+ fireEvent.keyDown(menu, { key: '0', repeat: true })
+ expect(onSelect).not.toHaveBeenCalled()
+ fireEvent.keyDown(menu, { key: '0' })
+ expect(onSelect).toHaveBeenCalledWith(expect.objectContaining({ id: 'trigger' }))
+ })
+
it('should ignore disabled options in the rendered menu', async () => {
const user = userEvent.setup()
diff --git a/web/app/components/workflow/header/__tests__/version-history-button.spec.tsx b/web/app/components/workflow/header/__tests__/version-history-button.spec.tsx
index f0b59300fba..a23c93a5183 100644
--- a/web/app/components/workflow/header/__tests__/version-history-button.spec.tsx
+++ b/web/app/components/workflow/header/__tests__/version-history-button.spec.tsx
@@ -1,39 +1,18 @@
-import { act, fireEvent, render, screen } from '@testing-library/react'
+import { HotkeysProvider } from '@tanstack/react-hotkeys'
+import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { VersionHistoryButton } from '../version-history-button'
let mockTheme: 'light' | 'dark' = 'light'
-const hotkeyRegistrations = vi.hoisted(
- () =>
- new Map<
- string,
- {
- callback: () => void
- options?: { ignoreInputs?: boolean }
- }
- >(),
-)
-
vi.mock('@/hooks/use-theme', () => ({
default: () => ({
theme: mockTheme,
}),
}))
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (hotkey: string, callback: () => void, options?: { ignoreInputs?: boolean }) => {
- hotkeyRegistrations.set(hotkey, { callback, options })
- },
- }
-})
-
describe('VersionHistoryButton', () => {
beforeEach(() => {
vi.clearAllMocks()
- hotkeyRegistrations.clear()
mockTheme = 'light'
})
@@ -46,18 +25,35 @@ describe('VersionHistoryButton', () => {
expect(onClick).toHaveBeenCalledTimes(1)
})
- it('should trigger onClick when the version history shortcut is pressed', async () => {
+ it('opens history once per press from the page and respects editable and handled keys', async () => {
+ const user = userEvent.setup()
const onClick = vi.fn()
- render(<VersionHistoryButton onClick={onClick} />)
-
- await act(async () => {
- hotkeyRegistrations.get('Mod+Shift+H')?.callback()
- })
-
- expect(onClick).toHaveBeenCalledTimes(1)
- expect(hotkeyRegistrations.get('Mod+Shift+H')?.options).toEqual(
- expect.objectContaining({ ignoreInputs: true }),
+ render(
+ <HotkeysProvider defaultOptions={{ hotkey: { platform: 'windows' } }}>
+ <VersionHistoryButton onClick={onClick} />
+ <input aria-label="Prompt" />
+ <button onKeyDown={(event) => event.preventDefault()}>Local control</button>
+ </HotkeysProvider>,
)
+ for (const repeat of [false, true, true]) {
+ const event = new KeyboardEvent('keydown', {
+ key: 'h',
+ ctrlKey: true,
+ shiftKey: true,
+ repeat,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(document.body, event)
+ expect(event.defaultPrevented).toBe(true)
+ }
+ fireEvent.keyUp(document.body, { key: 'h', ctrlKey: true, shiftKey: true })
+ expect(onClick).toHaveBeenCalledTimes(1)
+ await user.click(screen.getByRole('textbox', { name: 'Prompt' }))
+ await user.keyboard('{Control>}{Shift>}h{/Shift}{/Control}')
+ await user.click(screen.getByRole('button', { name: 'Local control' }))
+ await user.keyboard('{Control>}{Shift>}h{/Shift}{/Control}')
+ expect(onClick).toHaveBeenCalledTimes(1)
})
it('should render the tooltip popup content on hover', async () => {
diff --git a/web/app/components/workflow/header/run-mode.tsx b/web/app/components/workflow/header/run-mode.tsx
index ce662b9f9ea..10ecf09458d 100644
--- a/web/app/components/workflow/header/run-mode.tsx
+++ b/web/app/components/workflow/header/run-mode.tsx
@@ -56,9 +56,22 @@ const RunMode = ({ text, disabled = false }: RunModeProps) => {
testRunMenuRef.current?.toggle()
}, [isRunDisabled])
- useHotkey(TEST_RUN_MENU_HOTKEY, handleToggleTestRunMenu, {
- ignoreInputs: true,
- })
+ useHotkey(
+ TEST_RUN_MENU_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ handleToggleTestRunMenu()
+ },
+ {
+ enabled: !isRunDisabled,
+ preventDefault: false,
+ stopPropagation: false,
+ ignoreInputs: true,
+ },
+ )
const handleStop = useCallback(() => {
handleStopRun(workflowRunningData?.task_id || '')
diff --git a/web/app/components/workflow/header/test-run-menu-helpers.tsx b/web/app/components/workflow/header/test-run-menu-helpers.tsx
index 90b2f1a6c81..66b691b3c94 100644
--- a/web/app/components/workflow/header/test-run-menu-helpers.tsx
+++ b/web/app/components/workflow/header/test-run-menu-helpers.tsx
@@ -1,7 +1,7 @@
-import type { MouseEvent, MouseEventHandler, ReactElement } from 'react'
+import type { KeyboardEvent, MouseEvent, MouseEventHandler, ReactElement } from 'react'
import type { TriggerOption } from './test-run-menu'
import { DropdownMenuItem } from '@langgenius/dify-ui/dropdown-menu'
-import { cloneElement, isValidElement, useEffect } from 'react'
+import { cloneElement, isValidElement } from 'react'
import { ShortcutKbd } from '../shortcuts/shortcut-kbd'
export type ShortcutMapping = {
@@ -9,7 +9,7 @@ export type ShortcutMapping = {
shortcutKey: string
}
-export const getNormalizedShortcutKey = (event: KeyboardEvent) => {
+export const getNormalizedShortcutKey = (event: Pick<KeyboardEvent, 'key'>) => {
return event.key === '`' ? '~' : event.key
}
@@ -38,36 +38,28 @@ export const OptionRow = ({
)
}
-export const useShortcutMenu = ({
- open,
- shortcutMappings,
- handleSelect,
-}: {
- open: boolean
- shortcutMappings: ShortcutMapping[]
- handleSelect: (option: TriggerOption) => void
-}) => {
- useEffect(() => {
- if (!open) return
-
- const handleKeyDown = (event: KeyboardEvent) => {
- if (event.defaultPrevented || event.repeat || event.altKey || event.ctrlKey || event.metaKey)
- return
-
- const normalizedKey = getNormalizedShortcutKey(event)
- const mapping = shortcutMappings.find(({ shortcutKey }) => shortcutKey === normalizedKey)
+export function handleShortcutMenuKeyDown(
+ event: KeyboardEvent,
+ shortcutMappings: ShortcutMapping[],
+ onSelect: (option: TriggerOption) => void,
+) {
+ if (
+ event.defaultPrevented ||
+ event.nativeEvent.isComposing ||
+ event.repeat ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey
+ )
+ return
- if (mapping) {
- event.preventDefault()
- handleSelect(mapping.option)
- }
- }
+ const normalizedKey = getNormalizedShortcutKey(event)
+ const mapping = shortcutMappings.find(({ shortcutKey }) => shortcutKey === normalizedKey)
+ if (!mapping) return
- window.addEventListener('keydown', handleKeyDown)
- return () => {
- window.removeEventListener('keydown', handleKeyDown)
- }
- }, [handleSelect, open, shortcutMappings])
+ event.preventDefault()
+ event.stopPropagation()
+ onSelect(mapping.option)
}
export const SingleOptionTrigger = ({
diff --git a/web/app/components/workflow/header/test-run-menu.tsx b/web/app/components/workflow/header/test-run-menu.tsx
index b931bd8abe0..34c570936c6 100644
--- a/web/app/components/workflow/header/test-run-menu.tsx
+++ b/web/app/components/workflow/header/test-run-menu.tsx
@@ -16,7 +16,7 @@ import {
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
-import { OptionRow, SingleOptionTrigger, useShortcutMenu } from './test-run-menu-helpers'
+import { handleShortcutMenuKeyDown, OptionRow, SingleOptionTrigger } from './test-run-menu-helpers'
export const TriggerType = {
UserInput: 'user_input',
@@ -84,7 +84,7 @@ const buildShortcutMappings = (options: TestRunOptions): ShortcutMapping[] => {
mappings.push({ option: options.runAll, shortcutKey: String(numericShortcut++) })
options.triggers.forEach((trigger) => {
- if (trigger.enabled !== false)
+ if (trigger.enabled !== false && numericShortcut < 10)
mappings.push({ option: trigger, shortcutKey: String(numericShortcut++) })
})
@@ -122,12 +122,6 @@ const TestRunMenu = forwardRef<TestRunMenuRef, TestRunMenuProps>(
if (soleEnabledOption) handleSelect(soleEnabledOption)
}, [handleSelect, soleEnabledOption])
- useShortcutMenu({
- open,
- shortcutMappings,
- handleSelect,
- })
-
useImperativeHandle(
ref,
() => ({
@@ -171,6 +165,7 @@ const TestRunMenu = forwardRef<TestRunMenuRef, TestRunMenuProps>(
<DropdownMenuTrigger style={{ userSelect: 'none' }}>{children}</DropdownMenuTrigger>
)}
<DropdownMenuContent
+ onKeyDown={(event) => handleShortcutMenuKeyDown(event, shortcutMappings, handleSelect)}
placement="bottom-start"
sideOffset={8}
alignOffset={-4}
diff --git a/web/app/components/workflow/header/version-history-button.tsx b/web/app/components/workflow/header/version-history-button.tsx
index 0d2de1059d1..9095ea0fcea 100644
--- a/web/app/components/workflow/header/version-history-button.tsx
+++ b/web/app/components/workflow/header/version-history-button.tsx
@@ -18,11 +18,17 @@ export function VersionHistoryButton({ onClick }: VersionHistoryButtonProps) {
useHotkey(
VERSION_HISTORY_HOTKEY,
- () => {
+ (event) => {
+ if (event.defaultPrevented) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
void onClick()
},
{
ignoreInputs: true,
+ preventDefault: false,
+ stopPropagation: false,
},
)
diff --git a/web/app/components/workflow/hooks/__tests__/use-shortcuts.spec.ts b/web/app/components/workflow/hooks/__tests__/use-shortcuts.spec.ts
deleted file mode 100644
index f58b8e25f73..00000000000
--- a/web/app/components/workflow/hooks/__tests__/use-shortcuts.spec.ts
+++ /dev/null
@@ -1,285 +0,0 @@
-import { renderWorkflowHook } from '../../__tests__/workflow-test-env'
-import { useWorkflowHotkeys } from '../../shortcuts/use-workflow-hotkeys'
-
-type KeyPressRegistration = {
- keyFilter: unknown
- handler: (event: KeyboardEvent) => void
- options?: {
- events?: string[]
- enabled?: boolean
- ignoreInputs?: boolean
- preventDefault?: boolean
- stopPropagation?: boolean
- meta?: {
- scope?: string
- }
- }
-}
-
-type ReactFlowNodeMock = {
- id: string
- data: {
- _isBundled?: boolean
- }
-}
-
-type HotkeyDefinitionMock = {
- hotkey: unknown
- callback: (event: KeyboardEvent) => void
- options?: KeyPressRegistration['options'] & { eventType?: 'keydown' | 'keyup' }
-}
-
-const keyPressRegistrations = vi.hoisted<KeyPressRegistration[]>(() => [])
-const mockZoomTo = vi.hoisted(() => vi.fn())
-const mockGetZoom = vi.hoisted(() => vi.fn(() => 1))
-const mockFitView = vi.hoisted(() => vi.fn())
-const mockGetNodes = vi.hoisted(() => vi.fn<() => ReactFlowNodeMock[]>(() => []))
-const mockHandleNodesDelete = vi.hoisted(() => vi.fn())
-const mockHandleEdgeDelete = vi.hoisted(() => vi.fn())
-const mockHandleNodesCopy = vi.hoisted(() => vi.fn())
-const mockHandleNodesPaste = vi.hoisted(() => vi.fn())
-const mockHandleNodesDuplicate = vi.hoisted(() => vi.fn())
-const mockHandleHistoryBack = vi.hoisted(() => vi.fn())
-const mockHandleHistoryForward = vi.hoisted(() => vi.fn())
-const mockDimOtherNodes = vi.hoisted(() => vi.fn())
-const mockUndimAllNodes = vi.hoisted(() => vi.fn())
-const mockHandleSyncWorkflowDraft = vi.hoisted(() => vi.fn())
-const mockHandleModeHand = vi.hoisted(() => vi.fn())
-const mockHandleModePointer = vi.hoisted(() => vi.fn())
-const mockHandleModeComment = vi.hoisted(() => vi.fn())
-const mockHandleLayout = vi.hoisted(() => vi.fn())
-const mockUseKeyHold = vi.hoisted(() => vi.fn(() => false))
-
-vi.mock('@tanstack/react-hotkeys', () => {
- const useHotkeys = (
- definitions: HotkeyDefinitionMock[],
- commonOptions?: KeyPressRegistration['options'],
- ) => {
- definitions.forEach((definition) => {
- keyPressRegistrations.push({
- keyFilter: definition.hotkey,
- handler: definition.callback,
- options: {
- ...commonOptions,
- ...definition.options,
- events: definition.options?.eventType ? [definition.options.eventType] : undefined,
- },
- })
- })
- }
-
- return {
- useHotkeys,
- useKeyHold: mockUseKeyHold,
- }
-})
-
-vi.mock('reactflow', () => ({
- useReactFlow: () => ({
- zoomTo: mockZoomTo,
- getZoom: mockGetZoom,
- fitView: mockFitView,
- getNodes: mockGetNodes,
- }),
-}))
-
-vi.mock('../use-nodes-interactions', () => ({
- useNodesInteractions: () => ({
- handleNodesCopy: mockHandleNodesCopy,
- handleNodesPaste: mockHandleNodesPaste,
- handleNodesDuplicate: mockHandleNodesDuplicate,
- handleNodesDelete: mockHandleNodesDelete,
- handleHistoryBack: mockHandleHistoryBack,
- handleHistoryForward: mockHandleHistoryForward,
- dimOtherNodes: mockDimOtherNodes,
- undimAllNodes: mockUndimAllNodes,
- }),
-}))
-
-vi.mock('../use-edges-interactions', () => ({
- useEdgesInteractions: () => ({
- handleEdgeDelete: mockHandleEdgeDelete,
- }),
-}))
-
-vi.mock('../use-nodes-sync-draft', () => ({
- useNodesSyncDraft: () => ({
- handleSyncWorkflowDraft: mockHandleSyncWorkflowDraft,
- }),
-}))
-
-vi.mock('../use-workflow-panel-interactions', () => ({
- useWorkflowMoveMode: () => ({
- handleModeHand: mockHandleModeHand,
- handleModePointer: mockHandleModePointer,
- handleModeComment: mockHandleModeComment,
- isCommentModeAvailable: true,
- }),
-}))
-
-vi.mock('../use-workflow-organize', () => ({
- useWorkflowOrganize: () => ({
- handleLayout: mockHandleLayout,
- }),
-}))
-
-const createKeyboardEvent = (target: HTMLElement = document.body) =>
- ({
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- target,
- }) as unknown as KeyboardEvent
-
-const createSelectionMock = (commonAncestorContainer: Node): Selection =>
- ({
- isCollapsed: false,
- rangeCount: 1,
- getRangeAt: () =>
- ({
- commonAncestorContainer,
- }) as unknown as Range,
- }) as unknown as Selection
-
-const findRegistration = (matcher: (registration: KeyPressRegistration) => boolean) => {
- const registration = keyPressRegistrations.find(matcher)
- expect(registration).toBeDefined()
- return registration as KeyPressRegistration
-}
-
-const isEditableTarget = (target: EventTarget | null) => {
- return (
- target instanceof HTMLInputElement ||
- target instanceof HTMLTextAreaElement ||
- target instanceof HTMLSelectElement ||
- (target instanceof HTMLElement && target.isContentEditable)
- )
-}
-
-const triggerShortcut = (
- registration: KeyPressRegistration,
- event: KeyboardEvent = createKeyboardEvent(),
-) => {
- if (registration.options?.enabled === false) return
-
- if (registration.options?.ignoreInputs !== false && isEditableTarget(event.target)) return
-
- if (registration.options?.preventDefault !== false) event.preventDefault()
-
- if (registration.options?.stopPropagation !== false) event.stopPropagation()
-
- registration.handler(event)
-}
-
-describe('useShortcuts', () => {
- beforeEach(() => {
- keyPressRegistrations.length = 0
- vi.clearAllMocks()
- mockUseKeyHold.mockReturnValue(false)
- mockGetNodes.mockReturnValue([])
- })
-
- it('deletes selected nodes and edges only outside editable inputs', () => {
- renderWorkflowHook(() => useWorkflowHotkeys())
-
- const deleteShortcut = findRegistration((registration) => registration.keyFilter === 'Delete')
- expect(deleteShortcut.options?.meta).toEqual(
- expect.objectContaining({ scope: 'workflow-canvas' }),
- )
-
- const bodyEvent = createKeyboardEvent()
- triggerShortcut(deleteShortcut, bodyEvent)
-
- expect(bodyEvent.preventDefault).toHaveBeenCalled()
- expect(mockHandleNodesDelete).toHaveBeenCalledTimes(1)
- expect(mockHandleEdgeDelete).toHaveBeenCalledTimes(1)
-
- const inputEvent = createKeyboardEvent(document.createElement('input'))
- triggerShortcut(deleteShortcut, inputEvent)
-
- expect(mockHandleNodesDelete).toHaveBeenCalledTimes(1)
- expect(mockHandleEdgeDelete).toHaveBeenCalledTimes(1)
- })
-
- it('runs layout and zoom shortcuts through the workflow actions', () => {
- renderWorkflowHook(() => useWorkflowHotkeys())
-
- const layoutShortcut = findRegistration((registration) => registration.keyFilter === 'Mod+O')
- const fitViewShortcut = findRegistration((registration) => registration.keyFilter === 'Mod+1')
- const halfZoomShortcut = findRegistration(
- (registration) => registration.keyFilter === 'Shift+5',
- )
- const zoomOutShortcut = findRegistration((registration) => registration.keyFilter === 'Mod+-')
- const zoomInShortcut = findRegistration((registration) => registration.keyFilter === 'Mod+=')
-
- triggerShortcut(layoutShortcut)
- triggerShortcut(fitViewShortcut)
- triggerShortcut(halfZoomShortcut)
- triggerShortcut(zoomOutShortcut)
- triggerShortcut(zoomInShortcut)
-
- expect(mockHandleLayout).toHaveBeenCalledTimes(1)
- expect(mockFitView).toHaveBeenCalledTimes(1)
- expect(mockZoomTo).toHaveBeenNthCalledWith(1, 0.5)
- expect(mockZoomTo).toHaveBeenNthCalledWith(2, 0.9)
- expect(mockZoomTo).toHaveBeenNthCalledWith(3, 1.1)
- expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledTimes(4)
- })
-
- it('copies bundled nodes even when an incidental text selection exists outside the workflow canvas', () => {
- const getSelectionSpy = vi.spyOn(document, 'getSelection')
- const textContainer = document.createElement('div')
- const selectedText = document.createElement('span')
- selectedText.textContent = 'Selected browser text'
- textContainer.appendChild(selectedText)
-
- getSelectionSpy.mockReturnValue(createSelectionMock(selectedText))
- mockGetNodes.mockReturnValue([
- {
- id: 'bundled-node',
- data: {
- _isBundled: true,
- },
- },
- ])
-
- renderWorkflowHook(() => useWorkflowHotkeys())
-
- const copyShortcut = findRegistration((registration) => registration.keyFilter === 'Mod+C')
- const event = createKeyboardEvent()
- triggerShortcut(copyShortcut, event)
-
- expect(event.preventDefault).toHaveBeenCalled()
- expect(mockHandleNodesCopy).toHaveBeenCalledTimes(1)
-
- getSelectionSpy.mockRestore()
- })
-
- it('dims while shift is held and undims when released', () => {
- const { rerender } = renderWorkflowHook(() => useWorkflowHotkeys())
-
- mockUseKeyHold.mockReturnValue(true)
- rerender()
-
- mockUseKeyHold.mockReturnValue(false)
- rerender()
-
- expect(mockDimOtherNodes).toHaveBeenCalledTimes(1)
- expect(mockUndimAllNodes).toHaveBeenCalledTimes(1)
- })
-
- it('does not dim when shift is held inside editable inputs', () => {
- const input = document.createElement('input')
- document.body.appendChild(input)
- input.focus()
-
- const { rerender } = renderWorkflowHook(() => useWorkflowHotkeys())
-
- mockUseKeyHold.mockReturnValue(true)
- rerender()
-
- expect(mockDimOtherNodes).not.toHaveBeenCalled()
- expect(mockUndimAllNodes).not.toHaveBeenCalled()
-
- input.remove()
- })
-})
diff --git a/web/app/components/workflow/hotkeys.ts b/web/app/components/workflow/hotkeys.ts
index f3288ab0ee7..86d954abe16 100644
--- a/web/app/components/workflow/hotkeys.ts
+++ b/web/app/components/workflow/hotkeys.ts
@@ -1,19 +1,4 @@
import type { Hotkey } from '@tanstack/react-hotkeys'
-import { matchesKeyboardEvent } from '@tanstack/react-hotkeys'
-import { WORKFLOW_CANVAS_SHORTCUTS } from './shortcuts/definitions'
export const TEST_RUN_MENU_HOTKEY = 'Alt+R' satisfies Hotkey
export const VERSION_HISTORY_HOTKEY = 'Mod+Shift+H' satisfies Hotkey
-
-const WORKFLOW_BROWSER_DEFAULT_GUARD_HOTKEYS = [
- ...WORKFLOW_CANVAS_SHORTCUTS['workflow.duplicate'].hotkeys,
- ...WORKFLOW_CANVAS_SHORTCUTS['workflow.undo'].hotkeys,
- ...WORKFLOW_CANVAS_SHORTCUTS['workflow.redo'].hotkeys,
- 'Mod+S',
-] satisfies readonly Hotkey[]
-
-export function shouldPreventWorkflowBrowserDefault(event: KeyboardEvent) {
- return WORKFLOW_BROWSER_DEFAULT_GUARD_HOTKEYS.some((hotkey) =>
- matchesKeyboardEvent(event, hotkey),
- )
-}
diff --git a/web/app/components/workflow/index.tsx b/web/app/components/workflow/index.tsx
index 486d66fcf80..293df78ec12 100644
--- a/web/app/components/workflow/index.tsx
+++ b/web/app/components/workflow/index.tsx
@@ -35,7 +35,7 @@ import {
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
-import ReactFlow, {
+import {
Background,
ReactFlowProvider,
SelectionMode,
@@ -63,6 +63,7 @@ import CommentManager from './comment-manager'
import { CommentIcon } from './comment/comment-icon'
import { CommentInput } from './comment/comment-input'
import { CommentCursor } from './comment/cursor'
+import { CommentPlacementPreview } from './comment/placement-preview'
import { CommentThread } from './comment/thread'
import { CUSTOM_EDGE, CUSTOM_NODE, WORKFLOW_DATA_UPDATE } from './constants'
import CustomConnectionLine from './custom-connection-line'
@@ -83,7 +84,6 @@ import { useWorkflowComment } from './hooks/use-workflow-comment'
import { useWorkflowControlScale } from './hooks/use-workflow-control-scale'
import { useWorkflowRefreshDraft } from './hooks/use-workflow-refresh-draft'
import { useWorkflowSearch } from './hooks/use-workflow-search'
-import { shouldPreventWorkflowBrowserDefault } from './hotkeys'
import CustomNode from './nodes'
import useMatchSchemaType from './nodes/_base/components/variable/use-match-schema-type'
import CustomDataSourceEmptyNode from './nodes/data-source-empty'
@@ -97,7 +97,7 @@ import { CUSTOM_NOTE_NODE } from './note-node/constants'
import Operator from './operator'
import Control from './operator/control'
import { WorkflowLocalStorageBridge } from './persistence/local-storage-bridge'
-import { useWorkflowHotkeys } from './shortcuts/use-workflow-hotkeys'
+import { WorkflowCanvas } from './shortcuts/workflow-canvas'
import CustomSimpleNode from './simple-node'
import { CUSTOM_SIMPLE_NODE } from './simple-node/constants'
import { useStore, useWorkflowStore } from './store/workflow'
@@ -142,37 +142,6 @@ export type WorkflowProps = {
onlineUsers?: OnlineUser[]
}
-const CommentPlacementPreview = memo(
- ({
- onSubmit,
- onCancel,
- }: {
- onSubmit: (content: string, mentionedUserIds: string[]) => void
- onCancel: () => void
- }) => {
- const isCommentPlacing = useStore((s) => s.isCommentPlacing)
- const pendingComment = useStore((s) => s.pendingComment)
- const mousePosition = useStore((s) => s.mousePosition)
-
- if (!isCommentPlacing || pendingComment) return null
-
- return (
- <CommentInput
- position={{
- x: mousePosition.elementX,
- y: mousePosition.elementY,
- }}
- onSubmit={onSubmit}
- onCancel={onCancel}
- autoFocus={false}
- disabled
- />
- )
- },
-)
-
-CommentPlacementPreview.displayName = 'CommentPlacementPreview'
-
export const Workflow: FC<WorkflowProps> = memo(
({
nodes: originalNodes,
@@ -502,9 +471,6 @@ export const Workflow: FC<WorkflowProps> = memo(
}
}, [handleSyncWorkflowDraftWhenPageClose, handleBeforeUnload])
- useEventListener('keydown', (e) => {
- if (shouldPreventWorkflowBrowserDefault(e)) e.preventDefault()
- })
useEventListener('mousemove', (e) => {
const containerClientRect = workflowContainerRef.current?.getBoundingClientRect()
@@ -588,7 +554,6 @@ export const Workflow: FC<WorkflowProps> = memo(
},
})
- useWorkflowHotkeys()
// Initialize workflow node search functionality
useWorkflowSearch()
@@ -767,7 +732,7 @@ export const Workflow: FC<WorkflowProps> = memo(
})}
{children}
<WorkflowContextmenu>
- <ReactFlow
+ <WorkflowCanvas
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
nodes={nodes}
@@ -826,7 +791,7 @@ export const Workflow: FC<WorkflowProps> = memo(
onlineUsers={onlineUsers || []}
/>
)}
- </ReactFlow>
+ </WorkflowCanvas>
</WorkflowContextmenu>
<SyncingDataModal />
</div>
diff --git a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
index fbc9f6ed761..8b6fc711995 100644
--- a/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
+++ b/web/app/components/workflow/node-actions-menu/__tests__/details.spec.tsx
@@ -1,9 +1,10 @@
import {
DropdownMenu,
- DropdownMenuContent,
+ DropdownMenuPortal,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
-import { screen, waitFor } from '@testing-library/react'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { useHooksStore } from '@/app/components/workflow/hooks-store'
@@ -105,14 +106,14 @@ function renderDropdownContent({
return renderWorkflowFlowComponent(
<DropdownMenu open>
<DropdownMenuTrigger render={<button type="button">open</button>} />
- <DropdownMenuContent>
+ <DropdownMenuPortal>
<NodeActionsDropdownContent
id="node-1"
data={{ type: BlockEnum.Code, title: 'Code Node', desc: '', ...data } as any}
onClose={onClose}
showHelpLink={showHelpLink}
/>
- </DropdownMenuContent>
+ </DropdownMenuPortal>
</DropdownMenu>,
{
nodes: [],
@@ -203,6 +204,16 @@ describe('node actions menu details', () => {
await user.click(changeNode)
const search = screen.getByRole('searchbox', { name: 'workflow.tabs.searchBlock' })
await waitFor(() => expect(search).toHaveFocus())
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await user.keyboard(`{${mod}>}cd{/${mod}}{Delete}`)
+ const replacement = screen.getByRole('button', { name: 'HTTP Request' })
+ act(() => replacement.focus())
+ await user.keyboard(`{${mod}>}cd{/${mod}}{Delete}`)
+ expect(handleNodesCopy).not.toHaveBeenCalled()
+ expect(handleNodesDuplicate).not.toHaveBeenCalled()
+ expect(handleNodeDelete).not.toHaveBeenCalled()
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ act(() => search.focus())
await user.keyboard('{ArrowDown}')
expect(search).toHaveFocus()
await user.keyboard('{Escape}')
@@ -290,7 +301,7 @@ describe('node actions menu details', () => {
const { rerender } = renderWorkflowFlowComponent(
<DropdownMenu open>
<DropdownMenuTrigger render={<button type="button">open</button>} />
- <DropdownMenuContent>
+ <DropdownMenuPortal>
<NodeActionsDropdownContent
id="node-2"
data={
@@ -305,7 +316,7 @@ describe('node actions menu details', () => {
onClose={vi.fn()}
showHelpLink={false}
/>
- </DropdownMenuContent>
+ </DropdownMenuPortal>
</DropdownMenu>,
{
nodes: [],
@@ -332,14 +343,14 @@ describe('node actions menu details', () => {
rerender(
<DropdownMenu open>
<DropdownMenuTrigger render={<button type="button">open</button>} />
- <DropdownMenuContent>
+ <DropdownMenuPortal>
<NodeActionsDropdownContent
id="node-3"
data={{ type: BlockEnum.End, title: 'Read only node', desc: '' } as any}
onClose={vi.fn()}
showHelpLink={false}
/>
- </DropdownMenuContent>
+ </DropdownMenuPortal>
</DropdownMenu>,
)
diff --git a/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx b/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx
index 4003a0f3f21..d0a655d6fad 100644
--- a/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/node-actions-menu/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
import type { UseQueryResult } from '@tanstack/react-query'
import type { ToolWithProvider } from '@/app/components/workflow/types'
-import { screen } from '@testing-library/react'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { BlockEnum } from '@/app/components/workflow/types'
@@ -102,6 +103,8 @@ const renderComponent = (showHelpLink: boolean = true, onOpenChange?: (open: boo
describe('NodeActionsDropdown', () => {
const handleNodeSelect = vi.fn()
const handleNodeDelete = vi.fn()
+ const handleNodesCopy = vi.fn()
+ const handleNodesDuplicate = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
@@ -115,9 +118,9 @@ describe('NodeActionsDropdown', () => {
} as ReturnType<typeof useNodeMetaData>)
mockUseNodesInteractions.mockReturnValue({
handleNodeDelete,
- handleNodesDuplicate: vi.fn(),
+ handleNodesDuplicate,
handleNodeSelect,
- handleNodesCopy: vi.fn(),
+ handleNodesCopy,
} as unknown as ReturnType<typeof useNodesInteractions>)
mockUseNodesReadOnly.mockReturnValue({
nodesReadOnly: false,
@@ -143,6 +146,71 @@ describe('NodeActionsDropdown', () => {
expect(store.getState().pendingSingleRun).toEqual({ nodeId: 'node-1', action: 'run' })
})
+ it.each([
+ { key: 'c', action: handleNodesCopy },
+ { key: 'd', action: handleNodesDuplicate },
+ { key: 'Delete', action: handleNodeDelete },
+ { key: 'Backspace', action: handleNodeDelete },
+ ])('runs $key from the focused portalled node menu', async ({ key, action }) => {
+ const user = userEvent.setup()
+ const { container } = renderComponent()
+ await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ await user.keyboard('{ArrowDown}')
+ const focusedItem = document.activeElement
+ expect(focusedItem).toHaveAttribute('role', 'menuitem')
+ expect(container.contains(focusedItem)).toBe(false)
+
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await user.keyboard(key.length === 1 ? `{${mod}>}${key}{/${mod}}` : `{${key}}`)
+
+ expect(action).toHaveBeenCalledExactlyOnceWith('node-1')
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ })
+
+ it('leaves composition alone and consumes held shortcuts without repeating the action', async () => {
+ const user = userEvent.setup()
+ renderComponent()
+ await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ await user.keyboard('{ArrowDown}')
+ const item = document.activeElement!
+ const modifier = detectPlatform() === 'mac' ? { metaKey: true } : { ctrlKey: true }
+ const composing = new KeyboardEvent('keydown', {
+ key: 'd',
+ ...modifier,
+ isComposing: true,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(item, composing)
+ expect(composing.defaultPrevented).toBe(false)
+ const repeat = new KeyboardEvent('keydown', {
+ key: 'd',
+ ...modifier,
+ repeat: true,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(item, repeat)
+ expect(repeat.defaultPrevented).toBe(true)
+ expect(handleNodesDuplicate).not.toHaveBeenCalled()
+ expect(screen.getByRole('menu')).toBeInTheDocument()
+ })
+
+ it('does not run unavailable editing shortcuts from a readonly node menu', async () => {
+ mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: true } as ReturnType<
+ typeof useNodesReadOnly
+ >)
+ const user = userEvent.setup()
+ renderComponent()
+ await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ await user.keyboard('{ArrowDown}')
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await user.keyboard(`{${mod}>}cd{/${mod}}{Delete}`)
+ expect(handleNodesCopy).not.toHaveBeenCalled()
+ expect(handleNodesDuplicate).not.toHaveBeenCalled()
+ expect(handleNodeDelete).not.toHaveBeenCalled()
+ })
+
it('should hide single-run actions when nodes are readonly', async () => {
const user = userEvent.setup()
mockUseNodesReadOnly.mockReturnValueOnce({
diff --git a/web/app/components/workflow/node-actions-menu/context-menu-content.tsx b/web/app/components/workflow/node-actions-menu/context-menu-content.tsx
index b8a9aba9457..def6bed31ef 100644
--- a/web/app/components/workflow/node-actions-menu/context-menu-content.tsx
+++ b/web/app/components/workflow/node-actions-menu/context-menu-content.tsx
@@ -1,5 +1,6 @@
import type { NodeActionsMenuProps } from './types'
import {
+ ContextMenuContent,
ContextMenuGroup,
ContextMenuItem,
ContextMenuLinkItem,
@@ -12,11 +13,15 @@ import {
PopoverPositioner,
PopoverTrigger,
} from '@langgenius/dify-ui/popover'
+import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useStoreApi } from 'reactflow'
+import { handleWorkflowMenuKeyDown } from '../shortcuts/handle-workflow-menu-key-down'
import { ChangeBlockPopup } from './change-block-popup'
import {
NODE_ACTIONS_MENU_DELETE_ITEM_CLASS_NAME,
NODE_ACTIONS_MENU_ITEM_WITH_SHORTCUT_CLASS_NAME,
+ NODE_ACTIONS_MENU_WIDTH_CLASS_NAME,
NodeActionsMenuAbout,
NodeActionsMenuItemContent,
} from './shared'
@@ -25,6 +30,8 @@ import { useNodeActionsMenuModel } from './use-node-actions-menu-model'
export function NodeActionsContextMenuContent(props: NodeActionsMenuProps) {
const { t } = useTranslation(['common', 'workflow', 'workflowDebug'])
const model = useNodeActionsMenuModel(props)
+ const flowStore = useStoreApi()
+ const deletingRef = useRef(false)
const hasRunGroup = model.canRun || model.canChangeBlock
const hasEditGroup = !model.nodesReadOnly && !model.isSingleton
const hasDeleteGroup = !model.nodesReadOnly && !model.isUndeletable
@@ -32,8 +39,24 @@ export function NodeActionsContextMenuContent(props: NodeActionsMenuProps) {
? t(($) => $['debug.variableInspect.trigger.stop'], { ns: 'workflowDebug' })
: t(($) => $['panel.runThisStep'], { ns: 'workflow' })
+ function handleDelete() {
+ deletingRef.current = true
+ model.handleDelete()
+ }
+
return (
- <>
+ <ContextMenuContent
+ finalFocus={() => (deletingRef.current ? (flowStore.getState().domNode ?? true) : true)}
+ className={NODE_ACTIONS_MENU_WIDTH_CLASS_NAME}
+ sideOffset={4}
+ onKeyDown={(event) =>
+ handleWorkflowMenuKeyDown(event, [
+ ['workflow.copy', hasEditGroup ? model.handleCopy : undefined],
+ ['workflow.duplicate', hasEditGroup ? model.handleDuplicate : undefined],
+ ['workflow.delete', hasDeleteGroup ? handleDelete : undefined],
+ ])
+ }
+ >
{hasRunGroup && (
<ContextMenuGroup>
{model.canRun && (
@@ -94,7 +117,7 @@ export function NodeActionsContextMenuContent(props: NodeActionsMenuProps) {
<ContextMenuGroup>
<ContextMenuItem
className={NODE_ACTIONS_MENU_DELETE_ITEM_CLASS_NAME}
- onClick={model.handleDelete}
+ onClick={handleDelete}
>
<NodeActionsMenuItemContent shortcut="workflow.delete">
{t(($) => $['operation.delete'], { ns: 'common' })}
@@ -128,6 +151,6 @@ export function NodeActionsContextMenuContent(props: NodeActionsMenuProps) {
description={model.about.description}
author={`${t(($) => $['panel.createdBy'], { ns: 'workflow' })} ${model.about.author}`}
/>
- </>
+ </ContextMenuContent>
)
}
diff --git a/web/app/components/workflow/node-actions-menu/dropdown-content.tsx b/web/app/components/workflow/node-actions-menu/dropdown-content.tsx
index d5e62f7363c..efac120b86b 100644
--- a/web/app/components/workflow/node-actions-menu/dropdown-content.tsx
+++ b/web/app/components/workflow/node-actions-menu/dropdown-content.tsx
@@ -3,6 +3,8 @@ import {
DropdownMenuGroup,
DropdownMenuItem,
DropdownMenuLinkItem,
+ DropdownMenuPopup,
+ DropdownMenuPositioner,
DropdownMenuSeparator,
} from '@langgenius/dify-ui/dropdown-menu'
import {
@@ -12,11 +14,15 @@ import {
PopoverPositioner,
PopoverTrigger,
} from '@langgenius/dify-ui/popover'
+import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { useStoreApi } from 'reactflow'
+import { handleWorkflowMenuKeyDown } from '../shortcuts/handle-workflow-menu-key-down'
import { ChangeBlockPopup } from './change-block-popup'
import {
NODE_ACTIONS_MENU_DELETE_ITEM_CLASS_NAME,
NODE_ACTIONS_MENU_ITEM_WITH_SHORTCUT_CLASS_NAME,
+ NODE_ACTIONS_MENU_WIDTH_CLASS_NAME,
NodeActionsMenuAbout,
NodeActionsMenuItemContent,
} from './shared'
@@ -25,6 +31,8 @@ import { useNodeActionsMenuModel } from './use-node-actions-menu-model'
export function NodeActionsDropdownContent(props: NodeActionsMenuProps) {
const { t } = useTranslation(['common', 'workflow', 'workflowDebug'])
const model = useNodeActionsMenuModel(props)
+ const flowStore = useStoreApi()
+ const deletingRef = useRef(false)
const hasRunGroup = model.canRun || model.canChangeBlock
const hasEditGroup = !model.nodesReadOnly && !model.isSingleton
const hasDeleteGroup = !model.nodesReadOnly && !model.isUndeletable
@@ -32,102 +40,125 @@ export function NodeActionsDropdownContent(props: NodeActionsMenuProps) {
? t(($) => $['debug.variableInspect.trigger.stop'], { ns: 'workflowDebug' })
: t(($) => $['panel.runThisStep'], { ns: 'workflow' })
+ function handleDelete() {
+ deletingRef.current = true
+ model.handleDelete()
+ }
+
return (
- <>
- {hasRunGroup && (
- <DropdownMenuGroup>
- {model.canRun && (
- <DropdownMenuItem onClick={model.handleRun}>{singleRunActionLabel}</DropdownMenuItem>
- )}
- {model.canChangeBlock && (
- <Popover modal="trap-focus">
- <DropdownMenuItem
- closeOnClick={false}
- render={<PopoverTrigger nativeButton={false} render={<div />} />}
- className="data-popup-open:bg-state-base-hover"
- >
- {t(($) => $['panel.changeBlock'], { ns: 'workflow' })}
- </DropdownMenuItem>
- <PopoverPortal>
- <PopoverBackdrop />
- <PopoverPositioner placement="right-start" positionMethod="fixed">
- <ChangeBlockPopup
- nodeId={model.id}
- nodeData={model.data}
- sourceHandle={model.sourceHandle}
- onComplete={props.onClose}
- />
- </PopoverPositioner>
- </PopoverPortal>
- </Popover>
+ <DropdownMenuPositioner placement="bottom-end">
+ <DropdownMenuPopup
+ finalFocus={() => (deletingRef.current ? (flowStore.getState().domNode ?? true) : true)}
+ className={`${NODE_ACTIONS_MENU_WIDTH_CLASS_NAME} border-[0.5px] border-components-panel-border bg-components-panel-bg-blur py-1 shadow-lg backdrop-blur-[5px]`}
+ onKeyDown={(event) =>
+ handleWorkflowMenuKeyDown(event, [
+ ['workflow.copy', hasEditGroup ? model.handleCopy : undefined],
+ ['workflow.duplicate', hasEditGroup ? model.handleDuplicate : undefined],
+ ['workflow.delete', hasDeleteGroup ? handleDelete : undefined],
+ ])
+ }
+ >
+ {hasRunGroup && (
+ <DropdownMenuGroup>
+ {model.canRun && (
+ <DropdownMenuItem onClick={model.handleRun}>{singleRunActionLabel}</DropdownMenuItem>
+ )}
+ {model.canChangeBlock && (
+ <Popover modal="trap-focus">
+ <DropdownMenuItem
+ closeOnClick={false}
+ render={<PopoverTrigger nativeButton={false} render={<div />} />}
+ className="data-popup-open:bg-state-base-hover"
+ >
+ {t(($) => $['panel.changeBlock'], { ns: 'workflow' })}
+ </DropdownMenuItem>
+ <PopoverPortal>
+ <PopoverBackdrop />
+ <PopoverPositioner placement="right-start" positionMethod="fixed">
+ <ChangeBlockPopup
+ nodeId={model.id}
+ nodeData={model.data}
+ sourceHandle={model.sourceHandle}
+ onComplete={props.onClose}
+ />
+ </PopoverPositioner>
+ </PopoverPortal>
+ </Popover>
+ )}
+ </DropdownMenuGroup>
+ )}
+ {hasRunGroup &&
+ (hasEditGroup || hasDeleteGroup || model.workflowAppHref || model.helpLinkUri) && (
+ <DropdownMenuSeparator />
)}
- </DropdownMenuGroup>
- )}
- {hasRunGroup &&
- (hasEditGroup || hasDeleteGroup || model.workflowAppHref || model.helpLinkUri) && (
+ {hasEditGroup && (
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ className={NODE_ACTIONS_MENU_ITEM_WITH_SHORTCUT_CLASS_NAME}
+ onClick={model.handleCopy}
+ >
+ <NodeActionsMenuItemContent shortcut="workflow.copy">
+ {t(($) => $['common.copy'], { ns: 'workflow' })}
+ </NodeActionsMenuItemContent>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className={NODE_ACTIONS_MENU_ITEM_WITH_SHORTCUT_CLASS_NAME}
+ onClick={model.handleDuplicate}
+ >
+ <NodeActionsMenuItemContent shortcut="workflow.duplicate">
+ {t(($) => $['common.duplicate'], { ns: 'workflow' })}
+ </NodeActionsMenuItemContent>
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ )}
+ {hasEditGroup && (hasDeleteGroup || model.workflowAppHref || model.helpLinkUri) && (
<DropdownMenuSeparator />
)}
- {hasEditGroup && (
- <DropdownMenuGroup>
- <DropdownMenuItem
- className={NODE_ACTIONS_MENU_ITEM_WITH_SHORTCUT_CLASS_NAME}
- onClick={model.handleCopy}
- >
- <NodeActionsMenuItemContent shortcut="workflow.copy">
- {t(($) => $['common.copy'], { ns: 'workflow' })}
- </NodeActionsMenuItemContent>
- </DropdownMenuItem>
- <DropdownMenuItem
- className={NODE_ACTIONS_MENU_ITEM_WITH_SHORTCUT_CLASS_NAME}
- onClick={model.handleDuplicate}
- >
- <NodeActionsMenuItemContent shortcut="workflow.duplicate">
- {t(($) => $['common.duplicate'], { ns: 'workflow' })}
- </NodeActionsMenuItemContent>
- </DropdownMenuItem>
- </DropdownMenuGroup>
- )}
- {hasEditGroup && (hasDeleteGroup || model.workflowAppHref || model.helpLinkUri) && (
+ {hasDeleteGroup && (
+ <DropdownMenuGroup>
+ <DropdownMenuItem
+ className={NODE_ACTIONS_MENU_DELETE_ITEM_CLASS_NAME}
+ onClick={handleDelete}
+ >
+ <NodeActionsMenuItemContent shortcut="workflow.delete">
+ {t(($) => $['operation.delete'], { ns: 'common' })}
+ </NodeActionsMenuItemContent>
+ </DropdownMenuItem>
+ </DropdownMenuGroup>
+ )}
+ {hasDeleteGroup && (model.workflowAppHref || model.helpLinkUri) && (
+ <DropdownMenuSeparator />
+ )}
+ {model.workflowAppHref && (
+ <DropdownMenuGroup>
+ <DropdownMenuLinkItem
+ href={model.workflowAppHref}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {t(($) => $['panel.openWorkflow'], { ns: 'workflow' })}
+ </DropdownMenuLinkItem>
+ </DropdownMenuGroup>
+ )}
+ {model.workflowAppHref && model.helpLinkUri && <DropdownMenuSeparator />}
+ {model.helpLinkUri && (
+ <DropdownMenuGroup>
+ <DropdownMenuLinkItem
+ href={model.helpLinkUri}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {t(($) => $['panel.helpLink'], { ns: 'workflow' })}
+ </DropdownMenuLinkItem>
+ </DropdownMenuGroup>
+ )}
<DropdownMenuSeparator />
- )}
- {hasDeleteGroup && (
- <DropdownMenuGroup>
- <DropdownMenuItem
- className={NODE_ACTIONS_MENU_DELETE_ITEM_CLASS_NAME}
- onClick={model.handleDelete}
- >
- <NodeActionsMenuItemContent shortcut="workflow.delete">
- {t(($) => $['operation.delete'], { ns: 'common' })}
- </NodeActionsMenuItemContent>
- </DropdownMenuItem>
- </DropdownMenuGroup>
- )}
- {hasDeleteGroup && (model.workflowAppHref || model.helpLinkUri) && <DropdownMenuSeparator />}
- {model.workflowAppHref && (
- <DropdownMenuGroup>
- <DropdownMenuLinkItem
- href={model.workflowAppHref}
- target="_blank"
- rel="noopener noreferrer"
- >
- {t(($) => $['panel.openWorkflow'], { ns: 'workflow' })}
- </DropdownMenuLinkItem>
- </DropdownMenuGroup>
- )}
- {model.workflowAppHref && model.helpLinkUri && <DropdownMenuSeparator />}
- {model.helpLinkUri && (
- <DropdownMenuGroup>
- <DropdownMenuLinkItem href={model.helpLinkUri} target="_blank" rel="noopener noreferrer">
- {t(($) => $['panel.helpLink'], { ns: 'workflow' })}
- </DropdownMenuLinkItem>
- </DropdownMenuGroup>
- )}
- <DropdownMenuSeparator />
- <NodeActionsMenuAbout
- title={t(($) => $['panel.about'], { ns: 'workflow' })}
- description={model.about.description}
- author={`${t(($) => $['panel.createdBy'], { ns: 'workflow' })} ${model.about.author}`}
- />
- </>
+ <NodeActionsMenuAbout
+ title={t(($) => $['panel.about'], { ns: 'workflow' })}
+ description={model.about.description}
+ author={`${t(($) => $['panel.createdBy'], { ns: 'workflow' })} ${model.about.author}`}
+ />
+ </DropdownMenuPopup>
+ </DropdownMenuPositioner>
)
}
diff --git a/web/app/components/workflow/node-actions-menu/index.tsx b/web/app/components/workflow/node-actions-menu/index.tsx
index 0a3d6d898ef..40d8df801ec 100644
--- a/web/app/components/workflow/node-actions-menu/index.tsx
+++ b/web/app/components/workflow/node-actions-menu/index.tsx
@@ -2,14 +2,13 @@ import type { Node } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import {
DropdownMenu,
- DropdownMenuContent,
+ DropdownMenuPortal,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { NodeActionsDropdownContent } from './dropdown-content'
-import { NODE_ACTIONS_MENU_WIDTH_CLASS_NAME } from './shared'
type NodeActionsDropdownProps = {
id: string
@@ -55,14 +54,14 @@ export function NodeActionsDropdown({
</IconButton>
}
/>
- <DropdownMenuContent placement="bottom-end" className={NODE_ACTIONS_MENU_WIDTH_CLASS_NAME}>
+ <DropdownMenuPortal>
<NodeActionsDropdownContent
id={id}
data={data}
onClose={closeMenu}
showHelpLink={showHelpLink}
/>
- </DropdownMenuContent>
+ </DropdownMenuPortal>
</DropdownMenu>
)
}
diff --git a/web/app/components/workflow/node-contextmenu.tsx b/web/app/components/workflow/node-contextmenu.tsx
index dfa0e9a8e05..3d451221a59 100644
--- a/web/app/components/workflow/node-contextmenu.tsx
+++ b/web/app/components/workflow/node-contextmenu.tsx
@@ -1,8 +1,6 @@
import type { Node } from './types'
-import { ContextMenuContent } from '@langgenius/dify-ui/context-menu'
import useNodes from '@/app/components/workflow/store/workflow/use-nodes'
import { NodeActionsContextMenuContent } from './node-actions-menu/context-menu-content'
-import { NODE_ACTIONS_MENU_WIDTH_CLASS_NAME } from './node-actions-menu/shared'
import { useStore } from './store'
export function NodeContextmenu({ onClose }: { onClose: () => void }) {
@@ -16,13 +14,11 @@ export function NodeContextmenu({ onClose }: { onClose: () => void }) {
if (!nodeId || !currentNode) return null
return (
- <ContextMenuContent className={NODE_ACTIONS_MENU_WIDTH_CLASS_NAME} sideOffset={4}>
- <NodeActionsContextMenuContent
- id={currentNode.id}
- data={currentNode.data}
- onClose={onClose}
- showHelpLink
- />
- </ContextMenuContent>
+ <NodeActionsContextMenuContent
+ id={currentNode.id}
+ data={currentNode.data}
+ onClose={onClose}
+ showHelpLink
+ />
)
}
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/add-variable-popup-with-position.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/add-variable-popup-with-position.spec.tsx
new file mode 100644
index 00000000000..1ea4cfa2749
--- /dev/null
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/add-variable-popup-with-position.spec.tsx
@@ -0,0 +1,76 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import ReactFlow, { ReactFlowProvider } from 'reactflow'
+import { BlockEnum, VarType } from '@/app/components/workflow/types'
+import AddVariablePopupWithPosition from '../add-variable-popup-with-position'
+
+const assignVariable = vi.fn()
+const workflowState = {
+ showAssignVariablePopup: {
+ nodeId: 'source',
+ nodeData: { type: BlockEnum.TemplateTransform },
+ variableAssignerNodeId: 'assigner',
+ variableAssignerNodeData: { output_type: VarType.string },
+ variableAssignerNodeHandleId: 'target',
+ x: 0,
+ y: 0,
+ },
+ setShowAssignVariablePopup: vi.fn(),
+}
+const availableVars = [
+ {
+ nodeId: 'source',
+ title: 'Source',
+ vars: [
+ { variable: 'first', type: VarType.string },
+ { variable: 'second', type: VarType.string },
+ ],
+ },
+]
+
+vi.mock('../../../../store', () => ({
+ useStore: (selector: (state: typeof workflowState) => unknown) => selector(workflowState),
+}))
+vi.mock('../../../../hooks/use-node-data-update', () => ({
+ useNodeDataUpdate: () => ({ handleNodeDataUpdate: vi.fn() }),
+}))
+vi.mock('../../../../hooks/use-workflow', () => ({
+ useIsChatMode: () => false,
+ useWorkflow: () => ({ getBeforeNodesInSameBranch: () => [] }),
+}))
+vi.mock('../../../../hooks/use-workflow-variables', () => ({
+ useWorkflowVariables: () => ({ getNodeAvailableVars: () => availableVars }),
+}))
+vi.mock('../../../variable-assigner/hooks', () => ({
+ useVariableAssigner: () => ({ handleAddVariableInAddVariablePopupWithPosition: assignVariable }),
+}))
+
+it('selects a connection variable from the owning canvas and preserves its focus', async () => {
+ const user = userEvent.setup()
+ render(
+ <>
+ <input aria-label="Outside" />
+ <ReactFlowProvider>
+ <ReactFlow aria-label="Workflow canvas" tabIndex={0} nodes={[]} edges={[]}>
+ <AddVariablePopupWithPosition nodeId="source" nodeData={{}} />
+ </ReactFlow>
+ </ReactFlowProvider>
+ </>,
+ )
+
+ screen.getByRole('textbox', { name: 'Outside' }).focus()
+ await user.keyboard('{ArrowDown}{Enter}')
+ expect(assignVariable).not.toHaveBeenCalled()
+ const canvas = screen.getByLabelText('Workflow canvas')
+ canvas.focus()
+ await user.keyboard('{ArrowDown}{Enter}')
+
+ expect(assignVariable).toHaveBeenCalledWith(
+ 'source',
+ 'assigner',
+ 'target',
+ ['source', 'second'],
+ expect.objectContaining({ variable: 'second' }),
+ )
+ expect(canvas).toHaveFocus()
+})
diff --git a/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx b/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx
index 6db6d22be37..5a208909911 100644
--- a/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx
+++ b/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx
@@ -1,6 +1,7 @@
import type { ValueSelector, Var, VarType } from '../../../types'
import { useClickAway } from 'ahooks'
import { memo, useCallback, useMemo, useRef } from 'react'
+import { useStore as useReactFlowStore } from 'reactflow'
import { useNodeDataUpdate } from '../../../hooks/use-node-data-update'
import { useIsChatMode, useWorkflow } from '../../../hooks/use-workflow'
import { useWorkflowVariables } from '../../../hooks/use-workflow-variables'
@@ -15,6 +16,7 @@ type AddVariablePopupWithPositionProps = {
}
const AddVariablePopupWithPosition = ({ nodeId, nodeData }: AddVariablePopupWithPositionProps) => {
const ref = useRef<HTMLDivElement>(null)
+ const canvasElement = useReactFlowStore((state) => state.domNode)
const showAssignVariablePopup = useStore((s) => s.showAssignVariablePopup)
const setShowAssignVariablePopup = useStore((s) => s.setShowAssignVariablePopup)
const { handleNodeDataUpdate } = useNodeDataUpdate()
@@ -113,7 +115,11 @@ const AddVariablePopupWithPosition = ({ nodeId, nodeData }: AddVariablePopupWith
}}
ref={ref}
>
- <AddVariablePopup availableVars={availableVars} onSelect={handleAddVariable} />
+ <AddVariablePopup
+ availableVars={availableVars}
+ keyboardTarget={canvasElement}
+ onSelect={handleAddVariable}
+ />
</div>
)
}
diff --git a/web/app/components/workflow/nodes/_base/components/add-variable-popup.tsx b/web/app/components/workflow/nodes/_base/components/add-variable-popup.tsx
index 2ad948f3975..45371aff06f 100644
--- a/web/app/components/workflow/nodes/_base/components/add-variable-popup.tsx
+++ b/web/app/components/workflow/nodes/_base/components/add-variable-popup.tsx
@@ -1,3 +1,4 @@
+import type { RefObject } from 'react'
import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -5,9 +6,10 @@ import VarReferenceVars from '@/app/components/workflow/nodes/_base/components/v
type AddVariablePopupProps = {
availableVars: NodeOutPutVar[]
+ keyboardTarget: HTMLElement | RefObject<HTMLElement | null> | null
onSelect: (value: ValueSelector, item: Var) => void
}
-const AddVariablePopup = ({ availableVars, onSelect }: AddVariablePopupProps) => {
+const AddVariablePopup = ({ availableVars, keyboardTarget, onSelect }: AddVariablePopupProps) => {
const { t } = useTranslation(['workflowLogic'])
return (
@@ -16,7 +18,13 @@ const AddVariablePopup = ({ availableVars, onSelect }: AddVariablePopupProps) =>
{t(($) => $['nodes.variableAssigner.setAssignVariable'], { ns: 'workflowLogic' })}
</div>
<div className="p-1">
- <VarReferenceVars hideSearch vars={availableVars} onChange={onSelect} isSupportFileVar />
+ <VarReferenceVars
+ hideSearch
+ keyboardTarget={keyboardTarget}
+ vars={availableVars}
+ onChange={onSelect}
+ isSupportFileVar
+ />
</div>
</div>
)
diff --git a/web/app/components/workflow/nodes/_base/components/editor/code-editor/__tests__/editor-support-vars.spec.tsx b/web/app/components/workflow/nodes/_base/components/editor/code-editor/__tests__/editor-support-vars.spec.tsx
new file mode 100644
index 00000000000..2f76baab886
--- /dev/null
+++ b/web/app/components/workflow/nodes/_base/components/editor/code-editor/__tests__/editor-support-vars.spec.tsx
@@ -0,0 +1,87 @@
+import type { Props as EditorProps } from '..'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useEffect, useEffectEvent, useRef } from 'react'
+import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
+import { VarType } from '@/app/components/workflow/types'
+import CodeEditor from '../editor-support-vars'
+
+vi.mock('..', () => ({
+ default: function MockEditor({ onMount }: EditorProps) {
+ const inputRef = useRef<HTMLTextAreaElement>(null)
+ const cursorListenerRef = useRef<((event: unknown) => void) | undefined>(undefined)
+ const mountEditor = useEffectEvent(() => {
+ const input = inputRef.current!
+ onMount?.(
+ {
+ getDomNode: () => input,
+ getModel: () => ({ getLineContent: () => input.value }),
+ getPosition: () => ({ lineNumber: 1, column: input.value.length + 1 }),
+ getScrolledVisiblePosition: () => ({ left: 0, top: 0 }),
+ onDidChangeCursorPosition: (listener: (event: unknown) => void) => {
+ cursorListenerRef.current = listener
+ },
+ executeEdits: (_source: string, edits: { text: string }[]) => {
+ input.value = edits[0]!.text
+ },
+ },
+ { Range: class {} },
+ )
+ })
+ useEffect(() => mountEditor(), [])
+ return (
+ <textarea
+ ref={inputRef}
+ aria-label="Code"
+ onInput={(event) => {
+ cursorListenerRef.current?.({
+ position: { lineNumber: 1, column: event.currentTarget.value.length + 1 },
+ })
+ }}
+ />
+ )
+ },
+}))
+
+describe('code editor variable completion', () => {
+ it('keeps variable navigation on its editor and inserts the selected variable', async () => {
+ const user = userEvent.setup()
+ const onAddVar = vi.fn()
+ render(
+ <>
+ <input aria-label="Outside" />
+ <CodeEditor
+ language={CodeLanguage.python3}
+ varList={[]}
+ onAddVar={onAddVar}
+ availableVars={[
+ {
+ nodeId: 'source',
+ title: 'Source',
+ vars: [
+ { variable: 'first', type: VarType.string },
+ { variable: 'second', type: VarType.string },
+ ],
+ },
+ ]}
+ />
+ </>,
+ )
+
+ const editor = screen.getByRole('textbox', { name: 'Code' })
+ await user.type(editor, '/')
+ expect(screen.getByText('first')).toBeInTheDocument()
+ await user.click(screen.getByRole('textbox', { name: 'Outside' }))
+ await user.keyboard('{ArrowDown}{Enter}')
+ expect(onAddVar).not.toHaveBeenCalled()
+ await user.click(editor)
+ await user.keyboard('{ArrowDown}{Enter}')
+
+ expect(onAddVar).toHaveBeenCalledWith({
+ variable: 'second',
+ value_selector: ['source', 'second'],
+ })
+ expect(editor).toHaveValue('{{ second }}')
+ expect(screen.queryByText('second')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/app/components/workflow/nodes/_base/components/editor/code-editor/editor-support-vars.tsx b/web/app/components/workflow/nodes/_base/components/editor/code-editor/editor-support-vars.tsx
index 18c5d703645..3d036de41e9 100644
--- a/web/app/components/workflow/nodes/_base/components/editor/code-editor/editor-support-vars.tsx
+++ b/web/app/components/workflow/nodes/_base/components/editor/code-editor/editor-support-vars.tsx
@@ -26,6 +26,7 @@ const CodeEditor: FC<Props> = ({ availableVars, varList, onAddVar, ...editorProp
const editorRef = useRef(null)
const monacoRef = useRef(null)
+ const [keyboardTarget, setKeyboardTarget] = useState<HTMLElement | null>(null)
const popupRef = useRef<HTMLDivElement>(null)
const [isShowVarPicker, setIsShowVarPicker] = useState(false)
@@ -72,6 +73,7 @@ const CodeEditor: FC<Props> = ({ availableVars, varList, onAddVar, ...editorProp
const onEditorMounted = (editor: any, monaco: any) => {
editorRef.current = editor
monacoRef.current = monaco
+ setKeyboardTarget(editor.getDomNode())
editor.onDidChangeCursorPosition(handleCursorPositionChange)
}
@@ -158,6 +160,7 @@ const CodeEditor: FC<Props> = ({ availableVars, varList, onAddVar, ...editorProp
>
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
vars={availableVars}
onChange={handleSelectVar}
isSupportFileVar={false}
diff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-vars.spec.tsx b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-vars.spec.tsx
index 096d6fb0276..77abef8b40c 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-vars.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-vars.spec.tsx
@@ -28,8 +28,14 @@ vi.mock('../manage-input-field', () => ({
}))
describe('VarReferenceVars', () => {
+ let keyboardTarget: HTMLInputElement
const createVars = (vars: NodeOutPutVar[]) => vars
+ beforeEach(() => {
+ render(<input aria-label="Variable owner" />)
+ keyboardTarget = screen.getByRole('textbox', { name: 'Variable owner' })
+ })
+
const baseVars = createVars([
{
title: 'Node A',
@@ -65,6 +71,7 @@ describe('VarReferenceVars', () => {
render(
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
vars={createVars([
{
title: 'Node A',
@@ -85,12 +92,15 @@ describe('VarReferenceVars', () => {
expect(firstItem).toHaveAttribute('data-selected', 'true')
expect(secondItem).toHaveAttribute('data-selected', 'false')
- fireEvent.keyDown(document, { key: 'ArrowDown' })
+ fireEvent.keyDown(document.body, { key: 'ArrowDown' })
+ fireEvent.keyDown(keyboardTarget, { key: 'ArrowDown', isComposing: true })
+ expect(firstItem).toHaveAttribute('data-selected', 'true')
+ fireEvent.keyDown(keyboardTarget, { key: 'ArrowDown' })
expect(firstItem).toHaveAttribute('data-selected', 'false')
expect(secondItem).toHaveAttribute('data-selected', 'true')
- fireEvent.keyDown(document, { key: 'Enter' })
+ fireEvent.keyDown(keyboardTarget, { key: 'Enter' })
expect(onChange).toHaveBeenCalledWith(
['node-a', 'second_value'],
@@ -137,6 +147,7 @@ describe('VarReferenceVars', () => {
render(
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
preferSchemaType
vars={createVars([
{
@@ -163,6 +174,7 @@ describe('VarReferenceVars', () => {
render(
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
vars={createVars([
{
title: 'Flat',
@@ -190,6 +202,7 @@ describe('VarReferenceVars', () => {
render(
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
isSupportFileVar
vars={createVars([
{
@@ -240,6 +253,7 @@ describe('VarReferenceVars', () => {
render(
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
isSupportFileVar
vars={createVars([
{
@@ -257,13 +271,13 @@ describe('VarReferenceVars', () => {
/>,
)
- fireEvent.keyDown(document, { key: 'Enter' })
- fireEvent.keyDown(document, { key: 'ArrowDown' })
- fireEvent.keyDown(document, { key: 'Enter' })
- fireEvent.keyDown(document, { key: 'ArrowDown' })
- fireEvent.keyDown(document, { key: 'Enter' })
- fireEvent.keyDown(document, { key: 'ArrowDown' })
- fireEvent.keyDown(document, { key: 'Enter' })
+ fireEvent.keyDown(keyboardTarget, { key: 'Enter' })
+ fireEvent.keyDown(keyboardTarget, { key: 'ArrowDown' })
+ fireEvent.keyDown(keyboardTarget, { key: 'Enter' })
+ fireEvent.keyDown(keyboardTarget, { key: 'ArrowDown' })
+ fireEvent.keyDown(keyboardTarget, { key: 'Enter' })
+ fireEvent.keyDown(keyboardTarget, { key: 'ArrowDown' })
+ fireEvent.keyDown(keyboardTarget, { key: 'Enter' })
expect(onChange).toHaveBeenNthCalledWith(
1,
@@ -293,6 +307,7 @@ describe('VarReferenceVars', () => {
render(
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
vars={createVars([
{
title: 'Object vars',
@@ -323,6 +338,7 @@ describe('VarReferenceVars', () => {
render(
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
searchText="child"
vars={createVars([
{
@@ -381,6 +397,7 @@ describe('VarReferenceVars', () => {
render(
<VarReferenceVars
hideSearch
+ keyboardTarget={keyboardTarget}
vars={createVars([
{
title: 'Files',
@@ -392,7 +409,7 @@ describe('VarReferenceVars', () => {
/>,
)
- fireEvent.keyDown(document, { key: 'Enter' })
+ fireEvent.keyDown(keyboardTarget, { key: 'Enter' })
expect(onChange).not.toHaveBeenCalled()
})
diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-vars.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-vars.tsx
index b19d20bf315..2f65dc8490f 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-vars.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-vars.tsx
@@ -323,7 +323,6 @@ const Item: FC<ItemProps> = ({
}
type Props = Readonly<{
- hideSearch?: boolean
searchText?: string
searchBoxClassName?: string
vars: NodeOutPutVar[]
@@ -338,9 +337,14 @@ type Props = Readonly<{
onManageInputField?: () => void
searchInputRef?: RefObject<HTMLInputElement | null>
preferSchemaType?: boolean
-}>
+}> &
+ (
+ | { hideSearch: true; keyboardTarget: HTMLElement | RefObject<HTMLElement | null> | null }
+ | { hideSearch?: false; keyboardTarget?: never }
+ )
const VarReferenceVars: FC<Props> = ({
hideSearch,
+ keyboardTarget,
searchText,
searchBoxClassName,
vars,
@@ -457,24 +461,38 @@ const VarReferenceVars: FC<Props> = ({
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.defaultPrevented || e.nativeEvent.isComposing) return
handleKeyboardEvent(e)
},
[handleKeyboardEvent],
)
useEffect(() => {
- if (!hideSearch) return
-
- const handleDocumentKeyDown = (event: KeyboardEvent) => {
- if (event.altKey || event.ctrlKey || event.metaKey) return
+ if (!hideSearch || !keyboardTarget) return
+ const target = 'current' in keyboardTarget ? keyboardTarget.current : keyboardTarget
+ if (!target) return
+
+ const handleTargetKeyDown = (event: KeyboardEvent) => {
+ if (
+ !(event.target instanceof Node) ||
+ !target.contains(event.target) ||
+ event.defaultPrevented ||
+ event.isComposing ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey
+ )
+ return
if (!['ArrowDown', 'ArrowUp', 'Enter', 'Escape'].includes(event.key)) return
handleKeyboardEvent(event)
}
- document.addEventListener('keydown', handleDocumentKeyDown, true)
- return () => document.removeEventListener('keydown', handleDocumentKeyDown, true)
- }, [handleKeyboardEvent, hideSearch])
+ // Run before React's node-movement capture handler while claiming only the declared owner.
+ const ownerDocument = target.ownerDocument
+ ownerDocument.addEventListener('keydown', handleTargetKeyDown, true)
+ return () => ownerDocument.removeEventListener('keydown', handleTargetKeyDown, true)
+ }, [handleKeyboardEvent, hideSearch, keyboardTarget])
return (
<>
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/edit-card.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/edit-card.spec.tsx
new file mode 100644
index 00000000000..5edc57f30dc
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/edit-card.spec.tsx
@@ -0,0 +1,93 @@
+import { fireEvent, render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { OutputEditCard } from '../edit-card'
+
+const state = {
+ draft: {
+ name: 'summary',
+ type: 'string' as const,
+ required: false,
+ description: '',
+ defaultValue: '',
+ children: [],
+ },
+}
+
+function confirmFrom(target: HTMLElement, options: KeyboardEventInit = {}) {
+ const event = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ ...options,
+ })
+ fireEvent(target, event)
+ fireEvent.keyUp(target, { key: 'Enter', ctrlKey: true })
+ return event
+}
+
+describe('OutputEditCard keyboard ownership', () => {
+ it('submits the actual form from its input and leaves outside shortcuts alone', () => {
+ const onConfirm = vi.fn()
+ render(
+ <OutputEditCard
+ state={state}
+ existingOutputs={[]}
+ onCancel={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+ expect(confirmFrom(document.body).defaultPrevented).toBe(false)
+ expect(onConfirm).not.toHaveBeenCalled()
+ const form = screen.getByRole('form')
+ const name = within(form).getByRole('textbox', {
+ name: 'workflowAgent.nodes.agent.outputVars.nameLabel',
+ })
+ expect(confirmFrom(name).defaultPrevented).toBe(true)
+ expect(onConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'summary', type: 'string' }),
+ state,
+ )
+ })
+
+ it('ignores composing submission and disables both paths for an invalid name', () => {
+ const onConfirm = vi.fn()
+ render(
+ <OutputEditCard
+ state={state}
+ existingOutputs={[]}
+ onCancel={vi.fn()}
+ onConfirm={onConfirm}
+ />,
+ )
+ const name = screen.getByRole('textbox', {
+ name: 'workflowAgent.nodes.agent.outputVars.nameLabel',
+ })
+ expect(confirmFrom(name, { isComposing: true }).defaultPrevented).toBe(false)
+ fireEvent.change(name, { target: { value: 'invalid name' } })
+ expect(
+ screen.getByRole('button', { name: 'workflowAgent.nodes.agent.outputVars.confirm' }),
+ ).toBeDisabled()
+ expect(confirmFrom(name).defaultPrevented).toBe(false)
+ expect(onConfirm).not.toHaveBeenCalled()
+ })
+
+ it('closes the portalled type selector before cancelling the output form', async () => {
+ const user = userEvent.setup()
+ const onCancel = vi.fn()
+ render(
+ <OutputEditCard state={state} existingOutputs={[]} onCancel={onCancel} onConfirm={vi.fn()} />,
+ )
+ const selector = screen.getByRole('combobox')
+ await user.click(selector)
+ expect(screen.getByRole('listbox')).toBeInTheDocument()
+ await user.keyboard('{Escape}')
+ expect(screen.queryByRole('listbox')).not.toBeInTheDocument()
+ expect(onCancel).not.toHaveBeenCalled()
+ await user.click(
+ screen.getByRole('textbox', { name: 'workflowAgent.nodes.agent.outputVars.nameLabel' }),
+ )
+ await user.keyboard('{Escape}')
+ expect(onCancel).toHaveBeenCalledOnce()
+ })
+})
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
index 5d8f5df09a6..5f51fe322a3 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
@@ -24,9 +24,7 @@ const CANCEL_HOTKEY = 'Escape' satisfies Hotkey
const CONFIRM_HOTKEY = 'Mod+Enter' satisfies Hotkey
function ConfirmHotkeyHint() {
- const displayKeys = formatForDisplay(CONFIRM_HOTKEY, { separatorToken: ' ' })
- .split(' ')
- .filter(Boolean)
+ const displayKeys = formatForDisplay(CONFIRM_HOTKEY, { parts: true })
return (
<KbdGroup aria-hidden="true">
@@ -58,7 +56,7 @@ export function OutputEditCard({
}) {
const { t } = useTranslation(['common', 'workflowAgent'])
const nameErrorId = useId()
- const editorRef = useRef<HTMLDivElement>(null)
+ const editorRef = useRef<HTMLFormElement>(null)
const [draft, setDraft] = useState(state.draft)
const trimmedName = draft.name.trim()
const duplicateName = existingOutputs.some(
@@ -77,129 +75,153 @@ export function OutputEditCard({
if (confirmDisabled) return
onConfirm(createOutputFromDraft(draft, { includeDefaultValue: allowDefaultValue }), state)
}
- useHotkey(CONFIRM_HOTKEY, handleConfirm, {
- target: editorRef,
- ignoreInputs: false,
- })
- useHotkey(CANCEL_HOTKEY, onCancel, { target: editorRef, ignoreInputs: false })
+ useHotkey(
+ CONFIRM_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented || event.isComposing) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ editorRef.current?.requestSubmit()
+ },
+ {
+ target: editorRef,
+ enabled: !confirmDisabled,
+ ignoreInputs: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
+ useHotkey(
+ CANCEL_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented || event.isComposing) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ onCancel()
+ },
+ {
+ target: editorRef,
+ ignoreInputs: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
return (
- <div ref={editorRef}>
- <Form
- aria-label={t(($) => $['nodes.agent.outputVars.editorLabel'], { ns: 'workflowAgent' })}
- className="flex flex-col overflow-hidden rounded-xl border border-components-panel-border bg-components-panel-bg shadow-md shadow-shadow-shadow-4"
- onSubmit={(event) => {
- event.preventDefault()
- handleConfirm()
- }}
- >
- <div className="px-2 pt-2">
- <div className="flex h-6 items-center gap-x-2">
- <Field name="name" invalid={hasNameError} className="contents">
- <FieldLabel className="sr-only">
- {t(($) => $['nodes.agent.outputVars.nameLabel'], { ns: 'workflowAgent' })}
- </FieldLabel>
- <Input
- aria-describedby={hasNameError ? nameErrorId : undefined}
- // oxlint-disable-next-line jsx-a11y/no-autofocus -- Inline editor opens from an explicit user action and should focus the first editable field.
- autoFocus
- required
- pattern={OUTPUT_NAME_PATTERN_SOURCE}
- value={draft.name}
- placeholder={t(($) => $['nodes.agent.outputVars.namePlaceholder'], {
- ns: 'workflowAgent',
- })}
- className="h-6 w-24 rounded-md px-1.5 py-0 code-sm-semibold"
- onChange={(event) => updateDraft({ name: event.currentTarget.value })}
- />
- </Field>
- <OutputTypeSelect
- value={draft.type}
- onChange={(value) => updateDraft({ type: value })}
- />
- <Field name="required" className="contents">
- <FieldLabel className="flex h-6 items-center gap-x-1 system-xs-regular text-text-tertiary">
- <Switch
- size="xs"
- checked={draft.required}
- onCheckedChange={(required) => updateDraft({ required })}
- />
- {t(($) => $['nodes.agent.outputVars.requiredLabel'], { ns: 'workflowAgent' })}
- </FieldLabel>
- </Field>
- </div>
- {hasNameError && (
- <Field name="nameError" invalid className="contents">
- <FieldError
- id={nameErrorId}
- match
- className="mt-1 px-1 py-0 system-xs-regular text-text-destructive"
- >
- {duplicateName
- ? t(($) => $['nodes.agent.outputVars.nameDuplicate'], { ns: 'workflowAgent' })
- : t(($) => $['nodes.agent.outputVars.nameInvalid'], { ns: 'workflowAgent' })}
- </FieldError>
- </Field>
- )}
- <Field name="description" className="contents">
+ <Form
+ ref={editorRef}
+ aria-label={t(($) => $['nodes.agent.outputVars.editorLabel'], { ns: 'workflowAgent' })}
+ className="flex flex-col overflow-hidden rounded-xl border border-components-panel-border bg-components-panel-bg shadow-md shadow-shadow-shadow-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ handleConfirm()
+ }}
+ >
+ <div className="px-2 pt-2">
+ <div className="flex h-6 items-center gap-x-2">
+ <Field name="name" invalid={hasNameError} className="contents">
<FieldLabel className="sr-only">
- {t(($) => $['nodes.agent.outputVars.descriptionLabel'], { ns: 'workflowAgent' })}
+ {t(($) => $['nodes.agent.outputVars.nameLabel'], { ns: 'workflowAgent' })}
</FieldLabel>
<Input
- value={draft.description}
- placeholder={t(($) => $['nodes.agent.outputVars.descriptionPlaceholder'], {
+ aria-describedby={hasNameError ? nameErrorId : undefined}
+ // oxlint-disable-next-line jsx-a11y/no-autofocus -- Inline editor opens from an explicit user action and should focus the first editable field.
+ autoFocus
+ required
+ pattern={OUTPUT_NAME_PATTERN_SOURCE}
+ value={draft.name}
+ placeholder={t(($) => $['nodes.agent.outputVars.namePlaceholder'], {
ns: 'workflowAgent',
})}
- className="mt-2 h-5 rounded-md border-transparent bg-transparent px-1 py-0 system-xs-regular shadow-none hover:border-transparent hover:bg-transparent focus:bg-transparent"
- onChange={(event) => updateDraft({ description: event.currentTarget.value })}
+ className="h-6 w-24 rounded-md px-1.5 py-0 code-sm-semibold"
+ onChange={(event) => updateDraft({ name: event.currentTarget.value })}
/>
</Field>
- </div>
- {allowDefaultValue && (
- <Collapsible>
- <CollapsibleTrigger className="group/collapsible flex h-8 min-h-8 w-full touch-manipulation items-center justify-start gap-2 gap-x-0.5 border-y border-divider-subtle pr-2 pl-2.5 text-start system-xs-regular text-text-tertiary outline-hidden select-none hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset">
- <span
- aria-hidden="true"
- className="i-ri-arrow-down-double-line size-3 transition-transform duration-100 ease-out group-data-panel-open/collapsible:rotate-180 motion-reduce:transition-none"
+ <OutputTypeSelect value={draft.type} onChange={(value) => updateDraft({ type: value })} />
+ <Field name="required" className="contents">
+ <FieldLabel className="flex h-6 items-center gap-x-1 system-xs-regular text-text-tertiary">
+ <Switch
+ size="xs"
+ checked={draft.required}
+ onCheckedChange={(required) => updateDraft({ required })}
/>
- {t(($) => $['nodes.agent.outputVars.showAdvancedOptions'], { ns: 'workflowAgent' })}
- </CollapsibleTrigger>
- <CollapsiblePanel className="border-t border-divider-subtle">
- <div className="px-3 py-2">
- <Field name="defaultValue">
- <FieldLabel className="system-xs-medium">
- {t(($) => $['nodes.agent.outputVars.defaultValueLabel'], {
- ns: 'workflowAgent',
- })}
- </FieldLabel>
- <Textarea
- size="small"
- value={draft.defaultValue}
- placeholder={t(($) => $['nodes.agent.outputVars.defaultValuePlaceholder'], {
- ns: 'workflowAgent',
- })}
- className="min-h-6"
- onValueChange={(defaultValue) => updateDraft({ defaultValue })}
- />
- {defaultValueErrorKey && (
- <FieldError match className="py-0 system-xs-regular text-text-destructive">
- {t(($) => $[defaultValueErrorKey], { ns: 'workflowAgent' })}
- </FieldError>
- )}
- </Field>
- </div>
- </CollapsiblePanel>
- </Collapsible>
- )}
- <div className="flex h-12 items-center justify-end gap-x-2 px-3">
- <Button type="button" size="small" variant="secondary" onClick={onCancel}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- <Button type="submit" size="small" variant="primary" disabled={confirmDisabled}>
- {t(($) => $['nodes.agent.outputVars.confirm'], { ns: 'workflowAgent' })}
- <ConfirmHotkeyHint />
- </Button>
+ {t(($) => $['nodes.agent.outputVars.requiredLabel'], { ns: 'workflowAgent' })}
+ </FieldLabel>
+ </Field>
</div>
- </Form>
- </div>
+ {hasNameError && (
+ <Field name="nameError" invalid className="contents">
+ <FieldError
+ id={nameErrorId}
+ match
+ className="mt-1 px-1 py-0 system-xs-regular text-text-destructive"
+ >
+ {duplicateName
+ ? t(($) => $['nodes.agent.outputVars.nameDuplicate'], { ns: 'workflowAgent' })
+ : t(($) => $['nodes.agent.outputVars.nameInvalid'], { ns: 'workflowAgent' })}
+ </FieldError>
+ </Field>
+ )}
+ <Field name="description" className="contents">
+ <FieldLabel className="sr-only">
+ {t(($) => $['nodes.agent.outputVars.descriptionLabel'], { ns: 'workflowAgent' })}
+ </FieldLabel>
+ <Input
+ value={draft.description}
+ placeholder={t(($) => $['nodes.agent.outputVars.descriptionPlaceholder'], {
+ ns: 'workflowAgent',
+ })}
+ className="mt-2 h-5 rounded-md border-transparent bg-transparent px-1 py-0 system-xs-regular shadow-none hover:border-transparent hover:bg-transparent focus:bg-transparent"
+ onChange={(event) => updateDraft({ description: event.currentTarget.value })}
+ />
+ </Field>
+ </div>
+ {allowDefaultValue && (
+ <Collapsible>
+ <CollapsibleTrigger className="group/collapsible flex h-8 min-h-8 w-full touch-manipulation items-center justify-start gap-2 gap-x-0.5 border-y border-divider-subtle pr-2 pl-2.5 text-start system-xs-regular text-text-tertiary outline-hidden select-none hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset">
+ <span
+ aria-hidden="true"
+ className="i-ri-arrow-down-double-line size-3 transition-transform duration-100 ease-out group-data-panel-open/collapsible:rotate-180 motion-reduce:transition-none"
+ />
+ {t(($) => $['nodes.agent.outputVars.showAdvancedOptions'], { ns: 'workflowAgent' })}
+ </CollapsibleTrigger>
+ <CollapsiblePanel className="border-t border-divider-subtle">
+ <div className="px-3 py-2">
+ <Field name="defaultValue">
+ <FieldLabel className="system-xs-medium">
+ {t(($) => $['nodes.agent.outputVars.defaultValueLabel'], {
+ ns: 'workflowAgent',
+ })}
+ </FieldLabel>
+ <Textarea
+ size="small"
+ value={draft.defaultValue}
+ placeholder={t(($) => $['nodes.agent.outputVars.defaultValuePlaceholder'], {
+ ns: 'workflowAgent',
+ })}
+ className="min-h-6"
+ onValueChange={(defaultValue) => updateDraft({ defaultValue })}
+ />
+ {defaultValueErrorKey && (
+ <FieldError match className="py-0 system-xs-regular text-text-destructive">
+ {t(($) => $[defaultValueErrorKey], { ns: 'workflowAgent' })}
+ </FieldError>
+ )}
+ </Field>
+ </div>
+ </CollapsiblePanel>
+ </Collapsible>
+ )}
+ <div className="flex h-12 items-center justify-end gap-x-2 px-3">
+ <Button type="button" size="small" variant="secondary" onClick={onCancel}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
+ <Button type="submit" size="small" variant="primary" disabled={confirmDisabled}>
+ {t(($) => $['nodes.agent.outputVars.confirm'], { ns: 'workflowAgent' })}
+ <ConfirmHotkeyHint />
+ </Button>
+ </div>
+ </Form>
)
}
diff --git a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content.spec.tsx b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content.spec.tsx
index c20f48cfd89..9d74c8930bf 100644
--- a/web/app/components/workflow/nodes/human-input/components/__tests__/form-content.spec.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/__tests__/form-content.spec.tsx
@@ -183,7 +183,7 @@ describe('FormContent', () => {
editable: true,
shortcutPopups: [
expect.objectContaining({
- hotkey: ['mod', '/'],
+ hotkey: 'Mod+/',
displayMode: 'workflow-panel-adjacent-center',
}),
],
diff --git a/web/app/components/workflow/nodes/human-input/components/form-content.tsx b/web/app/components/workflow/nodes/human-input/components/form-content.tsx
index 10c7c627d94..99ef0113458 100644
--- a/web/app/components/workflow/nodes/human-input/components/form-content.tsx
+++ b/web/app/components/workflow/nodes/human-input/components/form-content.tsx
@@ -149,7 +149,7 @@ const FormContent: FC<FormContentProps> = ({
return [
{
- hotkey: ['mod', '/'],
+ hotkey: 'Mod+/' as const,
displayMode: 'workflow-panel-adjacent-center' as const,
Popup: AddInputFieldShortcutPopup,
},
diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/__tests__/advanced-actions.spec.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/__tests__/advanced-actions.spec.tsx
index ed081a06ee7..964f143ce3d 100644
--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/__tests__/advanced-actions.spec.tsx
+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/__tests__/advanced-actions.spec.tsx
@@ -1,65 +1,62 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
+import type { ComponentProps } from 'react'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { useRef } from 'react'
import { AdvancedActions } from '../advanced-actions'
-const hotkeyRegistrations = vi.hoisted(
- () =>
- new Map<
- string,
- {
- callback: () => void
- options?: { enabled?: boolean; ignoreInputs?: boolean }
- }
- >(),
-)
-
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- useHotkey: (
- hotkey: string,
- callback: () => void,
- options?: { enabled?: boolean; ignoreInputs?: boolean },
- ) => {
- hotkeyRegistrations.set(hotkey, { callback, options })
- },
- }
-})
-
-describe('AdvancedActions', () => {
- beforeEach(() => {
- hotkeyRegistrations.clear()
+function Editor(props: Omit<ComponentProps<typeof AdvancedActions>, 'target'>) {
+ const target = useRef<HTMLDivElement>(null)
+ return (
+ <div ref={target}>
+ <input aria-label="Property name" />
+ <AdvancedActions {...props} target={target} />
+ </div>
+ )
+}
+
+function submit(target: HTMLElement, options: KeyboardEventInit = {}) {
+ const event = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ ...options,
})
+ fireEvent(target, event)
+ fireEvent.keyUp(target, { key: 'Enter', ctrlKey: true })
+ return event
+}
- it('runs the matching actions from the buttons', async () => {
- const user = userEvent.setup()
- const onCancel = vi.fn()
+describe('AdvancedActions', () => {
+ it('confirms from the property input and the confirm button', () => {
const onConfirm = vi.fn()
- render(<AdvancedActions isConfirmDisabled={false} onCancel={onCancel} onConfirm={onConfirm} />)
-
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- await user.click(screen.getByRole('button', { name: /^common\.operation\.confirm/ }))
-
+ const onCancel = vi.fn()
+ render(<Editor onConfirm={onConfirm} onCancel={onCancel} isConfirmDisabled={false} />)
+ expect(submit(screen.getByRole('textbox')).defaultPrevented).toBe(true)
+ fireEvent.click(screen.getByRole('button', { name: /operation.confirm/ }))
+ fireEvent.click(screen.getByRole('button', { name: /operation.cancel/ }))
+ expect(onConfirm).toHaveBeenCalledTimes(2)
expect(onCancel).toHaveBeenCalledOnce()
- expect(onConfirm).toHaveBeenCalledOnce()
})
- it('registers the confirm shortcut for input fields', () => {
+ it('does not submit from outside the property editor or while disabled', () => {
const onConfirm = vi.fn()
- render(<AdvancedActions isConfirmDisabled={false} onCancel={vi.fn()} onConfirm={onConfirm} />)
-
- const registration = hotkeyRegistrations.get('Mod+Enter')
- registration?.callback()
-
- expect(onConfirm).toHaveBeenCalledOnce()
- expect(registration?.options).toEqual({ enabled: true, ignoreInputs: false })
+ const { rerender } = render(
+ <Editor onConfirm={onConfirm} onCancel={vi.fn()} isConfirmDisabled={false} />,
+ )
+ expect(submit(document.body).defaultPrevented).toBe(false)
+ rerender(<Editor onConfirm={onConfirm} onCancel={vi.fn()} isConfirmDisabled />)
+ expect(screen.getByRole('button', { name: /operation.confirm/ })).toBeDisabled()
+ expect(submit(screen.getByRole('textbox')).defaultPrevented).toBe(false)
+ expect(onConfirm).not.toHaveBeenCalled()
})
- it('disables both confirmation paths when confirmation is unavailable', () => {
- render(<AdvancedActions isConfirmDisabled onCancel={vi.fn()} onConfirm={vi.fn()} />)
-
- expect(screen.getByRole('button', { name: /^common\.operation\.confirm/ })).toBeDisabled()
- expect(hotkeyRegistrations.get('Mod+Enter')?.options?.enabled).toBe(false)
+ it('preserves claimed and IME events', () => {
+ const onConfirm = vi.fn()
+ render(<Editor onConfirm={onConfirm} onCancel={vi.fn()} isConfirmDisabled={false} />)
+ const input = screen.getByRole('textbox')
+ expect(submit(input, { isComposing: true }).defaultPrevented).toBe(false)
+ input.addEventListener('keydown', (event) => event.preventDefault(), { once: true })
+ submit(input)
+ expect(onConfirm).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/advanced-actions.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/advanced-actions.tsx
index 57de638f37c..2f945ff7127 100644
--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/advanced-actions.tsx
+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/advanced-actions.tsx
@@ -1,4 +1,5 @@
import type { Hotkey } from '@tanstack/react-hotkeys'
+import type { RefObject } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { useHotkey } from '@tanstack/react-hotkeys'
import { useTranslation } from 'react-i18next'
@@ -7,21 +8,34 @@ import { ShortcutKbd } from '@/app/components/workflow/shortcuts/shortcut-kbd'
const JSON_SCHEMA_CONFIRM_HOTKEY = 'Mod+Enter' satisfies Hotkey
type AdvancedActionsProps = {
+ target: RefObject<HTMLDivElement | null>
isConfirmDisabled: boolean
onCancel: () => void
onConfirm: () => void
}
-export function AdvancedActions({ isConfirmDisabled, onCancel, onConfirm }: AdvancedActionsProps) {
+export function AdvancedActions({
+ target,
+ isConfirmDisabled,
+ onCancel,
+ onConfirm,
+}: AdvancedActionsProps) {
const { t } = useTranslation(['common'])
useHotkey(
JSON_SCHEMA_CONFIRM_HOTKEY,
- () => {
+ (event) => {
+ if (event.defaultPrevented || event.isComposing) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
onConfirm()
},
{
+ target,
enabled: !isConfirmDisabled,
+ preventDefault: false,
+ stopPropagation: false,
ignoreInputs: false,
},
)
diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/index.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/index.tsx
index 2871c9c5a12..58cbeec8ffa 100644
--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/index.tsx
+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/edit-card/index.tsx
@@ -67,6 +67,7 @@ const EditCard: FC<EditCardProps> = ({ fields, depth, path, parentPath }) => {
const setAdvancedEditing = useVisualEditorStore((state) => state.setAdvancedEditing)
const { emit, useSubscribe } = useMittContext()
const blurWithActions = useRef(false)
+ const editorRef = useRef<HTMLDivElement>(null)
const maximumDepthReached = depth === JSON_SCHEMA_MAX_DEPTH
const disableAddBtn =
@@ -227,7 +228,10 @@ const EditCard: FC<EditCardProps> = ({ fields, depth, path, parentPath }) => {
})
return (
- <div className="flex flex-col rounded-lg bg-components-panel-bg py-0.5 shadow-sm shadow-shadow-shadow-4">
+ <div
+ ref={editorRef}
+ className="flex flex-col rounded-lg bg-components-panel-bg py-0.5 shadow-sm shadow-shadow-shadow-4"
+ >
<div className="flex h-6 items-center pr-0.5 pl-1">
<div className="flex grow items-center gap-x-1">
<AutoWidthInput
@@ -255,6 +259,7 @@ const EditCard: FC<EditCardProps> = ({ fields, depth, path, parentPath }) => {
<Separator decorative orientation="vertical" className="mx-2 h-3" />
{isAdvancedEditing ? (
<AdvancedActions
+ target={editorRef}
isConfirmDisabled={currentFields.name === ''}
onCancel={handleCancel}
onConfirm={handleConfirm}
diff --git a/web/app/components/workflow/nodes/variable-assigner/components/add-variable/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/variable-assigner/components/add-variable/__tests__/index.spec.tsx
index e5973f6b3a0..b694ee6e720 100644
--- a/web/app/components/workflow/nodes/variable-assigner/components/add-variable/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/variable-assigner/components/add-variable/__tests__/index.spec.tsx
@@ -1,6 +1,7 @@
import type { VariableAssignerNodeType } from '../../../types'
import type { NodeOutPutVar, Var } from '@/app/components/workflow/types'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { VarType } from '@/app/components/workflow/types'
import AddVariable from '../index'
@@ -42,8 +43,9 @@ describe('variable-assigner/add-variable', () => {
vi.clearAllMocks()
})
- it('opens the real popup and assigns the selected variable', () => {
- const { container } = render(
+ it('opens the real popup from its named trigger and assigns the selected variable', async () => {
+ const user = userEvent.setup()
+ render(
<AddVariable
availableVars={availableVars}
variableAssignerNodeId="node-target"
@@ -52,20 +54,23 @@ describe('variable-assigner/add-variable', () => {
/>,
)
- const triggerButton = container.querySelector('button')!
- const triggerVisual = triggerButton.firstElementChild!
+ const triggerButton = screen.getByRole('button', {
+ name: 'workflowLogic.nodes.variableAssigner.setAssignVariable',
+ })
expect(triggerButton).not.toHaveAttribute('data-popup-open')
- fireEvent.click(triggerButton)
+ await user.click(triggerButton)
expect(triggerButton).toHaveAttribute('data-popup-open', '')
- expect(triggerVisual).toHaveClass('bg-primary-600!')
+ expect(triggerButton).toHaveAccessibleName(
+ 'workflowLogic.nodes.variableAssigner.setAssignVariable',
+ )
expect(
screen.getByText('workflowLogic.nodes.variableAssigner.setAssignVariable'),
).toBeInTheDocument()
- fireEvent.click(screen.getByText('answer'))
+ await user.click(screen.getByText('answer'))
expect(mockHandleAssignVariableValueChange).toHaveBeenCalledWith(
'node-target',
@@ -77,4 +82,42 @@ describe('variable-assigner/add-variable', () => {
'group-1',
)
})
+
+ it('assigns the highlighted variable from the focused popup without handling outside keys', async () => {
+ const user = userEvent.setup()
+ render(
+ <>
+ <input aria-label="Outside" />
+ <AddVariable
+ availableVars={[
+ {
+ ...availableVars[0]!,
+ vars: [...availableVars[0]!.vars, { variable: 'second', type: VarType.string }],
+ },
+ ]}
+ variableAssignerNodeId="node-target"
+ variableAssignerNodeData={nodeData}
+ />
+ </>,
+ )
+
+ await user.click(
+ screen.getByRole('button', {
+ name: 'workflowLogic.nodes.variableAssigner.setAssignVariable',
+ }),
+ )
+ const popup = screen.getByRole('dialog')
+ expect(popup).toContainElement(document.activeElement as HTMLElement)
+ await user.keyboard('{ArrowDown}{Enter}')
+
+ expect(mockHandleAssignVariableValueChange).toHaveBeenCalledWith(
+ 'node-target',
+ ['node-source', 'second'],
+ expect.objectContaining({ variable: 'second' }),
+ undefined,
+ )
+ await user.click(screen.getByRole('textbox', { name: 'Outside' }))
+ await user.keyboard('{ArrowDown}{Enter}')
+ expect(mockHandleAssignVariableValueChange).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/web/app/components/workflow/nodes/variable-assigner/components/add-variable/index.tsx b/web/app/components/workflow/nodes/variable-assigner/components/add-variable/index.tsx
index c84890b93e3..4c799613308 100644
--- a/web/app/components/workflow/nodes/variable-assigner/components/add-variable/index.tsx
+++ b/web/app/components/workflow/nodes/variable-assigner/components/add-variable/index.tsx
@@ -2,7 +2,8 @@ import type { VariableAssignerNodeType } from '../../types'
import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
-import { memo, useCallback, useState } from 'react'
+import { memo, useCallback, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
import AddVariablePopup from '@/app/components/workflow/nodes/_base/components/add-variable-popup'
import { useVariableAssigner } from '../../hooks'
@@ -18,7 +19,9 @@ const AddVariable = ({
variableAssignerNodeData,
handleId,
}: AddVariableProps) => {
+ const { t } = useTranslation(['workflowLogic'])
const [open, setOpen] = useState(false)
+ const popupRef = useRef<HTMLDivElement>(null)
const { handleAssignVariableValueChange } = useVariableAssigner()
const handleSelectVariable = useCallback(
@@ -37,6 +40,9 @@ const AddVariable = ({
<button
{...props}
type="button"
+ aria-label={t(($) => $['nodes.variableAssigner.setAssignVariable'], {
+ ns: 'workflowLogic',
+ })}
className={cn('block border-none bg-transparent p-0', props.className)}
>
<div
@@ -63,11 +69,16 @@ const AddVariable = ({
)}
/>
<PopoverContent
+ ref={popupRef}
placement="right"
sideOffset={4}
className="border-none bg-transparent shadow-none"
>
- <AddVariablePopup onSelect={handleSelectVariable} availableVars={availableVars} />
+ <AddVariablePopup
+ onSelect={handleSelectVariable}
+ availableVars={availableVars}
+ keyboardTarget={popupRef}
+ />
</PopoverContent>
</Popover>
</div>
diff --git a/web/app/components/workflow/note-node/index.tsx b/web/app/components/workflow/note-node/index.tsx
index 90bc7545580..a81b9e4f7ed 100644
--- a/web/app/components/workflow/note-node/index.tsx
+++ b/web/app/components/workflow/note-node/index.tsx
@@ -29,7 +29,6 @@ const Icon = () => {
const NoteNode = ({ id, data }: NodeProps<NoteNodeType>) => {
const { t } = useTranslation(['workflow'])
const controlPromptEditorRerenderKey = useStore((s) => s.controlPromptEditorRerenderKey)
- const setHistoryShortcutsEnabled = useStore((s) => s.setHistoryShortcutsEnabled)
const ref = useRef<HTMLDivElement | null>(null)
const theme = data.theme
const { handleThemeChange, handleEditorChange, handleShowAuthorChange } = useNote(id)
@@ -90,7 +89,6 @@ const NoteNode = ({ id, data }: NodeProps<NoteNodeType>) => {
containerElement={ref.current}
placeholder={t(($) => $['nodes.note.editor.placeholder'], { ns: 'workflow' }) || ''}
onChange={handleEditorChange}
- setHistoryShortcutsEnabled={setHistoryShortcutsEnabled}
/>
</div>
</div>
diff --git a/web/app/components/workflow/note-node/note-editor/__tests__/editor.spec.tsx b/web/app/components/workflow/note-node/note-editor/__tests__/editor.spec.tsx
index 145dc14b724..a793457dccb 100644
--- a/web/app/components/workflow/note-node/note-editor/__tests__/editor.spec.tsx
+++ b/web/app/components/workflow/note-node/note-editor/__tests__/editor.spec.tsx
@@ -3,7 +3,7 @@ import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { $createLinkNode } from '@lexical/link'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, render, screen, waitFor } from '@testing-library/react'
import { $createParagraphNode, $createTextNode, $getRoot } from 'lexical'
import { useEffect } from 'react'
import { NoteEditorContextProvider } from '../context'
@@ -88,23 +88,6 @@ describe('Editor', () => {
})
})
- // Focus and blur should toggle workflow shortcuts while editing content.
- describe('Focus Management', () => {
- it('should disable shortcuts on focus and re-enable them on blur-sm', () => {
- const setHistoryShortcutsEnabled = vi.fn()
-
- renderEditor({ setHistoryShortcutsEnabled })
-
- const contentEditable = screen.getByRole('textbox')
-
- fireEvent.focus(contentEditable)
- fireEvent.blur(contentEditable)
-
- expect(setHistoryShortcutsEnabled).toHaveBeenNthCalledWith(1, false)
- expect(setHistoryShortcutsEnabled).toHaveBeenNthCalledWith(2, true)
- })
- })
-
// Lexical change events should be forwarded to the external onChange callback.
describe('Change Handling', () => {
it('should pass editor updates through onChange', async () => {
diff --git a/web/app/components/workflow/note-node/note-editor/editor.tsx b/web/app/components/workflow/note-node/note-editor/editor.tsx
index bb8acc5c205..13e82f73bbf 100644
--- a/web/app/components/workflow/note-node/note-editor/editor.tsx
+++ b/web/app/components/workflow/note-node/note-editor/editor.tsx
@@ -20,14 +20,8 @@ type EditorProps = {
placeholder?: string
onChange?: (editorState: EditorState) => void
containerElement: HTMLDivElement | null
- setHistoryShortcutsEnabled?: (v: boolean) => void
}
-const Editor = ({
- placeholder,
- onChange,
- containerElement,
- setHistoryShortcutsEnabled,
-}: EditorProps) => {
+const Editor = ({ placeholder, onChange, containerElement }: EditorProps) => {
const { t } = useTranslation(['workflow'])
const handleEditorChange = useCallback(
(editorState: EditorState) => {
@@ -43,8 +37,6 @@ const Editor = ({
<div>
<ContentEditable
aria-label={t(($) => $['nodes.note.editor.label'], { ns: 'workflow' })}
- onFocus={() => setHistoryShortcutsEnabled?.(false)}
- onBlur={() => setHistoryShortcutsEnabled?.(true)}
spellCheck={false}
className="size-full text-text-secondary caret-primary-600 outline-hidden"
/>
diff --git a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/index.spec.tsx b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/index.spec.tsx
index 74cc15b5eb1..638dc030d4e 100644
--- a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/index.spec.tsx
@@ -1,4 +1,5 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { ReactFlowProvider } from 'reactflow'
import { NoteTheme } from '../../../types'
import Toolbar from '../index'
@@ -61,15 +62,17 @@ describe('NoteEditor Toolbar', () => {
const onShowAuthorChange = vi.fn()
const onThemeChange = vi.fn()
const { container } = render(
- <Toolbar
- theme={NoteTheme.blue}
- onThemeChange={onThemeChange}
- onCopy={onCopy}
- onDuplicate={onDuplicate}
- onDelete={onDelete}
- showAuthor={false}
- onShowAuthorChange={onShowAuthorChange}
- />,
+ <ReactFlowProvider>
+ <Toolbar
+ theme={NoteTheme.blue}
+ onThemeChange={onThemeChange}
+ onCopy={onCopy}
+ onDuplicate={onDuplicate}
+ onDelete={onDelete}
+ showAuthor={false}
+ onShowAuthorChange={onShowAuthorChange}
+ />
+ </ReactFlowProvider>,
)
expect(screen.getByText('workflow.nodes.note.editor.medium')).toBeInTheDocument()
diff --git a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx
index 0474c4464bb..6ee4a8e283b 100644
--- a/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx
+++ b/web/app/components/workflow/note-node/note-editor/toolbar/__tests__/operator.spec.tsx
@@ -1,5 +1,8 @@
-import { render, screen } from '@testing-library/react'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { act, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { ReactFlowProvider } from 'reactflow'
import Operator from '../operator'
const renderOperator = (showAuthor = false) => {
@@ -8,15 +11,24 @@ const renderOperator = (showAuthor = false) => {
const onDelete = vi.fn()
const onShowAuthorChange = vi.fn()
- render(
- <Operator
- onCopy={onCopy}
- onDuplicate={onDuplicate}
- onDelete={onDelete}
- showAuthor={showAuthor}
- onShowAuthorChange={onShowAuthorChange}
- />,
- )
+ function NoteMenu() {
+ const [authorVisible, setAuthorVisible] = useState(showAuthor)
+ return (
+ <ReactFlowProvider>
+ <Operator
+ onCopy={onCopy}
+ onDuplicate={onDuplicate}
+ onDelete={onDelete}
+ showAuthor={authorVisible}
+ onShowAuthorChange={(value) => {
+ setAuthorVisible(value)
+ onShowAuthorChange(value)
+ }}
+ />
+ </ReactFlowProvider>
+ )
+ }
+ render(<NoteMenu />)
return {
onCopy,
@@ -27,6 +39,19 @@ const renderOperator = (showAuthor = false) => {
}
describe('NoteEditor Toolbar Operator', () => {
+ it.each(['c', 'd', 'Delete'])('runs %s from its focused note menu', async (key) => {
+ const user = userEvent.setup()
+ const { onCopy, onDuplicate, onDelete } = renderOperator()
+ await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
+ const item = screen.getByRole('menuitem', { name: /workflow.common.copy/ })
+ act(() => item.focus())
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await user.keyboard(key.length === 1 ? `{${mod}>}${key}{/${mod}}` : `{${key}}`)
+ const action = key === 'c' ? onCopy : key === 'd' ? onDuplicate : onDelete
+ expect(action).toHaveBeenCalledTimes(1)
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ })
+
it('triggers copy, duplicate, and delete from the opened menu', async () => {
const user = userEvent.setup()
const { onCopy, onDelete, onDuplicate } = renderOperator()
@@ -44,13 +69,28 @@ describe('NoteEditor Toolbar Operator', () => {
expect(onDelete).toHaveBeenCalledTimes(1)
})
- it('keeps the menu open when toggling show author', async () => {
+ it('lets the keyboard toggle show author and return to the trigger', async () => {
const user = userEvent.setup()
- renderOperator(true)
+ const { onShowAuthorChange } = renderOperator(true)
- await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
- await user.click(screen.getByRole('switch'))
+ const trigger = screen.getByRole('button', { name: 'common.operation.more' })
+ await user.tab()
+ expect(trigger).toHaveFocus()
+ await user.keyboard('{Enter}')
+ const option = screen.getByRole('menuitemcheckbox', {
+ name: 'workflow.nodes.note.editor.showAuthor',
+ checked: true,
+ })
+ await user.keyboard('{End}{ArrowUp}')
+ expect(option).toHaveFocus()
+ await user.keyboard(' ')
- expect(screen.getByText('workflow.nodes.note.editor.showAuthor')).toBeInTheDocument()
+ expect(onShowAuthorChange).toHaveBeenCalledWith(false)
+ expect(option).toHaveAttribute('aria-checked', 'false')
+ expect(option).toHaveFocus()
+ expect(screen.getByRole('menu')).toBeInTheDocument()
+ await user.keyboard('{Escape}')
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ expect(trigger).toHaveFocus()
})
})
diff --git a/web/app/components/workflow/note-node/note-editor/toolbar/operator.tsx b/web/app/components/workflow/note-node/note-editor/toolbar/operator.tsx
index 6a21318e5e3..8789e975266 100644
--- a/web/app/components/workflow/note-node/note-editor/toolbar/operator.tsx
+++ b/web/app/components/workflow/note-node/note-editor/toolbar/operator.tsx
@@ -1,6 +1,8 @@
import { cn } from '@langgenius/dify-ui/cn'
import {
DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuCheckboxItemIndicator,
DropdownMenuItem,
DropdownMenuPopup,
DropdownMenuPortal,
@@ -8,9 +10,10 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
-import { Switch } from '@langgenius/dify-ui/switch'
-import { memo, useState } from 'react'
+import { memo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { useStoreApi } from 'reactflow'
+import { handleWorkflowMenuKeyDown } from '@/app/components/workflow/shortcuts/handle-workflow-menu-key-down'
import { ShortcutKbd } from '@/app/components/workflow/shortcuts/shortcut-kbd'
export type OperatorProps = {
@@ -29,9 +32,32 @@ const Operator = ({
}: OperatorProps) => {
const { t } = useTranslation(['common', 'workflow'])
const [open, setOpen] = useState(false)
+ const deletingRef = useRef(false)
+ const flowStore = useStoreApi()
+
+ function handleOpenChange(nextOpen: boolean) {
+ if (nextOpen) deletingRef.current = false
+ setOpen(nextOpen)
+ }
+
+ function handleCopy() {
+ setOpen(false)
+ onCopy()
+ }
+
+ function handleDuplicate() {
+ setOpen(false)
+ onDuplicate()
+ }
+
+ function handleDelete() {
+ deletingRef.current = true
+ setOpen(false)
+ onDelete()
+ }
return (
- <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenu open={open} onOpenChange={handleOpenChange}>
<DropdownMenuTrigger
aria-label={t(($) => $['operation.more'], { ns: 'common' })}
className={cn(
@@ -42,7 +68,7 @@ const Operator = ({
event.preventDefault()
event.stopPropagation()
event.preventBaseUIHandler()
- setOpen((prev) => !prev)
+ handleOpenChange(!open)
}}
onClick={(event) => event.stopPropagation()}
>
@@ -50,25 +76,28 @@ const Operator = ({
</DropdownMenuTrigger>
<DropdownMenuPortal>
<DropdownMenuPositioner placement="bottom-end" sideOffset={4}>
- <DropdownMenuPopup>
+ <DropdownMenuPopup
+ finalFocus={() => (deletingRef.current ? (flowStore.getState().domNode ?? true) : true)}
+ onKeyDown={(event) =>
+ handleWorkflowMenuKeyDown(event, [
+ ['workflow.copy', handleCopy],
+ ['workflow.duplicate', handleDuplicate],
+ ['workflow.delete', handleDelete],
+ ])
+ }
+ >
<div className="min-w-48 rounded-md border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-xl">
<div className="p-1">
<DropdownMenuItem
className="justify-between rounded-md px-3 text-sm text-text-secondary"
- onClick={() => {
- setOpen(false)
- onCopy()
- }}
+ onClick={handleCopy}
>
{t(($) => $['common.copy'], { ns: 'workflow' })}
<ShortcutKbd shortcut="workflow.copy" />
</DropdownMenuItem>
<DropdownMenuItem
className="justify-between rounded-md px-3 text-sm text-text-secondary"
- onClick={() => {
- setOpen(false)
- onDuplicate()
- }}
+ onClick={handleDuplicate}
>
{t(($) => $['common.duplicate'], { ns: 'workflow' })}
<ShortcutKbd shortcut="workflow.duplicate" />
@@ -76,23 +105,22 @@ const Operator = ({
</div>
<DropdownMenuSeparator className="my-0" />
<div className="p-1">
- <div
- className="flex h-8 cursor-pointer items-center justify-between rounded-md px-3 text-sm text-text-secondary hover:bg-state-base-hover"
- onClick={(e) => e.stopPropagation()}
+ <DropdownMenuCheckboxItem
+ checked={showAuthor}
+ onCheckedChange={onShowAuthorChange}
+ closeOnClick={false}
+ className="justify-between rounded-md px-3 text-sm text-text-secondary"
>
- <div>{t(($) => $['nodes.note.editor.showAuthor'], { ns: 'workflow' })}</div>
- <Switch size="lg" checked={showAuthor} onCheckedChange={onShowAuthorChange} />
- </div>
+ {t(($) => $['nodes.note.editor.showAuthor'], { ns: 'workflow' })}
+ <DropdownMenuCheckboxItemIndicator />
+ </DropdownMenuCheckboxItem>
</div>
<DropdownMenuSeparator className="my-0" />
<div className="p-1">
<DropdownMenuItem
variant="destructive"
className="justify-between rounded-md px-3 text-sm text-text-secondary"
- onClick={() => {
- setOpen(false)
- onDelete()
- }}
+ onClick={handleDelete}
>
{t(($) => $['operation.delete'], { ns: 'common' })}
<ShortcutKbd shortcut="workflow.delete" />
diff --git a/web/app/components/workflow/operator/__tests__/zoom-in-out.spec.tsx b/web/app/components/workflow/operator/__tests__/zoom-in-out.spec.tsx
index d3f1599dba7..d61f04ff1d4 100644
--- a/web/app/components/workflow/operator/__tests__/zoom-in-out.spec.tsx
+++ b/web/app/components/workflow/operator/__tests__/zoom-in-out.spec.tsx
@@ -1,4 +1,5 @@
-import { fireEvent, screen, within } from '@testing-library/react'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { act, fireEvent, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { renderWithConsoleQuery } from '@/test/console/query-data'
@@ -100,6 +101,25 @@ describe('workflow zoom controls', () => {
collaborationEnabled = true
})
+ it.each([
+ { key: '1', modifier: 'Mod', zoom: undefined },
+ { key: '1', modifier: 'Shift', zoom: 1 },
+ { key: '5', modifier: 'Shift', zoom: 0.5 },
+ ])('applies $modifier+$key from the focused zoom menu', async ({ key, modifier, zoom }) => {
+ const user = userEvent.setup()
+ renderZoomInOut()
+ await user.click(screen.getByRole('button', { name: '100%' }))
+ const item = screen.getByRole('menuitem', { name: '200%' })
+ act(() => item.focus())
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ const heldKey = modifier === 'Mod' ? mod : modifier
+ await user.keyboard(`{${heldKey}>}${key}{/${heldKey}}`)
+ if (zoom === undefined) expect(mockFitView).toHaveBeenCalledTimes(1)
+ else expect(mockZoomTo).toHaveBeenCalledExactlyOnceWith(zoom)
+ expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledTimes(1)
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()
+ })
+
it('zooms out and zooms in when the viewport is within the supported range', () => {
renderZoomInOut()
diff --git a/web/app/components/workflow/operator/zoom-in-out.tsx b/web/app/components/workflow/operator/zoom-in-out.tsx
index 6162d4e39af..bef66cd24b8 100644
--- a/web/app/components/workflow/operator/zoom-in-out.tsx
+++ b/web/app/components/workflow/operator/zoom-in-out.tsx
@@ -10,12 +10,13 @@ import {
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
import { useSuspenseQuery } from '@tanstack/react-query'
-import { Fragment, memo } from 'react'
+import { Fragment, memo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useReactFlow, useViewport } from 'reactflow'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useNodesSyncDraft } from '../hooks/use-nodes-sync-draft'
import { useWorkflowReadOnly } from '../hooks/use-workflow'
+import { handleWorkflowMenuKeyDown } from '../shortcuts/handle-workflow-menu-key-down'
import { ShortcutKbd } from '../shortcuts/shortcut-kbd'
import TipPopup from './tip-popup'
@@ -53,6 +54,7 @@ const ZoomInOut: FC<ZoomInOutProps> = ({
isCommentMode = false,
}) => {
const { t } = useTranslation(['workflow'])
+ const [open, setOpen] = useState(false)
const { zoomIn, zoomOut, zoomTo, fitView } = useReactFlow()
const { zoom } = useViewport()
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
@@ -150,6 +152,11 @@ const ZoomInOut: FC<ZoomInOutProps> = ({
handleSyncWorkflowDraft()
}
+ function selectZoom(type: ZoomType) {
+ handleZoom(type)
+ setOpen(false)
+ }
+
return (
<div
className={`h-9 cursor-pointer rounded-lg border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 text-[13px] shadow-lg backdrop-blur-[5px] hover:bg-state-base-hover ${workflowReadOnly && 'cursor-not-allowed! opacity-50'} `}
@@ -177,7 +184,7 @@ const ZoomInOut: FC<ZoomInOutProps> = ({
/>
</button>
</TipPopup>
- <DropdownMenu>
+ <DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger
disabled={getWorkflowReadOnly()}
className="flex h-8 w-8.5 items-center justify-center rounded-lg system-sm-medium text-text-tertiary hover:bg-black/5 hover:text-text-secondary data-popup-open:bg-black/5 data-popup-open:text-text-secondary"
@@ -186,7 +193,16 @@ const ZoomInOut: FC<ZoomInOutProps> = ({
</DropdownMenuTrigger>
<DropdownMenuPortal>
<DropdownMenuPositioner placement="top-start" sideOffset={4} alignOffset={-2}>
- <DropdownMenuPopup>
+ <DropdownMenuPopup
+ onKeyDown={(event) => {
+ if (workflowReadOnly) return
+ handleWorkflowMenuKeyDown(event, [
+ ['workflow.zoom-to-fit', () => selectZoom(ZoomType.zoomToFit)],
+ ['workflow.zoom-to-100', () => selectZoom(ZoomType.zoomTo100)],
+ ['workflow.zoom-to-50', () => selectZoom(ZoomType.zoomTo50)],
+ ])
+ }}
+ >
<div className="w-48 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-[5px]">
{zoomOptions.map((options, groupIndex) => (
<Fragment key={options[0]!.key}>
@@ -200,7 +216,7 @@ const ZoomInOut: FC<ZoomInOutProps> = ({
checked={option.checked}
disabled={option.key === ZoomType.toggleUserComments && isCommentMode}
closeOnClick
- onCheckedChange={() => handleZoom(option.key)}
+ onCheckedChange={() => selectZoom(option.key)}
>
<span
aria-hidden
@@ -216,7 +232,7 @@ const ZoomInOut: FC<ZoomInOutProps> = ({
<DropdownMenuItem
key={option.key}
className="justify-between px-3 py-1.5 system-md-regular text-text-secondary"
- onClick={() => handleZoom(option.key)}
+ onClick={() => selectZoom(option.key)}
>
<div className="flex items-center gap-2">
{option.key === ZoomType.zoomToFit && (
diff --git a/web/app/components/workflow/panel-contextmenu.tsx b/web/app/components/workflow/panel-contextmenu.tsx
index 004b7dfd12c..733bd935e86 100644
--- a/web/app/components/workflow/panel-contextmenu.tsx
+++ b/web/app/components/workflow/panel-contextmenu.tsx
@@ -18,6 +18,7 @@ import { TEST_RUN_MENU_HOTKEY } from './hotkeys'
import { isSnippetCanvas } from './nodes/_base/hooks/snippet-input-field-vars'
import AddBlock from './operator/add-block'
import { useOperator } from './operator/hooks'
+import { handleWorkflowMenuKeyDown } from './shortcuts/handle-workflow-menu-key-down'
import { ShortcutKbd } from './shortcuts/shortcut-kbd'
import { useStore } from './store'
import { WorkflowRunningStatus } from './types'
@@ -73,8 +74,22 @@ export function PanelContextmenu({ onClose }: { onClose: () => void }) {
if (!isPanelContextMenu) return null
+ function pasteNodes() {
+ if (!clipboardElements.length) return
+ handleNodesPaste()
+ onClose()
+ }
+
return (
- <ContextMenuContent className="w-50 rounded-lg" sideOffset={4}>
+ <ContextMenuContent
+ className="w-50 rounded-lg"
+ sideOffset={4}
+ onKeyDown={(event) =>
+ handleWorkflowMenuKeyDown(event, [
+ ['workflow.paste', canEditWorkflow && clipboardElements.length ? pasteNodes : undefined],
+ ])
+ }
+ >
<ContextMenuGroup>
{canEditWorkflow && (
<AddBlock
@@ -137,12 +152,7 @@ export function PanelContextmenu({ onClose }: { onClose: () => void }) {
'justify-between gap-4 px-3 text-text-secondary',
!clipboardElements.length && 'cursor-not-allowed opacity-50',
)}
- onClick={() => {
- if (clipboardElements.length) {
- handleNodesPaste()
- onClose()
- }
- }}
+ onClick={pasteNodes}
>
{t(($) => $['common.pasteHere'], { ns: 'workflow' })}
<ShortcutKbd shortcut="workflow.paste" />
diff --git a/web/app/components/workflow/selection-contextmenu.tsx b/web/app/components/workflow/selection-contextmenu.tsx
index db38adee60f..9f05067ddef 100644
--- a/web/app/components/workflow/selection-contextmenu.tsx
+++ b/web/app/components/workflow/selection-contextmenu.tsx
@@ -9,9 +9,9 @@ import {
} from '@langgenius/dify-ui/context-menu'
import { produce } from 'immer'
import { useAtomValue } from 'jotai'
-import { useCallback } from 'react'
+import { useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { useStore as useReactFlowStore } from 'reactflow'
+import { useStore as useReactFlowStore, useStoreApi } from 'reactflow'
import { useCreateSnippetFromSelection } from '@/app/components/snippets/hooks/use-create-snippet-from-selection'
import { canCreateAndModifySnippets } from '@/app/components/snippets/utils/permission'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
@@ -20,6 +20,7 @@ import { useNodesInteractions } from './hooks/use-nodes-interactions'
import { useNodesSyncDraft } from './hooks/use-nodes-sync-draft'
import { useNodesReadOnly } from './hooks/use-workflow'
import { useWorkflowHistory, WorkflowHistoryEvent } from './hooks/use-workflow-history'
+import { handleWorkflowMenuKeyDown } from './shortcuts/handle-workflow-menu-key-down'
import { ShortcutKbd } from './shortcuts/shortcut-kbd'
import { useStore, useWorkflowStore } from './store'
import { BlockEnum } from './types'
@@ -247,6 +248,8 @@ const distributeNodes = (nodesToAlign: Node[], nodes: Node[], alignType: AlignTy
export function SelectionContextmenu({ onClose }: { onClose: () => void }) {
const { t } = useTranslation(['common', 'workflow'])
const { getNodesReadOnly } = useNodesReadOnly()
+ const flowStore = useStoreApi()
+ const deletingRef = useRef(false)
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
const { handleNodesCopy, handleNodesDelete, handleNodesDuplicate } = useNodesInteractions()
const isSelectionContextMenu = useStore((s) => s.contextMenuTarget?.type === 'selection')
@@ -285,6 +288,7 @@ export function SelectionContextmenu({ onClose }: { onClose: () => void }) {
}, [handleNodesDuplicate, onClose])
const handleDeleteNodes = useCallback(() => {
+ deletingRef.current = true
handleNodesDelete()
onClose()
}, [handleNodesDelete, onClose])
@@ -398,7 +402,23 @@ export function SelectionContextmenu({ onClose }: { onClose: () => void }) {
return (
<>
- <ContextMenuContent className="w-60" sideOffset={4}>
+ <ContextMenuContent
+ finalFocus={() => {
+ const returnToCanvas = deletingRef.current
+ deletingRef.current = false
+ return returnToCanvas ? (flowStore.getState().domNode ?? true) : true
+ }}
+ className="w-60"
+ sideOffset={4}
+ onKeyDown={(event) => {
+ if (getNodesReadOnly()) return
+ handleWorkflowMenuKeyDown(event, [
+ ['workflow.copy', handleCopyNodes],
+ ['workflow.duplicate', handleDuplicateNodes],
+ ['workflow.delete', handleDeleteNodes],
+ ])
+ }}
+ >
{canCreateSnippet && (
<>
<ContextMenuGroup>
diff --git a/web/app/components/workflow/shortcuts/__tests__/workflow-canvas.browser.spec.tsx b/web/app/components/workflow/shortcuts/__tests__/workflow-canvas.browser.spec.tsx
new file mode 100644
index 00000000000..5c1d96e2b4e
--- /dev/null
+++ b/web/app/components/workflow/shortcuts/__tests__/workflow-canvas.browser.spec.tsx
@@ -0,0 +1,617 @@
+import type { ContextMenuActions } from '@langgenius/dify-ui/context-menu'
+import type { Edge, Node, NodeProps } from 'reactflow'
+import type { StoreApi } from 'zustand'
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuTrigger,
+} from '@langgenius/dify-ui/context-menu'
+import { detectPlatform } from '@tanstack/react-hotkeys'
+import { useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
+import { Handle, Position, ReactFlowProvider, useStore as useReactFlowStore } from 'reactflow'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { createStore, useStore } from 'zustand'
+import { WorkflowContext } from '../../context'
+import { EdgeContextmenu } from '../../edge-contextmenu'
+import { useNodeKeyboardInteractions } from '../../hooks/use-node-keyboard-interactions'
+import { NodeActionsDropdown } from '../../node-actions-menu'
+import { NodeActionsContextMenuContent } from '../../node-actions-menu/context-menu-content'
+import VarReferenceVars from '../../nodes/_base/components/variable/var-reference-vars'
+import { NoteEditor, NoteEditorContextProvider } from '../../note-node/note-editor'
+import NoteOperator from '../../note-node/note-editor/toolbar/operator'
+import { SelectionContextmenu } from '../../selection-contextmenu'
+import { createWorkflowStore } from '../../store/workflow'
+import { BlockEnum, VarType } from '../../types'
+import { WorkflowCanvas } from '../workflow-canvas'
+import 'reactflow/dist/style.css'
+
+const actions = vi.hoisted(() => ({
+ copy: vi.fn(),
+ paste: vi.fn(),
+ duplicate: vi.fn(),
+ deleteNodes: vi.fn(),
+ deleteEdge: vi.fn(),
+ undo: vi.fn(),
+ redo: vi.fn(),
+ save: vi.fn(),
+ organize: vi.fn(),
+ hand: vi.fn(),
+ pointer: vi.fn(),
+ comment: vi.fn(),
+ dim: vi.fn(),
+ undim: vi.fn(),
+ zoomTo: vi.fn(),
+ fitView: vi.fn(),
+ getZoom: vi.fn(() => 1),
+ getNodes: vi.fn<() => { data: { _isBundled?: boolean } }[]>(() => []),
+}))
+
+vi.mock('../../hooks/use-nodes-interactions', () => ({
+ useNodesInteractions: () => ({
+ handleNodesCopy: actions.copy,
+ handleNodesPaste: actions.paste,
+ handleNodesDuplicate: actions.duplicate,
+ handleNodesDelete: actions.deleteNodes,
+ handleNodeDelete: actions.deleteNodes,
+ handleHistoryBack: actions.undo,
+ handleHistoryForward: actions.redo,
+ dimOtherNodes: actions.dim,
+ undimAllNodes: actions.undim,
+ }),
+}))
+vi.mock('../../hooks/use-edges-interactions', () => ({
+ useEdgesInteractions: () => ({
+ handleEdgeDelete: actions.deleteEdge,
+ handleEdgeDeleteById: actions.deleteEdge,
+ }),
+}))
+vi.mock('../../hooks/use-nodes-sync-draft', () => ({
+ useNodesSyncDraft: () => ({ handleSyncWorkflowDraft: actions.save }),
+}))
+vi.mock('../../hooks/use-workflow', () => ({
+ useNodesReadOnly: () => ({ nodesReadOnly: false, getNodesReadOnly: () => false }),
+}))
+vi.mock('../../hooks/use-workflow-organize', () => ({
+ useWorkflowOrganize: () => ({ handleLayout: actions.organize }),
+}))
+vi.mock('../../hooks/use-workflow-panel-interactions', () => ({
+ useWorkflowMoveMode: () => ({
+ handleModeHand: actions.hand,
+ handleModePointer: actions.pointer,
+ handleModeComment: actions.comment,
+ canUseCommentMode: true,
+ }),
+}))
+
+vi.mock('../../hooks-store', () => ({
+ useHooksStore: (selector: (state: { accessControl: { canRun: boolean } }) => unknown) =>
+ selector({ accessControl: { canRun: false } }),
+}))
+vi.mock('../../hooks/use-nodes-meta-data', () => ({
+ useNodeMetaData: () => ({
+ isTypeFixed: true,
+ isSingleton: false,
+ isUndeletable: false,
+ description: 'Test node',
+ author: 'Dify',
+ }),
+}))
+vi.mock('@/service/use-tools', () => ({ useAllWorkflowTools: () => ({ data: [] }) }))
+vi.mock('../../node-actions-menu/change-block-popup', () => ({ ChangeBlockPopup: () => null }))
+
+vi.mock('@/context/permission-state', async () => {
+ const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
+ return createPermissionStateModuleMock(() => ({ workspacePermissionKeys: [] }))
+})
+vi.mock('@/app/components/snippets/hooks/use-create-snippet-from-selection', () => ({
+ useCreateSnippetFromSelection: () => ({
+ createSnippetDialog: null,
+ handleOpenCreateSnippet: () => {},
+ isCreateSnippetDialogOpen: false,
+ }),
+}))
+vi.mock('../../hooks/use-workflow-history', () => ({
+ WorkflowHistoryEvent: { NodeDragStop: 'NodeDragStop' },
+ useWorkflowHistory: () => ({ saveStateToHistory: () => {} }),
+}))
+
+function NodeWithMenu({ id }: NodeProps) {
+ return (
+ <div className="nodrag nopan">
+ Workflow node
+ <NodeActionsDropdown
+ id={id}
+ data={{ type: BlockEnum.Code, title: 'Workflow node', desc: '' }}
+ showHelpLink={false}
+ />
+ </div>
+ )
+}
+function NoteWithMenu() {
+ return (
+ <div className="nodrag nopan">
+ Note node
+ <NoteOperator
+ onCopy={actions.copy}
+ onDuplicate={actions.duplicate}
+ onDelete={actions.deleteNodes}
+ showAuthor={false}
+ onShowAuthorChange={() => {}}
+ />
+ </div>
+ )
+}
+const nodeTypes = { menu: NodeWithMenu, note: NoteWithMenu }
+
+const initialNodes: Node[] = [
+ { id: 'node', position: { x: 350, y: 150 }, data: { label: 'Workflow node' } },
+]
+type GraphState = { nodes: Node[]; edges: Edge[] }
+const createGraph = () => createStore<GraphState>(() => ({ nodes: initialNodes, edges: [] }))
+
+function Canvas({
+ graph,
+ contextMenuType,
+}: {
+ graph?: StoreApi<GraphState>
+ contextMenuType?: 'node' | 'edge' | 'selection'
+}) {
+ const contextMenuActionsRef = useRef<ContextMenuActions>(null)
+ const [defaultGraph] = useState(createGraph)
+ const nodes = useStore(graph ?? defaultGraph, (state) => state.nodes)
+ const edges = useStore(graph ?? defaultGraph, (state) => state.edges)
+ const [store] = useState(() => createWorkflowStore({}))
+ return (
+ <WorkflowContext value={store}>
+ <ReactFlowProvider>
+ <ContextMenu actionsRef={contextMenuActionsRef}>
+ <ContextMenuTrigger render={<div style={{ width: 800, height: 500 }} />}>
+ <WorkflowCanvas
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={nodeTypes}
+ selectionOnDrag={contextMenuType === 'selection'}
+ panOnDrag={contextMenuType !== 'selection'}
+ onSelectionContextMenu={() =>
+ store.setState({ contextMenuTarget: { type: 'selection' } })
+ }
+ onEdgeContextMenu={(_, edge) =>
+ store.setState({ contextMenuTarget: { type: 'edge', edgeId: edge.id } })
+ }
+ >
+ <textarea
+ aria-label="Node prompt"
+ style={{ position: 'absolute', zIndex: 5, top: 20, left: 20 }}
+ />
+ <div
+ style={{
+ position: 'absolute',
+ zIndex: 5,
+ top: 80,
+ left: 20,
+ width: 240,
+ minHeight: 80,
+ }}
+ >
+ <NoteEditorContextProvider>
+ <NoteEditor containerElement={null} />
+ </NoteEditorContextProvider>
+ </div>
+ {createPortal(<button>Popup action</button>, document.body)}
+ </WorkflowCanvas>
+ </ContextMenuTrigger>
+ {contextMenuType === 'node' ? (
+ nodes.length > 0 && (
+ <NodeActionsContextMenuContent
+ id="node"
+ data={{ type: BlockEnum.Code, title: 'Workflow node', desc: '' }}
+ onClose={() => contextMenuActionsRef.current?.close()}
+ showHelpLink={false}
+ />
+ )
+ ) : contextMenuType === 'selection' ? (
+ <SelectionContextmenu onClose={() => contextMenuActionsRef.current?.close()} />
+ ) : contextMenuType === 'edge' ? (
+ <EdgeContextmenu onClose={() => contextMenuActionsRef.current?.close()} />
+ ) : (
+ <ContextMenuContent>
+ <ContextMenuItem>Canvas menu action</ContextMenuItem>
+ </ContextMenuContent>
+ )}
+ </ContextMenu>
+ <input aria-label="Outside canvas input" />
+ </ReactFlowProvider>
+ </WorkflowContext>
+ )
+}
+
+beforeEach(() => {
+ vi.resetAllMocks()
+})
+
+it('admits and releases keyboard focus while keeping character shortcuts inside the canvas', async () => {
+ // Native Tab navigation and shifted printable keys establish the focused-component boundary.
+ await page.viewport(1000, 700)
+ const screen = await render(
+ <>
+ <button>Before canvas</button>
+ <Canvas />
+ </>,
+ )
+ const before = screen.getByRole('button', { name: 'Before canvas' })
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ const node = screen.getByRole('button', { name: 'Workflow node' })
+ const outside = screen.getByRole('textbox', { name: 'Outside canvas input' })
+
+ await userEvent.keyboard('{Tab}')
+ await expect.element(before).toHaveFocus()
+ await userEvent.keyboard('{Tab}')
+ await expect.element(canvas).toHaveFocus()
+ await userEvent.keyboard('vhc')
+ expect(actions.pointer).toHaveBeenCalledOnce()
+ expect(actions.hand).toHaveBeenCalledOnce()
+ expect(actions.comment).toHaveBeenCalledOnce()
+
+ const initialWidth = node.element().getBoundingClientRect().width
+ expect(initialWidth).toBeGreaterThan(0)
+ await userEvent.keyboard('{Shift>}[Digit5]{/Shift}')
+ await expect
+ .poll(() => node.element().getBoundingClientRect().width)
+ .toBeCloseTo(initialWidth / 2)
+ await userEvent.keyboard('{Shift>}[Digit1]{/Shift}')
+ await expect.poll(() => node.element().getBoundingClientRect().width).toBeCloseTo(initialWidth)
+
+ await userEvent.keyboard('{Shift>}{Tab}{/Shift}')
+ await expect.element(before).toHaveFocus()
+ await userEvent.keyboard('vhc{Shift>}[Digit5]{/Shift}')
+ expect(node.element().getBoundingClientRect().width).toBeCloseTo(initialWidth)
+
+ await userEvent.keyboard('{Tab}')
+ await expect.element(canvas).toHaveFocus()
+ for (let steps = 0; steps < 10 && document.activeElement !== outside.element(); steps++)
+ await userEvent.keyboard('{Tab}')
+ await expect.element(outside).toHaveFocus()
+ await userEvent.keyboard('vhc')
+ await expect.element(outside).toHaveValue('vhc')
+
+ await screen.getByRole('textbox', { name: 'workflow.nodes.note.editor.label' }).click()
+ await userEvent.keyboard('vhc')
+ await screen.getByRole('button', { name: 'Popup action' }).click()
+ await userEvent.keyboard('vhc{Shift>}[Digit5]{/Shift}')
+ expect(node.element().getBoundingClientRect().width).toBeCloseTo(initialWidth)
+ expect(actions.pointer).toHaveBeenCalledOnce()
+ expect(actions.hand).toHaveBeenCalledOnce()
+ expect(actions.comment).toHaveBeenCalledOnce()
+})
+
+it('acquires canvas focus from pane and node clicks while preserving native editor undo', async () => {
+ // Native focus, React Flow pointer handling, and textarea undo cannot be proved by synthetic key events.
+ await page.viewport(1000, 700)
+ const screen = await render(<Canvas />)
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await canvas.click({ position: { x: 650, y: 400 } })
+ await expect.element(canvas).toHaveFocus()
+ await userEvent.keyboard(`{${mod}>}s{/${mod}}`)
+ expect(actions.save).toHaveBeenCalledTimes(1)
+
+ const node = screen.getByRole('button', { name: 'Workflow node' })
+ await node.click()
+ await expect.element(node).toHaveFocus()
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+
+ const prompt = screen.getByRole('textbox', { name: 'Node prompt' })
+ await prompt.click()
+ await userEvent.keyboard('Draft text')
+ await expect.element(prompt).toHaveValue('Draft text')
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(prompt).toHaveValue('')
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+
+ await screen.getByRole('button', { name: 'Popup action' }).click()
+ await userEvent.keyboard(`{${mod}>}s{/${mod}}`)
+ expect(actions.save).toHaveBeenCalledTimes(1)
+
+ await canvas.click({ position: { x: 650, y: 400 } })
+ await expect.element(canvas).toHaveFocus()
+ await userEvent.keyboard(`{${mod}>}s{/${mod}}`)
+ expect(actions.save).toHaveBeenCalledTimes(2)
+})
+
+it('keeps canvas focus when delete, undo, or redo removes the focused node', async () => {
+ await page.viewport(1000, 700)
+ const graph = createGraph()
+ actions.deleteNodes.mockImplementation(() => graph.setState({ nodes: [] }))
+ actions.undo.mockImplementation(() => graph.setState({ nodes: initialNodes }))
+ actions.redo.mockImplementation(() => graph.setState({ nodes: [] }))
+ const screen = await render(<Canvas graph={graph} />)
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ const node = screen.getByRole('button', { name: 'Workflow node' })
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+
+ await node.click()
+ await userEvent.keyboard('{Delete}')
+ await expect.element(node).not.toBeInTheDocument()
+ await expect.element(canvas).toHaveFocus()
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(node).toBeInTheDocument()
+
+ await node.click()
+ await userEvent.keyboard(`{${mod}>}{Shift>}z{/Shift}{/${mod}}`)
+ await expect.element(node).not.toBeInTheDocument()
+ await expect.element(canvas).toHaveFocus()
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(node).toBeInTheDocument()
+
+ actions.undo.mockImplementation(() => graph.setState({ nodes: [] }))
+ actions.redo.mockImplementation(() => graph.setState({ nodes: initialNodes }))
+ await node.click()
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(node).not.toBeInTheDocument()
+ await expect.element(canvas).toHaveFocus()
+ await userEvent.keyboard(`{${mod}>}{Shift>}z{/Shift}{/${mod}}`)
+ await expect.element(node).toBeInTheDocument()
+})
+
+it('lets the production Note editor own text history and returns graph history on a pane click', async () => {
+ await page.viewport(1000, 700)
+ const screen = await render(<Canvas />)
+ const note = screen.getByRole('textbox', { name: 'workflow.nodes.note.editor.label' })
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await note.click()
+ await userEvent.keyboard('Note text')
+ await expect.element(note).toHaveTextContent('Note text')
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(note).toBeEmptyDOMElement()
+ expect(actions.undo).not.toHaveBeenCalled()
+ await userEvent.keyboard(`{${mod}>}{Shift>}z{/Shift}{/${mod}}`)
+ await expect.element(note).toHaveTextContent('Note text')
+ expect(actions.redo).not.toHaveBeenCalled()
+
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ await canvas.click({ position: { x: 650, y: 400 } })
+ await expect.element(canvas).toHaveFocus()
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+})
+
+it('returns focus to the canvas after a context menu opened from outside focus closes', async () => {
+ await page.viewport(1000, 700)
+ const screen = await render(<Canvas />)
+ const outsideInput = screen.getByRole('textbox', { name: 'Outside canvas input' })
+ await outsideInput.click()
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ await canvas.click({ button: 'right', position: { x: 650, y: 400 } })
+ await expect.element(screen.getByRole('menuitem', { name: 'Canvas menu action' })).toBeVisible()
+ await userEvent.keyboard('{ArrowDown}{Escape}')
+ await expect.element(canvas).toHaveFocus()
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+})
+
+it.each(['menu', 'note'])(
+ 'returns to canvas history after the %s menu deletes its own trigger',
+ async (nodeType) => {
+ await page.viewport(1000, 700)
+ const graph = createGraph()
+ const menuNodes = initialNodes.map((node) => ({ ...node, type: nodeType }))
+ graph.setState({ nodes: menuNodes })
+ actions.deleteNodes.mockImplementation(() => graph.setState({ nodes: [] }))
+ actions.undo.mockImplementation(() => graph.setState({ nodes: menuNodes }))
+ const screen = await render(<Canvas graph={graph} />)
+ const more = screen.getByRole('button', { name: 'common.operation.more' })
+ await more.click()
+ await screen.getByRole('menuitem', { name: /common.operation.delete/ }).click()
+ await expect.element(more).not.toBeInTheDocument()
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ await expect.element(canvas).toHaveFocus()
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(more).toBeInTheDocument()
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+ },
+)
+
+it('returns to canvas undo after a node context-menu action removes the focused node', async () => {
+ await page.viewport(1000, 700)
+ const graph = createGraph()
+ actions.deleteNodes.mockImplementation(() => graph.setState({ nodes: [] }))
+ actions.undo.mockImplementation(() => graph.setState({ nodes: initialNodes }))
+ const screen = await render(<Canvas graph={graph} contextMenuType="node" />)
+ const node = screen.getByRole('button', { name: 'Workflow node' })
+ await node.click({ button: 'right' })
+ await screen.getByRole('menuitem', { name: /common.operation.delete/ }).click()
+ await expect.element(node).not.toBeInTheDocument()
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ await expect.element(canvas).toHaveFocus()
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(node).toBeInTheDocument()
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+})
+
+it('returns to canvas undo after an edge context-menu action removes the focused edge', async () => {
+ await page.viewport(1000, 700)
+ const graph = createGraph()
+ const nodes = [
+ ...initialNodes,
+ { id: 'other', position: { x: 500, y: 300 }, data: { label: 'Other node' } },
+ ]
+ const edges = [{ id: 'edge', source: 'node', target: 'other' }]
+ graph.setState({ nodes, edges })
+ actions.deleteEdge.mockImplementation(() => graph.setState({ edges: [] }))
+ actions.undo.mockImplementation(() => graph.setState({ edges }))
+ const screen = await render(<Canvas graph={graph} contextMenuType="edge" />)
+ const edge = screen.getByTestId('rf__edge-edge')
+ const outsideInput = screen.getByLabelText('Outside canvas input')
+ await outsideInput.click()
+ await edge.click({ button: 'right' })
+ await screen.getByRole('menuitem', { name: /common.operation.delete/ }).click()
+ await expect.element(edge).not.toBeInTheDocument()
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ await expect.element(canvas).toHaveFocus()
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(edge).toBeInTheDocument()
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+ await edge.click({ button: 'right' })
+ await userEvent.keyboard('{Escape}')
+ await expect.element(canvas).toHaveFocus()
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ expect(actions.undo).toHaveBeenCalledTimes(2)
+})
+
+it('returns to canvas undo after a selection context-menu action removes the focused selection', async () => {
+ await page.viewport(1000, 700)
+ const graph = createGraph()
+ const nodes = [
+ ...initialNodes,
+ { id: 'other', position: { x: 500, y: 300 }, data: { label: 'Other node' } },
+ ]
+ graph.setState({ nodes })
+ actions.deleteNodes.mockImplementation(() => graph.setState({ nodes: [] }))
+ actions.undo.mockImplementation(() => graph.setState({ nodes }))
+ const screen = await render(<Canvas graph={graph} contextMenuType="selection" />)
+ const canvas = screen.getByRole('region', { name: 'app.types.workflow' })
+ await userEvent.dragAndDrop(canvas, canvas, {
+ sourcePosition: { x: 300, y: 120 },
+ targetPosition: { x: 700, y: 380 },
+ steps: 5,
+ })
+ await expect
+ .poll(() => canvas.element().querySelector('.react-flow__nodesselection-rect'))
+ .not.toBeNull()
+ await canvas.click({ button: 'right', position: { x: 450, y: 220 } })
+ await screen.getByRole('menuitem', { name: /common.operation.delete/ }).click()
+ await expect
+ .element(screen.getByRole('button', { name: 'Workflow node' }))
+ .not.toBeInTheDocument()
+ await expect.element(canvas).toHaveFocus()
+ const mod = detectPlatform() === 'mac' ? 'Meta' : 'Control'
+ await userEvent.keyboard(`{${mod}>}z{/${mod}}`)
+ await expect.element(screen.getByRole('button', { name: 'Workflow node' })).toBeInTheDocument()
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+})
+
+it('keeps focus on an outside input when it dismisses a node dropdown', async () => {
+ await page.viewport(1000, 700)
+ const graph = createGraph()
+ graph.setState({ nodes: initialNodes.map((node) => ({ ...node, type: 'menu' })) })
+ const screen = await render(<Canvas graph={graph} />)
+ await screen.getByRole('button', { name: 'common.operation.more' }).click()
+ await expect.element(screen.getByRole('menuitem', { name: /workflow.common.copy/ })).toBeVisible()
+ const outsideInput = screen.getByRole('textbox', { name: 'Outside canvas input' })
+ await outsideInput.click()
+ await expect
+ .element(screen.getByRole('menuitem', { name: /workflow.common.copy/ }))
+ .not.toBeInTheDocument()
+ await expect.element(outsideInput).toHaveFocus()
+})
+
+function VariableConnectionNode({ id }: NodeProps) {
+ return (
+ <div style={{ width: 150, height: 80 }}>
+ {id}
+ <Handle type="source" position={Position.Right} data-testid={`source-${id}`} />
+ <Handle type="target" position={Position.Left} data-testid={`target-${id}`} />
+ </div>
+ )
+}
+const variableConnectionNodeTypes = { connection: VariableConnectionNode }
+const variableConnectionNodes: Node[] = [
+ {
+ id: 'source',
+ type: 'connection',
+ position: { x: 100, y: 150 },
+ data: { type: BlockEnum.Code, title: 'Source' },
+ },
+ {
+ id: 'assigner',
+ type: 'connection',
+ position: { x: 500, y: 150 },
+ data: { type: BlockEnum.VariableAssigner, title: 'Assigner' },
+ },
+]
+
+function VariableConnectionCanvas({ onSelect }: { onSelect: (value: string[]) => void }) {
+ const [showPicker, setShowPicker] = useState(false)
+ const canvas = useReactFlowStore((state) => state.domNode)
+ const handleNodeKeyDown = useNodeKeyboardInteractions(() => {})
+
+ return (
+ <div style={{ width: 800, height: 500 }}>
+ <WorkflowCanvas
+ nodes={variableConnectionNodes}
+ edges={[]}
+ nodeTypes={variableConnectionNodeTypes}
+ onKeyDownCapture={handleNodeKeyDown}
+ onConnectEnd={() => setShowPicker(true)}
+ deleteKeyCode={null}
+ >
+ {showPicker && (
+ <VarReferenceVars
+ hideSearch
+ keyboardTarget={canvas}
+ vars={[
+ {
+ nodeId: 'source',
+ title: 'Source',
+ vars: [
+ { variable: 'first', type: VarType.string },
+ { variable: 'second', type: VarType.string },
+ ],
+ },
+ ]}
+ onChange={onSelect}
+ />
+ )}
+ </WorkflowCanvas>
+ </div>
+ )
+}
+
+it('selects a connection variable before node movement handles the focused node keys', async () => {
+ // Real handle dragging preserves node focus; React capture must not move that node before the picker sees its keys.
+ await page.viewport(1000, 700)
+ const store = createWorkflowStore({})
+ const onSelect = vi.fn()
+ const screen = await render(
+ <WorkflowContext value={store}>
+ <ReactFlowProvider>
+ <VariableConnectionCanvas onSelect={onSelect} />
+ <textarea aria-label="Outside variable picker" />
+ </ReactFlowProvider>
+ </WorkflowContext>,
+ )
+
+ const source = screen.getByTestId('rf__node-source')
+ await source.click()
+ await userEvent.dragAndDrop(
+ screen.getByTestId('source-source'),
+ screen.getByTestId('target-assigner'),
+ { steps: 5 },
+ )
+ await expect.element(screen.getByText('first', { exact: true })).toBeVisible()
+ await expect.element(source).toHaveFocus()
+ const sourcePosition = source.element().getBoundingClientRect()
+
+ await userEvent.keyboard('{ArrowDown}{Enter}')
+
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith(
+ ['source', 'second'],
+ expect.objectContaining({ variable: 'second' }),
+ )
+ expect(source.element().getBoundingClientRect().x).toBe(sourcePosition.x)
+ expect(source.element().getBoundingClientRect().y).toBe(sourcePosition.y)
+
+ const outside = screen.getByRole('textbox', { name: 'Outside variable picker' })
+ await outside.click()
+ await userEvent.keyboard('top{Enter}bottom{Home}{ArrowUp}x')
+ await expect.element(outside).toHaveValue('xtop\nbottom')
+ expect(onSelect).toHaveBeenCalledTimes(1)
+})
diff --git a/web/app/components/workflow/shortcuts/__tests__/workflow-canvas.spec.tsx b/web/app/components/workflow/shortcuts/__tests__/workflow-canvas.spec.tsx
new file mode 100644
index 00000000000..45028f2f30b
--- /dev/null
+++ b/web/app/components/workflow/shortcuts/__tests__/workflow-canvas.spec.tsx
@@ -0,0 +1,311 @@
+import { HotkeysProvider } from '@tanstack/react-hotkeys'
+import { act, fireEvent, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { createPortal } from 'react-dom'
+import { ReactFlowProvider } from 'reactflow'
+import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
+import { WorkflowCanvas } from '../workflow-canvas'
+
+const actions = vi.hoisted(() => ({
+ nodesReadOnly: false,
+ copy: vi.fn(),
+ paste: vi.fn(),
+ duplicate: vi.fn(),
+ deleteNodes: vi.fn(),
+ deleteEdge: vi.fn(),
+ undo: vi.fn(),
+ redo: vi.fn(),
+ save: vi.fn(),
+ organize: vi.fn(),
+ hand: vi.fn(),
+ pointer: vi.fn(),
+ comment: vi.fn(),
+ dim: vi.fn(),
+ undim: vi.fn(),
+ zoomTo: vi.fn(),
+ fitView: vi.fn(),
+ getZoom: vi.fn(() => 1),
+ getNodes: vi.fn<() => { data: { _isBundled?: boolean } }[]>(() => []),
+}))
+
+vi.mock('reactflow', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('reactflow')>()),
+ useReactFlow: () => ({
+ zoomTo: actions.zoomTo,
+ fitView: actions.fitView,
+ getZoom: actions.getZoom,
+ getNodes: actions.getNodes,
+ }),
+}))
+vi.mock('../../hooks/use-nodes-interactions', () => ({
+ useNodesInteractions: () => ({
+ handleNodesCopy: actions.copy,
+ handleNodesPaste: actions.paste,
+ handleNodesDuplicate: actions.duplicate,
+ handleNodesDelete: actions.deleteNodes,
+ handleHistoryBack: actions.undo,
+ handleHistoryForward: actions.redo,
+ dimOtherNodes: actions.dim,
+ undimAllNodes: actions.undim,
+ }),
+}))
+vi.mock('../../hooks/use-edges-interactions', () => ({
+ useEdgesInteractions: () => ({ handleEdgeDelete: actions.deleteEdge }),
+}))
+vi.mock('../../hooks/use-nodes-sync-draft', () => ({
+ useNodesSyncDraft: () => ({ handleSyncWorkflowDraft: actions.save }),
+}))
+vi.mock('../../hooks/use-workflow', () => ({
+ useNodesReadOnly: () => ({ nodesReadOnly: actions.nodesReadOnly }),
+}))
+vi.mock('../../hooks/use-workflow-organize', () => ({
+ useWorkflowOrganize: () => ({ handleLayout: actions.organize }),
+}))
+vi.mock('../../hooks/use-workflow-panel-interactions', () => ({
+ useWorkflowMoveMode: () => ({
+ handleModeHand: actions.hand,
+ handleModePointer: actions.pointer,
+ handleModeComment: actions.comment,
+ canUseCommentMode: true,
+ }),
+}))
+
+function Canvas() {
+ return (
+ <ReactFlowProvider>
+ <WorkflowCanvas nodes={[]} edges={[]}>
+ <input aria-label="Node name" />
+ <textarea aria-label="Node prompt" />
+ <div contentEditable suppressContentEditableWarning role="textbox" aria-label="Note">
+ <span>Note content</span>
+ </div>
+ <button onKeyDown={(event) => event.preventDefault()}>Handled by a local widget</button>
+ {createPortal(<button>Popup action</button>, document.body)}
+ </WorkflowCanvas>
+ <button>Outside canvas</button>
+ </ReactFlowProvider>
+ )
+}
+
+function renderCanvas(platform: 'mac' | 'windows' = 'windows') {
+ return renderWorkflowComponent(
+ <HotkeysProvider defaultOptions={{ hotkey: { platform } }}>
+ <Canvas />
+ </HotkeysProvider>,
+ )
+}
+
+function focusCanvas() {
+ const canvas = screen.getByLabelText('app.types.workflow')
+ act(() => canvas.focus())
+ return canvas
+}
+
+describe('Workflow canvas commands', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ actions.nodesReadOnly = false
+ actions.getNodes.mockReturnValue([])
+ actions.getZoom.mockReturnValue(1)
+ })
+
+ it.each(['mac', 'windows'] as const)(
+ 'runs graph actions only from its canvas on %s',
+ async (platform) => {
+ const user = userEvent.setup()
+ renderCanvas(platform)
+ const mod = platform === 'mac' ? 'Meta' : 'Control'
+ focusCanvas()
+ await user.keyboard(`{${mod}>}cvszy{/${mod}}{Delete}`)
+ expect(actions.copy).toHaveBeenCalledTimes(1)
+ expect(actions.paste).toHaveBeenCalledTimes(1)
+ expect(actions.save).toHaveBeenCalledTimes(1)
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+ expect(actions.redo).toHaveBeenCalledTimes(1)
+ expect(actions.deleteNodes).toHaveBeenCalledTimes(1)
+ expect(actions.deleteEdge).toHaveBeenCalledTimes(1)
+
+ await user.click(screen.getByRole('button', { name: 'Popup action' }))
+ await user.keyboard(`{${mod}>}cvszy{/${mod}}{Delete}`)
+ await user.click(screen.getByRole('button', { name: 'Outside canvas' }))
+ await user.keyboard(`{${mod}>}cvszy{/${mod}}{Delete}`)
+ expect(actions.copy).toHaveBeenCalledTimes(1)
+ expect(actions.save).toHaveBeenCalledTimes(1)
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+ expect(actions.deleteNodes).toHaveBeenCalledTimes(1)
+ },
+ )
+
+ it.each(['Node name', 'Node prompt', 'Note', 'Note content'])(
+ 'leaves editor keys and native defaults to %s',
+ (name) => {
+ renderCanvas()
+ const editor =
+ name === 'Note content' ? screen.getByText(name) : screen.getByRole('textbox', { name })
+ for (const key of ['s', 'z', 'c', 'v']) {
+ const event = new KeyboardEvent('keydown', {
+ key,
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(editor, event)
+ fireEvent.keyUp(editor, { key, ctrlKey: true })
+ expect(event.defaultPrevented).toBe(false)
+ }
+ const event = new KeyboardEvent('keydown', { key: 'Delete', bubbles: true, cancelable: true })
+ fireEvent(editor, event)
+ expect(event.defaultPrevented).toBe(false)
+ expect(actions.save).not.toHaveBeenCalled()
+ expect(actions.undo).not.toHaveBeenCalled()
+ expect(actions.copy).not.toHaveBeenCalled()
+ expect(actions.paste).not.toHaveBeenCalled()
+ expect(actions.deleteNodes).not.toHaveBeenCalled()
+ },
+ )
+
+ it('ignores a claimed event, composition, and repeats until the key is released', async () => {
+ const user = userEvent.setup()
+ renderCanvas()
+ await user.click(screen.getByRole('button', { name: 'Handled by a local widget' }))
+ await user.keyboard('{Control>}s{/Control}')
+ expect(actions.save).not.toHaveBeenCalled()
+
+ const canvas = focusCanvas()
+ fireEvent.keyDown(canvas, { key: 's', ctrlKey: true, isComposing: true })
+ fireEvent.keyUp(canvas, { key: 's', ctrlKey: true })
+ expect(actions.save).not.toHaveBeenCalled()
+ const composingDelete = new KeyboardEvent('keydown', {
+ key: 'Delete',
+ isComposing: true,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(canvas, composingDelete)
+ fireEvent.keyUp(canvas, { key: 'Delete' })
+ expect(composingDelete.defaultPrevented).toBe(false)
+ expect(actions.deleteNodes).not.toHaveBeenCalled()
+ await user.keyboard('{Control>}{s>3/}{/Control}')
+ expect(actions.save).toHaveBeenCalledTimes(1)
+ await user.keyboard('{Control>}s{/Control}')
+ expect(actions.save).toHaveBeenCalledTimes(2)
+ })
+
+ it('consumes every owned repeat while performing discrete actions only once', () => {
+ renderCanvas()
+ const canvas = focusCanvas()
+ for (const key of ['s', 'd', 'o', 'c']) {
+ for (const repeat of [false, true, true]) {
+ const event = new KeyboardEvent('keydown', {
+ key,
+ ctrlKey: true,
+ repeat,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(canvas, event)
+ expect(event.defaultPrevented).toBe(true)
+ }
+ fireEvent.keyUp(canvas, { key, ctrlKey: true })
+ }
+ expect(actions.save).toHaveBeenCalledTimes(1)
+ expect(actions.duplicate).toHaveBeenCalledTimes(1)
+ expect(actions.organize).toHaveBeenCalledTimes(1)
+ expect(actions.copy).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not consume unavailable editing commands while still allowing viewport zoom', async () => {
+ const user = userEvent.setup()
+ actions.nodesReadOnly = true
+ renderCanvas()
+ const canvas = focusCanvas()
+ for (const key of ['s', 'd', 'o', 'z']) {
+ const event = new KeyboardEvent('keydown', {
+ key,
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(canvas, event)
+ fireEvent.keyUp(canvas, { key, ctrlKey: true })
+ expect(event.defaultPrevented).toBe(false)
+ }
+ const deletion = new KeyboardEvent('keydown', {
+ key: 'Delete',
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(canvas, deletion)
+ expect(deletion.defaultPrevented).toBe(false)
+ expect(actions.save).not.toHaveBeenCalled()
+ expect(actions.deleteNodes).not.toHaveBeenCalled()
+ expect(actions.duplicate).not.toHaveBeenCalled()
+ expect(actions.organize).not.toHaveBeenCalled()
+ expect(actions.undo).not.toHaveBeenCalled()
+ await user.keyboard('{Control>}{=>3/}{/Control}')
+ expect(actions.zoomTo).toHaveBeenCalledTimes(3)
+ })
+
+ it('keeps graph history disabled while debug preview is open', async () => {
+ const user = userEvent.setup()
+ const { store } = renderCanvas()
+ focusCanvas()
+ act(() => store.setState({ showDebugAndPreviewPanel: true }))
+ await user.keyboard('{Control>}zy{/Control}')
+ expect(actions.undo).not.toHaveBeenCalled()
+ expect(actions.redo).not.toHaveBeenCalled()
+ act(() => store.setState({ showDebugAndPreviewPanel: false }))
+ await user.keyboard('{Control>}zy{/Control}')
+ expect(actions.undo).toHaveBeenCalledTimes(1)
+ expect(actions.redo).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps layout and zoom bound to the canvas and saves the viewport', async () => {
+ const user = userEvent.setup()
+ renderCanvas()
+ focusCanvas()
+ await user.keyboard('{Control>}o1-={/Control}{Shift>}5{/Shift}')
+ expect(actions.organize).toHaveBeenCalledTimes(1)
+ expect(actions.fitView).toHaveBeenCalledTimes(1)
+ expect(actions.zoomTo).toHaveBeenNthCalledWith(1, 0.9)
+ expect(actions.zoomTo).toHaveBeenNthCalledWith(2, 1.1)
+ expect(actions.zoomTo).toHaveBeenNthCalledWith(3, 0.5)
+ expect(actions.save).toHaveBeenCalledTimes(4)
+ })
+
+ it('dims only while Shift is held with canvas focus and clears on focus loss', async () => {
+ const user = userEvent.setup()
+ renderCanvas()
+ focusCanvas()
+ await user.keyboard('{Shift>}')
+ expect(actions.dim).toHaveBeenCalledTimes(1)
+ act(() => screen.getByRole('textbox', { name: 'Node prompt' }).focus())
+ expect(actions.undim).toHaveBeenCalledTimes(1)
+ await user.keyboard('{/Shift}{Shift>}{/Shift}')
+ expect(actions.dim).toHaveBeenCalledTimes(1)
+ })
+
+ it('preserves text selection copying unless bundled nodes are selected', async () => {
+ const user = userEvent.setup()
+ renderCanvas()
+ const canvas = focusCanvas()
+ const selection = document.getSelection()!
+ const range = document.createRange()
+ range.selectNodeContents(screen.getByText('Note content'))
+ selection.addRange(range)
+ await user.keyboard('{Control>}c{/Control}')
+ expect(actions.copy).not.toHaveBeenCalled()
+ actions.getNodes.mockReturnValue([{ data: { _isBundled: true } }])
+ const event = new KeyboardEvent('keydown', {
+ key: 'c',
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ })
+ fireEvent(canvas, event)
+ fireEvent.keyUp(canvas, { key: 'c', ctrlKey: true })
+ expect(event.defaultPrevented).toBe(true)
+ expect(actions.copy).toHaveBeenCalledTimes(1)
+ selection.removeAllRanges()
+ })
+})
diff --git a/web/app/components/workflow/shortcuts/definitions.ts b/web/app/components/workflow/shortcuts/definitions.ts
index 545c5a020b1..8e01e0bfaff 100644
--- a/web/app/components/workflow/shortcuts/definitions.ts
+++ b/web/app/components/workflow/shortcuts/definitions.ts
@@ -1,24 +1,5 @@
import type { Hotkey, IndividualKey } from '@tanstack/react-hotkeys'
-export type WorkflowCanvasShortcutId =
- | 'workflow.delete'
- | 'workflow.copy'
- | 'workflow.paste'
- | 'workflow.duplicate'
- | 'workflow.undo'
- | 'workflow.redo'
- | 'workflow.pointer-mode'
- | 'workflow.hand-mode'
- | 'workflow.comment-mode'
- | 'workflow.organize'
- | 'workflow.zoom-to-fit'
- | 'workflow.zoom-to-100'
- | 'workflow.zoom-to-50'
- | 'workflow.zoom-out'
- | 'workflow.zoom-in'
- | 'workflow.download-import-log'
- | 'workflow.dim-other-nodes'
-
export type WorkflowCanvasHotkeyMeta = {
id: WorkflowCanvasShortcutId
scope: 'workflow-canvas'
@@ -27,13 +8,12 @@ export type WorkflowCanvasHotkeyMeta = {
}
type WorkflowCanvasShortcutDefinitionBase = {
- id: WorkflowCanvasShortcutId
name: string
description: string
}
export type WorkflowCanvasHotkeyDefinition = WorkflowCanvasShortcutDefinitionBase & {
- hotkeys: readonly Hotkey[]
+ hotkeys: readonly [Hotkey, ...Hotkey[]]
displayHotkey?: Hotkey
}
@@ -46,112 +26,107 @@ type WorkflowCanvasShortcutDefinition =
| WorkflowCanvasHoldKeyDefinition
export const WORKFLOW_CANVAS_SHORTCUTS = {
+ 'workflow.save-draft': {
+ hotkeys: ['Mod+S'],
+ name: 'Save draft',
+ description: 'Save the current workflow draft',
+ },
'workflow.delete': {
- id: 'workflow.delete',
hotkeys: ['Delete', 'Backspace'],
displayHotkey: 'Delete',
name: 'Delete selection',
description: 'Delete selected workflow nodes or edges',
},
'workflow.copy': {
- id: 'workflow.copy',
hotkeys: ['Mod+C'],
name: 'Copy',
description: 'Copy selected workflow nodes',
},
'workflow.paste': {
- id: 'workflow.paste',
hotkeys: ['Mod+V'],
name: 'Paste',
description: 'Paste copied workflow nodes',
},
'workflow.duplicate': {
- id: 'workflow.duplicate',
hotkeys: ['Mod+D'],
name: 'Duplicate',
description: 'Duplicate selected workflow nodes',
},
'workflow.undo': {
- id: 'workflow.undo',
hotkeys: ['Mod+Z'],
name: 'Undo',
description: 'Undo the previous workflow change',
},
'workflow.redo': {
- id: 'workflow.redo',
hotkeys: ['Mod+Y', 'Mod+Shift+Z'],
displayHotkey: 'Mod+Y',
name: 'Redo',
description: 'Redo the next workflow change',
},
'workflow.pointer-mode': {
- id: 'workflow.pointer-mode',
hotkeys: ['V'],
name: 'Pointer mode',
description: 'Switch to pointer mode',
},
'workflow.hand-mode': {
- id: 'workflow.hand-mode',
hotkeys: ['H'],
name: 'Hand mode',
description: 'Switch to hand mode',
},
'workflow.comment-mode': {
- id: 'workflow.comment-mode',
hotkeys: ['C'],
name: 'Comment mode',
description: 'Switch to comment mode',
},
'workflow.organize': {
- id: 'workflow.organize',
hotkeys: ['Mod+O'],
name: 'Organize blocks',
description: 'Automatically organize workflow blocks',
},
'workflow.zoom-to-fit': {
- id: 'workflow.zoom-to-fit',
hotkeys: ['Mod+1'],
name: 'Zoom to fit',
description: 'Fit the workflow canvas into view',
},
'workflow.zoom-to-100': {
- id: 'workflow.zoom-to-100',
hotkeys: ['Shift+1'],
name: 'Zoom to 100%',
description: 'Zoom the workflow canvas to 100%',
},
'workflow.zoom-to-50': {
- id: 'workflow.zoom-to-50',
hotkeys: ['Shift+5'],
name: 'Zoom to 50%',
description: 'Zoom the workflow canvas to 50%',
},
'workflow.zoom-out': {
- id: 'workflow.zoom-out',
hotkeys: ['Mod+-'],
name: 'Zoom out',
description: 'Zoom out of the workflow canvas',
},
'workflow.zoom-in': {
- id: 'workflow.zoom-in',
hotkeys: ['Mod+='],
displayHotkey: 'Mod+=',
name: 'Zoom in',
description: 'Zoom into the workflow canvas',
},
'workflow.download-import-log': {
- id: 'workflow.download-import-log',
hotkeys: ['Mod+Shift+L'],
name: 'Download import log',
description: 'Download the workflow graph import log',
},
'workflow.dim-other-nodes': {
- id: 'workflow.dim-other-nodes',
holdKey: 'Shift',
name: 'Dim other nodes',
description: 'Dim nodes outside the current workflow selection',
},
-} as const satisfies Record<WorkflowCanvasShortcutId, WorkflowCanvasShortcutDefinition>
+} as const satisfies Record<string, WorkflowCanvasShortcutDefinition>
+
+export type WorkflowCanvasShortcutId = keyof typeof WORKFLOW_CANVAS_SHORTCUTS
+export type WorkflowCanvasHotkeyId = {
+ [
+ Id in WorkflowCanvasShortcutId
+ ]: (typeof WORKFLOW_CANVAS_SHORTCUTS)[Id] extends WorkflowCanvasHotkeyDefinition ? Id : never
+}[WorkflowCanvasShortcutId]
export const getWorkflowCanvasShortcutDisplayKey = (
id: WorkflowCanvasShortcutId,
diff --git a/web/app/components/workflow/shortcuts/handle-workflow-menu-key-down.ts b/web/app/components/workflow/shortcuts/handle-workflow-menu-key-down.ts
new file mode 100644
index 00000000000..00f074c755a
--- /dev/null
+++ b/web/app/components/workflow/shortcuts/handle-workflow-menu-key-down.ts
@@ -0,0 +1,35 @@
+import type { KeyboardEvent } from 'react'
+import type { WorkflowCanvasHotkeyId } from './definitions'
+import { matchesKeyboardEvent } from '@tanstack/react-hotkeys'
+import { WORKFLOW_CANVAS_SHORTCUTS } from './definitions'
+
+export function handleWorkflowMenuKeyDown(
+ event: KeyboardEvent<HTMLElement>,
+ actions: ReadonlyArray<readonly [WorkflowCanvasHotkeyId, (() => void) | undefined]>,
+) {
+ if (
+ event.defaultPrevented ||
+ event.nativeEvent.isComposing ||
+ !(event.target instanceof HTMLElement) ||
+ !event.currentTarget.contains(event.target) ||
+ event.target.closest(
+ 'input, textarea, select, [contenteditable]:not([contenteditable="false"])',
+ )
+ )
+ return
+
+ for (const [shortcut, action] of actions) {
+ if (
+ !action ||
+ !WORKFLOW_CANVAS_SHORTCUTS[shortcut].hotkeys.some((hotkey) =>
+ matchesKeyboardEvent(event.nativeEvent, hotkey),
+ )
+ )
+ continue
+
+ event.preventDefault()
+ event.stopPropagation()
+ if (!event.repeat) action()
+ return
+ }
+}
diff --git a/web/app/components/workflow/shortcuts/shortcut-kbd.tsx b/web/app/components/workflow/shortcuts/shortcut-kbd.tsx
index 4feb7acd1d8..59a68f04cbd 100644
--- a/web/app/components/workflow/shortcuts/shortcut-kbd.tsx
+++ b/web/app/components/workflow/shortcuts/shortcut-kbd.tsx
@@ -1,5 +1,5 @@
import type { KbdColor } from '@langgenius/dify-ui/kbd'
-import type { FormatDisplayOptions, Hotkey, IndividualKey } from '@tanstack/react-hotkeys'
+import type { FormatDisplayOptions, Hotkey } from '@tanstack/react-hotkeys'
import type { WorkflowCanvasShortcutId } from './definitions'
import { cn } from '@langgenius/dify-ui/cn'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
@@ -18,18 +18,6 @@ type ShortcutKbdProps = ShortcutKbdSource & {
platform?: FormatDisplayOptions['platform']
}
-const getDisplayKeys = (
- hotkey: Hotkey | IndividualKey,
- platform?: FormatDisplayOptions['platform'],
-) => {
- const displayOptions = platform ? { platform } : undefined
-
- return hotkey
- .split('+')
- .filter(Boolean)
- .map((key) => formatForDisplay(key, displayOptions))
-}
-
export const ShortcutKbd = ({
shortcut,
hotkey,
@@ -46,7 +34,7 @@ export const ShortcutKbd = ({
const displayKeys = displayKey
? [formatForDisplay(displayKey, displayOptions)]
: shortcutDisplayKey
- ? getDisplayKeys(shortcutDisplayKey, platform)
+ ? formatForDisplay(shortcutDisplayKey, { platform, parts: true })
: []
if (!displayKeys.length) return null
diff --git a/web/app/components/workflow/shortcuts/use-workflow-hotkeys.ts b/web/app/components/workflow/shortcuts/use-workflow-hotkeys.ts
index 6c9e85979dc..33fc9128de8 100644
--- a/web/app/components/workflow/shortcuts/use-workflow-hotkeys.ts
+++ b/web/app/components/workflow/shortcuts/use-workflow-hotkeys.ts
@@ -1,12 +1,18 @@
import type { HotkeyCallback, UseHotkeyDefinition, UseHotkeyOptions } from '@tanstack/react-hotkeys'
-import type { WorkflowCanvasHotkeyDefinition, WorkflowCanvasHotkeyMeta } from './definitions'
+import type { RefObject } from 'react'
+import type {
+ WorkflowCanvasHotkeyDefinition,
+ WorkflowCanvasHotkeyId,
+ WorkflowCanvasHotkeyMeta,
+} from './definitions'
import { useHotkeys, useKeyHold } from '@tanstack/react-hotkeys'
-import { useCallback, useEffect, useEffectEvent, useMemo, useRef } from 'react'
+import { useEffect, useEffectEvent, useRef } from 'react'
import { useReactFlow } from 'reactflow'
import { collaborationManager } from '../collaboration/core/collaboration-manager'
import { useEdgesInteractions } from '../hooks/use-edges-interactions'
import { useNodesInteractions } from '../hooks/use-nodes-interactions'
import { useNodesSyncDraft } from '../hooks/use-nodes-sync-draft'
+import { useNodesReadOnly } from '../hooks/use-workflow'
import { useWorkflowOrganize } from '../hooks/use-workflow-organize'
import { useWorkflowMoveMode } from '../hooks/use-workflow-panel-interactions'
import { useStore } from '../store/workflow'
@@ -14,32 +20,44 @@ import { WORKFLOW_CANVAS_SHORTCUTS } from './definitions'
const workflowHotkeyOptions = {
ignoreInputs: true,
- conflictBehavior: 'warn',
+ preventDefault: false,
+ stopPropagation: false,
} satisfies UseHotkeyOptions
-const isInputLikeElement = (element: Element | null) => {
- if (!element) return false
-
- return (
- element instanceof HTMLInputElement ||
- element instanceof HTMLTextAreaElement ||
- element instanceof HTMLSelectElement ||
- (element instanceof HTMLElement && element.isContentEditable)
- )
+type WorkflowHotkeyOptions = {
+ enabled?: boolean
+ allowRepeat?: boolean
+ shouldHandle?: () => boolean
}
const toHotkeyDefinitions = (
+ id: WorkflowCanvasHotkeyId,
shortcut: WorkflowCanvasHotkeyDefinition,
callback: HotkeyCallback,
- options?: UseHotkeyOptions,
+ target: RefObject<HTMLDivElement | null>,
+ options?: WorkflowHotkeyOptions,
): UseHotkeyDefinition[] => {
+ const { allowRepeat = false, shouldHandle, ...registrationOptions } = options ?? {}
return shortcut.hotkeys.map((hotkey) => ({
hotkey,
- callback,
+ callback: (event, context) => {
+ if (
+ event.defaultPrevented ||
+ event.isComposing ||
+ !(event.target instanceof Node) ||
+ !target.current?.contains(event.target) ||
+ (shouldHandle && !shouldHandle())
+ )
+ return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat && !allowRepeat) return
+ callback(event, context)
+ },
options: {
- ...options,
+ ...registrationOptions,
meta: {
- id: shortcut.id,
+ id,
scope: 'workflow-canvas',
name: shortcut.name,
description: shortcut.description,
@@ -48,7 +66,10 @@ const toHotkeyDefinitions = (
}))
}
-export const useWorkflowHotkeys = (): void => {
+export const useWorkflowHotkeys = (
+ target: RefObject<HTMLDivElement | null>,
+ canvasHasFocus: boolean,
+): void => {
const {
handleNodesCopy,
handleNodesPaste,
@@ -62,160 +83,168 @@ export const useWorkflowHotkeys = (): void => {
const { handleSyncWorkflowDraft } = useNodesSyncDraft()
const { handleEdgeDelete } = useEdgesInteractions()
const showDebugAndPreviewPanel = useStore((s) => s.showDebugAndPreviewPanel)
- const historyShortcutsEnabled = useStore((s) => s.historyShortcutsEnabled)
- const { handleModeHand, handleModePointer, handleModeComment, isCommentModeAvailable } =
+ const { handleModeHand, handleModePointer, handleModeComment, canUseCommentMode } =
useWorkflowMoveMode()
const { handleLayout } = useWorkflowOrganize()
+ const { nodesReadOnly } = useNodesReadOnly()
const { zoomTo, getZoom, fitView, getNodes } = useReactFlow()
const isShiftHeld = useKeyHold(WORKFLOW_CANVAS_SHORTCUTS['workflow.dim-other-nodes'].holdKey)
const shiftDimmedRef = useRef(false)
const undimAllNodesOnUnmount = useEffectEvent(undimAllNodes)
- const constrainedZoomOut = useCallback(() => {
+ function constrainedZoomOut() {
const currentZoom = getZoom()
const newZoom = Math.max(currentZoom - 0.1, 0.25)
zoomTo(newZoom)
- }, [getZoom, zoomTo])
+ }
- const constrainedZoomIn = useCallback(() => {
+ function constrainedZoomIn() {
const currentZoom = getZoom()
const newZoom = Math.min(currentZoom + 0.1, 2)
zoomTo(newZoom)
- }, [getZoom, zoomTo])
+ }
- const shouldHandleCopy = useCallback(() => {
+ function shouldHandleCopy() {
if (getNodes().some((node) => node.data._isBundled)) return true
const selection = document.getSelection()
return !selection || selection.isCollapsed || !selection.rangeCount
- }, [getNodes])
+ }
- const handleCopy = useCallback<HotkeyCallback>(
- (event) => {
- if (!shouldHandleCopy()) return
+ const bind = (
+ id: WorkflowCanvasHotkeyId,
+ callback: HotkeyCallback,
+ options?: WorkflowHotkeyOptions,
+ ) => toHotkeyDefinitions(id, WORKFLOW_CANVAS_SHORTCUTS[id], callback, target, options)
- event.preventDefault()
- event.stopPropagation()
- handleNodesCopy()
- },
- [handleNodesCopy, shouldHandleCopy],
- )
-
- const hotkeys = useMemo<UseHotkeyDefinition[]>(
- () => [
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.delete'], () => {
+ const hotkeys: UseHotkeyDefinition[] = [
+ ...bind(
+ 'workflow.save-draft',
+ () => {
+ handleSyncWorkflowDraft()
+ },
+ { enabled: !nodesReadOnly },
+ ),
+ ...bind(
+ 'workflow.delete',
+ () => {
+ target.current?.focus({ preventScroll: true })
handleNodesDelete()
handleEdgeDelete()
- }),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.copy'], handleCopy, {
- preventDefault: false,
- stopPropagation: false,
- enabled: !showDebugAndPreviewPanel,
- }),
- ...toHotkeyDefinitions(
- WORKFLOW_CANVAS_SHORTCUTS['workflow.paste'],
- () => {
- handleNodesPaste()
- },
- {
- enabled: !showDebugAndPreviewPanel,
- },
- ),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.duplicate'], () => {
+ },
+ { enabled: !nodesReadOnly },
+ ),
+ ...bind('workflow.copy', () => handleNodesCopy(), {
+ shouldHandle: shouldHandleCopy,
+ enabled: !nodesReadOnly && !showDebugAndPreviewPanel,
+ }),
+ ...bind(
+ 'workflow.paste',
+ () => {
+ handleNodesPaste()
+ },
+ {
+ enabled: !nodesReadOnly && !showDebugAndPreviewPanel,
+ },
+ ),
+ ...bind(
+ 'workflow.duplicate',
+ () => {
handleNodesDuplicate()
- }),
- ...toHotkeyDefinitions(
- WORKFLOW_CANVAS_SHORTCUTS['workflow.undo'],
- () => {
- handleHistoryBack()
- },
- {
- enabled: !showDebugAndPreviewPanel && historyShortcutsEnabled,
- },
- ),
- ...toHotkeyDefinitions(
- WORKFLOW_CANVAS_SHORTCUTS['workflow.redo'],
- () => {
- handleHistoryForward()
- },
- {
- enabled: !showDebugAndPreviewPanel && historyShortcutsEnabled,
- },
- ),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.hand-mode'], () => {
+ },
+ { enabled: !nodesReadOnly },
+ ),
+ ...bind(
+ 'workflow.undo',
+ () => {
+ target.current?.focus({ preventScroll: true })
+ handleHistoryBack()
+ },
+ {
+ enabled: !nodesReadOnly && !showDebugAndPreviewPanel,
+ },
+ ),
+ ...bind(
+ 'workflow.redo',
+ () => {
+ target.current?.focus({ preventScroll: true })
+ handleHistoryForward()
+ },
+ {
+ enabled: !nodesReadOnly && !showDebugAndPreviewPanel,
+ },
+ ),
+ ...bind(
+ 'workflow.hand-mode',
+ () => {
handleModeHand()
- }),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.pointer-mode'], () => {
+ },
+ { enabled: !nodesReadOnly },
+ ),
+ ...bind(
+ 'workflow.pointer-mode',
+ () => {
handleModePointer()
- }),
- ...toHotkeyDefinitions(
- WORKFLOW_CANVAS_SHORTCUTS['workflow.comment-mode'],
- () => {
- handleModeComment()
- },
- {
- enabled: isCommentModeAvailable,
- },
- ),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.organize'], () => {
+ },
+ { enabled: !nodesReadOnly },
+ ),
+ ...bind(
+ 'workflow.comment-mode',
+ () => {
+ handleModeComment()
+ },
+ {
+ enabled: canUseCommentMode,
+ },
+ ),
+ ...bind(
+ 'workflow.organize',
+ () => {
handleLayout()
- }),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.zoom-to-fit'], () => {
- fitView()
- handleSyncWorkflowDraft()
- }),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.zoom-to-100'], () => {
- zoomTo(1)
- handleSyncWorkflowDraft()
- }),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.zoom-to-50'], () => {
- zoomTo(0.5)
- handleSyncWorkflowDraft()
- }),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.zoom-out'], () => {
+ },
+ { enabled: !nodesReadOnly },
+ ),
+ ...bind('workflow.zoom-to-fit', () => {
+ fitView()
+ handleSyncWorkflowDraft()
+ }),
+ ...bind('workflow.zoom-to-100', () => {
+ zoomTo(1)
+ handleSyncWorkflowDraft()
+ }),
+ ...bind('workflow.zoom-to-50', () => {
+ zoomTo(0.5)
+ handleSyncWorkflowDraft()
+ }),
+ ...bind(
+ 'workflow.zoom-out',
+ () => {
constrainedZoomOut()
handleSyncWorkflowDraft()
- }),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.zoom-in'], () => {
+ },
+ { allowRepeat: true },
+ ),
+ ...bind(
+ 'workflow.zoom-in',
+ () => {
constrainedZoomIn()
handleSyncWorkflowDraft()
- }),
- ...toHotkeyDefinitions(WORKFLOW_CANVAS_SHORTCUTS['workflow.download-import-log'], () => {
- collaborationManager.downloadGraphImportLog()
- }),
- ],
- [
- constrainedZoomIn,
- constrainedZoomOut,
- fitView,
- handleCopy,
- handleEdgeDelete,
- handleHistoryBack,
- handleHistoryForward,
- handleLayout,
- handleModeComment,
- handleModeHand,
- handleModePointer,
- handleNodesDelete,
- handleNodesDuplicate,
- handleNodesPaste,
- handleSyncWorkflowDraft,
- historyShortcutsEnabled,
- isCommentModeAvailable,
- showDebugAndPreviewPanel,
- zoomTo,
- ],
- )
+ },
+ { allowRepeat: true },
+ ),
+ ...bind('workflow.download-import-log', () => {
+ collaborationManager.downloadGraphImportLog()
+ }),
+ ]
+ // Listen after React's delegated child handlers, then claim only events from this canvas.
useHotkeys(hotkeys, workflowHotkeyOptions)
useEffect(() => {
- if (isShiftHeld) {
+ if (isShiftHeld && canvasHasFocus) {
if (shiftDimmedRef.current) return
- if (isInputLikeElement(document.activeElement)) return
-
shiftDimmedRef.current = true
dimOtherNodes()
return
@@ -225,7 +254,7 @@ export const useWorkflowHotkeys = (): void => {
shiftDimmedRef.current = false
undimAllNodes()
- }, [dimOtherNodes, isShiftHeld, undimAllNodes])
+ }, [canvasHasFocus, dimOtherNodes, isShiftHeld, undimAllNodes])
useEffect(() => {
return () => {
diff --git a/web/app/components/workflow/shortcuts/workflow-canvas.tsx b/web/app/components/workflow/shortcuts/workflow-canvas.tsx
new file mode 100644
index 00000000000..9d209e22c68
--- /dev/null
+++ b/web/app/components/workflow/shortcuts/workflow-canvas.tsx
@@ -0,0 +1,90 @@
+import type { ReactFlowProps } from 'reactflow'
+import { cn } from '@langgenius/dify-ui/cn'
+import { useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import ReactFlow from 'reactflow'
+import { useWorkflowHotkeys } from './use-workflow-hotkeys'
+
+export function WorkflowCanvas({
+ className,
+ onFocus,
+ onBlur,
+ onPaneClick,
+ onNodeClick,
+ onEdgeContextMenu,
+ onNodeDragStart,
+ onSelectionStart,
+ ...props
+}: ReactFlowProps) {
+ const canvasRef = useRef<HTMLDivElement>(null)
+ const { t } = useTranslation(['app'])
+ const [canvasHasFocus, setCanvasHasFocus] = useState(false)
+ useWorkflowHotkeys(canvasRef, canvasHasFocus)
+
+ function isCanvasFocusTarget(element: EventTarget | null) {
+ return (
+ element instanceof HTMLElement &&
+ !!canvasRef.current?.contains(element) &&
+ !element.isContentEditable &&
+ !['INPUT', 'TEXTAREA', 'SELECT'].includes(element.tagName)
+ )
+ }
+
+ function focusCanvas() {
+ canvasRef.current?.focus({ preventScroll: true })
+ }
+
+ return (
+ <ReactFlow
+ {...props}
+ ref={canvasRef}
+ tabIndex={0}
+ role="region"
+ aria-label={t(($) => $['types.workflow'], { ns: 'app' })}
+ className={cn(
+ 'focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-none focus-visible:ring-inset',
+ className,
+ )}
+ onFocus={(event) => {
+ setCanvasHasFocus(isCanvasFocusTarget(event.target))
+ onFocus?.(event)
+ }}
+ onBlur={(event) => {
+ setCanvasHasFocus(isCanvasFocusTarget(event.relatedTarget))
+ onBlur?.(event)
+ }}
+ onPaneClick={(event) => {
+ focusCanvas()
+ onPaneClick?.(event)
+ }}
+ onNodeClick={(event, node) => {
+ const target = event.target
+ const control =
+ target instanceof Element
+ ? target.closest(
+ 'a[href], button, input, textarea, select, [contenteditable], [tabindex]',
+ )
+ : null
+ if (
+ (!control || control === event.currentTarget) &&
+ event.currentTarget instanceof HTMLElement
+ )
+ event.currentTarget.focus({ preventScroll: true })
+ onNodeClick?.(event, node)
+ }}
+ onEdgeContextMenu={(event, edge) => {
+ // SVG edge anchors cannot be the menu primitive's HTML focus return target.
+ focusCanvas()
+ onEdgeContextMenu?.(event, edge)
+ }}
+ onNodeDragStart={(event, node, nodes) => {
+ focusCanvas()
+ onNodeDragStart?.(event, node, nodes)
+ }}
+ onSelectionStart={(event) => {
+ focusCanvas()
+ onSelectionStart?.(event)
+ }}
+ />
+ )
+}
diff --git a/web/app/components/workflow/store/workflow/history-slice.ts b/web/app/components/workflow/store/workflow/history-slice.ts
index 6639b3659e2..437ece2dc06 100644
--- a/web/app/components/workflow/store/workflow/history-slice.ts
+++ b/web/app/components/workflow/store/workflow/history-slice.ts
@@ -39,8 +39,6 @@ export type HistorySliceShape = {
initializedWorkflowHistory?: WorkflowHistoryState
initializeWorkflowHistory: (workflowHistory: WorkflowHistoryState) => void
setWorkflowHistory: (workflowHistory: WorkflowHistoryState) => void
- historyShortcutsEnabled: boolean
- setHistoryShortcutsEnabled: (enabled: boolean) => void
historyWorkflowData?: HistoryWorkflowData
setHistoryWorkflowData: (historyWorkflowData?: HistoryWorkflowData) => void
showRunHistory: boolean
@@ -60,8 +58,6 @@ export const createHistorySlice: StateCreator<HistorySliceShape> = (set) => ({
initializeWorkflowHistory: (workflowHistory) =>
set(() => ({ workflowHistory, initializedWorkflowHistory: workflowHistory })),
setWorkflowHistory: (workflowHistory) => set(() => ({ workflowHistory })),
- historyShortcutsEnabled: true,
- setHistoryShortcutsEnabled: (historyShortcutsEnabled) => set(() => ({ historyShortcutsEnabled })),
historyWorkflowData: undefined,
setHistoryWorkflowData: (historyWorkflowData) => set(() => ({ historyWorkflowData })),
showRunHistory: false,
diff --git a/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx b/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx
index 25819037497..c0648743280 100644
--- a/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx
@@ -95,6 +95,27 @@ describe('WorkflowGeneratorModal', () => {
expect(instruction).toHaveValue('Summarize a URL')
})
+ it.each([{ isComposing: true }, { repeat: true }])(
+ 'should leave a composing or repeated submit key unclaimed (%j)',
+ async (keyboardState) => {
+ const user = userEvent.setup()
+ render(<WorkflowGeneratorModal />)
+ const instruction = screen.getByRole('textbox', {
+ name: /workflowGenerator\.instruction/i,
+ })
+ await user.type(instruction, 'Summarize a URL')
+
+ expect(
+ fireEvent.keyDown(instruction, {
+ key: 'Enter',
+ ctrlKey: true,
+ ...keyboardState,
+ }),
+ ).toBe(true)
+ expect(mockGenerateWorkflowStream).not.toHaveBeenCalled()
+ },
+ )
+
it('should generate from the instruction shortcut', async () => {
const user = userEvent.setup()
render(<WorkflowGeneratorModal />)
diff --git a/web/app/components/workflow/workflow-generator/index.tsx b/web/app/components/workflow/workflow-generator/index.tsx
index c72e259cf07..115daed2f94 100644
--- a/web/app/components/workflow/workflow-generator/index.tsx
+++ b/web/app/components/workflow/workflow-generator/index.tsx
@@ -643,9 +643,12 @@ function WorkflowGeneratorModal() {
value={instruction}
onValueChange={setInstruction}
onKeyDown={(e) => {
+ if (e.defaultPrevented || e.nativeEvent.isComposing || e.repeat || isLoading)
+ return
if (matchesKeyboardEvent(e.nativeEvent, WORKFLOW_GENERATOR_SUBMIT_HOTKEY)) {
e.preventDefault()
- if (!isLoading) onGenerate()
+ e.stopPropagation()
+ onGenerate()
}
}}
maxLength={MAX_INSTRUCTION_LENGTH}
diff --git a/web/docs/hotkeys.md b/web/docs/hotkeys.md
new file mode 100644
index 00000000000..b918541825f
--- /dev/null
+++ b/web/docs/hotkeys.md
@@ -0,0 +1,135 @@
+# Keyboard Commands
+
+Keep each command's binding, action, availability, and registration with the feature that owns
+it. Use TanStack Hotkeys for application commands; keep text editing, widget navigation, and
+primitive dismissal with their existing controls.
+
+## Default pattern
+
+Inside mounted content, bind directly to the actual command owner's ref:
+
+```tsx
+import type { Hotkey } from '@tanstack/react-hotkeys'
+import { useHotkey } from '@tanstack/react-hotkeys'
+import { useRef } from 'react'
+
+const PUBLISH_HOTKEY = 'Mod+Shift+P' satisfies Hotkey
+
+const popupRef = useRef<HTMLDivElement>(null)
+useHotkey(PUBLISH_HOTKEY, publish, {
+ target: popupRef,
+ enabled: canPublish,
+ ignoreInputs: true,
+ requireReset: true,
+})
+```
+
+Attach `popupRef` to the actual Popup. Call the same action as the button, with the same
+availability. The library matches modifiers, consumes accepted events before the callback,
+and keeps that callback current.
+
+- **Scope:** pass the owner's ref. Omit `target` for intentional page/application commands.
+ `ignoreInputs` only controls input filtering; form commands usually allow input targets.
+- **Availability:** align `enabled` with permissions, loading, validation, and open state.
+ Keep validation in the action too, since buttons and menus also invoke it.
+- **Repeat:** use `requireReset: true` for one-shot commands; allow repeats for continuous zoom.
+
+## Choose the registration boundary
+
+| Situation | Pattern |
+| ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
+| The hook and target mount together | `useHotkey` with the actual owner ref. The ref may be local or passed from a parent. |
+| Form content mounts later than its transaction owner | The actual Form's `onKeyDown + matchesKeyboardEvent` is a direct option; a hook inside mounted content also works. |
+| Child React handlers must process the key first | Handle it during React bubbling, or at document bubble with an owner-ref containment check, as Workflow does. |
+
+Choose by lifetime and event order. Being inside a Popup alone does not determine the API.
+The target must exist when the hook's registration effect runs; changing `ref.current` does
+not re-render the hook owner. Keep normal targets in `useRef` and transactions with their
+business owner. Element state is useful when an external subscription reports target
+replacement, such as Lexical's root listener; guard a nullable element with `enabled`, since
+a bare null target falls back to document.
+
+For a real form, call `event.currentTarget.requestSubmit()` to share submission and validation.
+React Portal events follow React ancestry: a local handler should check DOM containment when
+nested portals must stay outside its command. A feature may intentionally include its own
+portalled menus, as the Skills file tree does.
+
+## Bindings and hints
+
+| Need | API and type |
+| ------------------------------- | --------------------------------------------------------------------- |
+| One command / a command group | `useHotkey` / `useHotkeys`; retain feature command IDs. |
+| Binding definition | `satisfies Hotkey` for strings; `satisfies RawHotkey` for objects. |
+| Existing React keyboard handler | `matchesKeyboardEvent(event.nativeEvent, binding)`. |
+| Keycap hint | `formatForDisplay(binding, { parts: true })` with `Kbd` / `KbdGroup`. |
+| A held modifier | `useKeyHold`; combine key state with the interaction's actual scope. |
+
+Share bindings between registration and hints; keep single-owner constants local. Use
+`RegisterableHotkey` where both binding forms are accepted. `DisplayHotkey` is wider and belongs
+only to display. Validate dynamic bindings before parsing; narrow the `key`/`code` union when
+inspecting objects. Logical `Mod+S` follows the character; `Mod+[KeyS]` follows physical position.
+
+Preserve the initial platform through SSR hydration, as navigation search does.
+`aria-keyshortcuts` uses `Meta+K` or `Control+K`, not keycap glyphs or `Mod`.
+
+## Conditional event handling
+
+Use library defaults unless ownership or event priority requires a decision before consumption.
+An element's native listener can precede child React handlers, and the manager does not skip
+`defaultPrevented`. For these conditional owners, set `preventDefault: false` and
+`stopPropagation: false`, check scope and `defaultPrevented`, then consume the accepted event.
+For one-shot actions in this mode, consume repeats before returning on `event.repeat`; leave
+`requireReset` unset so its latch cannot bypass that consumption.
+
+The library filters composing printable shortcuts such as `Mod+S`. Custom submission and
+logical Enter/Escape still need IME protection; retain existing composition-end handling.
+`stopPropagation()` stops ancestors, not another callback on the same manager target.
+Keep eligible owners unambiguous; `conflictBehavior: 'replace'` is not a restoring modal stack,
+and provider defaults or metadata do not establish scope.
+
+Let Dialog, Popover, and Menu primitives own dismissal. A container handling bubbled child
+events keeps its actual semantics; an explained lint exception is preferable to inventing a
+button role or tab stop. Custom nonmodal panels should describe their real modality.
+
+## Workflow ownership
+
+| Layer | Responsibility |
+| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
+| Canvas | `WorkflowCanvas` supplies the ReactFlow root ref. `useWorkflowHotkeys` runs after child React handlers and accepts events within that subtree. |
+| Graph actions | Existing graph hooks own permissions, mutations, history, and persistence; keyboard commands invoke them. |
+| Editors and node navigation | ReactFlow, local node handlers, Lexical, CodeMirror, and forms own navigation, undo, suggestions, and submission. |
+| Portalled menus | Each menu matches its displayed commands and acts on its actual node, edge, or selection. |
+| Run and history | Header features own page commands with button-aligned availability; header focus is unnecessary. |
+| Comments | The focused draft/thread handles dismissal after suggestions. Active pointer-following placement owns Escape without taking focus. |
+
+The outer Workflow container includes unrelated panels. Use the canvas root for graph scope,
+restore canvas focus when deleting its focused object or applying graph undo/redo, and use
+Popup `finalFocus` when a menu action deletes its return target. Keep text undo with editors.
+Hold-to-dim combines key state with canvas focus and clears on focus loss.
+
+## Verification and maintenance
+
+Follow [the Web testing policy]. Use the real matcher/manager to verify scope, availability,
+mount/reopen behavior, child event priority, IME flags, and repeat where affected. Verify
+native editing, focus, and selection in a browser; check both platform modifiers for binding
+or hint changes. State the limits of simulated IME and SDK mocks.
+
+Follow these patterns for new commands. Recorders, remapping, and extra wrappers need a
+concrete product requirement.
+
+## References
+
+- [TanStack Hotkeys options]
+- [TanStack formatting]
+- [React Portal events]
+- [Delegated event handlers]
+- [Modal dialog requirements]
+- [Character shortcuts and focus]
+
+[Character shortcuts and focus]: https://www.w3.org/WAI/WCAG22/Understanding/character-key-shortcuts.html
+[Delegated event handlers]: https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/main/docs/rules/no-static-element-interactions.md
+[Modal dialog requirements]: https://www.w3.org/WAI/ARIA/apg/patterns/dialog-modal
+[React Portal events]: https://react.dev/reference/react-dom/createPortal
+[TanStack Hotkeys options]: https://tanstack.com/hotkeys/latest/docs/framework/react/guides/hotkeys
+[TanStack formatting]: https://tanstack.com/hotkeys/latest/docs/framework/react/guides/formatting-display
+[the Web testing policy]: test.md
diff --git a/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
index 70f8212c43c..d65f9292580 100644
--- a/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx
@@ -732,6 +732,30 @@ describe('AgentPromptEditor', () => {
})
})
+ it('should leave slash-menu navigation and selection to IME while composing', async () => {
+ const user = userEvent.setup()
+ const { store } = renderAgentPromptEditor('Review /')
+ const textbox = screen.getByRole('textbox')
+
+ textbox.focus()
+ const menu = await openSlashMenuFromEditor(textbox)
+ await user.keyboard('{ArrowDown}{ArrowRight}{ArrowDown}')
+ const skill = screen.getByRole('button', { name: 'Library Skill' })
+ expect(skill).toHaveAttribute('data-agent-prompt-menu-active')
+
+ for (const key of ['ArrowDown', 'Enter', 'Escape'])
+ fireEvent.keyDown(textbox, { key, isComposing: true })
+
+ expect(menu).toBeInTheDocument()
+ expect(skill).toHaveAttribute('data-agent-prompt-menu-active')
+ expect(store.get(agentComposerPromptAtom)).toBe('Review /')
+
+ await user.keyboard('{Enter}')
+ expect(store.get(agentComposerPromptAtom)).toBe(
+ 'Review [§skill:library-skill:Library Skill§] ',
+ )
+ })
+
it('should keep editor focus when selecting slash menu items with a pointer', async () => {
const user = userEvent.setup()
const { store } = renderAgentPromptEditor('Review these tenders /')
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx
index 962a408488e..4aaa51911df 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx
@@ -37,18 +37,6 @@ vi.mock('@/features/system-features/state', async () => {
return { deploymentEditionAtom: atom('CLOUD') }
})
-const hotkeyRegistrations = vi.hoisted(
- () =>
- new Map<
- string,
- {
- callback: (event: { preventDefault: () => void }) => void
- options?: { enabled?: boolean; ignoreInputs?: boolean }
- }
- >(),
-)
-
-const mockFormatForDisplay = vi.hoisted(() => vi.fn((hotkey: string) => `display:${hotkey}`))
const mockFormatTimeFromNow = vi.hoisted(() => vi.fn(() => 'just now'))
const mockFormatTime = vi.hoisted(() => vi.fn((timestamp: number) => `formatted:${timestamp}`))
const restoreVersionMutation = vi.hoisted(() =>
@@ -77,27 +65,6 @@ vi.mock('@/app/notifications', () => ({
toast: toastMock,
}))
-vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()
- return {
- ...actual,
- formatForDisplay: mockFormatForDisplay,
- useHotkey: (
- hotkey: string,
- callback: (event: { preventDefault: () => void }) => void,
- options?: { enabled?: boolean; ignoreInputs?: boolean },
- ) => {
- hotkeyRegistrations.set(hotkey, { callback, options })
- },
- }
-})
-
-vi.mock('@/hooks/use-format-time-from-now', () => ({
- useFormatTimeFromNow: () => ({
- formatTimeFromNow: mockFormatTimeFromNow,
- }),
-}))
-
vi.mock('@/hooks/use-timestamp', () => ({
default: () => ({
formatTime: mockFormatTime,
@@ -373,10 +340,13 @@ function renderPublishBar({
}
}
+vi.mock('@/hooks/use-format-time-from-now', () => ({
+ useFormatTimeFromNow: () => ({ formatTimeFromNow: mockFormatTimeFromNow }),
+}))
+
describe('AgentConfigurePublishBar', () => {
beforeEach(() => {
vi.clearAllMocks()
- hotkeyRegistrations.clear()
restoreAccess.canRestore = true
restoreAccess.plan = 'professional'
restoreVersionMutation.mockResolvedValue({
@@ -403,13 +373,9 @@ describe('AgentConfigurePublishBar', () => {
expect(
screen.getByRole('button', { name: /agentV2\.agentDetail\.publish/ }),
).toBeInTheDocument()
- expect(screen.getByText('display:Mod')).toBeInTheDocument()
- expect(screen.getByText('display:Shift')).toBeInTheDocument()
- expect(screen.getByText('display:P')).toBeInTheDocument()
- expect(mockFormatForDisplay).toHaveBeenCalledWith('Mod')
- expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: true, ignoreInputs: false }),
- )
+ expect(screen.getByText('Ctrl')).toBeInTheDocument()
+ expect(screen.getByText('Shift')).toBeInTheDocument()
+ expect(screen.getByText('P')).toBeInTheDocument()
})
it('should allow publish request when knowledge retrieval validation fails', async () => {
@@ -438,9 +404,6 @@ describe('AgentConfigurePublishBar', () => {
'common.errorMsg.fieldRequired:{"field":"agentV2.agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label"}',
),
).not.toBeInTheDocument()
- expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: true, ignoreInputs: false }),
- )
fireEvent.click(
screen.getByRole('button', {
@@ -638,11 +601,7 @@ describe('AgentConfigurePublishBar', () => {
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' }),
).toBeDisabled()
- expect(screen.queryByText('display:Mod')).not.toBeInTheDocument()
expect(mockFormatTimeFromNow).toHaveBeenCalledWith(1710000000 * 1000)
- expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: false, ignoreInputs: false }),
- )
fireEvent.click(
screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' }),
@@ -661,9 +620,6 @@ describe('AgentConfigurePublishBar', () => {
expect(screen.getByRole('button', { name: /agentV2\.agentDetail\.publish/ })).toBeDisabled()
})
expect(screen.getByRole('button', { name: /agentV2\.agentDetail\.publish/ })).toBeDisabled()
- expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: false, ignoreInputs: false }),
- )
})
it('should fail closed when refreshing cached Composer state fails', async () => {
@@ -680,9 +636,6 @@ describe('AgentConfigurePublishBar', () => {
}),
).toBeDisabled()
})
- expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: false, ignoreInputs: false }),
- )
})
it('should show unpublished state from local draft changes even when active config is published', () => {
@@ -700,9 +653,6 @@ describe('AgentConfigurePublishBar', () => {
name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/,
}),
).toBeInTheDocument()
- expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: true, ignoreInputs: false }),
- )
})
it('should initialize unpublished state when active config is not published', async () => {
@@ -720,9 +670,6 @@ describe('AgentConfigurePublishBar', () => {
name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/,
}),
).toBeInTheDocument()
- expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: true, ignoreInputs: false }),
- )
fireEvent.click(
screen.getByRole('button', {
@@ -894,10 +841,6 @@ describe('AgentConfigurePublishBar', () => {
expect(
screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.publishing' }),
).not.toHaveAttribute('aria-busy')
- expect(screen.queryByText('display:Mod')).not.toBeInTheDocument()
- expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
- expect.objectContaining({ enabled: false, ignoreInputs: false }),
- )
})
it('should expand affected workflow details above the publish toolbar when clicking a publishable agent in use', async () => {
@@ -961,9 +904,9 @@ describe('AgentConfigurePublishBar', () => {
'noopener noreferrer',
)
expect(within(impactDetails).getAllByText('just now')).toHaveLength(2)
- expect(screen.getByText('display:Mod')).toBeInTheDocument()
- expect(screen.getByText('display:Shift')).toBeInTheDocument()
- expect(screen.getByText('display:P')).toBeInTheDocument()
+ expect(screen.getByText('Ctrl')).toBeInTheDocument()
+ expect(screen.getByText('Shift')).toBeInTheDocument()
+ expect(screen.getByText('P')).toBeInTheDocument()
})
it('should publish from the fixed toolbar action after affected workflow details expand', async () => {
@@ -1098,10 +1041,10 @@ describe('AgentConfigurePublishBar', () => {
prompt: 'Updated system prompt',
usedByAppReferences: publishedReferences,
})
- const publishShortcut = hotkeyRegistrations.get('Mod+Shift+P')
await act(async () => {
- await publishShortcut?.callback({ preventDefault: vi.fn() })
+ fireEvent.keyDown(document.body, { key: 'P', code: 'KeyP', ctrlKey: true, shiftKey: true })
+ fireEvent.keyUp(document.body, { key: 'P', code: 'KeyP', ctrlKey: true, shiftKey: true })
})
expect(onPublish).not.toHaveBeenCalled()
@@ -1112,7 +1055,8 @@ describe('AgentConfigurePublishBar', () => {
).toBeInTheDocument()
await act(async () => {
- await hotkeyRegistrations.get('Mod+Shift+P')?.callback({ preventDefault: vi.fn() })
+ fireEvent.keyDown(document.body, { key: 'P', code: 'KeyP', ctrlKey: true, shiftKey: true })
+ fireEvent.keyUp(document.body, { key: 'P', code: 'KeyP', ctrlKey: true, shiftKey: true })
})
expect(onPublish).toHaveBeenCalledTimes(1)
@@ -1123,10 +1067,10 @@ describe('AgentConfigurePublishBar', () => {
activeConfigSnapshot,
prompt: 'Updated system prompt',
})
- const publishShortcut = hotkeyRegistrations.get('Mod+Shift+P')
await act(async () => {
- await publishShortcut?.callback({ preventDefault: vi.fn() })
+ fireEvent.keyDown(document.body, { key: 'P', code: 'KeyP', ctrlKey: true, shiftKey: true })
+ fireEvent.keyUp(document.body, { key: 'P', code: 'KeyP', ctrlKey: true, shiftKey: true })
})
expect(
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
index 3c9b8715894..ef2caa469a3 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
@@ -650,7 +650,7 @@ export function AgentPromptEditor() {
const handleEditorKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
handledEditorMenuKeyRef.current = false
- if (readOnly) return
+ if (readOnly || event.nativeEvent.isComposing) return
if (event.key === 'Escape' && isSlashMenuOpen) {
event.preventDefault()
@@ -887,6 +887,8 @@ export function AgentPromptEditor() {
if (!menuElement) return
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
+ if (event.isComposing) return
+
const activeElement = menuElement.ownerDocument.activeElement
if (!menuElement.contains(activeElement)) return
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx
index ea426514a5f..27f7020b409 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx
@@ -74,9 +74,9 @@ function getPublishState({
function PublishShortcut() {
return (
<KbdGroup aria-hidden>
- {PUBLISH_AGENT_HOTKEY.split('+').map((key) => (
+ {formatForDisplay(PUBLISH_AGENT_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white">
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
@@ -200,11 +200,16 @@ export function AgentConfigurePublishBar({
useHotkey(
PUBLISH_AGENT_HOTKEY,
(event) => {
+ if (event.defaultPrevented) return
event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
requestPublish()
},
{
enabled: canPublish && !selectedVersionSnapshot,
+ preventDefault: false,
+ stopPropagation: false,
ignoreInputs: false,
},
)
diff --git a/web/features/agent-v2/agent-detail/navigation.tsx b/web/features/agent-v2/agent-detail/navigation.tsx
index 5baa17acf28..af2d9fc3aeb 100644
--- a/web/features/agent-v2/agent-detail/navigation.tsx
+++ b/web/features/agent-v2/agent-detail/navigation.tsx
@@ -144,8 +144,8 @@ export function AgentDetailTop({ expand = true, onToggle }: AgentDetailTopProps)
<TooltipContent placement="bottom" className="flex items-center gap-1">
<span className="px-0.5">{tApp(($) => $['gotoAnything.quickAction'])}</span>
<KbdGroup>
- {GOTO_ANYTHING_HOTKEY.split('+').map((key) => (
- <Kbd key={key}>{formatForDisplay(key)}</Kbd>
+ {formatForDisplay(GOTO_ANYTHING_HOTKEY, { parts: true }).map((key) => (
+ <Kbd key={key}>{key}</Kbd>
))}
</KbdGroup>
</TooltipContent>
diff --git a/web/features/skills/__tests__/detail-page-clipboard.spec.tsx b/web/features/skills/__tests__/detail-page-clipboard.spec.tsx
index 7351836a976..c677aa0f9b5 100644
--- a/web/features/skills/__tests__/detail-page-clipboard.spec.tsx
+++ b/web/features/skills/__tests__/detail-page-clipboard.spec.tsx
@@ -1,4 +1,10 @@
-import { act, fireEvent, screen, waitFor, within } from '@testing-library/react'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@langgenius/dify-ui/dropdown-menu'
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import {
@@ -61,6 +67,26 @@ function createSelectionSkillDetail() {
describe('SkillDetailPage clipboard', () => {
beforeEach(resetDetailPageFixture)
+ it('leaves shortcuts in another page menu to that menu', async () => {
+ const user = userEvent.setup()
+ renderSkillDetailPage()
+ await waitFor(() => expect(getFileTreeItem('SKILL.md')).toBeInTheDocument())
+ render(
+ <DropdownMenu>
+ <DropdownMenuTrigger>Other actions</DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem>Other copy</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>,
+ )
+ await user.click(screen.getByRole('button', { name: 'Other actions' }))
+ const menuItem = await screen.findByRole('menuitem', { name: 'Other copy' })
+ fireEvent.keyDown(menuItem, { key: 'c', code: 'KeyC', ...primaryModifier })
+ fireEvent.keyDown(menuItem, { key: 'x', code: 'KeyX', ...primaryModifier })
+ expect(mocks.copyToClipboard).not.toHaveBeenCalled()
+ expect(mocks.toastSuccess).not.toHaveBeenCalled()
+ })
+
it('copies the context-menu file with the displayed keyboard shortcut', async () => {
renderSkillDetailPage()
@@ -77,7 +103,6 @@ describe('SkillDetailPage clipboard', () => {
const copyMenuItem = screen.getByRole('menuitem', {
name: /skillManagement\.detail\.copyFile/,
})
- copyMenuItem.addEventListener('keydown', (event) => event.stopPropagation())
fireEvent.keyDown(copyMenuItem, {
code: 'KeyC',
key: 'c',
@@ -89,6 +114,68 @@ describe('SkillDetailPage clipboard', () => {
)
})
+ it('copies the dropdown file instead of the previously selected file', async () => {
+ const user = userEvent.setup()
+ mocks.skillDetail = createSelectionSkillDetail()
+ renderSkillDetailPage()
+ await waitFor(() => expect(getFileTreeButton('SKILL.md')).toBeInTheDocument())
+ await user.click(getFileTreeButton('SKILL.md'))
+ await openFileTreeActions(user, 'README.md')
+ const copyMenuItem = await screen.findByRole('menuitem', {
+ name: /skillManagement\.detail\.copyFile/,
+ })
+ fireEvent.keyDown(copyMenuItem, {
+ key: 'c',
+ code: 'KeyC',
+ ...primaryModifier,
+ isComposing: true,
+ })
+ expect(mocks.copyToClipboard).not.toHaveBeenCalled()
+ fireEvent.keyDown(copyMenuItem, { key: 'c', code: 'KeyC', ...primaryModifier })
+ expect(
+ fireEvent.keyDown(copyMenuItem, {
+ key: 'c',
+ code: 'KeyC',
+ ...primaryModifier,
+ repeat: true,
+ }),
+ ).toBe(false)
+
+ expect(mocks.copyToClipboard).toHaveBeenCalledExactlyOnceWith('# README')
+ })
+
+ it.each([false, true])(
+ 'cuts the dropdown file while preserving an existing multi-selection: %s',
+ async (multiSelection) => {
+ const user = userEvent.setup()
+ mocks.skillDetail = createSelectionSkillDetail()
+ renderSkillDetailPage()
+ await waitFor(() => expect(getFileTreeButton('SKILL.md')).toBeInTheDocument())
+ await user.click(getFileTreeButton('SKILL.md'))
+ if (multiSelection) fireEvent.click(getFileTreeButton('README.md'), primaryModifier)
+ await openFileTreeActions(user, 'README.md')
+ const cutMenuItem = await screen.findByRole('menuitem', {
+ name: /skillManagement\.detail\.cutFile/,
+ })
+ fireEvent.keyDown(cutMenuItem, { key: 'x', code: 'KeyX', ...primaryModifier })
+ await user.keyboard('{Escape}')
+ await user.click(getFileTreeButton('references'))
+ fireEvent.paste(getFileTreeButton('references'))
+
+ const paths = multiSelection ? ['SKILL.md', 'README.md'] : ['README.md']
+ await waitFor(() => expect(mocks.saveDraftFileMutationFn).toHaveBeenCalledTimes(paths.length))
+ expect(mocks.saveDraftFileMutationFn.mock.calls.map(([request]) => request.body)).toEqual(
+ paths.map((path) =>
+ expect.objectContaining({
+ operation: 'rename',
+ path,
+ target_path: `references/${path}`,
+ }),
+ ),
+ )
+ },
+ )
+
it('cuts the context-menu file with the displayed keyboard shortcut', async () => {
renderSkillDetailPage()
@@ -105,7 +192,6 @@ describe('SkillDetailPage clipboard', () => {
const cutMenuItem = screen.getByRole('menuitem', {
name: /skill\.skillManagement\.detail\.cutFile/,
})
- cutMenuItem.addEventListener('keydown', (event) => event.stopPropagation())
fireEvent.keyDown(cutMenuItem, {
code: 'KeyX',
key: 'x',
diff --git a/web/features/skills/__tests__/detail-page-editor.spec.tsx b/web/features/skills/__tests__/detail-page-editor.spec.tsx
index c4eb4b67365..3e2adfee58b 100644
--- a/web/features/skills/__tests__/detail-page-editor.spec.tsx
+++ b/web/features/skills/__tests__/detail-page-editor.spec.tsx
@@ -359,6 +359,8 @@ describe('SkillDetailPage editor', () => {
if (!liveEditor) throw new Error('live editor not found')
await user.click(liveEditor)
+ expect(fireEvent.keyDown(liveEditor, { key: 'Enter', isComposing: true })).toBe(true)
+ expect(liveEditor).toHaveTextContent('')
await user.type(liveEditor, 'First line{Enter}Second line')
await user.click(
screen.getByRole('button', { name: 'skill.skillManagement.detail.publishUpdate' }),
diff --git a/web/features/skills/detail/__tests__/publish-bar.spec.tsx b/web/features/skills/detail/__tests__/publish-bar.spec.tsx
index 0be27952665..d415c25f68f 100644
--- a/web/features/skills/detail/__tests__/publish-bar.spec.tsx
+++ b/web/features/skills/detail/__tests__/publish-bar.spec.tsx
@@ -1,4 +1,4 @@
-import { render, screen } from '@testing-library/react'
+import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { SkillPublishBar } from '../publish-bar'
@@ -47,6 +47,32 @@ describe('SkillPublishBar', () => {
expect(
screen.getByRole('button', { name: 'skill.skillManagement.detail.published' }),
).toBeDisabled()
+ expect(fireEvent.keyDown(document.body, { key: 'P', ctrlKey: true, shiftKey: true })).toBe(true)
+ expect(onPublish).not.toHaveBeenCalled()
+ })
+
+ it('publishes from page inputs while preserving IME, local ownership, and repeat defaults', () => {
+ render(
+ <>
+ <SkillPublishBar
+ metaLabel="Saved just now"
+ state="draft"
+ onOpenVersions={onOpenVersions}
+ onPublish={onPublish}
+ />
+ <input aria-label="Description" />
+ <input aria-label="Editor command" onKeyDown={(event) => event.preventDefault()} />
+ </>,
+ )
+ const input = screen.getByRole('textbox', { name: 'Description' })
+ const binding = { key: 'P', ctrlKey: true, shiftKey: true }
+ expect(fireEvent.keyDown(input, { ...binding, isComposing: true })).toBe(true)
+ fireEvent.keyDown(screen.getByRole('textbox', { name: 'Editor command' }), binding)
+ expect(onPublish).not.toHaveBeenCalled()
+
+ expect(fireEvent.keyDown(input, binding)).toBe(false)
+ expect(fireEvent.keyDown(input, { ...binding, repeat: true })).toBe(false)
+ expect(onPublish).toHaveBeenCalledOnce()
})
it('labels an edited published skill as an unpublished update', () => {
diff --git a/web/features/skills/detail/file-editor.tsx b/web/features/skills/detail/file-editor.tsx
index 9e11f974342..42a73be9b99 100644
--- a/web/features/skills/detail/file-editor.tsx
+++ b/web/features/skills/detail/file-editor.tsx
@@ -737,7 +737,7 @@ export function FileEditor({
event: KeyboardEvent<HTMLDivElement | HTMLTextAreaElement>,
bodyMode = false,
) => {
- if (!isMarkdown || readonly) return
+ if (!isMarkdown || readonly || event.nativeEvent.isComposing) return
if (
bodyMode &&
@@ -1209,7 +1209,8 @@ export function FileEditor({
setMetadataKey(event.target.value)
}}
onKeyDown={(event) => {
- if (event.key === 'Escape') handleCancelAddMetadata()
+ if (!event.nativeEvent.isComposing && event.key === 'Escape')
+ handleCancelAddMetadata()
}}
/>
<button
@@ -1230,6 +1231,7 @@ export function FileEditor({
setMetadataValue(event.target.value)
}}
onKeyDown={(event) => {
+ if (event.nativeEvent.isComposing) return
if (event.key === 'Escape') {
handleCancelAddMetadata()
return
@@ -1244,7 +1246,7 @@ export function FileEditor({
}
}}
onKeyUp={(event) => {
- if (event.key !== 'Enter') return
+ if (event.nativeEvent.isComposing || event.key !== 'Enter') return
event.preventDefault()
event.stopPropagation()
diff --git a/web/features/skills/detail/file-tree-items.tsx b/web/features/skills/detail/file-tree-items.tsx
index 727b79cfbd6..0a4b19317df 100644
--- a/web/features/skills/detail/file-tree-items.tsx
+++ b/web/features/skills/detail/file-tree-items.tsx
@@ -4,7 +4,7 @@ import type {
SkillDetailResponse,
SkillFileResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
-import type { DragEvent, MouseEvent, ReactElement } from 'react'
+import type { DragEvent, KeyboardEvent, MouseEvent, ReactElement } from 'react'
import type { SkillDropTarget } from './file-tree-dnd'
import type { FileTreeInlineAction, FileTreeNode } from './shared'
import { cn } from '@langgenius/dify-ui/cn'
@@ -23,12 +23,14 @@ import {
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
+import { formatForDisplay, matchesKeyboardEvent } from '@tanstack/react-hotkeys'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { setSkillFileDragPreview } from './file-tree-drag-preview'
import {
getDraggedSkillPaths,
getSkillFileIconClass,
+ isEditableKeyboardTarget,
skillFileDragPathsType,
skillFileDragType,
skillFileHotkeys,
@@ -164,7 +166,7 @@ function FileActionMenuItems({
<span aria-hidden className="i-ri-scissors-cut-line size-4 text-text-tertiary" />
<span>{t(($) => $['skillManagement.detail.cutFile'])}</span>
<KbdGroup className="ml-auto">
- {skillFileHotkeys.cut.keycaps.map((keycap) => (
+ {formatForDisplay(skillFileHotkeys.cut.command, { parts: true }).map((keycap) => (
<Kbd key={keycap}>{keycap}</Kbd>
))}
</KbdGroup>
@@ -179,7 +181,7 @@ function FileActionMenuItems({
<span aria-hidden className="i-ri-file-copy-line size-4 text-text-tertiary" />
<span>{t(($) => $['skillManagement.detail.copyFile'])}</span>
<KbdGroup className="ml-auto">
- {skillFileHotkeys.copy.keycaps.map((keycap) => (
+ {formatForDisplay(skillFileHotkeys.copy.command, { parts: true }).map((keycap) => (
<Kbd key={keycap}>{keycap}</Kbd>
))}
</KbdGroup>
@@ -255,6 +257,7 @@ function FileActions({
onCreateFolder,
onCut,
onDelete,
+ onMenuKeyDown,
onRename,
onUploadFiles,
}: {
@@ -265,6 +268,7 @@ function FileActions({
onCreateFolder: () => void
onCut: (path: string) => void
onDelete: () => void
+ onMenuKeyDown: (event: KeyboardEvent<HTMLElement>) => void
onRename: () => void
onUploadFiles: (files: File[], targetDirectory: string | undefined) => void
}) {
@@ -284,7 +288,12 @@ function FileActions({
>
<span aria-hidden className="i-ri-more-fill size-4" />
</DropdownMenuTrigger>
- <DropdownMenuContent placement="bottom-end" className={skillFileMenuPopupClassName}>
+ <DropdownMenuContent
+ data-skill-file-menu
+ onKeyDown={onMenuKeyDown}
+ placement="bottom-end"
+ className={skillFileMenuPopupClassName}
+ >
<FileActionMenuItems
kind="dropdown"
node={node}
@@ -419,6 +428,25 @@ export function FileTreeItem({
? inlineAction
: undefined
+ const handleMenuKeyDown = (event: KeyboardEvent<HTMLElement>) => {
+ if (readonly || inlineActionLoading || inlineAction || node.type !== 'file') return
+ if (event.defaultPrevented) return
+ if (!(event.target instanceof Node) || !event.currentTarget.contains(event.target)) return
+ if (isEditableKeyboardTarget(event.target)) return
+
+ const action = matchesKeyboardEvent(event.nativeEvent, skillFileHotkeys.copy.command)
+ ? onCopy
+ : matchesKeyboardEvent(event.nativeEvent, skillFileHotkeys.cut.command)
+ ? onCut
+ : undefined
+ if (!action) return
+
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ action(node.path)
+ }
+
useEffect(
() => () => {
if (expandTimerRef.current) clearTimeout(expandTimerRef.current)
@@ -513,7 +541,11 @@ export function FileTreeItem({
<>
<ContextMenu>
<ContextMenuTrigger render={trigger} />
- <ContextMenuContent className={skillFileMenuPopupClassName}>
+ <ContextMenuContent
+ data-skill-file-menu
+ className={skillFileMenuPopupClassName}
+ onKeyDown={handleMenuKeyDown}
+ >
<FileActionMenuItems
kind="context"
node={node}
@@ -597,6 +629,7 @@ export function FileTreeItem({
onCreateFolder={() => onCreate('directory', node.path)}
onCut={onCut}
onDelete={() => onDelete(node)}
+ onMenuKeyDown={handleMenuKeyDown}
onRename={() => onRename(node)}
onUploadFiles={onUploadFiles}
visible={actionsVisible}
@@ -717,6 +750,7 @@ export function FileTreeItem({
onCreateFolder={() => onCreate('directory', node.path)}
onCut={onCut}
onDelete={() => onDelete(node)}
+ onMenuKeyDown={handleMenuKeyDown}
onRename={() => onRename(node)}
onUploadFiles={onUploadFiles}
visible={actionsVisible}
diff --git a/web/features/skills/detail/file-tree.tsx b/web/features/skills/detail/file-tree.tsx
index f82404e32be..23c518a8dde 100644
--- a/web/features/skills/detail/file-tree.tsx
+++ b/web/features/skills/detail/file-tree.tsx
@@ -961,57 +961,53 @@ export function FileTree({
!readonly && !!shortcutTargetPath && !fileMutation.isPending && !inlineAction
const isInSidebar = (target: EventTarget | null) =>
target instanceof Node && !!sidebarRef.current?.contains(target)
- const handleOpenMenuHotkey = useEffectEvent((event: globalThis.KeyboardEvent) => {
+ const handleOpenMenuPaste = (event: ReactKeyboardEvent<HTMLElement>) => {
if (readonly || fileMutation.isPending || inlineAction) return
- if (!(event.target instanceof Element) || !event.target.closest('[role="menu"]')) return
-
- if (
- shortcutTargetPath &&
- (matchesKeyboardEvent(event, 'Meta+X') || matchesKeyboardEvent(event, 'Control+X'))
- ) {
- event.preventDefault()
- event.stopPropagation()
- handleCut(shortcutTargetPath)
+ if (event.defaultPrevented) return
+ if (!(event.target instanceof Element) || !event.target.closest('[data-skill-file-menu]'))
return
- }
-
- if (
- shortcutTargetPath &&
- (matchesKeyboardEvent(event, 'Meta+C') || matchesKeyboardEvent(event, 'Control+C'))
- ) {
- event.preventDefault()
- event.stopPropagation()
- handleCopy(shortcutTargetPath)
- return
- }
+ if (isEditableKeyboardTarget(event.target)) return
- if (
- clipboard &&
- (matchesKeyboardEvent(event, 'Meta+V') || matchesKeyboardEvent(event, 'Control+V'))
- ) {
+ if (clipboard && matchesKeyboardEvent(event.nativeEvent, skillFileHotkeys.paste.command)) {
event.preventDefault()
event.stopPropagation()
+ if (event.repeat) return
handlePaste(getPasteTargetDirectory())
}
- })
+ }
- useEffect(() => {
- document.addEventListener('keydown', handleOpenMenuHotkey, true)
- return () => document.removeEventListener('keydown', handleOpenMenuHotkey, true)
- }, [])
+ const handleRootMenuKeyDown = (event: ReactKeyboardEvent<HTMLElement>) => {
+ if (!fileShortcutEnabled || !shortcutTargetPath) return
+ if (event.defaultPrevented) return
+ if (!(event.target instanceof Node) || !event.currentTarget.contains(event.target)) return
+ if (isEditableKeyboardTarget(event.target)) return
+
+ const action = matchesKeyboardEvent(event.nativeEvent, skillFileHotkeys.copy.command)
+ ? handleCopy
+ : matchesKeyboardEvent(event.nativeEvent, skillFileHotkeys.cut.command)
+ ? handleCut
+ : undefined
+ if (!action) return
+
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ action(shortcutTargetPath)
+ }
useHotkey(
skillFileHotkeys.cut.command,
(event) => {
- if (!shortcutTargetPath) return
- if (!isInSidebar(event.target)) return
+ if (!shortcutTargetPath || event.defaultPrevented) return
event.preventDefault()
event.stopPropagation()
+ if (event.repeat) return
handleCut(shortcutTargetPath)
},
{
enabled: fileShortcutEnabled,
+ target: sidebarRef,
ignoreInputs: true,
preventDefault: false,
stopPropagation: false,
@@ -1020,15 +1016,16 @@ export function FileTree({
useHotkey(
skillFileHotkeys.copy.command,
(event) => {
- if (!shortcutTargetPath) return
- if (!isInSidebar(event.target)) return
+ if (!shortcutTargetPath || event.defaultPrevented) return
event.preventDefault()
event.stopPropagation()
+ if (event.repeat) return
handleCopy(shortcutTargetPath)
},
{
enabled: fileShortcutEnabled,
+ target: sidebarRef,
ignoreInputs: true,
preventDefault: false,
stopPropagation: false,
@@ -1163,9 +1160,11 @@ export function FileTree({
return (
<>
+ {/* oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The sidebar delegates paste shortcuts from its portalled menus after child handlers. */}
<section
aria-labelledby={filesTitleId}
ref={sidebarRef}
+ onKeyDown={handleOpenMenuPaste}
data-testid="skill-detail-sidebar-shell"
className={cn(
'relative flex h-full shrink-0 bg-background-body p-1',
@@ -1263,8 +1262,8 @@ export function FileTree({
<TooltipContent placement="bottom" className="flex items-center gap-1">
<span className="px-0.5">{tApp(($) => $['gotoAnything.quickAction'])}</span>
<KbdGroup>
- {GOTO_ANYTHING_HOTKEY.split('+').map((key) => (
- <Kbd key={key}>{formatForDisplay(key)}</Kbd>
+ {formatForDisplay(GOTO_ANYTHING_HOTKEY, { parts: true }).map((key) => (
+ <Kbd key={key}>{key}</Kbd>
))}
</KbdGroup>
</TooltipContent>
@@ -1361,7 +1360,12 @@ export function FileTree({
>
<span aria-hidden className="i-ri-add-line size-4" />
</DropdownMenuTrigger>
- <DropdownMenuContent placement="bottom-end" className={skillFileMenuPopupClassName}>
+ <DropdownMenuContent
+ data-skill-file-menu
+ onKeyDown={handleRootMenuKeyDown}
+ placement="bottom-end"
+ className={skillFileMenuPopupClassName}
+ >
<RootFileActionMenuItems
kind="dropdown"
onCreateFile={() =>
@@ -1505,7 +1509,11 @@ export function FileTree({
</ul>
)}
</ContextMenuTrigger>
- <ContextMenuContent className={skillFileMenuPopupClassName}>
+ <ContextMenuContent
+ data-skill-file-menu
+ className={skillFileMenuPopupClassName}
+ onKeyDown={handleRootMenuKeyDown}
+ >
<RootFileActionMenuItems
kind="context"
onCreateFile={() =>
diff --git a/web/features/skills/detail/publish-bar.tsx b/web/features/skills/detail/publish-bar.tsx
index 7534401bf5f..e4968b2c5bf 100644
--- a/web/features/skills/detail/publish-bar.tsx
+++ b/web/features/skills/detail/publish-bar.tsx
@@ -36,9 +36,9 @@ export function SkillPublishBottomActions({ children }: { children: ReactNode })
export function SkillPublishShortcut() {
return (
<KbdGroup aria-hidden>
- {PUBLISH_SKILL_HOTKEY.split('+').map((key) => (
+ {formatForDisplay(PUBLISH_SKILL_HOTKEY, { parts: true }).map((key) => (
<Kbd key={key} color="white">
- {formatForDisplay(key)}
+ {key}
</Kbd>
))}
</KbdGroup>
@@ -56,10 +56,22 @@ export function SkillPublishBar({
const { t } = useTranslation(['skill'])
const canPublish = hasPublishPermission && (state === 'draft' || state === 'unpublished')
- useHotkey(PUBLISH_SKILL_HOTKEY, onPublish, {
- enabled: canPublish,
- ignoreInputs: false,
- })
+ useHotkey(
+ PUBLISH_SKILL_HOTKEY,
+ (event) => {
+ if (event.defaultPrevented) return
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.repeat) return
+ onPublish()
+ },
+ {
+ enabled: canPublish,
+ ignoreInputs: false,
+ preventDefault: false,
+ stopPropagation: false,
+ },
+ )
const stateMeta = {
draft: {
diff --git a/web/features/skills/detail/shared.tsx b/web/features/skills/detail/shared.tsx
index e740e8d084a..7f581b3e447 100644
--- a/web/features/skills/detail/shared.tsx
+++ b/web/features/skills/detail/shared.tsx
@@ -6,6 +6,7 @@ import type {
SkillResponse,
SkillVersionResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
+import type { Hotkey } from '@tanstack/react-hotkeys'
import type { InfiniteData, useQueryClient } from '@tanstack/react-query'
import type {
DefaultModel,
@@ -80,13 +81,12 @@ export function runSkillFileMutation(
export const skillFileHotkeys = {
copy: {
- command: 'Mod+C',
- keycaps: ['⌘', 'C'],
+ command: 'Mod+C' satisfies Hotkey,
},
cut: {
- command: 'Mod+X',
- keycaps: ['⌘', 'X'],
+ command: 'Mod+X' satisfies Hotkey,
},
+ paste: { command: 'Mod+V' satisfies Hotkey },
} as const
export const skillFileMenuPopupClassName = 'w-[168px] data-ending-style:transition-none'