main.tsx 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. import { StrictMode, useCallback, useEffect, useMemo, useRef, useState } from "react";
  2. import { createRoot } from "react-dom/client";
  3. import { applyHostStyleVariables } from "@modelcontextprotocol/ext-apps";
  4. import {
  5. kindOf,
  6. type DocKind,
  7. type DocumentInfo,
  8. type DocxBlockKey,
  9. type FileHandle,
  10. type Selection,
  11. type ShowTarget,
  12. type ViewerSnapshot,
  13. } from "#office/contract.ts";
  14. import { formatAnchor } from "#office/domain/anchor.ts";
  15. import { PROFILE } from "#office/profile.ts";
  16. import { wellFormed, wellFormedDeep } from "#office/domain/text.ts";
  17. import { readFileBytes } from "#ui/assets.ts";
  18. import { getHost } from "#ui/host.ts";
  19. import {
  20. clip,
  21. describeFailure,
  22. readRecent,
  23. useHostContext,
  24. writeRecent,
  25. type AgentPointer,
  26. type Failure,
  27. type LoadedDoc,
  28. type Picked,
  29. type Reference,
  30. } from "#ui/shell/state.ts";
  31. import { describeAt, strings } from "#ui/i18n.ts";
  32. import { Icon } from "#ui/icons.tsx";
  33. import { baseName, call } from "#ui/rpc.ts";
  34. import { InlineShell } from "#ui/shell/inline.tsx";
  35. import { MoreMenu, SwitchMenu } from "#ui/shell/menus.tsx";
  36. import {
  37. ChangedBanner,
  38. Drawer,
  39. EmptyState,
  40. useNativeFileInput,
  41. ErrorState,
  42. Skeleton,
  43. type DrawerTab,
  44. } from "#ui/shell/panes.tsx";
  45. import {
  46. AgentCallout,
  47. FindBar,
  48. OffscreenChip,
  49. PagePill,
  50. SelectionBar,
  51. offscreenText,
  52. type BarMode,
  53. } from "#ui/shell/parts.tsx";
  54. import { CLOSED_FIND, useFind } from "#ui/shell/useFind.ts";
  55. import { useCaptureView } from "#ui/shell/useCaptureView.ts";
  56. import { useOffscreenTargets } from "#ui/shell/useOffscreenTargets.ts";
  57. import { useShellKeys } from "#ui/shell/useShellKeys.ts";
  58. import { VIEWERS } from "#ui/viewers/registry.ts";
  59. import type {
  60. PageState,
  61. RevealedTarget,
  62. SelectionDetail,
  63. ViewerHandle,
  64. ZoomState,
  65. } from "#ui/viewers/types.ts";
  66. const host = getHost();
  67. const PAGED: DocKind[] = ["pdf", "docx", "pptx"];
  68. /** Viewers with fit modes and zoom in the page control. */
  69. const ZOOMABLE: DocKind[] = ["pdf", "docx"];
  70. /** Below this panel width the drawer floats over the pages; at or above it, it docks. */
  71. const DOCK_WIDTH = 720;
  72. const INLINE_HEIGHT = 380;
  73. function Shell() {
  74. const context = useHostContext();
  75. const t = strings(context?.locale ?? navigator.language);
  76. const dark = context?.theme === "dark";
  77. const inline = context?.displayMode === "inline";
  78. const [doc, setDoc] = useState<LoadedDoc | null>(null);
  79. const [pending, setPending] = useState<string | null>(null);
  80. const [ready, setReady] = useState(false);
  81. const [failure, setFailure] = useState<Failure | null>(null);
  82. const [menu, setMenu] = useState<"switch" | "more" | null>(null);
  83. const [drawer, setDrawer] = useState<{ open: boolean; tab: DrawerTab }>({
  84. open: false,
  85. tab: "pages",
  86. });
  87. const [location, setLocation] = useState<string | null>(null);
  88. const [page, setPage] = useState<PageState | null>(null);
  89. const [zoom, setZoom] = useState<ZoomState | null>(null);
  90. const [picked, setPicked] = useState<Picked | null>(null);
  91. const pickedRef = useRef(picked);
  92. pickedRef.current = picked;
  93. const [barMode, setBarMode] = useState<BarMode>("bar");
  94. const [copied, setCopied] = useState(false);
  95. const [agent, setAgent] = useState<AgentPointer | null>(null);
  96. const [changed, setChanged] = useState<string | null>(null);
  97. const [notice, setNotice] = useState<string | null>(null);
  98. const [recent, setRecent] = useState(readRecent);
  99. const [wide, setWide] = useState(false);
  100. const appRef = useRef<HTMLDivElement>(null);
  101. const canvasRef = useRef<HTMLDivElement>(null);
  102. const [offscreen, setOffscreen] = useOffscreenTargets(canvasRef, agent);
  103. const viewer = useRef<ViewerHandle | null>(null);
  104. const viewerReady = useRef(false);
  105. const pendingReveal = useRef<{ targets: ShowTarget[]; note: string | null } | null>(null);
  106. const lastRevealSeq = useRef(0);
  107. const docRef = useRef<LoadedDoc | null>(null);
  108. docRef.current = doc;
  109. const loadSeq = useRef(0);
  110. /** Path being loaded; a second load of it without a reveal must not drop the pending one. */
  111. const loadingPath = useRef<string | null>(null);
  112. const loadKey = useRef(0);
  113. const references = useRef<Reference[]>([]);
  114. const dismissedRevision = useRef<string | null>(null);
  115. const onOpenFind = useCallback(() => {
  116. viewer.current?.clearReveal();
  117. viewer.current?.clearSelection();
  118. setPicked(null);
  119. setAgent(null);
  120. setMenu(null);
  121. }, []);
  122. const { find, setFind, openFind, closeFind, queryFind, stepFind } = useFind({
  123. viewer,
  124. docRef,
  125. ready,
  126. onOpen: onOpenFind,
  127. });
  128. /**
  129. * The agent's current target stays in view until the user scrolls, clicks or types in the
  130. * document: ZCode animates the pane open, and each resize re-lays the pages out under it.
  131. */
  132. const pinned = useRef(false);
  133. const kind = doc?.info.kind ?? (pending ? kindOf(pending) : null);
  134. const path = pending ?? failure?.path ?? doc?.info.path ?? null;
  135. useEffect(() => {
  136. document.documentElement.dataset.theme = dark ? "dark" : "light";
  137. const variables = context?.styles?.variables;
  138. if (variables) applyHostStyleVariables(variables);
  139. }, [dark, context?.styles?.variables]);
  140. useEffect(() => {
  141. // An inline card is a fixed-height glance; the side panel fills the pane.
  142. if (inline) void host.app.sendSizeChanged({ height: INLINE_HEIGHT }).catch(() => undefined);
  143. }, [inline]);
  144. useEffect(() => {
  145. const app = appRef.current!;
  146. const resize = new ResizeObserver(() => setWide(app.clientWidth >= DOCK_WIDTH));
  147. resize.observe(app);
  148. return () => resize.disconnect();
  149. }, []);
  150. const showNotice = useCallback((text: string) => {
  151. setNotice(text);
  152. setTimeout(() => setNotice((current) => (current === text ? null : current)), 2500);
  153. }, []);
  154. const resetDocumentState = useCallback(() => {
  155. viewerReady.current = false;
  156. setReady(false);
  157. setPicked(null);
  158. setBarMode("bar");
  159. setAgent(null);
  160. setOffscreen(null);
  161. setLocation(null);
  162. setPage(null);
  163. setZoom(null);
  164. setChanged(null);
  165. setFind(CLOSED_FIND);
  166. }, []);
  167. const load = useCallback(
  168. async (target: string, reveal?: { targets: ShowTarget[]; note: string | null } | null) => {
  169. const mine = ++loadSeq.current;
  170. if (reveal) pendingReveal.current = reveal;
  171. else if (loadingPath.current !== target) pendingReveal.current = null;
  172. loadingPath.current = target;
  173. setPending(target);
  174. setFailure(null);
  175. try {
  176. const loaded = await call<{
  177. info: DocumentInfo;
  178. file: FileHandle;
  179. blocks?: DocxBlockKey[];
  180. }>("load_document", { path: target });
  181. const [bytes] = await Promise.all([
  182. readFileBytes(loaded.file),
  183. VIEWERS[loaded.info.kind]?.prepare?.(),
  184. ]);
  185. if (mine !== loadSeq.current) return;
  186. resetDocumentState();
  187. dismissedRevision.current = null;
  188. setDoc({ info: loaded.info, bytes, blocks: loaded.blocks, key: ++loadKey.current });
  189. host.saveDocument(loaded.info.path);
  190. setRecent((items) => {
  191. const next = [
  192. { path: loaded.info.path, kind: loaded.info.kind },
  193. ...items.filter((item) => item.path !== loaded.info.path),
  194. ].slice(0, 5);
  195. writeRecent(next);
  196. return next;
  197. });
  198. } catch (error) {
  199. if (mine !== loadSeq.current) return;
  200. setDoc(null);
  201. resetDocumentState();
  202. setFailure(describeFailure(t, error, target));
  203. } finally {
  204. if (mine === loadSeq.current) {
  205. setPending(null);
  206. loadingPath.current = null;
  207. }
  208. }
  209. },
  210. [resetDocumentState, t],
  211. );
  212. const runReveal = useCallback(async (targets: ShowTarget[], note: string | null) => {
  213. const handle = viewer.current;
  214. if (!handle) return;
  215. // The agent's marks and find highlights are never shown together.
  216. handle.clearFind();
  217. setFind(CLOSED_FIND);
  218. const results = await handle.reveal(targets).catch(() => [] as RevealedTarget[]);
  219. pinned.current = results.length > 0;
  220. setAgent(
  221. results.length
  222. ? { note, targets: results, index: 0, visible: Boolean(note) || results.length > 1 }
  223. : null,
  224. );
  225. }, []);
  226. const applyReveal = useCallback(
  227. (targets: ShowTarget[], note: string | null) => {
  228. if (viewer.current && viewerReady.current) void runReveal(targets, note);
  229. else pendingReveal.current = { targets, note };
  230. },
  231. [runReveal],
  232. );
  233. /** Bring the viewer in line with a snapshot from the server (tool result or get_viewer). */
  234. const applySnapshot = useCallback(
  235. (snapshot: ViewerSnapshot | undefined) => {
  236. if (!snapshot?.document) return;
  237. const reveal =
  238. snapshot.reveal && snapshot.reveal.seq > lastRevealSeq.current ? snapshot.reveal : null;
  239. if (reveal) lastRevealSeq.current = reveal.seq;
  240. const current = docRef.current?.info;
  241. const pointer = reveal ? { targets: reveal.targets, note: reveal.note ?? null } : null;
  242. if (
  243. !current ||
  244. current.path !== snapshot.document.path ||
  245. current.revision !== snapshot.document.revision
  246. ) {
  247. void load(snapshot.document.path, pointer);
  248. } else if (pointer) applyReveal(pointer.targets, pointer.note);
  249. },
  250. [load, applyReveal],
  251. );
  252. // Tool results routed to this panel (open_document, show_in_viewer).
  253. useEffect(() => {
  254. const drain = () => {
  255. for (const result of host.takeResults()) {
  256. if (result.isError) continue;
  257. const truncated = (result._meta as Record<string, unknown> | undefined)?.[
  258. "zcode/truncated"
  259. ];
  260. if (truncated) void call<ViewerSnapshot>("get_viewer").then(applySnapshot, () => undefined);
  261. else applySnapshot(result.structuredContent as ViewerSnapshot | undefined);
  262. }
  263. };
  264. window.addEventListener("office:toolresult", drain);
  265. void host.ready().then(async () => {
  266. setRecent(readRecent());
  267. const buffered = host.takeResults();
  268. const path = host.readDocument();
  269. // 恢复本窗口的手动选择优先于历史工具结果;新窗口没有记录,保持空状态。
  270. if (path) void load(path);
  271. else for (const result of buffered)
  272. if (!result.isError) applySnapshot(result.structuredContent as ViewerSnapshot | undefined);
  273. });
  274. return () => window.removeEventListener("office:toolresult", drain);
  275. }, [applySnapshot, load]);
  276. // Tell the server where the user is (debounced) so get_view answers "what am I looking at".
  277. const selection = picked?.selection ?? null;
  278. useEffect(() => {
  279. if (!doc) return;
  280. const timer = setTimeout(() => {
  281. void call("report_view", { viewId: host.viewId, path: doc.info.path, at: location, selection }).catch(
  282. () => undefined,
  283. );
  284. }, 400);
  285. return () => clearTimeout(timer);
  286. }, [doc, location, selection]);
  287. // Notice when the file changes on disk under the panel.
  288. useEffect(() => {
  289. if (!doc || inline) return;
  290. const timer = setInterval(() => {
  291. if (document.visibilityState !== "visible") return;
  292. void call<{ revision: string }>("check_document", { path: doc.info.path }).then(
  293. ({ revision }) => {
  294. if (docRef.current !== doc) return;
  295. if (revision !== doc.info.revision && revision !== dismissedRevision.current)
  296. setChanged(revision);
  297. },
  298. () => undefined,
  299. );
  300. }, 4000);
  301. return () => clearInterval(timer);
  302. }, [doc, inline]);
  303. useCaptureView(docRef, viewer);
  304. const onReady = useCallback(() => {
  305. viewerReady.current = true;
  306. setReady(true);
  307. const reveal = pendingReveal.current;
  308. pendingReveal.current = null;
  309. if (reveal?.targets.length) setTimeout(() => void runReveal(reveal.targets, reveal.note), 50);
  310. }, [runReveal]);
  311. const onSelect = useCallback((next: Selection | null, detail?: SelectionDetail) => {
  312. setBarMode("bar");
  313. setCopied(false);
  314. setPicked(next && detail ? { selection: next, detail } : null);
  315. // Acting on the page dismisses the agent's note (its marks stay).
  316. if (next && detail?.user) setAgent((current) => current && { ...current, visible: false });
  317. }, []);
  318. const agentRef = useRef(agent);
  319. agentRef.current = agent;
  320. useEffect(() => {
  321. const canvas = canvasRef.current;
  322. if (!canvas) return;
  323. let timer = 0;
  324. const resize = new ResizeObserver(() => {
  325. if (!pinned.current) return;
  326. clearTimeout(timer);
  327. timer = window.setTimeout(() => {
  328. const current = agentRef.current;
  329. if (pinned.current && current) current.targets[current.index]?.scrollTo();
  330. }, 200);
  331. });
  332. resize.observe(canvas);
  333. const unpin = () => {
  334. pinned.current = false;
  335. };
  336. canvas.addEventListener("wheel", unpin, { passive: true });
  337. canvas.addEventListener("pointerdown", unpin, true);
  338. canvas.addEventListener("keydown", unpin, true);
  339. return () => {
  340. clearTimeout(timer);
  341. resize.disconnect();
  342. canvas.removeEventListener("wheel", unpin);
  343. canvas.removeEventListener("pointerdown", unpin, true);
  344. canvas.removeEventListener("keydown", unpin, true);
  345. };
  346. }, [doc]);
  347. // Clicking one of the agent's marks brings its note back, when there is one to show.
  348. const onRevealHit = useCallback((index: number) => {
  349. const current = agentRef.current;
  350. if (!current?.targets[index] || !(current.note || current.targets.length > 1)) return false;
  351. setAgent({ ...current, index, visible: true });
  352. return true;
  353. }, []);
  354. const clearSelection = useCallback(() => {
  355. viewer.current?.clearSelection();
  356. setPicked(null);
  357. setBarMode("bar");
  358. }, []);
  359. const addReference = useCallback(async () => {
  360. const current = docRef.current;
  361. if (!current || !picked) return;
  362. const anchor = formatAnchor(current.info.path, picked.selection.at);
  363. const text = picked.selection.text;
  364. const next = [
  365. ...references.current.filter((item) => item.anchor !== anchor || item.text !== text),
  366. { anchor, text },
  367. ].slice(-10);
  368. const lines = next.map(
  369. (item) => `- ${item.anchor}${item.text ? `: "${clip(item.text, 600)}"` : ""}`,
  370. );
  371. try {
  372. await host.ready();
  373. await host.app.updateModelContext({
  374. content: [
  375. {
  376. type: "text",
  377. text: wellFormed(
  378. `The user referenced these locations in the ${PROFILE.title.en} viewer (use read_document / show_in_viewer with the anchors):\n${lines.join("\n")}`,
  379. ),
  380. },
  381. ],
  382. structuredContent: wellFormedDeep({ references: next }),
  383. });
  384. references.current = next;
  385. setBarMode("added");
  386. const added = picked;
  387. setTimeout(() => {
  388. if (pickedRef.current === added) clearSelection();
  389. }, 1500);
  390. } catch {
  391. showNotice(t.contextFailed);
  392. }
  393. }, [picked, clearSelection, showNotice, t]);
  394. const ask = useCallback(
  395. async (question: string) => {
  396. const current = docRef.current;
  397. if (!current || !picked) return false;
  398. const anchor = formatAnchor(current.info.path, picked.selection.at);
  399. const text = picked.selection.text;
  400. const quote = text ? `\n> ${clip(text, 800).replace(/\n/g, "\n> ")}` : "";
  401. try {
  402. const result = await host.app.sendMessage({
  403. role: "user",
  404. content: [
  405. {
  406. type: "text",
  407. text: wellFormed(
  408. `${question}\n\n(About ${anchor} in the ${PROFILE.title.en} viewer${quote ? ":" : "."})${quote}`,
  409. ),
  410. },
  411. ],
  412. });
  413. if (result.isError) throw new Error();
  414. clearSelection();
  415. return true;
  416. } catch {
  417. showNotice(t.sendFailed);
  418. return false;
  419. }
  420. },
  421. [picked, clearSelection, showNotice, t],
  422. );
  423. const copy = useCallback(async () => {
  424. const text = picked?.selection.text;
  425. if (!text) return;
  426. try {
  427. await navigator.clipboard.writeText(text);
  428. } catch {
  429. // The sandbox may deny the async clipboard; the live selection still copies.
  430. document.execCommand("copy");
  431. }
  432. setCopied(true);
  433. setTimeout(() => setCopied(false), 1200);
  434. }, [picked]);
  435. const goToPage = useCallback((n: number) => viewer.current?.goToPage?.(n), []);
  436. const stepAgent = useCallback((index?: number) => {
  437. setAgent((current) => {
  438. if (!current) return current;
  439. const next = index ?? (current.index + 1) % current.targets.length;
  440. current.targets[next]?.scrollTo();
  441. pinned.current = true;
  442. return { ...current, index: next, visible: true };
  443. });
  444. }, []);
  445. // Pressing on the page (outside the callout) dismisses the agent's note.
  446. useEffect(() => {
  447. const canvas = canvasRef.current;
  448. if (!canvas) return;
  449. const onDown = (event: PointerEvent) => {
  450. if ((event.target as Element).closest(".callout, .chip, .pop, .pill")) return;
  451. setAgent((current) => (current?.visible ? { ...current, visible: false } : current));
  452. };
  453. canvas.addEventListener("pointerdown", onDown, true);
  454. return () => canvas.removeEventListener("pointerdown", onDown, true);
  455. }, [doc]);
  456. const docked = wide && !inline;
  457. const paged = Boolean(kind && PAGED.includes(kind));
  458. const drawerAvailable =
  459. Boolean(doc && ready && kind !== "xlsx") &&
  460. Boolean(viewer.current?.thumbnail || doc?.info.outline.length);
  461. useShellKeys({
  462. docRef,
  463. viewer,
  464. picked,
  465. addReference,
  466. openFind,
  467. closeFind,
  468. clearSelection,
  469. paged,
  470. page,
  471. goToPage,
  472. drawer,
  473. setDrawer,
  474. docked,
  475. find,
  476. agent,
  477. setAgent,
  478. });
  479. const openPath = useCallback(
  480. (target: string) => {
  481. setMenu(null);
  482. void call<ViewerSnapshot>("open_document", { path: target }).then(applySnapshot, (error) => {
  483. // The user asked for another file: close this one and say why that one did not open.
  484. loadSeq.current++;
  485. setDoc(null);
  486. resetDocumentState();
  487. setFailure(describeFailure(t, error, target));
  488. });
  489. },
  490. [applySnapshot, resetDocumentState, t],
  491. );
  492. const filePicker = useNativeFileInput(t, openPath, (error, name) =>
  493. setFailure(describeFailure(t, error, name)),
  494. );
  495. const Viewer = doc ? (VIEWERS[doc.info.kind]?.view ?? null) : null;
  496. const viewerProps = useMemo(
  497. () =>
  498. doc
  499. ? {
  500. bytes: doc.bytes,
  501. info: doc.info,
  502. blocks: doc.blocks,
  503. dark,
  504. glance: inline,
  505. onLocation: setLocation,
  506. onSelect,
  507. onRevealHit,
  508. onPage: setPage,
  509. onZoom: setZoom,
  510. onLink: (url: string) => void host.app.openLink({ url }).catch(() => undefined),
  511. onReady,
  512. onError: (error: Error) =>
  513. setFailure(describeFailure(t, error, docRef.current?.info.path ?? null)),
  514. }
  515. : null,
  516. // `t` only words errors; a locale change does not need a new viewer.
  517. [doc, dark, inline, onReady, onSelect, onRevealHit],
  518. );
  519. const showSkeleton = !failure && (Boolean(pending) || Boolean(doc && !ready));
  520. const nothing = !doc && !pending && !failure;
  521. const label = picked ? describeAt(picked.selection.at, t) : "";
  522. if (inline)
  523. return (
  524. <InlineShell
  525. appRef={appRef}
  526. canvasRef={canvasRef}
  527. t={t}
  528. path={path}
  529. info={doc?.info}
  530. kind={kind}
  531. showSkeleton={showSkeleton}
  532. failure={failure}
  533. nothing={nothing}
  534. onExpand={() =>
  535. void host.app.requestDisplayMode({ mode: "fullscreen" }).catch(() => undefined)
  536. }
  537. >
  538. {Viewer && viewerProps ? <Viewer key={doc!.key} ref={viewer} {...viewerProps} /> : null}
  539. </InlineShell>
  540. );
  541. return (
  542. <div ref={appRef} className="app">
  543. {nothing ? null : find.open ? (
  544. <FindBar
  545. t={t}
  546. query={find.query}
  547. total={find.total}
  548. index={find.index}
  549. onQuery={queryFind}
  550. onStep={stepFind}
  551. onClose={closeFind}
  552. />
  553. ) : (
  554. <header className="docbar">
  555. {doc || pending || failure ? (
  556. <button
  557. type="button"
  558. className={`btn icon ${drawer.open && drawerAvailable ? "secondary" : "dim"}`}
  559. title={t.pagesAndOutline}
  560. aria-label={t.pagesAndOutline}
  561. aria-pressed={drawer.open && drawerAvailable}
  562. disabled={!drawerAvailable}
  563. hidden={kind === "xlsx"}
  564. onClick={() => setDrawer((state) => ({ ...state, open: !state.open }))}
  565. >
  566. <Icon name="panel-left" />
  567. </button>
  568. ) : null}
  569. <button
  570. type="button"
  571. className={`doctitle${menu === "switch" ? " open" : ""}`}
  572. title={path ?? undefined}
  573. aria-haspopup="menu"
  574. aria-expanded={menu === "switch"}
  575. aria-label={`${t.switchDocument}: ${path ?? ""}`}
  576. data-menu-trigger=""
  577. onClick={() => setMenu((value) => (value === "switch" ? null : "switch"))}
  578. >
  579. <span className="name">{path ? baseName(path) : t.title}</span>
  580. <Icon name="chevron-down" size={12} className="chev" />
  581. </button>
  582. <span className="spacer" />
  583. {doc && !failure ? (
  584. <>
  585. <button
  586. type="button"
  587. className="btn icon dim"
  588. title={`${t.find} (⌘F)`}
  589. aria-label={t.find}
  590. disabled={!ready}
  591. onClick={openFind}
  592. >
  593. <Icon name="search" />
  594. </button>
  595. <button
  596. type="button"
  597. className={`btn icon dim${menu === "more" ? " active" : ""}`}
  598. title={t.more}
  599. aria-label={t.more}
  600. aria-haspopup="menu"
  601. aria-expanded={menu === "more"}
  602. data-menu-trigger=""
  603. onClick={() => setMenu((value) => (value === "more" ? null : "more"))}
  604. >
  605. <Icon name="ellipsis" />
  606. </button>
  607. </>
  608. ) : null}
  609. </header>
  610. )}
  611. {changed ? (
  612. <ChangedBanner
  613. t={t}
  614. onReload={() => doc && void load(doc.info.path)}
  615. onDismiss={() => {
  616. dismissedRevision.current = changed;
  617. setChanged(null);
  618. }}
  619. />
  620. ) : null}
  621. {nothing ? (
  622. <EmptyState t={t} importing={filePicker.importing} onBrowse={filePicker.browse} />
  623. ) : (
  624. <div className="stage">
  625. {drawer.open && drawerAvailable && doc ? (
  626. <>
  627. {docked ? null : (
  628. <div
  629. className="scrim"
  630. onClick={() => setDrawer((state) => ({ ...state, open: false }))}
  631. />
  632. )}
  633. <Drawer
  634. t={t}
  635. info={doc.info}
  636. handle={viewer.current}
  637. page={paged ? page : null}
  638. tab={drawer.tab}
  639. docked={docked}
  640. onTab={(tab) => setDrawer((state) => ({ ...state, tab }))}
  641. onPage={(n) => {
  642. goToPage(n);
  643. if (!docked) setDrawer((state) => ({ ...state, open: false }));
  644. }}
  645. onOutline={(at) => {
  646. viewer.current?.goTo(at);
  647. if (!docked) setDrawer((state) => ({ ...state, open: false }));
  648. }}
  649. />
  650. </>
  651. ) : null}
  652. <div ref={canvasRef} className="canvas">
  653. {Viewer && viewerProps ? <Viewer key={doc!.key} ref={viewer} {...viewerProps} /> : null}
  654. {showSkeleton ? <Skeleton kind={kind} /> : null}
  655. {failure ? (
  656. <ErrorState
  657. t={t}
  658. title={failure.title}
  659. detail={failure.detail}
  660. onOpenAnother={filePicker.browse}
  661. />
  662. ) : null}
  663. {doc && ready && !failure && picked?.detail.user ? (
  664. <SelectionBar
  665. key={`${picked.selection.at}:${picked.selection.text.length}`}
  666. t={t}
  667. frame={canvasRef}
  668. locate={picked.detail.locate}
  669. text={picked.detail.text}
  670. label={label}
  671. quote={clip(picked.selection.text.replace(/\s+/g, " "), 60)}
  672. short={doc.info.kind === "xlsx"}
  673. mode={barMode}
  674. canAsk={Boolean(host.capabilities?.message)}
  675. copied={copied}
  676. onAdd={() => void addReference()}
  677. onAsk={() => setBarMode("ask")}
  678. onCopy={() => void copy()}
  679. onCancelAsk={() => setBarMode("bar")}
  680. onSend={ask}
  681. />
  682. ) : null}
  683. {agent?.visible && agent.targets[agent.index] && !failure ? (
  684. <AgentCallout
  685. t={t}
  686. frame={canvasRef}
  687. locate={agent.targets[agent.index].locate}
  688. note={agent.note}
  689. index={agent.index}
  690. total={agent.targets.length}
  691. onNext={() => stepAgent()}
  692. onClose={() => setAgent({ ...agent, visible: false })}
  693. />
  694. ) : null}
  695. {agent && offscreen ? (
  696. <OffscreenChip
  697. text={offscreenText(
  698. t,
  699. offscreen.indexes.map((i) => agent.targets[i].at),
  700. )}
  701. down={offscreen.down}
  702. raised={paged}
  703. onClick={() => stepAgent(offscreen.indexes[0])}
  704. />
  705. ) : null}
  706. {doc && ready && !failure && paged && page ? (
  707. <PagePill
  708. t={t}
  709. frame={canvasRef}
  710. page={page}
  711. zoom={kind && ZOOMABLE.includes(kind) ? zoom : null}
  712. onPage={goToPage}
  713. onZoom={(direction) => viewer.current?.zoom(direction)}
  714. onFit={() => viewer.current?.fit("width")}
  715. />
  716. ) : null}
  717. {notice ? <div className="chip notice">{notice}</div> : null}
  718. </div>
  719. </div>
  720. )}
  721. {menu === "switch" ? (
  722. <SwitchMenu
  723. t={t}
  724. recent={recent}
  725. currentPath={doc?.info.path}
  726. onOpen={openPath}
  727. onBrowse={() => {
  728. setMenu(null);
  729. filePicker.browse();
  730. }}
  731. onClose={() => setMenu(null)}
  732. />
  733. ) : null}
  734. {menu === "more" && doc ? (
  735. <MoreMenu
  736. t={t}
  737. zoomable={ZOOMABLE.includes(doc.info.kind)}
  738. zoomMode={zoom?.mode}
  739. onFit={(mode) => {
  740. viewer.current?.fit(mode);
  741. setMenu(null);
  742. }}
  743. onFind={openFind}
  744. onReload={() => {
  745. setMenu(null);
  746. void load(doc.info.path);
  747. }}
  748. onClose={() => setMenu(null)}
  749. />
  750. ) : null}
  751. {filePicker.input}
  752. </div>
  753. );
  754. }
  755. const root = document.getElementById("root")!;
  756. root.textContent = "";
  757. createRoot(root).render(
  758. <StrictMode>
  759. <Shell />
  760. </StrictMode>,
  761. );
  762. void host.ready();