The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | // Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode. |
| 2 | import { |
| 3 | initWasm, |
| 4 | openWorkbook, |
| 5 | toTsv, |
| 6 | type SheetInfo, |
| 7 | type WorkbookHandle, |
| 8 | type XlsxCellRead, |
| 9 | type XlsxRangeTarget, |
| 10 | } from "@betteroffice/xlsx"; |
| 11 | import type { CellRange } from "@betteroffice/xlsx/headless"; |
| 12 | import { anchorRange, attempt, lastCell, parseRange, parseSpans } from "./sheet-cells"; |
| 13 | import type { WorkbookView } from "../officePreviewProtocol"; |
| 14 | import { chartFonts, drawFrame, paintFrame, withoutGridlines } from "./sheet-frame"; |
| 15 | import { maximumTrackSize, minimumTrackSize } from "./sheet-sizing"; |
| 16 | import { sheetFonts } from "./sheet-fonts"; |
| 17 | import { frozenSize } from "./sheet-paint"; |
| 18 | import type { SheetLayout, SheetMethods, SheetTab } from "./sheet-protocol"; |
| 19 | import { serveWorker, Transfer } from "./worker-rpc"; |
| 20 | |
| 21 | // One worker holds one open workbook: its engine, recalculation, display lists and the painting of its cells. The |
| 22 | // window terminates the worker when the workbook closes, which is the only way the engine's memory is given back. |
| 23 | |
| 24 | type Opened = { |
| 25 | readonly workbook: WorkbookHandle; |
| 26 | /** The active sheet's metadata; the engine draws only the active sheet. */ |
| 27 | info: SheetInfo; |
| 28 | /** Where each sheet's last cell ends, by sheet and frozen panes' size; measured once, as it costs a frame. */ |
| 29 | readonly ends: Map<string, { readonly x: number; readonly y: number } | undefined>; |
| 30 | /** The one canvas every frame paints on and hands over as a bitmap. */ |
| 31 | readonly surface: OffscreenCanvas; |
| 32 | /** The sheets whose view hides gridlines, which the engine draws on every sheet. */ |
| 33 | readonly hiddenGridlines: ReadonlySet<number>; |
| 34 | readonly themeFonts: WorkbookView["themeFonts"]; |
| 35 | }; |
| 36 | |
| 37 | /** The workbook this worker opened, once it has. */ |
| 38 | type State = { opened: Opened | undefined }; |
| 39 | |
| 40 | const state: State = { opened: undefined }; |
| 41 | |
| 42 | const loadFonts = sheetFonts(); |
| 43 | |
| 44 | serveWorker<SheetMethods>({ |
| 45 | open: async (input) => { |
| 46 | if (state.opened) throw new Error("The worker already holds a workbook"); |
| 47 | |
| 48 | await initWasm(); |
| 49 | |
| 50 | const workbook = openWorkbook(new Uint8Array(input.bytes)); |
| 51 | const info = workbook.sheetInfo(); |
| 52 | |
| 53 | state.opened = { |
| 54 | workbook, |
| 55 | info, |
| 56 | ends: new Map(), |
| 57 | surface: new OffscreenCanvas(1, 1), |
| 58 | hiddenGridlines: new Set(input.view.hiddenGridlines), |
| 59 | themeFonts: input.view.themeFonts, |
| 60 | }; |
| 61 | |
| 62 | const tabs = visibleTabs(workbook, info); |
| 63 | // A workbook saved on a hidden sheet opens on the first visible one, as Excel does. |
| 64 | const first = tabs.find((tab) => tab.index === info.activeSheet) ?? tabs[0]; |
| 65 | |
| 66 | if (!first) return undefined; |
| 67 | |
| 68 | return { tabs, layout: show(state.opened, first.index) }; |
| 69 | }, |
| 70 | show: (input) => { |
| 71 | const opened = required(); |
| 72 | const current = opened.info.activeSheet; |
| 73 | const layout = attempt(() => show(opened, input.sheet)); |
| 74 | |
| 75 | if (layout) return layout; |
| 76 | |
| 77 | // One sheet that fails to open leaves the others readable: go back to the sheet on show. |
| 78 | attempt(() => show(opened, current)); |
| 79 | |
| 80 | throw new Error(`Sheet ${input.sheet} could not open`); |
| 81 | }, |
| 82 | resize: (input) => { |
| 83 | const opened = active(input.sheet); |
| 84 | if ( |
| 85 | !Number.isInteger(input.index) || |
| 86 | input.index < 0 || |
| 87 | input.index > (input.axis === "row" ? lastCell.row : lastCell.col) || |
| 88 | !Number.isFinite(input.delta) |
| 89 | ) |
| 90 | throw new Error("Invalid track resize"); |
| 91 | const rect = opened.workbook.cellRect( |
| 92 | input.sheet, |
| 93 | input.axis === "row" ? input.index : 0, |
| 94 | input.axis === "column" ? input.index : 0, |
| 95 | ); |
| 96 | const current = input.axis === "column" ? rect.w : rect.h; |
| 97 | const size = Math.max( |
| 98 | minimumTrackSize, |
| 99 | Math.min(maximumTrackSize[input.axis], current + input.delta), |
| 100 | ); |
| 101 | const operation = |
| 102 | input.axis === "column" |
| 103 | ? { type: "setColWidth", sheet: input.sheet, col: input.index, width: (size - 5) / 7 } |
| 104 | : { type: "setRowHeight", sheet: input.sheet, row: input.index, height: size * 0.75 }; |
| 105 | opened.info = opened.workbook.applyOps([operation]).sheetInfo; |
| 106 | opened.ends.clear(); |
| 107 | const { chartWidth, chartHeight } = layout(opened.workbook, input.sheet); |
| 108 | return { info: opened.info, chartWidth, chartHeight }; |
| 109 | }, |
| 110 | frame: async (input) => { |
| 111 | const opened = active(input.sheet); |
| 112 | const frozen = { rows: opened.info.frozenRows, cols: opened.info.frozenCols }; |
| 113 | const viewport = { x: input.x, y: input.y, width: input.width, height: input.height }; |
| 114 | const frame = drawFrame(opened.workbook, viewport, frozen, input.wider); |
| 115 | |
| 116 | if (!frame) return undefined; |
| 117 | |
| 118 | const drawn = chartFonts( |
| 119 | opened.hiddenGridlines.has(input.sheet) ? withoutGridlines(frame) : frame, |
| 120 | opened.themeFonts, |
| 121 | ); |
| 122 | |
| 123 | await loadFonts(drawn.tiles.map((tile) => tile.list)); |
| 124 | |
| 125 | const surface = opened.surface; |
| 126 | const width = Math.ceil(input.offset.x + drawn.viewport.width * input.ratio); |
| 127 | const height = Math.ceil(input.offset.y + drawn.viewport.height * input.ratio); |
| 128 | |
| 129 | if (surface.width !== width) surface.width = width; |
| 130 | |
| 131 | if (surface.height !== height) surface.height = height; |
| 132 | |
| 133 | const context = surface.getContext("2d"); |
| 134 | |
| 135 | if (!context) return undefined; |
| 136 | |
| 137 | paintFrame(context, drawn, { ratio: input.ratio, origin: input.offset }); |
| 138 | |
| 139 | const bitmap = surface.transferToImageBitmap(); |
| 140 | const grid = drawn.list.grid; |
| 141 | const panes = frozenSize(grid, frozen); |
| 142 | |
| 143 | return new Transfer( |
| 144 | { |
| 145 | bitmap, |
| 146 | viewport: drawn.viewport, |
| 147 | grid, |
| 148 | hyperlinks: drawn.list.hyperlinks ?? [], |
| 149 | frozen: panes, |
| 150 | end: end(opened, input.sheet, panes), |
| 151 | }, |
| 152 | [bitmap], |
| 153 | ); |
| 154 | }, |
| 155 | position: (input) => { |
| 156 | const workbook = required().workbook; |
| 157 | const cell = input.cell; |
| 158 | const start = attempt(() => workbook.cellPosition(input.sheet, cell.row, cell.col)); |
| 159 | |
| 160 | const next = attempt(() => |
| 161 | workbook.cellPosition( |
| 162 | input.sheet, |
| 163 | Math.min(cell.row + 1, lastCell.row), |
| 164 | Math.min(cell.col + 1, lastCell.col), |
| 165 | ), |
| 166 | ); |
| 167 | |
| 168 | return start && next ? { start, next } : undefined; |
| 169 | }, |
| 170 | cells: (input) => { |
| 171 | const cells = read(required(), input.sheet, input.range); |
| 172 | const range = input.range; |
| 173 | |
| 174 | return Array.from({ length: range.bottom - range.top + 1 }, (_, row) => |
| 175 | Array.from( |
| 176 | { length: range.right - range.left + 1 }, |
| 177 | (_, col) => cells?.[row]?.[col]?.displayText ?? "", |
| 178 | ), |
| 179 | ); |
| 180 | }, |
| 181 | // Copies the cells as they show, which is what a reader expects to paste, not the formulas behind them. |
| 182 | copy: (input) => { |
| 183 | const cells = read(required(), input.sheet, input.range); |
| 184 | |
| 185 | if (!cells) return undefined; |
| 186 | |
| 187 | return toTsv( |
| 188 | cells.map((row) => |
| 189 | row.map((cell) => ({ input: cell.displayText, isFormula: literal(cell) })), |
| 190 | ), |
| 191 | ); |
| 192 | }, |
| 193 | }); |
| 194 | |
| 195 | function required() { |
| 196 | if (!state.opened) throw new Error("The worker holds no workbook"); |
| 197 | |
| 198 | return state.opened; |
| 199 | } |
| 200 | |
| 201 | /** The workbook with `sheet` active, as a frame from a grid that has since given way to another sheet may ask. */ |
| 202 | function active(sheet: number) { |
| 203 | const opened = required(); |
| 204 | |
| 205 | if (opened.info.activeSheet !== sheet) show(opened, sheet); |
| 206 | |
| 207 | return opened; |
| 208 | } |
| 209 | |
| 210 | /** Makes a sheet the active one and reads what its grid needs. */ |
| 211 | function show(opened: Opened, sheet: number): SheetLayout { |
| 212 | opened.workbook.setActiveSheet(sheet); |
| 213 | opened.info = opened.workbook.sheetInfo(); |
| 214 | |
| 215 | return { info: opened.info, ...layout(opened.workbook, sheet) }; |
| 216 | } |
| 217 | |
| 218 | /** |
| 219 | * The used range, the merged cells, the hidden rows and columns, and how far the charts reach, from one export of the |
| 220 | * sheet's metadata. One cell is enough: the lists before the cells are complete however soon the export stops. |
| 221 | */ |
| 222 | function layout(workbook: WorkbookHandle, sheet: number) { |
| 223 | const result = attempt(() => |
| 224 | workbook.exportStructured({ |
| 225 | scope: [{ sheet, range: "A1:XFD1048576" }], |
| 226 | maxCells: 1, |
| 227 | includeDefinedNames: false, |
| 228 | }), |
| 229 | ); |
| 230 | |
| 231 | const exported = result?.ok ? result.content.sheets[0] : undefined; |
| 232 | |
| 233 | const charts = (exported?.objects ?? []) |
| 234 | .filter((object) => object.kind === "chart" && !object.hidden) |
| 235 | .flatMap((object) => (object.anchor ? anchorRange(object.anchor) : [])) |
| 236 | // The corner cell holds the chart's edge somewhere inside it, so the cell past it bounds the chart. |
| 237 | .flatMap((range) => { |
| 238 | const corner = attempt(() => |
| 239 | workbook.cellPosition( |
| 240 | sheet, |
| 241 | Math.min(range.bottom + 1, lastCell.row), |
| 242 | Math.min(range.right + 1, lastCell.col), |
| 243 | ), |
| 244 | ); |
| 245 | |
| 246 | return corner ? [corner] : []; |
| 247 | }); |
| 248 | |
| 249 | return { |
| 250 | used: exported?.usedRange ? parseRange(exported.usedRange) : undefined, |
| 251 | merges: (exported?.merges ?? []).flatMap((merge) => anchorRange(merge.anchor)), |
| 252 | hidden: { |
| 253 | rows: parseSpans(exported?.hiddenRows ?? [], "rows"), |
| 254 | columns: parseSpans(exported?.hiddenColumns ?? [], "columns"), |
| 255 | }, |
| 256 | chartWidth: Math.max(0, ...charts.map((corner) => corner.x)), |
| 257 | chartHeight: Math.max(0, ...charts.map((corner) => corner.y)), |
| 258 | }; |
| 259 | } |
| 260 | |
| 261 | /** Where the sheet's last cell ends, past the frozen panes. A viewport past it makes the engine throw. */ |
| 262 | function end( |
| 263 | opened: Opened, |
| 264 | sheet: number, |
| 265 | frozen: { readonly width: number; readonly height: number }, |
| 266 | ) { |
| 267 | const key = `${sheet}:${frozen.width}:${frozen.height}`; |
| 268 | |
| 269 | if (opened.ends.has(key)) return opened.ends.get(key); |
| 270 | |
| 271 | const measured = measureEnd(opened.workbook, sheet, frozen); |
| 272 | |
| 273 | opened.ends.set(key, measured); |
| 274 | |
| 275 | return measured; |
| 276 | } |
| 277 | |
| 278 | function measureEnd( |
| 279 | workbook: WorkbookHandle, |
| 280 | sheet: number, |
| 281 | frozen: { readonly width: number; readonly height: number }, |
| 282 | ) { |
| 283 | const last = attempt(() => workbook.cellPosition(sheet, lastCell.row, lastCell.col)); |
| 284 | |
| 285 | if (!last) return undefined; |
| 286 | |
| 287 | // A viewport one pixel past the frozen panes, on the last cell, reports where that cell ends. |
| 288 | const grid = attempt( |
| 289 | () => |
| 290 | workbook.displayList({ |
| 291 | x: last.x, |
| 292 | y: last.y, |
| 293 | width: frozen.width + 1, |
| 294 | height: frozen.height + 1, |
| 295 | }).grid, |
| 296 | ); |
| 297 | |
| 298 | // The engine works in single precision there, so stay a little short of the edge. |
| 299 | const margin = 2; |
| 300 | |
| 301 | return { |
| 302 | x: |
| 303 | last.x + |
| 304 | Math.max(0, (grid ? (grid.colOffsets[grid.colOffsets.length - 1] ?? 0) : 0) - frozen.width) - |
| 305 | margin, |
| 306 | y: |
| 307 | last.y + |
| 308 | Math.max(0, (grid ? (grid.rowOffsets[grid.rowOffsets.length - 1] ?? 0) : 0) - frozen.height) - |
| 309 | margin, |
| 310 | }; |
| 311 | } |
| 312 | |
| 313 | /** The cells of a range on a sheet as the engine reads them, row by row; undefined when it cannot. */ |
| 314 | function read(opened: Opened, sheet: number, range: CellRange) { |
| 315 | if ((range.bottom - range.top + 1) * (range.right - range.left + 1) > 200_000) return undefined; |
| 316 | const target: XlsxRangeTarget = { |
| 317 | sheetId: opened.info.sheetIds[sheet]!, |
| 318 | range: { |
| 319 | kind: "rowCol", |
| 320 | start: { row: range.top, col: range.left }, |
| 321 | end: { row: range.bottom, col: range.right }, |
| 322 | }, |
| 323 | }; |
| 324 | |
| 325 | const result = attempt(() => opened.workbook.readCells({ ranges: [target] })); |
| 326 | |
| 327 | return result?.ok ? result.ranges[0]?.cells : undefined; |
| 328 | } |
| 329 | |
| 330 | /** The workbook's sheets but its hidden and very hidden ones, which Excel lists only to unhide. */ |
| 331 | function visibleTabs(workbook: WorkbookHandle, info: SheetInfo): SheetTab[] { |
| 332 | const names = info.sheetNames; |
| 333 | |
| 334 | const result = attempt(() => |
| 335 | workbook.exportStructured({ |
| 336 | includeHiddenSheets: true, |
| 337 | includeDefinedNames: false, |
| 338 | scope: names.map((_, sheet) => ({ sheet, range: "A1" })), |
| 339 | }), |
| 340 | ); |
| 341 | |
| 342 | const hidden = new Set( |
| 343 | (result?.ok ? result.content.sheets : []) |
| 344 | .filter((sheet) => sheet.visibility === "hidden" || sheet.visibility === "veryHidden") |
| 345 | .flatMap((sheet) => (sheet.anchor.kind === "sheet" ? [sheet.anchor.sheet.index] : [])), |
| 346 | ); |
| 347 | |
| 348 | return names.flatMap((name, index) => (hidden.has(index) ? [] : [{ index, name }])); |
| 349 | } |
| 350 | |
| 351 | /** |
| 352 | * Whether a cell's text pastes as it is. `toTsv` quotes text that a spreadsheet would read as a formula; a number shown |
| 353 | * with a sign, such as "-12.50", is safe, and quoting it would paste text instead of the number. |
| 354 | */ |
| 355 | function literal(cell: XlsxCellRead) { |
| 356 | return ( |
| 357 | cell.value.kind === "number" && /^[-+][\d\s.,%\p{Sc}]+(?:e[-+]\d+)?$/iu.test(cell.displayText) |
| 358 | ); |
| 359 | } |