useFocusNode.tsx 1.9 KB

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