useOffscreenTargets.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { useEffect, useState, type RefObject } from "react";
  2. import type { AgentPointer } from "#ui/shell/state.ts";
  3. export interface OffscreenTargets {
  4. indexes: number[];
  5. down: boolean;
  6. }
  7. /**
  8. * Agent 标出的目标中不在可视区域内的那些,用于「还有 N 处」提示。
  9. * 从 main.tsx 的 Shell 拆出以控制单文件规模,行为不变;setOffscreen 交还 Shell 供重置文档状态时清空。
  10. */
  11. export function useOffscreenTargets(
  12. canvasRef: RefObject<HTMLDivElement | null>,
  13. agent: AgentPointer | null,
  14. ) {
  15. const [offscreen, setOffscreen] = useState<OffscreenTargets | null>(null);
  16. useEffect(() => {
  17. const canvas = canvasRef.current;
  18. if (!canvas || !agent || agent.targets.length < 2) {
  19. setOffscreen(null);
  20. return;
  21. }
  22. let frame = 0;
  23. const check = () => {
  24. frame = 0;
  25. const bounds = canvas.getBoundingClientRect();
  26. const below: number[] = [];
  27. const above: number[] = [];
  28. agent.targets.forEach((target, i) => {
  29. if (i === agent.index) return;
  30. const box = target.locate();
  31. if (!box) return;
  32. if (box.top > bounds.bottom - 8) below.push(i);
  33. else if (box.bottom < bounds.top + 8) above.push(i);
  34. });
  35. const next = below.length
  36. ? { indexes: below, down: true }
  37. : above.length
  38. ? { indexes: above, down: false }
  39. : null;
  40. setOffscreen((current) =>
  41. JSON.stringify(current) === JSON.stringify(next) ? current : next,
  42. );
  43. };
  44. const schedule = () => {
  45. if (!frame) frame = requestAnimationFrame(check);
  46. };
  47. check();
  48. canvas.addEventListener("scroll", schedule, { capture: true, passive: true });
  49. const settle = setInterval(schedule, 500);
  50. return () => {
  51. canvas.removeEventListener("scroll", schedule, { capture: true });
  52. clearInterval(settle);
  53. if (frame) cancelAnimationFrame(frame);
  54. };
  55. }, [agent, canvasRef]);
  56. return [offscreen, setOffscreen] as const;
  57. }