state.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { useEffect, useState } from "react";
  2. import {
  3. type DocKind,
  4. type DocumentInfo,
  5. type DocxBlockKey,
  6. type Selection,
  7. } from "#office/contract.ts";
  8. import { cut } from "#office/domain/text.ts";
  9. import { getHost } from "#ui/host.ts";
  10. import type { Strings } from "#ui/i18n.ts";
  11. import { CallError } from "#ui/rpc.ts";
  12. import type { RevealedTarget, SelectionDetail } from "#ui/viewers/types.ts";
  13. // 面板外壳(main.tsx)共用的状态类型与持久化、错误描述等辅助函数,从 main.tsx 拆出以控制单文件规模。
  14. export interface LoadedDoc {
  15. info: DocumentInfo;
  16. bytes: ArrayBuffer;
  17. blocks?: DocxBlockKey[];
  18. /** Increments on every (re)load so the viewer remounts. */
  19. key: number;
  20. }
  21. export interface Reference {
  22. anchor: string;
  23. text: string;
  24. }
  25. export interface Picked {
  26. selection: Selection;
  27. detail: SelectionDetail;
  28. }
  29. export interface AgentPointer {
  30. note: string | null;
  31. targets: RevealedTarget[];
  32. index: number;
  33. /** The callout (note and stepping); the marks stay after it is dismissed. */
  34. visible: boolean;
  35. }
  36. export interface Failure {
  37. path: string | null;
  38. title: string;
  39. detail: string;
  40. }
  41. export const clip = (text: string, length: number) =>
  42. text.length > length ? `${cut(text, 0, length - 1)}…` : text;
  43. export function readRecent(): { path: string; kind: DocKind }[] {
  44. return getHost().readWindow().recent ?? [];
  45. }
  46. export function writeRecent(items: { path: string; kind: DocKind }[]) {
  47. getHost().saveWindow({ recent: items });
  48. }
  49. export function describeFailure(t: Strings, error: unknown, path: string | null): Failure {
  50. const code =
  51. error instanceof CallError
  52. ? error.code
  53. : (error as Error)?.name === "PasswordException"
  54. ? "password"
  55. : undefined;
  56. const [title, detail] = (code && t.errors[code]) || t.errors.generic;
  57. const message = error instanceof Error ? error.message : String(error);
  58. return { path, title, detail: detail || message };
  59. }
  60. export function useHostContext() {
  61. const [, setTick] = useState(0);
  62. useEffect(() => {
  63. const update = () => setTick((tick) => tick + 1);
  64. window.addEventListener("office:hostchange", update);
  65. return () => window.removeEventListener("office:hostchange", update);
  66. }, []);
  67. return getHost().context;
  68. }