useFind.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
  2. import type { ViewerHandle } from "#ui/viewers/types.ts";
  3. export interface FindState {
  4. open: boolean;
  5. query: string;
  6. total: number | null;
  7. index: number;
  8. }
  9. export const CLOSED_FIND: FindState = { open: false, query: "", total: null, index: -1 };
  10. /**
  11. * 面板内查找:输入即搜,Enter / ⇧Enter 在结果间跳转。
  12. * 从 main.tsx 的 Shell 拆出以控制单文件规模,行为与拆分前一致;setFind 仍交给 Shell,
  13. * 供载入新文档和 Agent 定位时直接关闭查找。
  14. */
  15. export function useFind({
  16. viewer,
  17. docRef,
  18. ready,
  19. onOpen,
  20. }: {
  21. viewer: RefObject<ViewerHandle | null>;
  22. docRef: RefObject<unknown>;
  23. ready: boolean;
  24. /** 打开查找前清理与查找互斥的界面状态(选区、Agent 标记、菜单)。 */
  25. onOpen(): void;
  26. }) {
  27. const [find, setFind] = useState<FindState>(CLOSED_FIND);
  28. const findSeq = useRef(0);
  29. const openFind = useCallback(() => {
  30. if (!docRef.current) return;
  31. onOpen();
  32. setFind((state) => ({ ...state, open: true }));
  33. // Re-focus when already open.
  34. requestAnimationFrame(() => {
  35. const input = document.querySelector<HTMLInputElement>(".findbar .find-input");
  36. input?.focus();
  37. input?.select();
  38. });
  39. }, [docRef, onOpen]);
  40. const closeFind = useCallback(() => {
  41. findSeq.current++;
  42. viewer.current?.clearFind();
  43. setFind(CLOSED_FIND);
  44. }, [viewer]);
  45. const queryFind = useCallback((query: string) => {
  46. setFind((state) => ({ ...state, query, total: query.trim() ? state.total : null }));
  47. }, []);
  48. useEffect(() => {
  49. if (!find.open || !ready) return;
  50. const mine = ++findSeq.current;
  51. const timer = setTimeout(async () => {
  52. const handle = viewer.current;
  53. if (!handle) return;
  54. const total = await handle.find(find.query).catch(() => 0);
  55. if (mine !== findSeq.current) return;
  56. setFind((state) => ({ ...state, total, index: total ? 0 : -1 }));
  57. if (total) handle.findGo(0);
  58. }, 200);
  59. return () => clearTimeout(timer);
  60. }, [find.open, find.query, ready, viewer]);
  61. const stepFind = useCallback(
  62. (direction: 1 | -1) => {
  63. if (!find.total) return;
  64. const index = (find.index + direction + find.total) % find.total;
  65. setFind((state) => ({ ...state, index }));
  66. viewer.current?.findGo(index);
  67. },
  68. [find.total, find.index, viewer],
  69. );
  70. return { find, setFind, openFind, closeFind, queryFind, stepFind };
  71. }