Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(editor): Add selection navigation using the keyboard on new canvas #11679

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions packages/editor-ui/src/components/canvas/Canvas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,6 @@ describe('Canvas', () => {
[
{
id: '1',
type: 'position',
dragging: true,
from: {
x: 100,
y: 100,
z: 0,
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this expected?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, position listener got changed.

position: { x: 120, y: 120 },
},
],
Expand Down
98 changes: 80 additions & 18 deletions packages/editor-ui/src/components/canvas/Canvas.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ import type {
Connection,
XYPosition,
ViewportTransform,
NodeChange,
NodePositionChange,
NodeDragEvent,
GraphNode,
} from '@vue-flow/core';
import { useVueFlow, VueFlow, PanelPosition, MarkerType } from '@vue-flow/core';
import { Background } from '@vue-flow/background';
Expand All @@ -29,9 +29,10 @@ import type { PinDataSource } from '@/composables/usePinnedData';
import { isPresent } from '@/utils/typesUtils';
import { GRID_SIZE } from '@/utils/nodeViewUtils';
import { CanvasKey } from '@/constants';
import { onKeyDown, onKeyUp, useDebounceFn } from '@vueuse/core';
import { onKeyDown, onKeyUp } from '@vueuse/core';
import CanvasArrowHeadMarker from './elements/edges/CanvasArrowHeadMarker.vue';
import CanvasBackgroundStripedPattern from './elements/CanvasBackgroundStripedPattern.vue';
import { useCanvasTraversal } from '@/composables/useCanvasTraversal';

const $style = useCssModule();

Expand Down Expand Up @@ -97,6 +98,7 @@ const props = withDefaults(

const { controlKeyCode } = useDeviceSupport();

const vueFlow = useVueFlow({ id: props.id, deleteKeyCode: null });
const {
getSelectedNodes: selectedNodes,
addSelectedNodes,
Expand All @@ -113,7 +115,14 @@ const {
onPaneReady,
findNode,
viewport,
} = useVueFlow({ id: props.id, deleteKeyCode: null });
} = vueFlow;
const {
getIncomingNodes,
getOutgoingNodes,
getSiblingNodes,
getDownstreamNodes,
getUpstreamNodes,
} = useCanvasTraversal(vueFlow);

const isPaneReady = ref(false);

Expand All @@ -131,7 +140,6 @@ const disableKeyBindings = computed(() => !props.keyBindings);
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#whitespace_keys
*/

const panningKeyCode = ref<string[]>([' ', controlKeyCode]);
const panningMouseButton = ref<number[]>([1]);
const selectionKeyCode = ref<true | null>(true);
Expand All @@ -144,6 +152,54 @@ onKeyUp(panningKeyCode.value, () => {
selectionKeyCode.value = true;
});

function selectLeftNode(id: string) {
const incomingNodes = getIncomingNodes(id);
const previousNode = incomingNodes[0];
if (previousNode) {
onSelectNodes({ ids: [previousNode.id] });
}
}

function selectRightNode(id: string) {
const outgoingNodes = getOutgoingNodes(id);
const nextNode = outgoingNodes[0];
if (nextNode) {
onSelectNodes({ ids: [nextNode.id] });
}
}

function selectLowerSiblingNode(id: string) {
const siblingNodes = getSiblingNodes(id);
const index = siblingNodes.findIndex((n) => n.id === id);
const nextNode = siblingNodes[index + 1] ?? siblingNodes[0];
if (nextNode) {
onSelectNodes({
ids: [nextNode.id],
});
}
}

function selectUpperSiblingNode(id: string) {
const siblingNodes = getSiblingNodes(id);
const index = siblingNodes.findIndex((n) => n.id === id);
const previousNode = siblingNodes[index - 1] ?? siblingNodes[siblingNodes.length - 1];
if (previousNode) {
onSelectNodes({
ids: [previousNode.id],
});
}
}

function selectDownstreamNodes(id: string) {
const downstreamNodes = getDownstreamNodes(id);
onSelectNodes({ ids: [...downstreamNodes.map((node) => node.id), id] });
}

function selectUpstreamNodes(id: string) {
const upstreamNodes = getUpstreamNodes(id);
onSelectNodes({ ids: [...upstreamNodes.map((node) => node.id), id] });
}

const keyMap = computed(() => ({
ctrl_c: emitWithSelectedNodes((ids) => emit('copy:nodes', ids)),
enter: emitWithLastSelectedNode((id) => onSetNodeActive(id)),
Expand All @@ -152,6 +208,12 @@ const keyMap = computed(() => ({
'-|_': async () => await onZoomOut(),
0: async () => await onResetZoom(),
1: async () => await onFitView(),
ArrowUp: emitWithLastSelectedNode(selectUpperSiblingNode),
ArrowDown: emitWithLastSelectedNode(selectLowerSiblingNode),
ArrowLeft: emitWithLastSelectedNode(selectLeftNode),
ArrowRight: emitWithLastSelectedNode(selectRightNode),
shift_ArrowLeft: emitWithLastSelectedNode(selectUpstreamNodes),
shift_ArrowRight: emitWithLastSelectedNode(selectDownstreamNodes),
// @TODO implement arrow key shortcuts to modify selection

...(props.readOnly
Expand All @@ -177,31 +239,30 @@ useKeybindings(keyMap, { disabled: disableKeyBindings });
* Nodes
*/

const lastSelectedNode = computed(() => selectedNodes.value[selectedNodes.value.length - 1]);
const hasSelection = computed(() => selectedNodes.value.length > 0);
const selectedNodeIds = computed(() => selectedNodes.value.map((node) => node.id));

const lastSelectedNode = ref<GraphNode>();
watch(selectedNodes, (nodes) => {
if (!lastSelectedNode.value || !nodes.find((node) => node.id === lastSelectedNode.value?.id)) {
lastSelectedNode.value = nodes[nodes.length - 1];
}
});

function onClickNodeAdd(id: string, handle: string) {
emit('click:node:add', id, handle);
}

// Debounced to prevent emitting too many events, necessary for undo/redo
const onUpdateNodesPosition = useDebounceFn((events: NodePositionChange[]) => {
function onUpdateNodesPosition(events: CanvasNodeMoveEvent[]) {
emit('update:nodes:position', events);
}, 200);
}

function onUpdateNodePosition(id: string, position: XYPosition) {
emit('update:node:position', id, position);
}

const isPositionChangeEvent = (event: NodeChange): event is NodePositionChange =>
event.type === 'position' && 'position' in event;

function onNodesChange(events: NodeChange[]) {
const positionChangeEndEvents = events.filter(isPositionChangeEvent);
if (positionChangeEndEvents.length > 0) {
void onUpdateNodesPosition(positionChangeEndEvents);
}
function onNodeDragStop(event: NodeDragEvent) {
onUpdateNodesPosition(event.nodes.map(({ id, position }) => ({ id, position })));
}

function onSetNodeActive(id: string) {
Expand Down Expand Up @@ -517,16 +578,17 @@ provide(CanvasKey, {
:class="classes"
:selection-key-code="selectionKeyCode"
:pan-activation-key-code="panningKeyCode"
:disable-keyboard-a11y="true"
data-test-id="canvas"
@connect-start="onConnectStart"
@connect="onConnect"
@connect-end="onConnectEnd"
@pane-click="onClickPane"
@contextmenu="onOpenContextMenu"
@viewport-change="onViewportChange"
@nodes-change="onNodesChange"
@move-start="onPaneMoveStart"
@move-end="onPaneMoveEnd"
@node-drag-stop="onNodeDragStop"
>
<template #node-canvas-node="canvasNodeProps">
<Node
Expand Down
180 changes: 180 additions & 0 deletions packages/editor-ui/src/composables/useCanvasTraversal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { useCanvasTraversal } from '@/composables/useCanvasTraversal';
import type { CanvasNode } from '@/types';
import type { VueFlowStore } from '@vue-flow/core';
import { mock } from 'vitest-mock-extended';

describe('useCanvasTraversal', () => {
const mockGetIncomers = vi.fn();
const mockGetOutgoers = vi.fn();

const vueFlow = mock<VueFlowStore>({
getIncomers: mockGetIncomers,
getOutgoers: mockGetOutgoers,
});

const {
sortNodesByVerticalPosition,
getIncomingNodes,
getOutgoingNodes,
getSiblingNodes,
getDownstreamNodes,
getUpstreamNodes,
} = useCanvasTraversal(vueFlow);

describe('sortNodesByVerticalPosition', () => {
it('should sort nodes by their vertical position', () => {
const nodes: CanvasNode[] = [
{ id: '1', position: { x: 0, y: 200 } },
{ id: '2', position: { x: 0, y: 100 } },
];
const result = sortNodesByVerticalPosition(nodes);
expect(result).toEqual([
{ id: '2', position: { x: 0, y: 100 } },
{ id: '1', position: { x: 0, y: 200 } },
]);
});
});

describe('getIncomingNodes', () => {
it('should return sorted incoming nodes by vertical position', () => {
const incomingNodes = [
{ id: '1', position: { x: 0, y: 200 } },
{ id: '2', position: { x: 0, y: 100 } },
];
mockGetIncomers.mockReturnValue([...incomingNodes]);
const result = getIncomingNodes('3');
expect(result).toEqual([incomingNodes[1], incomingNodes[0]]);
});
});

describe('getOutgoingNodes', () => {
it('should return sorted outgoing nodes by vertical position', () => {
const outgoingNodes = [
{ id: '1', position: { x: 0, y: 300 } },
{ id: '2', position: { x: 0, y: 150 } },
];
mockGetOutgoers.mockReturnValue([...outgoingNodes]);
const result = getOutgoingNodes('3');
expect(result).toEqual([outgoingNodes[1], outgoingNodes[0]]);
});
});

describe('getSiblingNodes', () => {
it('should return sorted sibling nodes by vertical position', () => {
const incomingNodes = [{ id: '1', position: { x: 0, y: 200 } }];
const incomingNodesOutgoingChildren = [{ id: '2', position: { x: 0, y: 400 } }];
const outgoingNodes = [{ id: '3', position: { x: 0, y: 300 } }];
const outgoingNodesIncomingChildren = [{ id: '4', position: { x: 0, y: 500 } }];

mockGetIncomers.mockReturnValueOnce(incomingNodes);
mockGetOutgoers.mockReturnValueOnce(incomingNodesOutgoingChildren);
mockGetOutgoers.mockReturnValueOnce(outgoingNodes);
mockGetIncomers.mockReturnValueOnce(outgoingNodesIncomingChildren);

const result = getSiblingNodes('5');
expect(result).toEqual([...incomingNodesOutgoingChildren, ...outgoingNodesIncomingChildren]);
});
});

describe('getDownstreamNodes', () => {
it('should return sorted downstream nodes by vertical position - one level', () => {
const outgoingNodes = [{ id: '2', position: { x: 0, y: 100 } }];

mockGetOutgoers.mockReturnValue(outgoingNodes);

const result = getDownstreamNodes('1');
expect(result).toEqual([{ id: '2', position: { x: 0, y: 100 } }]);
});

it('should return sorted downstream nodes by vertical position - multiple levels', () => {
const outgoingNodes1 = [{ id: '1', position: { x: 0, y: 100 } }];
const outgoingNodes2 = [{ id: '2', position: { x: 0, y: 200 } }];
const outgoingNodes3 = [{ id: '3', position: { x: 0, y: 300 } }];

mockGetOutgoers
.mockReturnValueOnce(outgoingNodes1)
.mockReturnValueOnce(outgoingNodes2)
.mockReturnValueOnce(outgoingNodes3);

const result = getDownstreamNodes('4');
expect(result).toEqual([...outgoingNodes1, ...outgoingNodes2, ...outgoingNodes3]);
});

it('should handle circular references in downstream nodes', () => {
const outgoingNodes1 = [{ id: '1', position: { x: 0, y: 100 } }];
const outgoingNodes2 = [
{ id: '1', position: { x: 0, y: 100 } },
{ id: '2', position: { x: 0, y: 300 } },
{ id: '3', position: { x: 0, y: 400 } },
];
const outgoingNodes3 = [
{ id: '1', position: { x: 0, y: 100 } },
{ id: '4', position: { x: 0, y: 600 } },
];

mockGetOutgoers
.mockReturnValueOnce(outgoingNodes1)
.mockReturnValueOnce(outgoingNodes2)
.mockReturnValueOnce(outgoingNodes3);

const result = getDownstreamNodes('5');
expect(result).toEqual([
outgoingNodes1[0],
outgoingNodes2[1],
outgoingNodes2[2],
outgoingNodes3[1],
]);
});
});

describe('getUpstreamNodes', () => {
it('should return sorted upstream nodes by vertical position - one level', () => {
const incomingNodes = [{ id: '2', position: { x: 0, y: 100 } }];

mockGetIncomers.mockReturnValue(incomingNodes);

const result = getUpstreamNodes('1');
expect(result).toEqual([{ id: '2', position: { x: 0, y: 100 } }]);
});

it('should return sorted upstream nodes by vertical position - multiple levels', () => {
const incomingNodes1 = [{ id: '1', position: { x: 0, y: 100 } }];
const incomingNodes2 = [{ id: '2', position: { x: 0, y: 200 } }];
const incomingNodes3 = [{ id: '3', position: { x: 0, y: 300 } }];

mockGetIncomers
.mockReturnValueOnce(incomingNodes1)
.mockReturnValueOnce(incomingNodes2)
.mockReturnValueOnce(incomingNodes3);

const result = getUpstreamNodes('4');
expect(result).toEqual([...incomingNodes1, ...incomingNodes2, ...incomingNodes3]);
});

it('should handle circular references in upstream nodes', () => {
const incomingNodes1 = [{ id: '1', position: { x: 0, y: 100 } }];
const incomingNodes2 = [
{ id: '1', position: { x: 0, y: 100 } },
{ id: '2', position: { x: 0, y: 300 } },
{ id: '3', position: { x: 0, y: 400 } },
];
const incomingNodes3 = [
{ id: '1', position: { x: 0, y: 100 } },
{ id: '4', position: { x: 0, y: 600 } },
];

mockGetIncomers
.mockReturnValueOnce(incomingNodes1)
.mockReturnValueOnce(incomingNodes2)
.mockReturnValueOnce(incomingNodes3);

const result = getUpstreamNodes('5');
expect(result).toEqual([
incomingNodes1[0],
incomingNodes2[1],
incomingNodes2[2],
incomingNodes3[1],
]);
});
});
});
Loading
Loading