wallnote/src/pages/wall/hooks/tab-node.ts
2025-03-12 00:50:44 +08:00

75 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { useReactFlow } from '@xyflow/react';
import { useEffect } from 'react';
import { useWallStore } from '../store/wall';
import { useShallow } from 'zustand/react/shallow';
export const useTabNode = () => {
const reactFlowInstance = useReactFlow();
useEffect(() => {
const listener = (event: any) => {
const selected = reactFlowInstance.getNodes().find((node) => node.selected);
if (!selected) return;
if (event.key === 'Tab') {
const nodes = reactFlowInstance.getNodes();
const selectedNode = nodes.find((node) => node.selected);
if (!selectedNode) return;
// 获取选中的节点
const { x, y } = selectedNode?.position || { x: 0, y: 0 };
// 根据nodes的position的x和y进行排序x小的在前x相等时y小的在前
const newNodes = nodes.sort((a, b) => {
const { x: ax, y: ay } = a.position || { x: 0, y: 0 };
const { x: bx, y: by } = b.position || { x: 0, y: 0 };
if (ax < bx) return -1;
if (ax > bx) return 1;
return ay - by;
});
const nextNode = newNodes.find((node) => {
if (node.id === selectedNode?.id) return false;
const { x: nx, y: ny } = node.position;
if (nx > x) {
return true;
} else if (nx === x) {
if (ny > y) {
return true;
}
}
return false;
});
if (nextNode) {
const newNodes = nodes.map((node) => {
if (node.id === nextNode.id) {
return { ...node, selected: true };
}
return { ...node, selected: false };
});
reactFlowInstance.setNodes(newNodes);
} else {
const newNodes = nodes.map((node) => {
if (node.id === nodes[0].id) {
return { ...node, selected: true };
}
return { ...node, selected: false };
});
reactFlowInstance.setNodes(newNodes);
}
event.preventDefault();
event.stopPropagation();
}
};
const rightClickListener = (event: any) => {
const selected = reactFlowInstance.getNodes().find((node) => node.selected);
if (!selected) return;
if (event.button === 2) {
event.preventDefault();
event.stopPropagation();
}
};
window.addEventListener('keydown', listener);
window.addEventListener('contextmenu', rightClickListener);
return () => {
window.removeEventListener('keydown', listener);
window.removeEventListener('contextmenu', rightClickListener);
};
}, [reactFlowInstance]);
};