The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Schema from "effect/Schema"; |
| 2 | import { observeResize } from "~/lib/observeResize"; |
| 3 | import { msg, useGT } from "gt-react"; |
| 4 | import { useEffect, useRef, useState } from "react"; |
| 5 | import { m } from "~/i18n/messages"; |
| 6 | import { |
| 7 | cellAtPoint, |
| 8 | normalizeRange, |
| 9 | selectionAt, |
| 10 | selectionKeyReducer, |
| 11 | extendTo, |
| 12 | hyperlinkAtCell, |
| 13 | safeExternalHyperlink, |
| 14 | parseHyperlinkLocation, |
| 15 | type Selection, |
| 16 | type CellAddr, |
| 17 | } from "@betteroffice/xlsx/headless"; |
| 18 | import { FileSurfaceLoading, FileSurfaceNotice } from "../fileSurfaceChrome"; |
| 19 | import type { WorkbookView } from "../officePreviewProtocol"; |
| 20 | import { createWorkerClient, SupersededError } from "./worker-rpc"; |
| 21 | import type { SheetLayout, SheetMethods, SheetFrameRequest, SheetTab } from "./sheet-protocol"; |
| 22 | import { |
| 23 | coverMerges, |
| 24 | contains, |
| 25 | lastCell, |
| 26 | settleMerges, |
| 27 | skipHidden, |
| 28 | columnName, |
| 29 | } from "./sheet-cells"; |
| 30 | import { |
| 31 | paintCells, |
| 32 | paintHeaders, |
| 33 | paintSelection, |
| 34 | shiftGrid, |
| 35 | headerHeight, |
| 36 | type Painted, |
| 37 | } from "./sheet-paint"; |
| 38 | import { externalUrl } from "./links"; |
| 39 | import { bufferedViewport, cachedViewport, retainCachedViewport } from "./sheet-viewport"; |
| 40 | |
| 41 | const isSupersededError = Schema.is(SupersededError); |
| 42 | |
| 43 | type Client = ReturnType<typeof createWorkerClient<SheetMethods>>; |
| 44 | type Opened = { |
| 45 | engine: Client; |
| 46 | tabs: readonly SheetTab[]; |
| 47 | layout: SheetLayout; |
| 48 | target?: CellAddr | undefined; |
| 49 | }; |
| 50 | export default function Spreadsheet(props: { |
| 51 | bytes: ArrayBuffer; |
| 52 | view: WorkbookView; |
| 53 | onDetails: (text: string) => void; |
| 54 | onError: (cause: unknown) => void; |
| 55 | }) { |
| 56 | const { onError, bytes: source, onDetails, view } = props; |
| 57 | const gt = useGT(); |
| 58 | const [opened, setOpened] = useState<Opened>(); |
| 59 | const [error, setError] = useState(""); |
| 60 | const picking = useRef<AbortController | null>(null); |
| 61 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Open the workbook worker and cancel workbook and sheet requests when the source changes or unmounts. |
| 62 | useEffect(() => { |
| 63 | const controller = new AbortController(); |
| 64 | const worker = new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), { |
| 65 | type: "module", |
| 66 | }); |
| 67 | const engine = createWorkerClient<SheetMethods>(worker); |
| 68 | const fail = (cause: unknown) => { |
| 69 | if (!controller.signal.aborted) onError(cause); |
| 70 | }; |
| 71 | worker.addEventListener("error", fail); |
| 72 | worker.addEventListener("messageerror", fail); |
| 73 | const bytes = source.slice(0); |
| 74 | void engine |
| 75 | .call("open", { bytes, view }, { transfer: [bytes], signal: controller.signal }) |
| 76 | .then((value) => { |
| 77 | if (!value) throw new Error(m(msg("This workbook has no visible sheets."))); |
| 78 | setOpened({ ...value, engine }); |
| 79 | onDetails( |
| 80 | m( |
| 81 | msg("{count, plural, one {{count} sheet} other {{count} sheets}}", { |
| 82 | count: value.tabs.length, |
| 83 | }), |
| 84 | ), |
| 85 | ); |
| 86 | }) |
| 87 | .catch(fail); |
| 88 | return () => { |
| 89 | controller.abort(); |
| 90 | picking.current?.abort(); |
| 91 | engine.close(); |
| 92 | }; |
| 93 | }, [source, view, onDetails, onError]); |
| 94 | const show = (sheet: number, target?: CellAddr) => { |
| 95 | if (!opened) return; |
| 96 | picking.current?.abort(); |
| 97 | if (sheet === opened.layout.info.activeSheet) return; |
| 98 | const controller = new AbortController(); |
| 99 | picking.current = controller; |
| 100 | void opened.engine |
| 101 | .call("show", { sheet }, { signal: controller.signal }) |
| 102 | .then((layout) => { |
| 103 | setError(""); |
| 104 | setOpened({ ...opened, layout, target }); |
| 105 | }) |
| 106 | .catch(() => { |
| 107 | if (!controller.signal.aborted) setError(m(msg("This sheet could not be opened."))); |
| 108 | }); |
| 109 | }; |
| 110 | if (!opened) return <FileSurfaceLoading />; |
| 111 | return ( |
| 112 | <div className="flex min-h-0 flex-1 flex-col"> |
| 113 | {error ? <FileSurfaceNotice>{error}</FileSurfaceNotice> : null} |
| 114 | <SpreadsheetGrid |
| 115 | key={opened.layout.info.activeSheet} |
| 116 | engine={opened.engine} |
| 117 | layout={opened.layout} |
| 118 | initialCell={opened.target} |
| 119 | onNavigate={(name, cell) => { |
| 120 | const tab = opened.tabs.find((tab) => tab.name.toLowerCase() === name.toLowerCase()); |
| 121 | if (tab) show(tab.index, cell); |
| 122 | }} |
| 123 | /> |
| 124 | <div |
| 125 | role="tablist" |
| 126 | aria-label={gt("Sheets")} |
| 127 | className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-t border-border px-2" |
| 128 | onKeyDown={(event) => { |
| 129 | const current = opened.tabs.findIndex( |
| 130 | (tab) => tab.index === opened.layout.info.activeSheet, |
| 131 | ); |
| 132 | const next = |
| 133 | event.key === "ArrowRight" |
| 134 | ? (current + 1) % opened.tabs.length |
| 135 | : event.key === "ArrowLeft" |
| 136 | ? (current + opened.tabs.length - 1) % opened.tabs.length |
| 137 | : event.key === "Home" |
| 138 | ? 0 |
| 139 | : event.key === "End" |
| 140 | ? opened.tabs.length - 1 |
| 141 | : -1; |
| 142 | if (next < 0) return; |
| 143 | event.preventDefault(); |
| 144 | const tab = opened.tabs[next]; |
| 145 | if (tab) show(tab.index); |
| 146 | event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="tab"]')[next]?.focus(); |
| 147 | }} |
| 148 | > |
| 149 | {opened.tabs.map((tab) => ( |
| 150 | <button |
| 151 | key={tab.index} |
| 152 | type="button" |
| 153 | role="tab" |
| 154 | aria-selected={tab.index === opened.layout.info.activeSheet} |
| 155 | tabIndex={tab.index === opened.layout.info.activeSheet ? 0 : -1} |
| 156 | onClick={() => show(tab.index)} |
| 157 | className="h-7 shrink-0 rounded-md px-2.5 text-xs text-muted-foreground hover:bg-accent aria-selected:bg-accent aria-selected:text-foreground" |
| 158 | > |
| 159 | {tab.name} |
| 160 | </button> |
| 161 | ))} |
| 162 | </div> |
| 163 | </div> |
| 164 | ); |
| 165 | } |
| 166 | |
| 167 | function SpreadsheetGrid(props: { |
| 168 | engine: Client; |
| 169 | layout: SheetLayout; |
| 170 | initialCell: CellAddr | undefined; |
| 171 | onNavigate: (sheet: string, cell: CellAddr) => void; |
| 172 | }) { |
| 173 | const { onNavigate, layout, engine, initialCell } = props; |
| 174 | const scroller = useRef<HTMLDivElement>(null); |
| 175 | const canvas = useRef<HTMLCanvasElement>(null); |
| 176 | const spacer = useRef<HTMLDivElement>(null); |
| 177 | const columnHeaderBand = useRef<HTMLDivElement>(null); |
| 178 | const rowHeaderBand = useRef<HTMLDivElement>(null); |
| 179 | const [notice, setNotice] = useState(""); |
| 180 | const [reader, setReader] = useState<{ row: number; col: number; text: string }[]>([]); |
| 181 | const [active, setActive] = useState({ row: 0, col: 0 }); |
| 182 | const navigate = useRef(onNavigate); |
| 183 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Keep the installed native pointer listener calling the latest navigation handler without restarting the canvas engine. |
| 184 | useEffect(() => { |
| 185 | navigate.current = onNavigate; |
| 186 | }, [onNavigate]); |
| 187 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own canvas painting, worker requests, resize observation, and native scroll, keyboard, and pointer listeners for this sheet. |
| 188 | useEffect(() => { |
| 189 | const root = scroller.current; |
| 190 | const target = canvas.current; |
| 191 | const space = spacer.current; |
| 192 | const columns = columnHeaderBand.current; |
| 193 | const rows = rowHeaderBand.current; |
| 194 | if (!root || !target || !space || !columns || !rows) return; |
| 195 | const context = target.getContext("2d"); |
| 196 | if (!context) return; |
| 197 | const controller = new AbortController(); |
| 198 | let info = layout.info; |
| 199 | let chartWidth = layout.chartWidth; |
| 200 | let chartHeight = layout.chartHeight; |
| 201 | const sheet = info.activeSheet; |
| 202 | const frozen = { rows: info.frozenRows, cols: info.frozenCols }; |
| 203 | const headers = { width: 44, height: headerHeight }; |
| 204 | let selection: Selection = selectionAt(initialCell ?? { row: 0, col: 0 }); |
| 205 | let painted: Painted | undefined; |
| 206 | let grid: ReturnType<typeof shiftGrid> | undefined; |
| 207 | let raf = 0; |
| 208 | let requested = ""; |
| 209 | let sent = 0; |
| 210 | let received = 0; |
| 211 | let drag = false; |
| 212 | let resizing: |
| 213 | | { |
| 214 | axis: "row" | "column"; |
| 215 | pointerId: number; |
| 216 | index: number; |
| 217 | start: number; |
| 218 | edge: number; |
| 219 | delta: number; |
| 220 | } |
| 221 | | undefined; |
| 222 | let resizingPending = false; |
| 223 | let header: "row" | "column" | "all" | undefined; |
| 224 | let pressed: { row: number; col: number } | undefined; |
| 225 | let end: { x: number; y: number } | undefined; |
| 226 | let left = info.initialScrollX; |
| 227 | let top = info.initialScrollY; |
| 228 | let drawn = { x: left, y: top }; |
| 229 | let reachX = 0; |
| 230 | let reachY = 0; |
| 231 | let readController: AbortController | undefined; |
| 232 | const range = () => coverMerges(normalizeRange(selection), layout.merges); |
| 233 | const at = (cell: { row: number; col: number }) => { |
| 234 | const merge = layout.merges.find((item) => contains(item, cell)); |
| 235 | return selectionAt(merge ? { row: merge.top, col: merge.left } : cell); |
| 236 | }; |
| 237 | const schedule = () => { |
| 238 | if (raf || controller.signal.aborted) return; |
| 239 | raf = requestAnimationFrame(() => { |
| 240 | raf = 0; |
| 241 | paint(); |
| 242 | }); |
| 243 | }; |
| 244 | const resizeArea = () => { |
| 245 | const width = Math.min( |
| 246 | (end?.x ?? Infinity) + (painted?.frame.frozen.width ?? 0), |
| 247 | Math.max(info.contentWidth, chartWidth, reachX, left + root.clientWidth) + root.clientWidth, |
| 248 | ); |
| 249 | const height = Math.min( |
| 250 | (end?.y ?? Infinity) + (painted?.frame.frozen.height ?? 0), |
| 251 | Math.max(info.contentHeight, chartHeight, reachY, top + root.clientHeight) + |
| 252 | root.clientHeight, |
| 253 | ); |
| 254 | space.style.width = `${headers.width + width}px`; |
| 255 | space.style.height = `${headers.height + height}px`; |
| 256 | }; |
| 257 | const paint = () => { |
| 258 | const ratio = window.devicePixelRatio || 1; |
| 259 | const width = root.clientWidth; |
| 260 | const height = root.clientHeight; |
| 261 | const size = { width: width - headers.width, height: height - headers.height }; |
| 262 | if (size.width <= 0 || size.height <= 0) return; |
| 263 | columns.style.width = `${size.width}px`; |
| 264 | rows.style.height = `${size.height}px`; |
| 265 | left = root.scrollLeft; |
| 266 | top = root.scrollTop; |
| 267 | resizeArea(); |
| 268 | const viewport = { x: left, y: top, ...size }; |
| 269 | drawn = painted ? cachedViewport(painted.frame.viewport, viewport) : viewport; |
| 270 | const input: SheetFrameRequest = { |
| 271 | sheet, |
| 272 | x: left, |
| 273 | y: top, |
| 274 | ...size, |
| 275 | ratio, |
| 276 | offset: { x: 0, y: 0 }, |
| 277 | wider: bufferedViewport(viewport), |
| 278 | }; |
| 279 | const key = JSON.stringify(input); |
| 280 | const needsFrame = |
| 281 | !painted || |
| 282 | requested === "" || |
| 283 | drawn.x !== left || |
| 284 | drawn.y !== top || |
| 285 | painted.request.width !== size.width || |
| 286 | painted.request.height !== size.height || |
| 287 | painted.request.ratio !== ratio; |
| 288 | if (needsFrame && key !== requested) { |
| 289 | requested = key; |
| 290 | sent += 1; |
| 291 | const order = sent; |
| 292 | void engine |
| 293 | .call("frame", input, { key: "frame", signal: controller.signal }) |
| 294 | .then((reply) => { |
| 295 | if (order < received || controller.signal.aborted) { |
| 296 | reply?.bitmap.close(); |
| 297 | return; |
| 298 | } |
| 299 | received = order; |
| 300 | if (!reply) { |
| 301 | if (requested === key) requested = ""; |
| 302 | setNotice(m(msg("These cells could not be drawn. Try scrolling to another area."))); |
| 303 | return; |
| 304 | } |
| 305 | if ( |
| 306 | painted && |
| 307 | retainCachedViewport(painted.frame.viewport, reply.viewport, { |
| 308 | x: root.scrollLeft, |
| 309 | y: root.scrollTop, |
| 310 | width: root.clientWidth - headers.width, |
| 311 | height: root.clientHeight - headers.height, |
| 312 | }) |
| 313 | ) { |
| 314 | reply.bitmap.close(); |
| 315 | if (requested === key) requested = JSON.stringify(painted.request); |
| 316 | return; |
| 317 | } |
| 318 | setNotice(""); |
| 319 | painted?.frame.bitmap.close(); |
| 320 | painted = { request: input, frame: reply }; |
| 321 | end = reply.end; |
| 322 | schedule(); |
| 323 | }) |
| 324 | .catch((cause: unknown) => { |
| 325 | if (!isSupersededError(cause) && !controller.signal.aborted) { |
| 326 | if (requested === key) requested = ""; |
| 327 | setNotice(m(msg("These cells could not be drawn."))); |
| 328 | } |
| 329 | }); |
| 330 | } |
| 331 | if ( |
| 332 | target.width !== Math.round(width * ratio) || |
| 333 | target.height !== Math.round(height * ratio) |
| 334 | ) { |
| 335 | target.width = Math.round(width * ratio); |
| 336 | target.height = Math.round(height * ratio); |
| 337 | target.style.width = `${width}px`; |
| 338 | target.style.height = `${height}px`; |
| 339 | } |
| 340 | if (!painted) { |
| 341 | context.fillStyle = "#fff"; |
| 342 | context.fillRect(0, 0, target.width, target.height); |
| 343 | return; |
| 344 | } |
| 345 | paintCells(context, painted, { ratio, headers, ...drawn, ...size }); |
| 346 | grid = |
| 347 | painted.frame.grid && |
| 348 | shiftGrid(painted.frame.grid, frozen, painted.frame.frozen, { |
| 349 | x: painted.frame.viewport.x - drawn.x, |
| 350 | y: painted.frame.viewport.y - drawn.y, |
| 351 | }); |
| 352 | if (!grid) return; |
| 353 | const anchor = selection.anchor; |
| 354 | paintSelection(context, { |
| 355 | grid, |
| 356 | ratio, |
| 357 | headers, |
| 358 | ...size, |
| 359 | range: range(), |
| 360 | active: coverMerges( |
| 361 | { top: anchor.row, left: anchor.col, bottom: anchor.row, right: anchor.col }, |
| 362 | layout.merges, |
| 363 | ), |
| 364 | }); |
| 365 | paintHeaders(context, { grid, ratio, headers, width, height, selected: range() }); |
| 366 | if (resizing) { |
| 367 | const edge = resizing.edge + resizing.delta; |
| 368 | context.save(); |
| 369 | context.setTransform(ratio, 0, 0, ratio, 0, 0); |
| 370 | context.strokeStyle = "#217346"; |
| 371 | context.lineWidth = 1; |
| 372 | context.setLineDash([4, 3]); |
| 373 | context.beginPath(); |
| 374 | if (resizing.axis === "column") { |
| 375 | context.moveTo(edge + headers.width, 0); |
| 376 | context.lineTo(edge + headers.width, height); |
| 377 | } else { |
| 378 | context.moveTo(0, edge + headers.height); |
| 379 | context.lineTo(width, edge + headers.height); |
| 380 | } |
| 381 | context.stroke(); |
| 382 | context.restore(); |
| 383 | } |
| 384 | }; |
| 385 | const read = () => { |
| 386 | const focus = selection.focus; |
| 387 | setActive(focus); |
| 388 | readController?.abort(); |
| 389 | readController = new AbortController(); |
| 390 | const top = Math.max(0, focus.row - 5); |
| 391 | const left = Math.max(0, focus.col - 3); |
| 392 | const range = { |
| 393 | top, |
| 394 | left, |
| 395 | bottom: Math.min(lastCell.row, top + 10), |
| 396 | right: Math.min(lastCell.col, left + 6), |
| 397 | }; |
| 398 | void engine |
| 399 | .call("cells", { sheet, range }, { key: "reader", signal: readController.signal }) |
| 400 | .then((rows) => { |
| 401 | if (!controller.signal.aborted) |
| 402 | setReader( |
| 403 | rows.flatMap((row, r) => |
| 404 | row.map((text, c) => ({ row: top + r, col: left + c, text })), |
| 405 | ), |
| 406 | ); |
| 407 | }) |
| 408 | .catch(() => undefined); |
| 409 | }; |
| 410 | const select = (next: Selection) => { |
| 411 | selection = next; |
| 412 | read(); |
| 413 | schedule(); |
| 414 | }; |
| 415 | const reveal = () => { |
| 416 | const cell = selection.focus; |
| 417 | void engine |
| 418 | .call("position", { sheet, cell }, { key: "position", signal: controller.signal }) |
| 419 | .then((position) => { |
| 420 | if (!position || controller.signal.aborted) return; |
| 421 | const panes = painted?.frame.frozen ?? { width: 0, height: 0 }; |
| 422 | const place = (start: number, next: number, current: number, visible: number) => |
| 423 | start < current ? start : next > current + visible ? next - visible : current; |
| 424 | const x = |
| 425 | cell.col < info.frozenCols |
| 426 | ? left |
| 427 | : place( |
| 428 | position.start.x, |
| 429 | position.next.x, |
| 430 | left, |
| 431 | root.clientWidth - headers.width - panes.width, |
| 432 | ); |
| 433 | const y = |
| 434 | cell.row < info.frozenRows |
| 435 | ? top |
| 436 | : place( |
| 437 | position.start.y, |
| 438 | position.next.y, |
| 439 | top, |
| 440 | root.clientHeight - headers.height - panes.height, |
| 441 | ); |
| 442 | reachX = Math.max(reachX, x + root.clientWidth); |
| 443 | reachY = Math.max(reachY, y + root.clientHeight); |
| 444 | resizeArea(); |
| 445 | root.scrollTo({ left: Math.max(0, x), top: Math.max(0, y) }); |
| 446 | schedule(); |
| 447 | }) |
| 448 | .catch(() => undefined); |
| 449 | }; |
| 450 | const hit = (event: PointerEvent) => { |
| 451 | if (!grid) return; |
| 452 | const rect = target.getBoundingClientRect(); |
| 453 | const x = event.clientX - rect.left - headers.width; |
| 454 | const y = event.clientY - rect.top - headers.height; |
| 455 | const frame = painted?.frame; |
| 456 | if ( |
| 457 | frame && |
| 458 | ((x >= frame.frozen.width && x < frame.frozen.width + frame.viewport.x - drawn.x) || |
| 459 | (y >= frame.frozen.height && y < frame.frozen.height + frame.viewport.y - drawn.y)) |
| 460 | ) |
| 461 | return; |
| 462 | const cell = cellAtPoint( |
| 463 | grid, |
| 464 | Math.max(0, Math.min(x, root.clientWidth - headers.width - 1)), |
| 465 | Math.max(0, Math.min(y, root.clientHeight - headers.height - 1)), |
| 466 | ); |
| 467 | return cell ? { cell, x, y } : undefined; |
| 468 | }; |
| 469 | const resizeHit = (event: PointerEvent) => { |
| 470 | if (!grid || resizingPending) return; |
| 471 | const rect = target.getBoundingClientRect(); |
| 472 | const x = event.clientX - rect.left - headers.width; |
| 473 | const y = event.clientY - rect.top - headers.height; |
| 474 | const axis: "row" | "column" | undefined = |
| 475 | x >= 0 && y < 0 ? "column" : y >= 0 && x < 0 ? "row" : undefined; |
| 476 | if (!axis) return; |
| 477 | const offsets = axis === "column" ? grid.colOffsets : grid.rowOffsets; |
| 478 | const indices = axis === "column" ? grid.colIndices : grid.rowIndices; |
| 479 | const start = axis === "column" ? grid.startCol : grid.startRow; |
| 480 | const point = axis === "column" ? x : y; |
| 481 | for (let i = 1; i < offsets.length; i++) { |
| 482 | const edge = offsets[i]!; |
| 483 | const size = edge - offsets[i - 1]!; |
| 484 | if (edge > 0 && size > 0 && Math.abs(point - edge) <= 4) |
| 485 | return { |
| 486 | axis, |
| 487 | pointerId: event.pointerId, |
| 488 | index: indices?.[i - 1] ?? start + i - 1, |
| 489 | start: axis === "column" ? event.clientX : event.clientY, |
| 490 | delta: 0, |
| 491 | edge, |
| 492 | } satisfies NonNullable<typeof resizing>; |
| 493 | } |
| 494 | }; |
| 495 | const pointerDown = (event: PointerEvent) => { |
| 496 | if (event.button !== 0 || resizingPending || resizing) return; |
| 497 | const track = resizeHit(event); |
| 498 | if (track) { |
| 499 | event.preventDefault(); |
| 500 | root.focus({ preventScroll: true }); |
| 501 | root.setPointerCapture(event.pointerId); |
| 502 | resizing = track; |
| 503 | pressed = undefined; |
| 504 | schedule(); |
| 505 | return; |
| 506 | } |
| 507 | const found = hit(event); |
| 508 | if (!found) return; |
| 509 | root.focus({ preventScroll: true }); |
| 510 | root.setPointerCapture(event.pointerId); |
| 511 | drag = true; |
| 512 | header = found.x < 0 ? (found.y < 0 ? "all" : "row") : found.y < 0 ? "column" : undefined; |
| 513 | pressed = header ? undefined : found.cell; |
| 514 | if (found.x < 0 && found.y < 0) |
| 515 | select({ anchor: { row: lastCell.row, col: lastCell.col }, focus: { row: 0, col: 0 } }); |
| 516 | else if (found.x < 0) |
| 517 | select({ |
| 518 | anchor: { row: found.cell.row, col: lastCell.col }, |
| 519 | focus: { row: found.cell.row, col: 0 }, |
| 520 | }); |
| 521 | else if (found.y < 0) |
| 522 | select({ |
| 523 | anchor: { row: lastCell.row, col: found.cell.col }, |
| 524 | focus: { row: 0, col: found.cell.col }, |
| 525 | }); |
| 526 | else select(event.shiftKey ? extendTo(selection, found.cell) : at(found.cell)); |
| 527 | }; |
| 528 | const pointerMove = (event: PointerEvent) => { |
| 529 | if (resizing) { |
| 530 | if (event.pointerId !== resizing.pointerId) return; |
| 531 | const point = resizing.axis === "column" ? event.clientX : event.clientY; |
| 532 | resizing.delta = Math.round(point - resizing.start); |
| 533 | schedule(); |
| 534 | return; |
| 535 | } |
| 536 | const hovered = resizeHit(event); |
| 537 | root.style.cursor = hovered ? (hovered.axis === "column" ? "col-resize" : "row-resize") : ""; |
| 538 | if (!drag) return; |
| 539 | const found = hit(event); |
| 540 | if (found && header !== "all") |
| 541 | select( |
| 542 | extendTo(selection, { |
| 543 | row: header === "column" ? 0 : found.cell.row, |
| 544 | col: header === "row" ? 0 : found.cell.col, |
| 545 | }), |
| 546 | ); |
| 547 | }; |
| 548 | const pointerUp = (event: PointerEvent) => { |
| 549 | if (resizing) { |
| 550 | if (event.pointerId !== resizing.pointerId) return; |
| 551 | const track = resizing; |
| 552 | resizing = undefined; |
| 553 | root.style.cursor = ""; |
| 554 | root.releasePointerCapture(event.pointerId); |
| 555 | schedule(); |
| 556 | if (track.delta === 0) return; |
| 557 | resizingPending = true; |
| 558 | setNotice(m(msg("Resizing preview..."))); |
| 559 | void engine |
| 560 | .call( |
| 561 | "resize", |
| 562 | { sheet, axis: track.axis, index: track.index, delta: track.delta }, |
| 563 | { signal: controller.signal }, |
| 564 | ) |
| 565 | .then((nextLayout) => { |
| 566 | if (controller.signal.aborted) return; |
| 567 | info = nextLayout.info; |
| 568 | chartWidth = nextLayout.chartWidth; |
| 569 | chartHeight = nextLayout.chartHeight; |
| 570 | painted?.frame.bitmap.close(); |
| 571 | painted = undefined; |
| 572 | grid = undefined; |
| 573 | sent += 1; |
| 574 | received = sent; |
| 575 | requested = ""; |
| 576 | end = undefined; |
| 577 | schedule(); |
| 578 | }) |
| 579 | .catch(() => { |
| 580 | if (!controller.signal.aborted) |
| 581 | setNotice(m(msg("This row or column could not be resized."))); |
| 582 | }) |
| 583 | .finally(() => { |
| 584 | resizingPending = false; |
| 585 | }); |
| 586 | return; |
| 587 | } |
| 588 | drag = false; |
| 589 | const found = hit(event); |
| 590 | if (!found || !pressed || found.cell.row !== pressed.row || found.cell.col !== pressed.col) |
| 591 | return; |
| 592 | const cell = at(found.cell).anchor; |
| 593 | const list = painted?.frame; |
| 594 | if (!list) return; |
| 595 | const link = hyperlinkAtCell( |
| 596 | { width: 0, height: 0, commands: [], hyperlinks: [...list.hyperlinks] }, |
| 597 | cell.row, |
| 598 | cell.col, |
| 599 | ); |
| 600 | if (!link) return; |
| 601 | const url = safeExternalHyperlink(link); |
| 602 | const safe = url && externalUrl(url); |
| 603 | if (safe) { |
| 604 | window.open(safe, "_blank", "noopener,noreferrer"); |
| 605 | return; |
| 606 | } |
| 607 | const internal = |
| 608 | link.location && parseHyperlinkLocation(link.location, info.sheetNames[sheet] ?? ""); |
| 609 | if (!internal) return; |
| 610 | if (internal.sheetName.toLowerCase() !== (info.sheetNames[sheet] ?? "").toLowerCase()) |
| 611 | navigate.current(internal.sheetName, { row: internal.row, col: internal.col }); |
| 612 | else { |
| 613 | select(at({ row: internal.row, col: internal.col })); |
| 614 | reveal(); |
| 615 | } |
| 616 | }; |
| 617 | const copy = () => { |
| 618 | const used = layout.used; |
| 619 | const selected = range(); |
| 620 | const clipped = { |
| 621 | ...selected, |
| 622 | bottom: Math.min(selected.bottom, Math.max(selected.top, used?.bottom ?? 0)), |
| 623 | right: Math.min(selected.right, Math.max(selected.left, used?.right ?? 0)), |
| 624 | }; |
| 625 | if ((clipped.bottom - clipped.top + 1) * (clipped.right - clipped.left + 1) > 200_000) { |
| 626 | setNotice(m(msg("Select fewer than 200,000 cells to copy."))); |
| 627 | return; |
| 628 | } |
| 629 | void engine |
| 630 | .call("copy", { sheet, range: clipped }, { signal: controller.signal }) |
| 631 | .then((text) => { |
| 632 | if (text === undefined) throw new Error("No cells"); |
| 633 | return navigator.clipboard.writeText(text); |
| 634 | }) |
| 635 | .catch(() => { |
| 636 | if (!controller.signal.aborted) |
| 637 | setNotice(m(msg("The selected cells could not be copied."))); |
| 638 | }); |
| 639 | }; |
| 640 | const key = (event: KeyboardEvent) => { |
| 641 | if (event.key === "Escape" && resizing) { |
| 642 | event.preventDefault(); |
| 643 | resizing = undefined; |
| 644 | root.style.cursor = ""; |
| 645 | schedule(); |
| 646 | return; |
| 647 | } |
| 648 | const command = event.ctrlKey || event.metaKey; |
| 649 | if (command && event.key.toLowerCase() === "c") { |
| 650 | event.preventDefault(); |
| 651 | copy(); |
| 652 | return; |
| 653 | } |
| 654 | if (event.key === "Tab" || event.altKey || event.isComposing) return; |
| 655 | const action = selectionKeyReducer(selection, event, { |
| 656 | rows: Math.max((layout.used?.bottom ?? 0) + 1, selection.focus.row + 1), |
| 657 | cols: Math.max((layout.used?.right ?? 0) + 1, selection.focus.col + 1), |
| 658 | rowsPerPage: Math.max(1, Math.floor((root.clientHeight - headerHeight) / 20)), |
| 659 | }); |
| 660 | if (action.type !== "move") return; |
| 661 | event.preventDefault(); |
| 662 | select( |
| 663 | skipHidden( |
| 664 | selection.focus, |
| 665 | settleMerges(selection, action.selection, layout.merges), |
| 666 | layout.hidden, |
| 667 | ), |
| 668 | ); |
| 669 | reveal(); |
| 670 | }; |
| 671 | const cancel = (event: PointerEvent) => { |
| 672 | if (resizing && event.pointerId !== resizing.pointerId) return; |
| 673 | drag = false; |
| 674 | pressed = undefined; |
| 675 | resizing = undefined; |
| 676 | root.style.cursor = ""; |
| 677 | schedule(); |
| 678 | }; |
| 679 | const leave = () => { |
| 680 | if (!drag && !resizing) root.style.cursor = ""; |
| 681 | }; |
| 682 | root.addEventListener("scroll", schedule); |
| 683 | root.addEventListener("keydown", key); |
| 684 | root.addEventListener("pointerdown", pointerDown); |
| 685 | root.addEventListener("pointermove", pointerMove); |
| 686 | root.addEventListener("pointerup", pointerUp); |
| 687 | root.addEventListener("pointercancel", cancel); |
| 688 | root.addEventListener("lostpointercapture", cancel); |
| 689 | root.addEventListener("pointerleave", leave); |
| 690 | const unobserve = observeResize(root, schedule); |
| 691 | window.addEventListener("resize", schedule); |
| 692 | resizeArea(); |
| 693 | root.scrollTo({ left, top }); |
| 694 | if (initialCell) { |
| 695 | selection = at(initialCell); |
| 696 | reveal(); |
| 697 | } |
| 698 | read(); |
| 699 | schedule(); |
| 700 | return () => { |
| 701 | controller.abort(); |
| 702 | readController?.abort(); |
| 703 | cancelAnimationFrame(raf); |
| 704 | unobserve(); |
| 705 | window.removeEventListener("resize", schedule); |
| 706 | painted?.frame.bitmap.close(); |
| 707 | root.removeEventListener("scroll", schedule); |
| 708 | root.removeEventListener("keydown", key); |
| 709 | root.removeEventListener("pointerdown", pointerDown); |
| 710 | root.removeEventListener("pointermove", pointerMove); |
| 711 | root.removeEventListener("pointerup", pointerUp); |
| 712 | root.removeEventListener("pointercancel", cancel); |
| 713 | root.removeEventListener("lostpointercapture", cancel); |
| 714 | root.removeEventListener("pointerleave", leave); |
| 715 | }; |
| 716 | }, [engine, layout, initialCell]); |
| 717 | return ( |
| 718 | <div className="relative flex min-h-0 flex-1"> |
| 719 | <div |
| 720 | ref={scroller} |
| 721 | dir="ltr" |
| 722 | tabIndex={0} |
| 723 | role="grid" |
| 724 | aria-label={layout.info.sheetNames[layout.info.activeSheet]} |
| 725 | aria-readonly="true" |
| 726 | aria-multiselectable="true" |
| 727 | aria-rowcount={lastCell.row + 1} |
| 728 | aria-colcount={lastCell.col + 1} |
| 729 | aria-activedescendant={`office-cell-${active.row}-${active.col}`} |
| 730 | // The sheet is white in every theme, so its scrollbars keep the light theme's thumb. |
| 731 | className="relative min-h-0 min-w-0 flex-1 select-none overflow-auto bg-white scheme-light outline-none [--app-scrollbar-thumb-hover:rgb(191_191_191)] [--app-scrollbar-thumb:rgb(217_217_217)] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring" |
| 732 | > |
| 733 | <div |
| 734 | ref={spacer} |
| 735 | aria-hidden="true" |
| 736 | className="pointer-events-none absolute left-0 top-0" |
| 737 | /> |
| 738 | <div aria-hidden="true" className="sticky left-0 top-0 h-0 w-0"> |
| 739 | <canvas ref={canvas} className="absolute left-0 top-0 block" /> |
| 740 | <div ref={columnHeaderBand} className="absolute left-11 top-0 h-5 touch-none" /> |
| 741 | <div ref={rowHeaderBand} className="absolute left-0 top-5 w-11 touch-none" /> |
| 742 | </div> |
| 743 | <div className="sr-only"> |
| 744 | {[...new Set(reader.map((cell) => cell.row))].map((row) => ( |
| 745 | <div key={row} role="row" aria-rowindex={row + 1}> |
| 746 | {reader |
| 747 | .filter((cell) => cell.row === row) |
| 748 | .map((cell) => ( |
| 749 | <span |
| 750 | key={cell.col} |
| 751 | role="gridcell" |
| 752 | id={`office-cell-${cell.row}-${cell.col}`} |
| 753 | aria-colindex={cell.col + 1} |
| 754 | aria-label={`${columnName(cell.col)}${cell.row + 1}`} |
| 755 | > |
| 756 | {cell.text} |
| 757 | </span> |
| 758 | ))} |
| 759 | </div> |
| 760 | ))} |
| 761 | </div> |
| 762 | </div> |
| 763 | {notice ? ( |
| 764 | <div |
| 765 | role="status" |
| 766 | className="absolute inset-x-3 bottom-3 rounded-md bg-background p-2 text-xs text-foreground shadow-md" |
| 767 | > |
| 768 | {notice} |
| 769 | </div> |
| 770 | ) : null} |
| 771 | </div> |
| 772 | ); |
| 773 | } |