parts.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. import {
  2. useEffect,
  3. useRef,
  4. useState,
  5. type ReactNode,
  6. type RefObject,
  7. type KeyboardEvent as ReactKeyboardEvent,
  8. type MouseEvent as ReactMouseEvent,
  9. } from "react";
  10. import { describeAt, type Strings } from "#ui/i18n.ts";
  11. import { Icon } from "#ui/icons.tsx";
  12. import { useFloating } from "#ui/shell/float.ts";
  13. import type { Locate, PageState, ZoomState } from "#ui/viewers/types.ts";
  14. /* ---------------------------------------------------------------- Menu */
  15. /** ZCode dropdown: closes on Escape and on any pointer press outside it. */
  16. export function Menu({
  17. className,
  18. onClose,
  19. children,
  20. label,
  21. }: {
  22. className: string;
  23. onClose(): void;
  24. children: ReactNode;
  25. label: string;
  26. }) {
  27. const ref = useRef<HTMLDivElement>(null);
  28. useEffect(() => {
  29. const onDown = (event: PointerEvent) => {
  30. const target = event.target as Element;
  31. if (!ref.current?.contains(target) && !target.closest?.("[data-menu-trigger]")) onClose();
  32. };
  33. const onKey = (event: KeyboardEvent) => {
  34. if (event.key !== "Escape") return;
  35. event.stopPropagation();
  36. onClose();
  37. };
  38. document.addEventListener("pointerdown", onDown, true);
  39. document.addEventListener("keydown", onKey, true);
  40. ref.current?.querySelector<HTMLElement>("[role^=menuitem]")?.focus();
  41. return () => {
  42. document.removeEventListener("pointerdown", onDown, true);
  43. document.removeEventListener("keydown", onKey, true);
  44. };
  45. }, [onClose]);
  46. const move = (event: ReactKeyboardEvent) => {
  47. if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
  48. event.preventDefault();
  49. const items = [...(ref.current?.querySelectorAll<HTMLElement>("[role^=menuitem]") ?? [])];
  50. const index = items.indexOf(document.activeElement as HTMLElement);
  51. items[(index + (event.key === "ArrowDown" ? 1 : -1) + items.length) % items.length]?.focus();
  52. };
  53. return (
  54. <div ref={ref} className={`menu ${className}`} role="menu" aria-label={label} onKeyDown={move}>
  55. {children}
  56. </div>
  57. );
  58. }
  59. export function MenuItem({
  60. icon,
  61. checked,
  62. children,
  63. hint,
  64. onSelect,
  65. }: {
  66. icon?: ReactNode;
  67. checked?: boolean;
  68. children: ReactNode;
  69. hint?: ReactNode;
  70. onSelect(): void;
  71. }) {
  72. return (
  73. <button
  74. type="button"
  75. role={checked === undefined ? "menuitem" : "menuitemradio"}
  76. aria-checked={checked}
  77. className="mi"
  78. onClick={onSelect}
  79. >
  80. <span className="mi-icon">{checked ? <Icon name="check" size={16} /> : icon}</span>
  81. <span className="mi-label">{children}</span>
  82. {hint ? <span className="mi-hint">{hint}</span> : null}
  83. </button>
  84. );
  85. }
  86. /* ---------------------------------------------------------------- Find */
  87. export function FindBar({
  88. t,
  89. query,
  90. total,
  91. index,
  92. onQuery,
  93. onStep,
  94. onClose,
  95. }: {
  96. t: Strings;
  97. query: string;
  98. total: number | null;
  99. index: number;
  100. onQuery(query: string): void;
  101. onStep(direction: 1 | -1): void;
  102. onClose(): void;
  103. }) {
  104. const input = useRef<HTMLInputElement>(null);
  105. useEffect(() => {
  106. input.current?.focus();
  107. input.current?.select();
  108. }, []);
  109. const count =
  110. !query.trim() || total === null ? "" : total ? t.findCount(index + 1, total) : t.noResults;
  111. return (
  112. <div className="docbar findbar" role="search">
  113. <label className="findfield">
  114. <Icon name="search" className="muted" />
  115. <input
  116. ref={input}
  117. className="find-input"
  118. type="text"
  119. aria-label={t.find}
  120. placeholder={t.findPlaceholder}
  121. value={query}
  122. onChange={(event) => onQuery(event.target.value)}
  123. onKeyDown={(event) => {
  124. if (event.key === "Enter") {
  125. event.preventDefault();
  126. onStep(event.shiftKey ? -1 : 1);
  127. } else if (event.key === "Escape") {
  128. event.preventDefault();
  129. event.stopPropagation();
  130. onClose();
  131. }
  132. }}
  133. />
  134. <span className="count" aria-live="polite">
  135. {count}
  136. </span>
  137. </label>
  138. <button
  139. type="button"
  140. className="btn icon dim"
  141. title={t.previousMatch}
  142. aria-label={t.previousMatch}
  143. disabled={!total}
  144. onClick={() => onStep(-1)}
  145. >
  146. <Icon name="chevron-up" />
  147. </button>
  148. <button
  149. type="button"
  150. className="btn icon dim"
  151. title={t.nextMatch}
  152. aria-label={t.nextMatch}
  153. disabled={!total}
  154. onClick={() => onStep(1)}
  155. >
  156. <Icon name="chevron-down" />
  157. </button>
  158. <button
  159. type="button"
  160. className="btn icon dim"
  161. title={t.closeFind}
  162. aria-label={t.closeFind}
  163. onClick={onClose}
  164. >
  165. <Icon name="x" />
  166. </button>
  167. </div>
  168. );
  169. }
  170. /* ---------------------------------------------------------------- Page / zoom pill */
  171. const IDLE_MS = 1500;
  172. /**
  173. * Floating page and zoom control. Shown while scrolling, while the pointer is near the bottom edge,
  174. * while focused or hovered; fades out after 1.5 s of stillness.
  175. */
  176. export function PagePill({
  177. t,
  178. frame,
  179. page,
  180. zoom,
  181. onPage,
  182. onZoom,
  183. onFit,
  184. }: {
  185. t: Strings;
  186. frame: RefObject<HTMLElement | null>;
  187. page: PageState;
  188. zoom: ZoomState | null;
  189. onPage(page: number): void;
  190. onZoom(direction: 1 | -1): void;
  191. onFit(): void;
  192. }) {
  193. const ref = useRef<HTMLDivElement>(null);
  194. const [visible, setVisible] = useState(true);
  195. const [draft, setDraft] = useState<string | null>(null);
  196. const hold = useRef(false);
  197. useEffect(() => {
  198. const container = frame.current;
  199. if (!container) return;
  200. let timer = 0;
  201. const idle = () => {
  202. clearTimeout(timer);
  203. timer = window.setTimeout(() => {
  204. if (!hold.current && !ref.current?.contains(document.activeElement)) setVisible(false);
  205. }, IDLE_MS);
  206. };
  207. const wake = () => {
  208. setVisible(true);
  209. idle();
  210. };
  211. const near = (event: PointerEvent) => {
  212. const bounds = container.getBoundingClientRect();
  213. if (event.clientY > bounds.bottom - 80) wake();
  214. };
  215. container.addEventListener("scroll", wake, { capture: true, passive: true });
  216. container.addEventListener("pointermove", near, { passive: true });
  217. idle();
  218. return () => {
  219. clearTimeout(timer);
  220. container.removeEventListener("scroll", wake, { capture: true });
  221. container.removeEventListener("pointermove", near);
  222. };
  223. }, [frame]);
  224. const go = () => {
  225. const value = Number(draft);
  226. setDraft(null);
  227. if (Number.isInteger(value) && value >= 1) onPage(Math.min(value, page.count));
  228. };
  229. return (
  230. <div
  231. ref={ref}
  232. className={`pill${visible ? "" : " faded"}`}
  233. onPointerEnter={() => {
  234. hold.current = true;
  235. setVisible(true);
  236. }}
  237. onPointerLeave={() => {
  238. hold.current = false;
  239. }}
  240. onFocus={() => setVisible(true)}
  241. >
  242. <button
  243. type="button"
  244. className="btn icon sm dim"
  245. title={t.previousPage}
  246. aria-label={t.previousPage}
  247. disabled={page.current <= 1}
  248. onClick={() => onPage(page.current - 1)}
  249. >
  250. <Icon name="chevron-up" />
  251. </button>
  252. <span className="pg">
  253. <input
  254. className="pgin"
  255. aria-label={t.pageNumber}
  256. inputMode="numeric"
  257. style={{ width: `${Math.max(2, String(page.count).length) + 1.6}ch` }}
  258. value={draft ?? String(page.current)}
  259. onFocus={(event) => {
  260. setDraft(String(page.current));
  261. event.target.select();
  262. }}
  263. onChange={(event) => setDraft(event.target.value.replace(/\D/g, ""))}
  264. onBlur={() => setDraft(null)}
  265. onKeyDown={(event) => {
  266. if (event.key === "Enter") {
  267. go();
  268. event.currentTarget.blur();
  269. } else if (event.key === "Escape") {
  270. event.stopPropagation();
  271. setDraft(null);
  272. event.currentTarget.blur();
  273. }
  274. }}
  275. />
  276. <span>{t.ofPages(page.count)}</span>
  277. </span>
  278. <button
  279. type="button"
  280. className="btn icon sm dim"
  281. title={t.nextPage}
  282. aria-label={t.nextPage}
  283. disabled={page.current >= page.count}
  284. onClick={() => onPage(page.current + 1)}
  285. >
  286. <Icon name="chevron-down" />
  287. </button>
  288. {zoom ? (
  289. <>
  290. <span className="vsep" />
  291. <button
  292. type="button"
  293. className="btn icon sm dim"
  294. title={t.zoomOut}
  295. aria-label={t.zoomOut}
  296. disabled={zoom.mode !== "width" && zoom.percent <= 25}
  297. onClick={() => onZoom(-1)}
  298. >
  299. <Icon name="minus" />
  300. </button>
  301. <button type="button" className="zoom" title={t.fitWidth} onClick={onFit}>
  302. {zoom.mode === "width" ? t.fit : `${zoom.percent}%`}
  303. </button>
  304. <button
  305. type="button"
  306. className="btn icon sm dim"
  307. title={t.zoomIn}
  308. aria-label={t.zoomIn}
  309. disabled={zoom.mode !== "width" && zoom.percent >= 400}
  310. onClick={() => onZoom(1)}
  311. >
  312. <Icon name="plus" />
  313. </button>
  314. </>
  315. ) : null}
  316. </div>
  317. );
  318. }
  319. /* ---------------------------------------------------------------- Selection bar and Ask */
  320. export type BarMode = "bar" | "ask" | "added";
  321. /** Keep the document's text selection when a press lands on the bar. */
  322. const keepSelection = (event: ReactMouseEvent) => {
  323. if (!(event.target as Element).closest("textarea")) event.preventDefault();
  324. };
  325. export function SelectionBar({
  326. t,
  327. frame,
  328. locate,
  329. text,
  330. label,
  331. quote,
  332. short,
  333. mode,
  334. canAsk,
  335. copied,
  336. onAdd,
  337. onAsk,
  338. onCopy,
  339. onCancelAsk,
  340. onSend,
  341. }: {
  342. t: Strings;
  343. frame: RefObject<HTMLElement | null>;
  344. locate: Locate;
  345. /** A text selection (offers Copy) rather than a block, page or cell range (shows its label). */
  346. text: boolean;
  347. label: string;
  348. quote: string;
  349. /** Use the short "Add" label (spreadsheets, where the range label takes the room). */
  350. short: boolean;
  351. mode: BarMode;
  352. canAsk: boolean;
  353. copied: boolean;
  354. onAdd(): void;
  355. onAsk(): void;
  356. onCopy(): void;
  357. onCancelAsk(): void;
  358. onSend(question: string): Promise<boolean>;
  359. }) {
  360. const asking = mode === "ask";
  361. const ref = useFloating<HTMLDivElement>(frame, locate, {
  362. side: asking ? "bottom" : "top",
  363. dock: true,
  364. });
  365. const [question, setQuestion] = useState("");
  366. const [sending, setSending] = useState(false);
  367. const send = async () => {
  368. if (!question.trim() || sending) return;
  369. setSending(true);
  370. const ok = await onSend(question.trim());
  371. setSending(false);
  372. if (ok) setQuestion("");
  373. };
  374. if (asking)
  375. return (
  376. <div
  377. ref={ref}
  378. className="pop ask"
  379. role="dialog"
  380. aria-label={t.ask}
  381. onMouseDown={keepSelection}
  382. >
  383. <div className="ctx">
  384. <span className="where">{label}</span>
  385. {quote ? <span className="q">“{quote}”</span> : null}
  386. </div>
  387. <textarea
  388. autoFocus
  389. className="textarea"
  390. rows={2}
  391. aria-label={t.askPlaceholder}
  392. placeholder={t.askPlaceholder}
  393. value={question}
  394. onChange={(event) => setQuestion(event.target.value)}
  395. onKeyDown={(event) => {
  396. if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {
  397. event.preventDefault();
  398. void send();
  399. } else if (event.key === "Escape") {
  400. event.preventDefault();
  401. event.stopPropagation();
  402. onCancelAsk();
  403. }
  404. }}
  405. />
  406. <div className="row">
  407. <span className="hint">
  408. <kbd>↵</kbd> {t.sendKey}
  409. </span>
  410. <button type="button" className="btn sm" onClick={onCancelAsk}>
  411. {t.cancel}
  412. </button>
  413. <button
  414. type="button"
  415. className="btn sm primary"
  416. disabled={!question.trim() || sending}
  417. onClick={() => void send()}
  418. >
  419. {t.send}
  420. </button>
  421. </div>
  422. </div>
  423. );
  424. return (
  425. <div
  426. ref={ref}
  427. className="pop bar"
  428. role="toolbar"
  429. aria-label={label}
  430. onMouseDown={keepSelection}
  431. >
  432. {!text ? (
  433. <>
  434. <span className="where">{label}</span>
  435. <span className="vsep" />
  436. </>
  437. ) : null}
  438. <button
  439. type="button"
  440. className="btn lg"
  441. title={t.addToChatHint}
  442. onClick={onAdd}
  443. disabled={mode === "added"}
  444. >
  445. {mode === "added" ? (
  446. <>
  447. <Icon name="check" size={16} className="ok" />
  448. {t.added}
  449. </>
  450. ) : (
  451. <>
  452. <Icon name="message-square-plus" size={16} />
  453. {short ? t.addShort : t.addToChat}
  454. </>
  455. )}
  456. </button>
  457. {canAsk ? (
  458. <button type="button" className="btn lg" onClick={onAsk}>
  459. <Icon name="message-circle-question" size={16} />
  460. {t.ask}
  461. </button>
  462. ) : null}
  463. {text ? (
  464. <>
  465. <span className="vsep" />
  466. <button
  467. type="button"
  468. className="btn icon lg dim"
  469. title={copied ? t.copied : t.copy}
  470. aria-label={copied ? t.copied : t.copy}
  471. onClick={onCopy}
  472. >
  473. <Icon name={copied ? "check" : "copy"} />
  474. </button>
  475. </>
  476. ) : null}
  477. </div>
  478. );
  479. }
  480. /* ---------------------------------------------------------------- Agent callout */
  481. export function AgentCallout({
  482. t,
  483. frame,
  484. locate,
  485. note,
  486. index,
  487. total,
  488. onNext,
  489. onClose,
  490. }: {
  491. t: Strings;
  492. frame: RefObject<HTMLElement | null>;
  493. locate: Locate | null;
  494. note: string | null;
  495. index: number;
  496. total: number;
  497. onNext(): void;
  498. onClose(): void;
  499. }) {
  500. const ref = useFloating<HTMLDivElement>(frame, locate, { side: "bottom", offset: 6, dock: true });
  501. return (
  502. <div ref={ref} className="callout" role="note">
  503. <div className="body">
  504. <div className="who">
  505. <span className="dot" />
  506. {total > 1 ? t.agentOf(index + 1, total) : t.agent}
  507. </div>
  508. {note ? <div className="text">{note}</div> : null}
  509. </div>
  510. {total > 1 ? (
  511. <button
  512. type="button"
  513. className="btn icon sm dim"
  514. title={t.nextTarget}
  515. aria-label={t.nextTarget}
  516. onClick={onNext}
  517. >
  518. <Icon name="chevron-down" />
  519. </button>
  520. ) : null}
  521. <button
  522. type="button"
  523. className="btn icon sm dim"
  524. title={t.close}
  525. aria-label={t.close}
  526. onClick={onClose}
  527. >
  528. <Icon name="x" />
  529. </button>
  530. </div>
  531. );
  532. }
  533. export function OffscreenChip({
  534. text,
  535. down,
  536. raised,
  537. onClick,
  538. }: {
  539. text: string;
  540. down: boolean;
  541. raised: boolean;
  542. onClick(): void;
  543. }) {
  544. return (
  545. <button type="button" className={`chip offscreen${raised ? " raised" : ""}`} onClick={onClick}>
  546. <span className="dot" />
  547. {text}
  548. <Icon name={down ? "arrow-down" : "arrow-up"} size={12} />
  549. </button>
  550. );
  551. }
  552. /** "1 more on page 4" for targets outside the view. */
  553. export function offscreenText(t: Strings, ats: string[]): string {
  554. return t.moreOn(ats.length, describeAt(ats[0], t, true));
  555. }