The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /* oxlint-disable react/no-array-index-key -- Text spans retain their order within an immutable page. */ |
| 2 | /* oxlint-disable react/no-unstable-nested-components -- These callbacks return overlays, and are invoked as render functions. */ |
| 3 | import { Tooltip, TooltipTrigger, TooltipPopup } from "~/components/ui/tooltip"; |
| 4 | import { msg } from "gt-react"; |
| 5 | import { Fragment, useEffect, useRef, useState } from "react"; |
| 6 | import { m } from "~/i18n/messages"; |
| 7 | import { FileSurfaceLoading } from "../fileSurfaceChrome"; |
| 8 | import { OfficePages, type PaintPage } from "./OfficePages"; |
| 9 | import { rasterize } from "./vector-pictures"; |
| 10 | import { createWorkerClient } from "./worker-rpc"; |
| 11 | import { |
| 12 | layerFont, |
| 13 | lineHeight, |
| 14 | type WordMethods, |
| 15 | type WordPageSize, |
| 16 | type WordSpan, |
| 17 | type WordLink, |
| 18 | } from "./word-protocol"; |
| 19 | |
| 20 | type Opened = { |
| 21 | pages: readonly WordPageSize[]; |
| 22 | paint: PaintPage; |
| 23 | engine: ReturnType<typeof createWorkerClient<WordMethods>>; |
| 24 | }; |
| 25 | |
| 26 | export default function WordDocument(props: { |
| 27 | bytes: ArrayBuffer; |
| 28 | onDetails: (text: string) => void; |
| 29 | onError: (cause: unknown) => void; |
| 30 | }) { |
| 31 | const { onError, bytes, onDetails } = props; |
| 32 | const [opened, setOpened] = useState<Opened>(); |
| 33 | const scroll = useRef<((index: number, y?: number) => void) | null>(null); |
| 34 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the document worker and cancel its layout and painting requests when the document changes or unmounts. |
| 35 | useEffect(() => { |
| 36 | const controller = new AbortController(); |
| 37 | const worker = new Worker(new URL("./document.worker.ts", import.meta.url), { type: "module" }); |
| 38 | const engine = createWorkerClient<WordMethods>(worker); |
| 39 | const fail = (error: unknown) => { |
| 40 | if (!controller.signal.aborted) onError(error); |
| 41 | }; |
| 42 | worker.addEventListener("error", fail); |
| 43 | worker.addEventListener("messageerror", fail); |
| 44 | const buffer = bytes.slice(0); |
| 45 | const paint = async ( |
| 46 | index: number, |
| 47 | canvas: HTMLCanvasElement, |
| 48 | scale: number, |
| 49 | signal: AbortSignal, |
| 50 | again = false, |
| 51 | ): Promise<void> => { |
| 52 | const painted = await engine.call( |
| 53 | "paint", |
| 54 | { index, scale, ratio: window.devicePixelRatio || 1 }, |
| 55 | { key: `paint:${index}`, signal }, |
| 56 | ); |
| 57 | void engine |
| 58 | .call("build", { index: index + 1 }, { key: "build", signal }) |
| 59 | .catch(() => undefined); |
| 60 | if (!painted) return; |
| 61 | const context = canvas.getContext("bitmaprenderer"); |
| 62 | if (!context || signal.aborted) { |
| 63 | painted.bitmap.close(); |
| 64 | return; |
| 65 | } |
| 66 | canvas.width = painted.bitmap.width; |
| 67 | canvas.height = painted.bitmap.height; |
| 68 | context.transferFromImageBitmap(painted.bitmap); |
| 69 | if (again || !painted.vectors.length) return; |
| 70 | const bitmaps = await Promise.all(painted.vectors.map(rasterize)); |
| 71 | if (signal.aborted) { |
| 72 | bitmaps.forEach((value) => value.bitmap?.close()); |
| 73 | return; |
| 74 | } |
| 75 | await engine.call("vectors", bitmaps, { |
| 76 | transfer: bitmaps.flatMap((value) => (value.bitmap ? [value.bitmap] : [])), |
| 77 | signal, |
| 78 | }); |
| 79 | if (!signal.aborted) await paint(index, canvas, scale, signal, true); |
| 80 | }; |
| 81 | void engine |
| 82 | .call("open", { bytes: buffer }, { transfer: [buffer], signal: controller.signal }) |
| 83 | .then(async (first) => { |
| 84 | if (controller.signal.aborted) return; |
| 85 | setOpened({ pages: first.pages, paint, engine }); |
| 86 | onDetails( |
| 87 | first.loading |
| 88 | ? m(msg("{count}+ pages", { count: String(first.pages.length) })) |
| 89 | : m( |
| 90 | msg("{count, plural, one {{count} page} other {{count} pages}}", { |
| 91 | count: first.pages.length, |
| 92 | }), |
| 93 | ), |
| 94 | ); |
| 95 | if (!first.loading) return; |
| 96 | await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))); |
| 97 | while (!controller.signal.aborted) { |
| 98 | const step = await engine.call("layout", undefined, { signal: controller.signal }); |
| 99 | if (!step.done) continue; |
| 100 | if (step.pages.length > 1000) throw new Error(m(msg("Preview limited to 1,000 pages."))); |
| 101 | setOpened({ pages: step.pages, paint, engine }); |
| 102 | onDetails( |
| 103 | m( |
| 104 | msg("{count, plural, one {{count} page} other {{count} pages}}", { |
| 105 | count: step.pages.length, |
| 106 | }), |
| 107 | ), |
| 108 | ); |
| 109 | break; |
| 110 | } |
| 111 | }) |
| 112 | .catch(fail); |
| 113 | return () => { |
| 114 | controller.abort(); |
| 115 | engine.close(); |
| 116 | }; |
| 117 | }, [bytes, onDetails, onError]); |
| 118 | if (!opened) return <FileSurfaceLoading />; |
| 119 | const follow = (link: WordLink) => { |
| 120 | if (link.kind === "external") { |
| 121 | window.open(link.url, "_blank", "noopener,noreferrer"); |
| 122 | return; |
| 123 | } |
| 124 | void opened.engine |
| 125 | .call("bookmark", { name: link.bookmark }) |
| 126 | .then((target) => { |
| 127 | if (target) scroll.current?.(target.index, target.y); |
| 128 | }) |
| 129 | .catch(onError); |
| 130 | }; |
| 131 | return ( |
| 132 | <OfficePages |
| 133 | pages={opened.pages} |
| 134 | paint={opened.paint} |
| 135 | kind="page" |
| 136 | scrollRef={scroll} |
| 137 | onError={onError} |
| 138 | overlay={(index) => ( |
| 139 | <WordTextLayer |
| 140 | engine={opened.engine} |
| 141 | index={index} |
| 142 | page={opened.pages[index]} |
| 143 | follow={follow} |
| 144 | /> |
| 145 | )} |
| 146 | /> |
| 147 | ); |
| 148 | } |
| 149 | |
| 150 | function WordTextLayer(props: { |
| 151 | engine: Opened["engine"]; |
| 152 | index: number; |
| 153 | page: WordPageSize | undefined; |
| 154 | follow: (link: WordLink) => void; |
| 155 | }) { |
| 156 | const { engine, index, page, follow } = props; |
| 157 | const [spans, setSpans] = useState<readonly WordSpan[]>([]); |
| 158 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Request selectable text from the document worker and cancel the request when its page leaves the viewport. |
| 159 | useEffect(() => { |
| 160 | if (!page) return; |
| 161 | const controller = new AbortController(); |
| 162 | void engine |
| 163 | .call("text", { index: index }, { signal: controller.signal }) |
| 164 | .then(setSpans) |
| 165 | .catch(() => undefined); |
| 166 | return () => controller.abort(); |
| 167 | }, [engine, index, page]); |
| 168 | return ( |
| 169 | <div |
| 170 | className="absolute inset-0 select-text overflow-hidden whitespace-pre text-transparent selection:bg-primary/30 selection:text-transparent" |
| 171 | style={{ containerType: "inline-size", fontFamily: layerFont, fontSize: 0, lineHeight }} |
| 172 | > |
| 173 | {spans.map((span, index) => { |
| 174 | const text = ( |
| 175 | <span |
| 176 | dir={span.dir} |
| 177 | role={span.link ? "link" : undefined} |
| 178 | tabIndex={span.link ? 0 : undefined} |
| 179 | aria-label={span.title} |
| 180 | className="absolute origin-top-left" |
| 181 | style={{ |
| 182 | left: `${span.left * 100}%`, |
| 183 | top: `${span.top * 100}%`, |
| 184 | fontSize: `${span.size * 100}cqw`, |
| 185 | transform: span.transform, |
| 186 | cursor: span.link ? "pointer" : "text", |
| 187 | }} |
| 188 | onClick={(event) => { |
| 189 | if (span.link && event.button === 0 && (getSelection()?.isCollapsed ?? true)) |
| 190 | follow(span.link); |
| 191 | }} |
| 192 | onKeyDown={(event) => { |
| 193 | if (span.link && event.key === "Enter") { |
| 194 | event.preventDefault(); |
| 195 | follow(span.link); |
| 196 | } |
| 197 | }} |
| 198 | > |
| 199 | {span.text} |
| 200 | </span> |
| 201 | ); |
| 202 | return ( |
| 203 | <Fragment key={index}> |
| 204 | {span.title ? ( |
| 205 | <Tooltip> |
| 206 | <TooltipTrigger render={text} /> |
| 207 | <TooltipPopup>{span.title}</TooltipPopup> |
| 208 | </Tooltip> |
| 209 | ) : ( |
| 210 | text |
| 211 | )} |
| 212 | {span.after === "br" ? <br /> : span.after === "tab" ? "\t" : null} |
| 213 | </Fragment> |
| 214 | ); |
| 215 | })} |
| 216 | </div> |
| 217 | ); |
| 218 | } |