useCaptureView.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { useEffect, type RefObject } from "react";
  2. import { formatAnchor, splitAnchor } from "#office/domain/anchor.ts";
  3. import { PROFILE } from "#office/profile.ts";
  4. import { getHost } from "#ui/host.ts";
  5. import type { LoadedDoc } from "#ui/shell/state.ts";
  6. import type { ViewerHandle } from "#ui/viewers/types.ts";
  7. /**
  8. * 页面工具 capture_view:Agent 截取面板当前文档的某处画面。
  9. * 从 main.tsx 的 Shell 拆出以控制单文件规模,行为不变;只在挂载时注册一次,通过 ref 读取最新文档与查看器。
  10. */
  11. export function useCaptureView(
  12. docRef: RefObject<LoadedDoc | null>,
  13. viewer: RefObject<ViewerHandle | null>,
  14. ) {
  15. useEffect(() => {
  16. const host = getHost();
  17. host.handleTool("capture_view", async (args) => {
  18. const current = docRef.current;
  19. if (!current || !viewer.current)
  20. throw new Error(
  21. `No document is open in the ${PROFILE.title.en} panel. Call open_document first.`,
  22. );
  23. let at: string | null = null;
  24. if (typeof args.anchor === "string" && args.anchor.trim()) {
  25. const split = splitAnchor(args.anchor);
  26. if (split.path.replace(/^\.\//, "") !== current.info.path)
  27. throw new Error(
  28. `The panel shows ${current.info.path}, not ${split.path}. Call open_document with that path first.`,
  29. );
  30. at = split.at;
  31. }
  32. const maxWidth =
  33. typeof args.maxWidth === "number" ? Math.min(2000, Math.max(320, args.maxWidth)) : 1600;
  34. const shot = await viewer.current.capture(at, maxWidth);
  35. return {
  36. content: [
  37. { type: "image", data: shot.data, mimeType: "image/png" },
  38. {
  39. type: "text",
  40. text: `Captured ${formatAnchor(current.info.path, shot.at)} (${shot.width}×${shot.height} px).`,
  41. },
  42. ],
  43. };
  44. });
  45. }, [docRef, viewer]);
  46. }