Merge pull request #5308 from xyflow/5030-focus-nodes-when-user-selects-via-tab

feat(NodeWrapper): focus nodes in the viewport on tab
This commit is contained in:
Moritz Klack
2025-06-10 10:13:01 +02:00
committed by GitHub
20 changed files with 214 additions and 80 deletions

View File

@@ -0,0 +1,6 @@
---
"@xyflow/react": minor
"@xyflow/svelte": minor
---
Focus nodes on tab if not within the viewport and add a new prop `autoPanOnNodeFocus`

View File

@@ -1,4 +1,4 @@
import { MouseEvent } from 'react';
import { MouseEvent, useState } from 'react';
import {
ReactFlow,
MiniMap,
@@ -8,40 +8,53 @@ import {
ReactFlowProvider,
Node,
Edge,
OnNodeDrag,
AriaLabelConfig,
Panel,
} from '@xyflow/react';
const onNodeDrag: OnNodeDrag = (_, node: Node, nodes: Node[]) => console.log('drag', node, nodes);
const onNodeDragStart = (_: MouseEvent, node: Node, nodes: Node[]) => console.log('drag start', node, nodes);
const onNodeDragStop = (_: MouseEvent, node: Node, nodes: Node[]) => console.log('drag stop', node, nodes);
const onNodeClick = (_: MouseEvent, node: Node) => console.log('click', node);
const initialNodes: Node[] = [
{
id: '1',
type: 'input',
data: { label: 'A11y Node 1' },
position: { x: 250, y: 5 },
className: 'light',
},
{
id: '2',
data: { label: 'Node 2' },
position: { x: 100, y: 100 },
className: 'light',
position: { x: 1000, y: 100 },
},
{
id: '3',
data: { label: 'Node 3' },
position: { x: 400, y: 100 },
position: { x: 100, y: 100 },
className: 'light',
ariaRoleDescription: 'custom node role',
ariaRole: 'button',
},
{
id: '4',
data: { label: 'Node 4' },
position: { x: 300, y: 100 },
},
{
id: '5',
data: { label: 'Node 5' },
position: { x: 400, y: 200 },
},
{
id: '6',
data: { label: 'Node 6' },
position: { x: -1000, y: 200 },
},
];
const initialEdges: Edge[] = [
{ id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e1-3', source: '1', target: '3' },
{ id: 'e1-4', source: '1', target: '4' },
{ id: 'e1-5', source: '4', target: '5' },
{ id: 'e1-6', source: '3', target: '6' },
];
const ariaLabelConfig: Partial<AriaLabelConfig> = {
@@ -59,19 +72,13 @@ const ariaLabelConfig: Partial<AriaLabelConfig> = {
};
const A11y = () => {
const [autoPanOnNodeFocus, setAutoPanOnNodeFocus] = useState(true);
return (
<ReactFlow
defaultNodes={initialNodes}
defaultEdges={initialEdges}
onNodesChange={console.log}
onNodeClick={onNodeClick}
onNodeDragStop={onNodeDragStop}
onNodeDragStart={onNodeDragStart}
onNodeDrag={onNodeDrag}
className="react-flow-basic-example"
minZoom={0.2}
maxZoom={4}
fitView
autoPanOnNodeFocus={autoPanOnNodeFocus}
selectNodesOnDrag={false}
elevateEdgesOnSelect
elevateNodesOnSelect={false}
@@ -81,6 +88,20 @@ const A11y = () => {
<Background variant={BackgroundVariant.Dots} />
<MiniMap />
<Controls />
<Panel position="top-right">
<div>
<label htmlFor="focusPannable">
<input
id="focusPannable"
type="checkbox"
checked={autoPanOnNodeFocus}
onChange={(event) => setAutoPanOnNodeFocus(event.target.checked)}
className="xy-theme__checkbox"
/>
autoPanOnNodeFocus
</label>
</div>
</Panel>
</ReactFlow>
);
};

View File

@@ -1,5 +1,5 @@
<script lang="ts">
import { SvelteFlow, Controls, Background, MiniMap } from '@xyflow/svelte';
import { SvelteFlow, Controls, Background, MiniMap, Panel } from '@xyflow/svelte';
import '@xyflow/svelte/dist/style.css';
@@ -10,7 +10,7 @@
data: { label: 'A' }
},
{ id: 'B', position: { x: -100, y: 150 }, data: { label: 'B' } },
{ id: 'C', position: { x: 100, y: 150 }, data: { label: 'C' } },
{ id: 'C', position: { x: 1000, y: 150 }, data: { label: 'C' } },
{ id: 'D', position: { x: 0, y: 260 }, data: { label: 'D' } }
]);
@@ -19,17 +19,19 @@
{ id: 'A-C', source: 'A', target: 'C' },
{ id: 'A-D', source: 'A', target: 'D' }
]);
</script>
<SvelteFlow
bind:nodes
bind:edges
fitView
ariaLabelConfig={{
let autoPanOnNodeFocus = $state(true);
const ariaLabelConfig = $state({
'node.a11yDescription.default': 'Svelte Custom Node Desc.',
'node.a11yDescription.keyboardDisabled': 'Svelte Custom Keyboard Desc.',
'node.a11yDescription.ariaLiveMessage': ({ direction, x, y }) =>
`Custom Moved selected node ${direction}. New position, x: ${x}, y: ${y}`,
'node.a11yDescription.ariaLiveMessage': ({
direction,
x,
y
}: {
direction: string;
x: number;
y: number;
}) => `Custom Moved selected node ${direction}. New position, x: ${x}, y: ${y}`,
'edge.a11yDescription.default': 'Svelte Custom Edge Desc.',
'controls.ariaLabel': 'Svelte Custom Control Aria Label',
'controls.zoomIn.ariaLabel': 'Svelte Custom Zoom in',
@@ -37,9 +39,24 @@
// 'controls.fitView.ariaLabel': 'Svelte Custom Fit View',
'controls.interactive.ariaLabel': 'Svelte Custom Toggle Interactivity',
'minimap.ariaLabel': 'Svelte Custom Minimap'
}}
>
});
</script>
<SvelteFlow bind:nodes bind:edges {autoPanOnNodeFocus} {ariaLabelConfig}>
<Controls />
<Background />
<MiniMap />
<Panel class="panel top-right">
<div>
<label for="focusPannable">
Enable Pan on Focus
<input
id="focusPannable"
type="checkbox"
bind:checked={autoPanOnNodeFocus}
class="svelte-flow__zoomonscroll"
/>
</label>
</div>
</Panel>
</SvelteFlow>

View File

@@ -7,6 +7,7 @@ import {
getNodeDimensions,
isInputDOMNode,
nodeHasDimensions,
getNodesInside,
} from '@xyflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore';
@@ -158,6 +159,28 @@ export function NodeWrapper<NodeType extends Node>({
});
}
};
const onFocus = () => {
if (disableKeyboardA11y || !nodeRef.current?.matches(':focus-visible')) {
return;
}
const { transform, width, height, autoPanOnNodeFocus, setCenter } = store.getState();
if (!autoPanOnNodeFocus) {
return;
}
const withinViewport =
getNodesInside(new Map([[id, node]]), { x: 0, y: 0, width, height }, transform, true).length > 0;
if (!withinViewport) {
setCenter(node.position.x + nodeDimensions.width / 2, node.position.y + nodeDimensions.height / 2, {
zoom: transform[2],
});
}
};
return (
<div
className={cc([
@@ -195,6 +218,7 @@ export function NodeWrapper<NodeType extends Node>({
onDoubleClick={onDoubleClickHandler}
onKeyDown={isFocusable ? onKeyDown : undefined}
tabIndex={isFocusable ? 0 : undefined}
onFocus={isFocusable ? onFocus : undefined}
role={node.ariaRole ?? (isFocusable ? 'group' : undefined)}
aria-roledescription={node.ariaRoleDescription || 'node'}
aria-describedby={disableKeyboardA11y ? undefined : `${ARIA_NODE_DESC_KEY}-${rfId}`}

View File

@@ -23,6 +23,7 @@ const reactFlowFieldsToTrack = [
'onClickConnectStart',
'onClickConnectEnd',
'nodesDraggable',
'autoPanOnNodeFocus',
'nodesConnectable',
'nodesFocusable',
'edgesFocusable',

View File

@@ -48,13 +48,13 @@ function NodeRendererComponent<NodeType extends Node>(props: NodeRendererProps<N
* The split of responsibilities between NodeRenderer and
* NodeComponentWrapper may appear weird. However, its designed to
* minimize the cost of updates when individual nodes change.
*
*
* For example, when youre dragging a single node, that node gets
* updated multiple times per second. If `NodeRenderer` were to update
* every time, it would have to re-run the `nodes.map()` loop every
* time. This gets pricey with hundreds of nodes, especially if every
* loop cycle does more than just rendering a JSX element!
*
*
* As a result of this choice, we took the following implementation
* decisions:
* - NodeRenderer subscribes *only* to node IDs and therefore

View File

@@ -77,6 +77,7 @@ function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
onlyRenderVisibleElements = false,
selectNodesOnDrag,
nodesDraggable,
autoPanOnNodeFocus,
nodesConnectable,
nodesFocusable,
nodeOrigin = defaultNodeOrigin,
@@ -261,6 +262,7 @@ function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
onClickConnectStart={onClickConnectStart}
onClickConnectEnd={onClickConnectEnd}
nodesDraggable={nodesDraggable}
autoPanOnNodeFocus={autoPanOnNodeFocus}
nodesConnectable={nodesConnectable}
nodesFocusable={nodesFocusable}
edgesFocusable={edgesFocusable}

View File

@@ -63,25 +63,7 @@ const useViewportHelper = (): ViewportHelperFunctions => {
return { x, y, zoom };
},
setCenter: async (x, y, options) => {
const { width, height, maxZoom, panZoom } = store.getState();
const nextZoom = typeof options?.zoom !== 'undefined' ? options.zoom : maxZoom;
const centerX = width / 2 - x * nextZoom;
const centerY = height / 2 - y * nextZoom;
if (!panZoom) {
return Promise.resolve(false);
}
await panZoom.setViewport(
{
x: centerX,
y: centerY,
zoom: nextZoom,
},
{ duration: options?.duration, ease: options?.ease, interpolate: options?.interpolate }
);
return Promise.resolve(true);
return store.getState().setCenter(x, y, options);
},
fitBounds: async (bounds, options) => {
const { width, height, minZoom, maxZoom, panZoom } = store.getState();

View File

@@ -360,6 +360,26 @@ const createStore = ({
return panBySystem({ delta, panZoom, transform, translateExtent, width, height });
},
setCenter: async (x, y, options) => {
const { width, height, maxZoom, panZoom } = get();
if (!panZoom) {
return Promise.resolve(false);
}
const nextZoom = typeof options?.zoom !== 'undefined' ? options.zoom : maxZoom;
await panZoom.setViewport(
{
x: width / 2 - x * nextZoom,
y: height / 2 - y * nextZoom,
zoom: nextZoom,
},
{ duration: options?.duration, ease: options?.ease, interpolate: options?.interpolate }
);
return Promise.resolve(true);
},
cancelConnection: () => {
set({
connection: { ...initialConnection },

View File

@@ -134,7 +134,9 @@ const getInitialState = ({
ariaLiveMessage: '',
autoPanOnConnect: true,
autoPanOnNodeDrag: true,
autoPanOnNodeFocus: true,
autoPanSpeed: 15,
connectionRadius: 20,
onError: devWarn,
isValidConnection: undefined,

View File

@@ -383,6 +383,11 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
* @default true
*/
nodesDraggable?: boolean;
/**
* When `true`, the viewport will pan when a node is focused.
* @default true
*/
autoPanOnNodeFocus?: boolean;
/**
* Controls whether all nodes should be connectable or not. Individual nodes can override this
* setting by setting their `connectable` prop.

View File

@@ -29,6 +29,7 @@ import {
type EdgeChange,
type ParentLookup,
type AriaLabelConfig,
SetCenter,
} from '@xyflow/system';
import type {
@@ -88,6 +89,7 @@ export type ReactFlowStore<NodeType extends Node = Node, EdgeType extends Edge =
snapGrid: SnapGrid;
nodesDraggable: boolean;
autoPanOnNodeFocus: boolean;
nodesConnectable: boolean;
nodesFocusable: boolean;
edgesFocusable: boolean;
@@ -171,6 +173,7 @@ export type ReactFlowActions<NodeType extends Node, EdgeType extends Edge> = {
triggerNodeChanges: (changes: NodeChange<NodeType>[]) => void;
triggerEdgeChanges: (changes: EdgeChange<EdgeType>[]) => void;
panBy: PanBy;
setCenter: SetCenter;
setPaneClickDistance: (distance: number) => void;
};

View File

@@ -5,7 +5,8 @@
errorMessages,
isInputDOMNode,
nodeHasDimensions,
Position
Position,
getNodesInside
} from '@xyflow/system';
import drag from '$lib/actions/drag';
@@ -197,6 +198,34 @@
store.moveSelectedNodes(arrowKeyDiffs[event.key], event.shiftKey ? 4 : 1);
}
}
const onFocus = () => {
if (
store.disableKeyboardA11y ||
!store.autoPanOnNodeFocus ||
!nodeRef?.matches(':focus-visible')
) {
return;
}
const { width, height, viewport } = store;
const withinViewport =
getNodesInside(
new Map([[id, node]]),
{ x: 0, y: 0, width, height },
[viewport.x, viewport.y, viewport.zoom],
true
).length > 0;
if (!withinViewport) {
store.setCenter(
node.position.x + (node.measured.width ?? 0) / 2,
node.position.y + (node.measured.height ?? 0) / 2,
{ zoom: viewport.zoom }
);
}
};
</script>
{#if !hidden}
@@ -252,6 +281,7 @@
? (event) => onnodecontextmenu({ node: userNode, event })
: undefined}
onkeydown={focusable ? onKeyDown : undefined}
onfocus={focusable ? onFocus : undefined}
tabIndex={focusable ? 0 : undefined}
role={node.ariaRole ?? (focusable ? 'group' : undefined)}
aria-roledescription={node.ariaRoleDescription || 'node'}

View File

@@ -84,6 +84,7 @@
elevateNodesOnSelect,
elevateEdgesOnSelect,
nodesDraggable,
autoPanOnNodeFocus,
nodesConnectable,
elementsSelectable,
nodesFocusable,
@@ -100,6 +101,16 @@
type OnlyDivAttributes<T> = {
[K in keyof T]: K extends keyof HTMLAttributes<HTMLDivElement> ? T[K] : never;
};
// Undo scroll events, preventing viewport from shifting when nodes outside of it are focused
function wrapperOnScroll(e: UIEvent & { currentTarget: EventTarget & HTMLDivElement }) {
e.currentTarget.scrollTo({ top: 0, left: 0, behavior: 'auto' });
// Forward the event to any existing onscroll handler if needed
if (rest.onscroll) {
rest.onscroll(e);
}
}
</script>
<div
@@ -111,6 +122,7 @@
class={['svelte-flow', 'svelte-flow__container', className, colorMode]}
data-testid="svelte-flow__wrapper"
role="application"
onscroll={wrapperOnScroll}
{...divAttributes satisfies OnlyDivAttributes<typeof divAttributes>}
>
{@render children?.()}

View File

@@ -232,6 +232,11 @@ export type SvelteFlowProps<
* @default true
*/
nodesDraggable?: boolean;
/**
* When `true`, the viewport will pan when a node is focused.
* @default true
*/
autoPanOnNodeFocus?: boolean;
/**
* Controls if all nodes should be connectable to each other
* @default true

View File

@@ -366,28 +366,8 @@ export function useSvelteFlow<NodeType extends Node = Node, EdgeType extends Edg
return Promise.resolve(true);
},
getViewport: () => $state.snapshot(store.viewport),
setCenter: async (x, y, options) => {
const nextZoom = typeof options?.zoom !== 'undefined' ? options.zoom : store.maxZoom;
const currentPanZoom = store.panZoom;
if (!currentPanZoom) {
return Promise.resolve(false);
}
await currentPanZoom.setViewport(
{
x: store.width / 2 - x * nextZoom,
y: store.height / 2 - y * nextZoom,
zoom: nextZoom
},
{ duration: options?.duration, ease: options?.ease, interpolate: options?.interpolate }
);
return Promise.resolve(true);
},
fitView: (options?: FitViewOptions) => {
return store.fitView(options);
},
setCenter: async (x, y, options) => store.setCenter(x, y, options),
fitView: (options?: FitViewOptions) => store.fitView(options),
fitBounds: async (bounds: Rect, options?: FitBoundsOptions) => {
if (!store.panZoom) {
return Promise.resolve(false);

View File

@@ -14,7 +14,8 @@ import {
type ConnectionState,
updateAbsolutePositions,
snapPosition,
calculateNodePosition
calculateNodePosition,
type SetCenterOptions
} from '@xyflow/system';
import type { EdgeTypes, NodeTypes, Node, Edge, FitViewOptions } from '$lib/types';
@@ -126,6 +127,26 @@ export function createStore<NodeType extends Node = Node, EdgeType extends Edge
return fitViewResolver.promise;
}
async function setCenter(x: number, y: number, options?: SetCenterOptions) {
const nextZoom = typeof options?.zoom !== 'undefined' ? options.zoom : store.maxZoom;
const currentPanZoom = store.panZoom;
if (!currentPanZoom) {
return Promise.resolve(false);
}
await currentPanZoom.setViewport(
{
x: store.width / 2 - x * nextZoom,
y: store.height / 2 - y * nextZoom,
zoom: nextZoom
},
{ duration: options?.duration, ease: options?.ease, interpolate: options?.interpolate }
);
return Promise.resolve(true);
}
function zoomBy(factor: number, options?: ViewportHelperFunctionOptions) {
const panZoom = store.panZoom;
if (!panZoom) {
@@ -372,6 +393,7 @@ export function createStore<NodeType extends Node = Node, EdgeType extends Edge
zoomIn,
zoomOut,
fitView,
setCenter,
setMinZoom,
setMaxZoom,
setTranslateExtent,

View File

@@ -266,6 +266,7 @@ export function getInitialStore<NodeType extends Node = Node, EdgeType extends E
nodeDragThreshold: number = $derived(signals.props.nodeDragThreshold ?? 1);
autoPanOnNodeDrag: boolean = $derived(signals.props.autoPanOnNodeDrag ?? true);
autoPanOnConnect: boolean = $derived(signals.props.autoPanOnConnect ?? true);
autoPanOnNodeFocus: boolean = $derived(signals.props.autoPanOnNodeFocus ?? true);
fitViewQueued: boolean = signals.props.fitView ?? false;
fitViewOptions: FitViewOptions | undefined = signals.props.fitViewOptions;

View File

@@ -6,7 +6,8 @@ import type {
UpdateNodePositions,
CoordinateExtent,
UpdateConnection,
Viewport
Viewport,
SetCenter
} from '@xyflow/system';
import type { getInitialStore } from './initial-store.svelte';
@@ -24,6 +25,7 @@ export type SvelteFlowStoreActions<NodeType extends Node = Node, EdgeType extend
setTranslateExtent: (extent: CoordinateExtent) => void;
setPaneClickDistance: (distance: number) => void;
fitView: (options?: FitViewOptions) => Promise<boolean>;
setCenter: SetCenter;
updateNodePositions: UpdateNodePositions;
updateNodeInternals: (updates: Map<string, InternalNodeUpdate>) => void;
unselectNodesAndEdges: (params?: { nodes?: NodeType[]; edges?: EdgeType[] }) => void;

View File

@@ -36,7 +36,6 @@ module.exports = {
projectService: true,
},
rules: {
'@typescript-eslint/no-deprecated': 'error',
'@typescript-eslint/no-unnecessary-type-assertion': 'error',
},
},