useFocusNode.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import React from "react";
  2. import useGraph from "src/store/useGraph";
  3. import { searchQuery, cleanupHighlight, highlightMatchedNodes } from "src/utils/search";
  4. export const useFocusNode = () => {
  5. const zoomPanPinch = useGraph(state => state.zoomPanPinch);
  6. const [selectedNode, setSelectedNode] = React.useState(0);
  7. const [content, setContent] = React.useState({
  8. value: "",
  9. debounced: "",
  10. });
  11. const skip = () => setSelectedNode(current => current + 1);
  12. React.useEffect(() => {
  13. const debouncer = setTimeout(() => {
  14. setContent(val => ({ ...val, debounced: content.value }));
  15. }, 800);
  16. return () => clearTimeout(debouncer);
  17. }, [content.value]);
  18. React.useEffect(() => {
  19. if (!zoomPanPinch) return;
  20. const ref = zoomPanPinch.instance.wrapperComponent;
  21. const matchedNodes: NodeListOf<Element> = searchQuery(
  22. `span[data-key*='${content.debounced}' i]`
  23. );
  24. const matchedNode: Element | null = matchedNodes[selectedNode] || null;
  25. cleanupHighlight();
  26. if (ref && matchedNode && matchedNode.parentElement) {
  27. const newScale = 0.8;
  28. const x = Number(matchedNode.getAttribute("data-x"));
  29. const y = Number(matchedNode.getAttribute("data-y"));
  30. const newPositionX =
  31. (ref.offsetLeft - x) * newScale +
  32. ref.clientWidth / 10 -
  33. matchedNode.getBoundingClientRect().width / 10;
  34. const newPositionY =
  35. (ref.offsetLeft - y) * newScale +
  36. ref.clientHeight / 10 -
  37. matchedNode.getBoundingClientRect().height / 10;
  38. highlightMatchedNodes(matchedNodes, selectedNode);
  39. zoomPanPinch?.setTransform(newPositionX, newPositionY, newScale);
  40. } else {
  41. setSelectedNode(0);
  42. }
  43. return () => {
  44. if (!content.value) setSelectedNode(0);
  45. };
  46. }, [content.debounced, content, selectedNode, zoomPanPinch]);
  47. return [content, setContent, skip] as const;
  48. };