feat: create enablePanOnFocus prop, update onFocus func

This commit is contained in:
Abbey Yacoe
2025-06-05 12:22:06 +02:00
parent 343ed4364b
commit 6693c7300e
14 changed files with 125 additions and 59 deletions
+30 -16
View File
@@ -1,4 +1,4 @@
import { MouseEvent } from 'react'; import { MouseEvent, useState } from 'react';
import { import {
ReactFlow, ReactFlow,
MiniMap, MiniMap,
@@ -10,13 +10,9 @@ import {
Edge, Edge,
OnNodeDrag, OnNodeDrag,
AriaLabelConfig, AriaLabelConfig,
Panel,
} from '@xyflow/react'; } 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[] = [ const initialNodes: Node[] = [
{ {
id: '1', id: '1',
@@ -41,9 +37,16 @@ const initialNodes: Node[] = [
id: '4', id: '4',
data: { label: 'Node 4' }, data: { label: 'Node 4' },
position: { x: 300, y: 100 }, position: { x: 300, y: 100 },
className: 'light', },
ariaRoleDescription: 'custom node role', {
ariaRole: 'button', id: '5',
data: { label: 'Node 5' },
position: { x: 400, y: 200 },
},
{
id: '6',
data: { label: 'Node 6' },
position: { x: -1000, y: 200 },
}, },
]; ];
@@ -51,6 +54,8 @@ const initialEdges: Edge[] = [
{ id: 'e1-2', source: '1', target: '2', animated: true }, { id: 'e1-2', source: '1', target: '2', animated: true },
{ id: 'e1-3', source: '1', target: '3' }, { id: 'e1-3', source: '1', target: '3' },
{ id: 'e1-4', source: '1', target: '4' }, { 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> = { const ariaLabelConfig: Partial<AriaLabelConfig> = {
@@ -68,19 +73,14 @@ const ariaLabelConfig: Partial<AriaLabelConfig> = {
}; };
const A11y = () => { const A11y = () => {
const [isFocusPannable, setEnablePanOnFocus] = useState(true);
return ( return (
<ReactFlow <ReactFlow
defaultNodes={initialNodes} defaultNodes={initialNodes}
defaultEdges={initialEdges} defaultEdges={initialEdges}
onNodesChange={console.log}
onNodeClick={onNodeClick}
onNodeDragStop={onNodeDragStop}
onNodeDragStart={onNodeDragStart}
onNodeDrag={onNodeDrag}
className="react-flow-basic-example"
minZoom={2} minZoom={2}
maxZoom={4} maxZoom={4}
// fitView enablePanOnFocus={isFocusPannable}
selectNodesOnDrag={false} selectNodesOnDrag={false}
elevateEdgesOnSelect elevateEdgesOnSelect
elevateNodesOnSelect={false} elevateNodesOnSelect={false}
@@ -90,6 +90,20 @@ const A11y = () => {
<Background variant={BackgroundVariant.Dots} /> <Background variant={BackgroundVariant.Dots} />
<MiniMap /> <MiniMap />
<Controls /> <Controls />
<Panel position="top-right">
<div>
<label htmlFor="focusPannable">
<input
id="focusPannable"
type="checkbox"
checked={isFocusPannable}
onChange={(event) => setEnablePanOnFocus(event.target.checked)}
className="xy-theme__checkbox"
/>
enablePanOnFocus
</label>
</div>
</Panel>
</ReactFlow> </ReactFlow>
); );
}; };
@@ -1,5 +1,5 @@
<script lang="ts"> <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'; import '@xyflow/svelte/dist/style.css';
@@ -10,7 +10,7 @@
data: { label: 'A' } data: { label: 'A' }
}, },
{ id: 'B', position: { x: -100, y: 150 }, data: { label: 'B' } }, { 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' } } { id: 'D', position: { x: 0, y: 260 }, data: { label: 'D' } }
]); ]);
@@ -19,16 +19,12 @@
{ id: 'A-C', source: 'A', target: 'C' }, { id: 'A-C', source: 'A', target: 'C' },
{ id: 'A-D', source: 'A', target: 'D' } { id: 'A-D', source: 'A', target: 'D' }
]); ]);
</script> let isFocusPannable = $state(true);
const ariaLabelConfig = $state(
<SvelteFlow {
bind:nodes
bind:edges
fitView
ariaLabelConfig={{
'node.a11yDescription.default': 'Svelte Custom Node Desc.', 'node.a11yDescription.default': 'Svelte Custom Node Desc.',
'node.a11yDescription.keyboardDisabled': 'Svelte Custom Keyboard Desc.', 'node.a11yDescription.keyboardDisabled': 'Svelte Custom Keyboard Desc.',
'node.a11yDescription.ariaLiveMessage': ({ direction, x, y }) => 'node.a11yDescription.ariaLiveMessage': ({ direction, x, y }: { direction: string; x: number; y: number }) =>
`Custom Moved selected node ${direction}. New position, x: ${x}, y: ${y}`, `Custom Moved selected node ${direction}. New position, x: ${x}, y: ${y}`,
'edge.a11yDescription.default': 'Svelte Custom Edge Desc.', 'edge.a11yDescription.default': 'Svelte Custom Edge Desc.',
'controls.ariaLabel': 'Svelte Custom Control Aria Label', 'controls.ariaLabel': 'Svelte Custom Control Aria Label',
@@ -37,9 +33,30 @@
// 'controls.fitView.ariaLabel': 'Svelte Custom Fit View', // 'controls.fitView.ariaLabel': 'Svelte Custom Fit View',
'controls.interactive.ariaLabel': 'Svelte Custom Toggle Interactivity', 'controls.interactive.ariaLabel': 'Svelte Custom Toggle Interactivity',
'minimap.ariaLabel': 'Svelte Custom Minimap' 'minimap.ariaLabel': 'Svelte Custom Minimap'
}} }
);
</script>
<SvelteFlow
bind:nodes
bind:edges
enablePanOnFocus={isFocusPannable}
ariaLabelConfig={ariaLabelConfig}
> >
<Controls /> <Controls />
<Background /> <Background />
<MiniMap /> <MiniMap />
<Panel class="panel top-right">
<div>
<label for="focusPannable">
Enable Pan on Focus
<input
id="focusPannable"
type="checkbox"
bind:checked={isFocusPannable}
class="svelte-flow__zoomonscroll"
/>
</label>
</div>
</Panel>
</SvelteFlow> </SvelteFlow>
@@ -7,6 +7,7 @@ import {
getNodeDimensions, getNodeDimensions,
isInputDOMNode, isInputDOMNode,
nodeHasDimensions, nodeHasDimensions,
getNodesInside,
} from '@xyflow/system'; } from '@xyflow/system';
import { useStore, useStoreApi } from '../../hooks/useStore'; import { useStore, useStoreApi } from '../../hooks/useStore';
@@ -29,6 +30,7 @@ export function NodeWrapper<NodeType extends Node>({
onContextMenu, onContextMenu,
onDoubleClick, onDoubleClick,
nodesDraggable, nodesDraggable,
enablePanOnFocus,
elementsSelectable, elementsSelectable,
nodesConnectable, nodesConnectable,
nodesFocusable, nodesFocusable,
@@ -163,28 +165,26 @@ export function NodeWrapper<NodeType extends Node>({
}; };
const onFocus = () => { const onFocus = () => {
if (disableKeyboardA11y) { if (disableKeyboardA11y || !enablePanOnFocus) {
return; return;
} }
// Return early if focus is not from keyboard navigation (i.e., was clicked)
if (!nodeRef.current?.matches(':focus-visible')) { if (!nodeRef.current?.matches(':focus-visible')) {
return; return;
} }
const { x, y, zoom } = getViewport();
const isNodeVisible = const { transform, width, height } = store.getState();
node.position.x >= x && const visibleNodes = getNodesInside(new Map([[id, node]]), { x: 0, y: 0, width, height }, transform, true);
node.position.x <= x + window.innerWidth &&
node.position.y >= y && const isNodeVisible = visibleNodes.length > 0;
node.position.y <= y + window.innerHeight;
if (!isNodeVisible) { if (!isNodeVisible) {
const zoomLevel = transform[2];
fitView({ fitView({
nodes: [{ id }], nodes: [{ id }],
duration: 100, duration: 100,
minZoom: zoom, minZoom: zoomLevel,
maxZoom: zoom, maxZoom: zoomLevel,
}); });
} }
}; };
@@ -23,6 +23,7 @@ const reactFlowFieldsToTrack = [
'onClickConnectStart', 'onClickConnectStart',
'onClickConnectEnd', 'onClickConnectEnd',
'nodesDraggable', 'nodesDraggable',
'enablePanOnFocus',
'nodesConnectable', 'nodesConnectable',
'nodesFocusable', 'nodesFocusable',
'edgesFocusable', 'edgesFocusable',
@@ -29,6 +29,7 @@ export type NodeRendererProps<NodeType extends Node> = Pick<
const selector = (s: ReactFlowState) => ({ const selector = (s: ReactFlowState) => ({
nodesDraggable: s.nodesDraggable, nodesDraggable: s.nodesDraggable,
enablePanOnFocus: s.enablePanOnFocus,
nodesConnectable: s.nodesConnectable, nodesConnectable: s.nodesConnectable,
nodesFocusable: s.nodesFocusable, nodesFocusable: s.nodesFocusable,
elementsSelectable: s.elementsSelectable, elementsSelectable: s.elementsSelectable,
@@ -36,7 +37,10 @@ const selector = (s: ReactFlowState) => ({
}); });
function NodeRendererComponent<NodeType extends Node>(props: NodeRendererProps<NodeType>) { function NodeRendererComponent<NodeType extends Node>(props: NodeRendererProps<NodeType>) {
const { nodesDraggable, nodesConnectable, nodesFocusable, elementsSelectable, onError } = useStore(selector, shallow); const { nodesDraggable, nodesConnectable, nodesFocusable, elementsSelectable, enablePanOnFocus, onError } = useStore(
selector,
shallow
);
const nodeIds = useVisibleNodeIds(props.onlyRenderVisibleElements); const nodeIds = useVisibleNodeIds(props.onlyRenderVisibleElements);
const resizeObserver = useResizeObserver(); const resizeObserver = useResizeObserver();
@@ -86,6 +90,7 @@ function NodeRendererComponent<NodeType extends Node>(props: NodeRendererProps<N
disableKeyboardA11y={props.disableKeyboardA11y} disableKeyboardA11y={props.disableKeyboardA11y}
resizeObserver={resizeObserver} resizeObserver={resizeObserver}
nodesDraggable={nodesDraggable} nodesDraggable={nodesDraggable}
enablePanOnFocus={enablePanOnFocus}
nodesConnectable={nodesConnectable} nodesConnectable={nodesConnectable}
nodesFocusable={nodesFocusable} nodesFocusable={nodesFocusable}
elementsSelectable={elementsSelectable} elementsSelectable={elementsSelectable}
@@ -77,6 +77,7 @@ function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
onlyRenderVisibleElements = false, onlyRenderVisibleElements = false,
selectNodesOnDrag, selectNodesOnDrag,
nodesDraggable, nodesDraggable,
enablePanOnFocus,
nodesConnectable, nodesConnectable,
nodesFocusable, nodesFocusable,
nodeOrigin = defaultNodeOrigin, nodeOrigin = defaultNodeOrigin,
@@ -261,6 +262,7 @@ function ReactFlow<NodeType extends Node = Node, EdgeType extends Edge = Edge>(
onClickConnectStart={onClickConnectStart} onClickConnectStart={onClickConnectStart}
onClickConnectEnd={onClickConnectEnd} onClickConnectEnd={onClickConnectEnd}
nodesDraggable={nodesDraggable} nodesDraggable={nodesDraggable}
enablePanOnFocus={enablePanOnFocus}
nodesConnectable={nodesConnectable} nodesConnectable={nodesConnectable}
nodesFocusable={nodesFocusable} nodesFocusable={nodesFocusable}
edgesFocusable={edgesFocusable} edgesFocusable={edgesFocusable}
+1
View File
@@ -112,6 +112,7 @@ const getInitialState = ({
snapToGrid: false, snapToGrid: false,
nodesDraggable: true, nodesDraggable: true,
enablePanOnFocus: false,
nodesConnectable: true, nodesConnectable: true,
nodesFocusable: true, nodesFocusable: true,
edgesFocusable: true, edgesFocusable: true,
@@ -383,6 +383,11 @@ export interface ReactFlowProps<NodeType extends Node = Node, EdgeType extends E
* @default true * @default true
*/ */
nodesDraggable?: boolean; nodesDraggable?: boolean;
/**
* When `true`, the viewport will pan when a node is focused.
* @default false
*/
enablePanOnFocus?: boolean;
/** /**
* Controls whether all nodes should be connectable or not. Individual nodes can override this * Controls whether all nodes should be connectable or not. Individual nodes can override this
* setting by setting their `connectable` prop. * setting by setting their `connectable` prop.
+1
View File
@@ -48,6 +48,7 @@ export type NodeWrapperProps<NodeType extends Node> = {
nodesConnectable: boolean; nodesConnectable: boolean;
elementsSelectable: boolean; elementsSelectable: boolean;
nodesDraggable: boolean; nodesDraggable: boolean;
enablePanOnFocus: boolean;
nodesFocusable: boolean; nodesFocusable: boolean;
onClick?: NodeMouseHandler<NodeType>; onClick?: NodeMouseHandler<NodeType>;
onDoubleClick?: NodeMouseHandler<NodeType>; onDoubleClick?: NodeMouseHandler<NodeType>;
+1
View File
@@ -88,6 +88,7 @@ export type ReactFlowStore<NodeType extends Node = Node, EdgeType extends Edge =
snapGrid: SnapGrid; snapGrid: SnapGrid;
nodesDraggable: boolean; nodesDraggable: boolean;
enablePanOnFocus: boolean;
nodesConnectable: boolean; nodesConnectable: boolean;
nodesFocusable: boolean; nodesFocusable: boolean;
edgesFocusable: boolean; edgesFocusable: boolean;
@@ -5,7 +5,8 @@
errorMessages, errorMessages,
isInputDOMNode, isInputDOMNode,
nodeHasDimensions, nodeHasDimensions,
Position Position,
getNodesInside,
} from '@xyflow/system'; } from '@xyflow/system';
import drag from '$lib/actions/drag'; import drag from '$lib/actions/drag';
@@ -198,26 +199,37 @@
} }
} }
function onFocus() { const onFocus = () => {
if (store.disableKeyboardA11y) { console.log('before', store.enablePanOnFocus);
if (store.disableKeyboardA11y || !store.enablePanOnFocus) {
console.log("should return early", store.enablePanOnFocus);
return; return;
} }
const zoom = store.panZoom?.getViewport().zoom ?? 1; if (!nodeRef?.matches(':focus-visible')) {
return;
}
const width = store.width;
const height = store.height;
const viewport: [number, number, number] = [store.viewport.x, store.viewport.y, store.viewport.zoom];
const zoom = store.viewport.zoom;
// Get node dimensions const visibleNodes = getNodesInside(new Map([[id, node]]), { x: 0, y: 0, width, height }, viewport, true);
const nodeWidth = nodeRef?.offsetWidth || 0;
const nodeHeight = nodeRef?.offsetHeight || 0;
store.panZoom?.setViewport( const isNodeVisible = visibleNodes.length > 0;
{
x: -(positionX + nodeWidth / 2) * zoom + window.innerWidth / 2, if (!isNodeVisible) {
y: -(positionY + nodeHeight / 2) * zoom + window.innerHeight / 2, console.log('About to call fitView - this should NOT happen when enablePanOnFocus is false');
zoom: zoom,
}, console.log('after', store.enablePanOnFocus);
{ duration: 100 } store.fitView({
); nodes: [{ id }],
} duration: 100,
minZoom: zoom,
maxZoom: zoom,
});
}
};
</script> </script>
{#if !hidden} {#if !hidden}
@@ -84,6 +84,7 @@
elevateNodesOnSelect, elevateNodesOnSelect,
elevateEdgesOnSelect, elevateEdgesOnSelect,
nodesDraggable, nodesDraggable,
enablePanOnFocus,
nodesConnectable, nodesConnectable,
elementsSelectable, elementsSelectable,
nodesFocusable, nodesFocusable,
@@ -232,6 +232,11 @@ export type SvelteFlowProps<
* @default true * @default true
*/ */
nodesDraggable?: boolean; nodesDraggable?: boolean;
/**
* When `true`, the viewport will pan when a node is focused.
* @default false
*/
enablePanOnFocus?: boolean;
/** /**
* Controls if all nodes should be connectable to each other * Controls if all nodes should be connectable to each other
* @default true * @default true
@@ -247,6 +247,7 @@ export function getInitialStore<NodeType extends Node = Node, EdgeType extends E
}); });
nodesDraggable: boolean = $derived(signals.props.nodesDraggable ?? true); nodesDraggable: boolean = $derived(signals.props.nodesDraggable ?? true);
enablePanOnFocus: boolean = $derived(signals.props.enablePanOnFocus ?? true);
nodesConnectable: boolean = $derived(signals.props.nodesConnectable ?? true); nodesConnectable: boolean = $derived(signals.props.nodesConnectable ?? true);
elementsSelectable: boolean = $derived(signals.props.elementsSelectable ?? true); elementsSelectable: boolean = $derived(signals.props.elementsSelectable ?? true);
nodesFocusable: boolean = $derived(signals.props.nodesFocusable ?? true); nodesFocusable: boolean = $derived(signals.props.nodesFocusable ?? true);