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.

chore(web): focus node panel on keyboard open (SNP-877) (#43047)

Joel1b21b8220d17
diff --git a/web/app/components/workflow/hooks/__tests__/use-node-keyboard-interactions.spec.tsx b/web/app/components/workflow/hooks/__tests__/use-node-keyboard-interactions.spec.tsx
index b4f4afed772..ec9d1e5c12c 100644
--- a/web/app/components/workflow/hooks/__tests__/use-node-keyboard-interactions.spec.tsx
+++ b/web/app/components/workflow/hooks/__tests__/use-node-keyboard-interactions.spec.tsx
@@ -81,9 +81,14 @@ describe('node keyboard interactions', () => {
it('selects and deselects the focused node while leaving editor keys alone', async () => {
const user = userEvent.setup()
- renderWorkflowComponent(<Canvas />)
+ const { store } = renderWorkflowComponent(<Canvas />)
await user.tab()
- await user.keyboard('{Enter}{Escape} ')
+ await user.keyboard('{Enter}')
+ expect(store.getState().pendingNodePanelFocusId).toBe('node')
+ await user.keyboard('{Escape}')
+ expect(store.getState().pendingNodePanelFocusId).toBeUndefined()
+ await user.keyboard(' ')
+ expect(store.getState().pendingNodePanelFocusId).toBe('node')
expect(state.select.mock.calls).toEqual([
['node', false],
['node', true],
diff --git a/web/app/components/workflow/hooks/use-node-keyboard-interactions.ts b/web/app/components/workflow/hooks/use-node-keyboard-interactions.ts
index c48f9852814..cc273cd0f04 100644
--- a/web/app/components/workflow/hooks/use-node-keyboard-interactions.ts
+++ b/web/app/components/workflow/hooks/use-node-keyboard-interactions.ts
@@ -52,7 +52,12 @@ export function useNodeKeyboardInteractions(onSelect: (id: string, cancel?: bool
return
if (isSelectionKey) {
- if (focusedNode) onSelect(focusedNode.id, event.key === 'Escape')
+ if (focusedNode) {
+ workflowStore
+ .getState()
+ .setPendingNodePanelFocusId(event.key === 'Escape' ? undefined : focusedNode.id)
+ onSelect(focusedNode.id, event.key === 'Escape')
+ }
return
}
if (getNodesReadOnly() || !movement) return
diff --git a/web/app/components/workflow/nodes/_base/components/title-description-input.tsx b/web/app/components/workflow/nodes/_base/components/title-description-input.tsx
index d48f692ea2d..f594e4bca8f 100644
--- a/web/app/components/workflow/nodes/_base/components/title-description-input.tsx
+++ b/web/app/components/workflow/nodes/_base/components/title-description-input.tsx
@@ -1,3 +1,4 @@
+import type { Ref } from 'react'
import { memo, useCallback, useEffect, useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Textarea from 'react-textarea-autosize'
@@ -62,8 +63,9 @@ TitleInput.displayName = 'TitleInput'
type DescriptionInputProps = {
value: string
onChange: (value: string) => void
+ inputRef?: Ref<HTMLTextAreaElement>
}
-export const DescriptionInput = memo(({ value, onChange }: DescriptionInputProps) => {
+export const DescriptionInput = memo(({ value, onChange, inputRef }: DescriptionInputProps) => {
const { t } = useTranslation(['workflow'])
const inputId = useId()
const [focus, setFocus] = useState(false)
@@ -83,6 +85,7 @@ export const DescriptionInput = memo(({ value, onChange }: DescriptionInputProps
className={`group flex max-h-15 overflow-y-auto rounded-lg bg-components-panel-bg px-2 py-1.25 leading-0 ${focus && 'shadow-xs!'} `}
>
<Textarea
+ ref={inputRef}
id={inputId}
value={value}
onChange={(e) => onChange(e.target.value)}
diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx
index 145f402027a..ef3efff133d 100644
--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx
@@ -3,7 +3,12 @@ import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { createDatasourceProvider } from '@/app/components/rag-pipeline/__tests__/datasource-fixtures'
-import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { createNode } from '@/app/components/workflow/__tests__/fixtures'
+import {
+ renderWorkflowComponent,
+ renderWorkflowFlowComponent,
+} from '@/app/components/workflow/__tests__/workflow-test-env'
+import { useNodeKeyboardInteractions } from '@/app/components/workflow/hooks/use-node-keyboard-interactions'
import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
import BasePanel from '../index'
@@ -379,9 +384,36 @@ const createData = (overrides: Record<string, unknown> = {}) => ({
...overrides,
})
+function KeyboardOpenedPanel({ type }: { type: BlockEnum }) {
+ const [open, setOpen] = React.useState(false)
+ const onKeyDownCapture = useNodeKeyboardInteractions(() => setOpen(true))
+
+ React.useEffect(() => {
+ mockHandleNodeSelect.mockImplementation((_id: string, cancel?: boolean) => {
+ if (cancel) setOpen(false)
+ })
+ }, [])
+
+ return (
+ <div id="workflow-container">
+ <div onKeyDownCapture={onKeyDownCapture}>
+ <div className="react-flow__node" data-id="node-1" role="button" tabIndex={0}>
+ Canvas node
+ </div>
+ </div>
+ {open && (
+ <BasePanel id="node-1" data={createData({ type }) as never}>
+ <div>panel-child</div>
+ </BasePanel>
+ )}
+ </div>
+ )
+}
+
describe('workflow-panel index', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockHandleNodeSelect.mockReset()
mockNodesReadOnly = false
mockCanRun = true
mockBuiltInTools = [
@@ -399,6 +431,84 @@ describe('workflow-panel index', () => {
mockLastRunState.singleRunParams = createMockSingleRunParams()
})
+ it.each([BlockEnum.Start, BlockEnum.End])(
+ 'moves focus from a keyboard opened %s node into its configuration panel',
+ async (type) => {
+ const user = userEvent.setup()
+ renderWorkflowFlowComponent(<KeyboardOpenedPanel type={type} />, {
+ nodes: [createNode({ id: 'node-1', data: { type } })],
+ })
+
+ const canvasNode = screen.getByRole('button', { name: 'Canvas node' })
+ await user.click(canvasNode)
+ await user.keyboard('{Enter}')
+
+ const description = await screen.findByRole('textbox', {
+ name: 'workflow.common.nodeDescription',
+ })
+ expect(description).toHaveFocus()
+ expect(canvasNode).not.toHaveFocus()
+ },
+ )
+
+ it.each([BlockEnum.Start, BlockEnum.End])(
+ 'closes a %s node configuration panel with Escape and restores focus to its canvas node',
+ async (type) => {
+ const user = userEvent.setup()
+ renderWorkflowFlowComponent(<KeyboardOpenedPanel type={type} />, {
+ nodes: [createNode({ id: 'node-1', data: { type } })],
+ })
+
+ const canvasNode = screen.getByRole('button', { name: 'Canvas node' })
+ await user.click(canvasNode)
+ await user.keyboard('{Enter}')
+
+ const description = await screen.findByRole('textbox', {
+ name: 'workflow.common.nodeDescription',
+ })
+ expect(description).toHaveFocus()
+
+ await user.keyboard('{Escape}')
+
+ expect(
+ screen.queryByRole('region', { name: /workflow\.panel\.nodePanel/ }),
+ ).not.toBeInTheDocument()
+ expect(canvasNode).toHaveFocus()
+ expect(mockHandleNodeSelect).toHaveBeenCalledWith('node-1', true)
+ },
+ )
+
+ it.each([{ view: 'single-run' }, { view: 'special-result' }])(
+ 'closes a keyboard opened $view panel with Escape and restores focus to its canvas node',
+ async ({ view }) => {
+ const user = userEvent.setup()
+ if (view === 'single-run') mockLastRunState.isShowSingleRun = true
+ else mockLogsState.showSpecialResultPanel = true
+
+ renderWorkflowFlowComponent(<KeyboardOpenedPanel type={BlockEnum.Tool} />, {
+ nodes: [createNode({ id: 'node-1', data: { type: BlockEnum.Tool } })],
+ })
+
+ const canvasNode = screen.getByRole('button', { name: 'Canvas node' })
+ await user.click(canvasNode)
+ await user.keyboard('{Enter}')
+
+ const panel = screen.getByRole('region', { name: /workflow\.panel\.nodePanel/ })
+ if (view === 'special-result')
+ expect(screen.getByText('special-result-panel')).toBeInTheDocument()
+ else expect(screen.queryByText('panel-child')).not.toBeInTheDocument()
+ expect(panel).toHaveFocus()
+
+ await user.keyboard('{Escape}')
+
+ expect(
+ screen.queryByRole('region', { name: /workflow\.panel\.nodePanel/ }),
+ ).not.toBeInTheDocument()
+ expect(canvasNode).toHaveFocus()
+ expect(mockHandleNodeSelect).toHaveBeenCalledWith('node-1', true)
+ },
+ )
+
it('should render the settings panel and wire title, description, run, and close actions', async () => {
renderWorkflowComponent(
<BasePanel id="node-1" data={createData() as never}>
@@ -819,6 +929,36 @@ describe('workflow-panel index', () => {
expect(screen.getByRole('button', { name: 'Before panel' })).toHaveFocus()
})
+ it.each([BlockEnum.Start, BlockEnum.End, BlockEnum.Tool, BlockEnum.StartPlaceholder])(
+ 'focuses the node panel once when keyboard selection opens a %s node',
+ async (type) => {
+ const user = userEvent.setup()
+ const { store } = renderWorkflowComponent(
+ <>
+ <button type="button">Canvas node</button>
+ <BasePanel id="node-1" data={createData({ type }) as never}>
+ <div>panel-child</div>
+ </BasePanel>
+ </>,
+ )
+
+ const canvasNode = screen.getByRole('button', { name: 'Canvas node' })
+ await user.click(canvasNode)
+ expect(canvasNode).toHaveFocus()
+
+ act(() => store.getState().setPendingNodePanelFocusId('node-1'))
+ const focusTarget =
+ type === BlockEnum.StartPlaceholder
+ ? screen.getByRole('region', { name: /Tool Node workflow\.panel\.nodePanel/i })
+ : screen.getByRole('textbox', { name: 'workflow.common.nodeDescription' })
+ await waitFor(() => expect(focusTarget).toHaveFocus())
+ expect(store.getState().pendingNodePanelFocusId).toBeUndefined()
+
+ await user.click(canvasNode)
+ expect(canvasNode).toHaveFocus()
+ },
+ )
+
it('should constrain keyboard resizing to the available space and keep unrelated keys untouched', async () => {
const user = userEvent.setup()
const onKeyDown = vi.fn()
diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx
index c7a6bafd4f5..43fb326540c 100644
--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx
+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx
@@ -1,4 +1,4 @@
-import type { CSSProperties, FC, ReactNode } from 'react'
+import type { CSSProperties, FC, KeyboardEvent, ReactNode } from 'react'
import type { SimpleSubscription } from '@/app/components/plugins/plugin-detail-panel/subscription-list'
import type { Node } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
@@ -154,6 +154,9 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {
const setNodePanelWidth = useStore((s) => s.setNodePanelWidth)
const pendingSingleRun = useStore((s) => s.pendingSingleRun)
const setPendingSingleRun = useStore((s) => s.setPendingSingleRun)
+ const pendingNodePanelFocusId = useStore((s) => s.pendingNodePanelFocusId)
+ const setPendingNodePanelFocusId = useStore((s) => s.setPendingNodePanelFocusId)
+ const descriptionInputRef = useRef<HTMLTextAreaElement>(null)
const setNodePanelWidthStorage = useSetWorkflowNodePanelWidth()
const reservedCanvasWidth = 400 // Reserve the minimum visible width for the canvas
@@ -204,6 +207,30 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {
}, [nodePanelWidth, otherPanelWidth, workflowCanvasWidth, debounceUpdate])
const { handleNodeSelect } = useNodesInteractions()
+ const handlePanelKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLElement>) => {
+ if (
+ event.key !== 'Escape' ||
+ event.defaultPrevented ||
+ event.nativeEvent.isComposing ||
+ event.altKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ !event.currentTarget.contains(event.target as globalThis.Node)
+ )
+ return
+
+ event.preventDefault()
+ event.stopPropagation()
+ const workflow = event.currentTarget.closest('#workflow-container')
+ const node = Array.from(
+ workflow?.querySelectorAll<HTMLElement>('.react-flow__node') ?? [],
+ ).find((element) => element.dataset.id === id)
+ node?.focus({ preventScroll: true })
+ handleNodeSelect(id, true)
+ },
+ [handleNodeSelect, id],
+ )
const { nodesReadOnly } = useNodesReadOnly()
const { availableNextBlocks } = useAvailableBlocks(
getNodeCatalogType(data),
@@ -305,6 +332,14 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {
setIsPaused(false)
}, [tabType])
+ useEffect(() => {
+ if (pendingNodePanelFocusId !== id || !containerRef.current) return
+
+ setTabType(TabType.settings)
+ ;(descriptionInputRef.current ?? containerRef.current).focus({ preventScroll: true })
+ setPendingNodePanelFocusId(undefined)
+ }, [containerRef, id, pendingNodePanelFocusId, setPendingNodePanelFocusId, setTabType])
+
useEffect(() => {
if (!pendingSingleRun || pendingSingleRun.nodeId !== id) return
@@ -440,10 +475,15 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {
if (logParams.showSpecialResultPanel) {
return (
<div className={cn('relative mr-1 h-full')}>
+ {/* oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The panel handles bubbling Escape after its child controls have handled it. */}
<div
ref={containerRef}
+ onKeyDown={handlePanelKeyDown}
+ role="region"
+ aria-label={`${data.title} ${t(($) => $['panel.nodePanel'], { ns: 'workflow' })}`}
+ tabIndex={-1}
className={cn(
- 'flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg',
+ 'flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden focus-visible:ring-inset',
isSingleRunPanelVisible ? 'overflow-hidden' : 'overflow-y-auto',
)}
style={{
@@ -494,10 +534,15 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {
return (
<div className={cn('relative mr-1 h-full')}>
+ {/* oxlint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- The panel handles bubbling Escape after its child controls have handled it. */}
<div
ref={containerRef}
+ onKeyDown={handlePanelKeyDown}
+ role="region"
+ aria-label={`${data.title} ${t(($) => $['panel.nodePanel'], { ns: 'workflow' })}`}
+ tabIndex={-1}
className={cn(
- 'flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg',
+ 'flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden focus-visible:ring-inset',
isSingleRunPanelVisible ? 'overflow-hidden' : 'overflow-y-auto',
)}
style={{
@@ -570,9 +615,13 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {
<Tabs
id={panelId}
ref={containerRef}
+ onKeyDown={handlePanelKeyDown}
+ role="region"
+ aria-label={`${data.title} ${t(($) => $['panel.nodePanel'], { ns: 'workflow' })}`}
+ tabIndex={-1}
value={tabType}
onValueChange={(selectedValue) => setTabType(selectedValue)}
- className="flex h-full flex-col overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg transition-[width] ease-linear"
+ className="flex h-full flex-col overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg transition-[width] ease-linear focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden focus-visible:ring-inset"
style={
{
width: `${nodePanelWidth}px`,
@@ -637,7 +686,11 @@ const BasePanel: FC<BasePanelProps> = ({ id, data, children }) => {
<StartPlaceholderPanelDescription />
) : (
<div className="p-2">
- <DescriptionInput value={data.desc || ''} onChange={handleDescriptionChange} />
+ <DescriptionInput
+ inputRef={descriptionInputRef}
+ value={data.desc || ''}
+ onChange={handleDescriptionChange}
+ />
</div>
)}
{!isStartPlaceholderPanel && (
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
index 5c1d96e2b4e..9960b42bf8e 100644
--- a/web/app/components/workflow/shortcuts/__tests__/workflow-canvas.browser.spec.tsx
+++ b/web/app/components/workflow/shortcuts/__tests__/workflow-canvas.browser.spec.tsx
@@ -8,7 +8,7 @@ import {
ContextMenuTrigger,
} from '@langgenius/dify-ui/context-menu'
import { detectPlatform } from '@tanstack/react-hotkeys'
-import { useRef, useState } from 'react'
+import { useEffect, 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'
@@ -575,6 +575,63 @@ function VariableConnectionCanvas({ onSelect }: { onSelect: (value: string[]) =>
)
}
+function KeyboardPanelFocusCanvas({ store }: { store: ReturnType<typeof createWorkflowStore> }) {
+ const [open, setOpen] = useState(false)
+ const pendingFocusId = useStore(store, (state) => state.pendingNodePanelFocusId)
+ const panelRef = useRef<HTMLDivElement>(null)
+ const descriptionRef = useRef<HTMLTextAreaElement>(null)
+ const handleNodeKeyDown = useNodeKeyboardInteractions(() => setOpen(true))
+
+ useEffect(() => {
+ if (!open || pendingFocusId !== 'node') return
+ ;(descriptionRef.current ?? panelRef.current)?.focus({ preventScroll: true })
+ store.getState().setPendingNodePanelFocusId(undefined)
+ }, [open, pendingFocusId, store])
+
+ return (
+ <>
+ <div style={{ width: 800, height: 500 }}>
+ <WorkflowCanvas
+ nodes={[
+ {
+ id: 'node',
+ type: 'focus',
+ position: { x: 100, y: 100 },
+ data: { type: BlockEnum.Code },
+ },
+ ]}
+ edges={[]}
+ nodeTypes={{ focus: () => <div>Workflow node</div> }}
+ onKeyDownCapture={handleNodeKeyDown}
+ />
+ </div>
+ {open && (
+ <div ref={panelRef} role="region" aria-label="Node configuration" tabIndex={-1}>
+ <textarea ref={descriptionRef} aria-label="Description" />
+ <button type="button">First setting</button>
+ </div>
+ )}
+ </>
+ )
+}
+
+it('keeps focus in the panel after Enter opens it from a real ReactFlow node', async () => {
+ const store = createWorkflowStore({})
+ const screen = await render(
+ <WorkflowContext value={store}>
+ <ReactFlowProvider>
+ <KeyboardPanelFocusCanvas store={store} />
+ </ReactFlowProvider>
+ </WorkflowContext>,
+ )
+
+ const node = screen.getByTestId('rf__node-node')
+ await node.click()
+ await expect.element(node).toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+ await expect.element(screen.getByRole('textbox', { name: 'Description' })).toHaveFocus()
+})
+
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)
diff --git a/web/app/components/workflow/store/workflow/node-slice.ts b/web/app/components/workflow/store/workflow/node-slice.ts
index 383a30eb224..d6b28dc9676 100644
--- a/web/app/components/workflow/store/workflow/node-slice.ts
+++ b/web/app/components/workflow/store/workflow/node-slice.ts
@@ -14,6 +14,8 @@ export type NodeSliceShape = {
setCandidateNode: (candidateNode?: Node) => void
openInlineAgentPanelNodeId?: string
setOpenInlineAgentPanelNodeId: (nodeId?: string) => void
+ pendingNodePanelFocusId?: string
+ setPendingNodePanelFocusId: (nodeId?: string) => void
showAssignVariablePopup?: {
nodeId: string
nodeData: Node['data']
@@ -66,6 +68,8 @@ export const createNodeSlice: StateCreator<NodeSliceShape> = (set) => ({
setCandidateNode: (candidateNode) => set(() => ({ candidateNode })),
openInlineAgentPanelNodeId: undefined,
setOpenInlineAgentPanelNodeId: (nodeId) => set(() => ({ openInlineAgentPanelNodeId: nodeId })),
+ pendingNodePanelFocusId: undefined,
+ setPendingNodePanelFocusId: (nodeId) => set(() => ({ pendingNodePanelFocusId: nodeId })),
showAssignVariablePopup: undefined,
setShowAssignVariablePopup: (showAssignVariablePopup) => set(() => ({ showAssignVariablePopup })),
hoveringAssignVariableGroupId: undefined,