merong-docs 0.1.11 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/OVERVIEW.md +19 -19
  2. package/OVERVIEW.zh-CN.md +19 -22
  3. package/README.md +77 -77
  4. package/README.zh-CN.md +81 -81
  5. package/client/android-file-share.ts +25 -25
  6. package/client/controls.tsx +163 -163
  7. package/client/document-panel.tsx +166 -166
  8. package/client/external-file.tsx +78 -78
  9. package/client/file-reader.tsx +43 -43
  10. package/client/markdown-panel.tsx +737 -737
  11. package/client/markdown-scroll.ts +122 -122
  12. package/client/messages.ts +224 -224
  13. package/client/native-contacts.ts +145 -145
  14. package/client/page-render-queue.ts +12 -12
  15. package/client/page-selection.tsx +227 -227
  16. package/client/page-tools.tsx +72 -72
  17. package/client/pdf-geometry.ts +96 -96
  18. package/client/pdf-panel.tsx +477 -477
  19. package/client/reader-find.tsx +190 -190
  20. package/client/reader-notice.tsx +46 -46
  21. package/client/settings.tsx +143 -143
  22. package/client/syntax.tsx +55 -55
  23. package/client/viewport-geometry.ts +61 -61
  24. package/client/web.ts +462 -462
  25. package/client/worksheet-panel.tsx +631 -631
  26. package/client/zoom-controls.tsx +140 -140
  27. package/index.client.tsx +36 -36
  28. package/index.server.ts +73 -73
  29. package/node_modules/markdown-it/bin/markdown-it.mjs +0 -0
  30. package/node_modules/yaml/bin.mjs +0 -0
  31. package/npm-shrinkwrap.json +2 -2
  32. package/package.json +1 -1
  33. package/scripts/prepare-office.mjs +20 -20
  34. package/server/engine.ts +89 -89
  35. package/server/external-file.ts +42 -42
  36. package/server/generated/document-worker.ts +1 -1
  37. package/server/generated/rust-reader_bg.wasm +0 -0
  38. package/server/markdown-index.ts +305 -305
  39. package/server/markdown-links.ts +51 -51
  40. package/server/markdown-page.ts +120 -120
  41. package/server/office-fonts.cjs +824 -824
  42. package/server/office-location.ts +41 -41
  43. package/server/office-preview.ts +186 -186
  44. package/server/office-worker.cjs +49 -49
  45. package/server/office-xml.ts +79 -79
  46. package/server/pdf-engine.ts +168 -168
  47. package/server/pdf-text-geometry.ts +60 -60
  48. package/server/rust-reader.ts +40 -40
  49. package/server/structured-document.ts +69 -69
  50. package/server/text-search.ts +15 -15
  51. package/server/worker-entry.ts +42 -42
  52. package/server/worker-protocol.ts +38 -38
  53. package/server/worksheet.ts +67 -67
  54. package/server/workspace-file.ts +63 -63
  55. package/shared/contracts.ts +187 -187
  56. package/shared/file-limits.ts +5 -5
  57. package/shared/markdown-constants.ts +4 -4
  58. package/shared/markdown-math.ts +198 -198
  59. package/shared/markdown-references.ts +83 -83
  60. package/shared/markdown-source-location.ts +8 -8
  61. package/shared/reader-settings.ts +15 -15
  62. package/shared/reader-shortcuts.ts +132 -132
  63. package/vendor/office2pdf/office2pdf_bg.wasm +2 -2
@@ -1,631 +1,631 @@
1
- import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
2
- import { Platform, Pressable, Text, View, type ScrollView as ScrollViewInstance, type TextStyle } from "react-native";
3
- import { useQuery } from "@tanstack/react-query";
4
- import { useRpc, useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
5
- import { copyText, Icon, Loading, ScrollView } from "@getpaseo/plugin/client/ui";
6
- import { findWorksheetText, readWorksheet, type Worksheet, type WorksheetMatch } from "../shared/contracts";
7
- import { Control, isTabActive, ReadError, Toolbar, useFileGeneration, useReaderShortcuts, type Theme } from "./controls";
8
- import { ExternalFileAction } from "./external-file";
9
- import { messages } from "./messages";
10
- import { useNativeContacts } from "./native-contacts";
11
- import { ReaderFindBar, useFindResults, useReaderFindShortcuts, useReaderFindVisibility } from "./reader-find";
12
- import { useReaderNotice } from "./reader-notice";
13
- import { boundZoom, clamp, constrainGrid, panAndPinch, zoomAround, zoomGridScroll, type Contact, type Point, type Position, type Size } from "./viewport-geometry";
14
- import { applyWebTitle, bindWorksheetGrid, bindWorksheetMenuDismiss, focusReaderFind, readerSelection, setWebCursor } from "./web";
15
- import { ZoomControls } from "./zoom-controls";
16
-
17
- const gutter = 48;
18
- const headingHeight = 26;
19
- const findId = "merong-worksheet-find";
20
- const webCellText = { overflowWrap: "anywhere", whiteSpace: "pre-wrap" } as TextStyle;
21
- type CellAddress = { row: number; column: number };
22
- type FrozenAxes = Partial<CellAddress>;
23
- type CellMenu = { address: CellAddress; point: Point };
24
- type CellPress = { contact: Contact; timer: ReturnType<typeof setTimeout>; held: boolean };
25
- type WorksheetHit = WorksheetMatch | [row: number, column: number];
26
- const noPins: FrozenAxes = {};
27
-
28
- function offsets(values: number[], scale: number) {
29
- let position = 0;
30
- return [0, ...values.map((value) => position += value * scale)];
31
- }
32
-
33
- function withoutTrack(values: number[], track?: number) {
34
- if (track === undefined) return values;
35
- const size = values[track + 1] - values[track];
36
- return values.map((offset, index) => index === track + 1 ? values[track] : index > track ? offset - size : offset);
37
- }
38
-
39
- function upperOffset(values: number[], target: number) {
40
- let first = 0;
41
- let end = values.length;
42
- while (first < end) {
43
- const middle = Math.floor((first + end) / 2);
44
- if (values[middle] <= target) first = middle + 1;
45
- else end = middle;
46
- }
47
- return first;
48
- }
49
-
50
- function visibleRange(values: number[], start: number, length: number) {
51
- const last = values.length - 1;
52
- return {
53
- first: Math.min(last, Math.max(0, upperOffset(values, start - 80) - 1)),
54
- end: Math.min(last, upperOffset(values, start + length + 80)),
55
- };
56
- }
57
-
58
- function columnName(column: number) {
59
- let name = "";
60
- for (let value = column + 1; value > 0; value = Math.floor((value - 1) / 26)) {
61
- name = String.fromCharCode(65 + (value - 1) % 26) + name;
62
- }
63
- return name;
64
- }
65
-
66
- function cellAddress(text: string): CellAddress | undefined {
67
- const match = /^\$?([A-Z]{1,3})\$?([1-9]\d{0,6})$/.exec(text.trim().toUpperCase());
68
- if (!match) return;
69
- let column = 0;
70
- for (const letter of match[1]) column = column * 26 + letter.charCodeAt(0) - 64;
71
- return { row: Number(match[2]) - 1, column: column - 1 };
72
- }
73
-
74
- function WorksheetGrid({ sheet, scale, theme, onZoom, focus, pinned, onPin, matches, active, compact, findOpen, dragMode, tabActive }: {
75
- sheet: Worksheet; scale: number; theme: Theme; onZoom: (scale: number) => void; compact: boolean;
76
- focus?: CellAddress; pinned: FrozenAxes; onPin: (axis: keyof CellAddress, index: number) => void; findOpen: boolean;
77
- matches: ReadonlyMap<string, WorksheetMatch[]>; active?: WorksheetMatch; dragMode: boolean; tabActive: boolean;
78
- }) {
79
- const { t } = useTranslation(messages);
80
- const notify = useReaderNotice();
81
- const web = Platform.OS === "web";
82
- const [viewport, setViewport] = useState({ width: 0, height: 0 });
83
- const [left, setLeft] = useState(0);
84
- const [top, setTop] = useState(0);
85
- const [position, setPosition] = useState<Position>({ x: 0, y: 0, scale });
86
- const current = useRef(position);
87
- const beforeFind = useRef<Position>(undefined);
88
- const gridViewport = useRef<View>(null);
89
- const shortcuts = useReaderShortcuts();
90
- const horizontal = useRef<ScrollViewInstance>(null);
91
- const vertical = useRef<ScrollViewInstance>(null);
92
- const webZoom = useRef<Position>(undefined);
93
- const [picked, setPicked] = useState<Worksheet["cells"][number]>();
94
- const [menu, setMenu] = useState<CellMenu>();
95
- const closeMenu = useCallback(() => setMenu(undefined), []);
96
- const press = useRef<CellPress | null>(undefined);
97
- const cellScale = web ? scale : 1;
98
- const fullColumns = useMemo(() => offsets(sheet.columns, cellScale), [sheet.columns, cellScale]);
99
- const fullRows = useMemo(() => offsets(sheet.rows, cellScale), [sheet.rows, cellScale]);
100
- const frozenRow = pinned.row !== undefined && sheet.rows[pinned.row] ? pinned.row : undefined;
101
- const frozenColumn = pinned.column !== undefined && sheet.columns[pinned.column] ? pinned.column : undefined;
102
- const rows = useMemo(() => withoutTrack(fullRows, frozenRow), [fullRows, frozenRow]);
103
- const columns = useMemo(() => withoutTrack(fullColumns, frozenColumn), [fullColumns, frozenColumn]);
104
- const frozenRowSize = frozenRow === undefined ? 0 : fullRows[frozenRow + 1] - fullRows[frozenRow];
105
- const frozenColumnSize = frozenColumn === undefined ? 0 : fullColumns[frozenColumn + 1] - fullColumns[frozenColumn];
106
- const width = columns[columns.length - 1];
107
- const height = rows[rows.length - 1];
108
- const content = useMemo(() => ({ width, height }), [width, height]);
109
- const zoom = web ? 1 : position.scale;
110
- const { x: frozenWidth, y: frozenHeight } = frozenInsets(zoom);
111
- const scrollLeft = web ? left : -position.x;
112
- const scrollTop = web ? top : -position.y;
113
- const { first: firstColumn, end: endColumn } = visibleRange(columns, scrollLeft / zoom, (viewport.width - frozenWidth) / zoom);
114
- const { first: firstRow, end: endRow } = visibleRange(rows, scrollTop / zoom, (viewport.height - frozenHeight) / zoom);
115
- function frozenInsets(scale: number) {
116
- return { x: Math.min(frozenColumnSize * scale, viewport.width / 3), y: Math.min(frozenRowSize * scale, viewport.height / 3) };
117
- }
118
- function viewportPosition(position: Position) {
119
- const inset = frozenInsets(position.scale);
120
- return { ...position, x: position.x + inset.x, y: position.y + inset.y };
121
- }
122
- function constrainInViewport(position: Position) {
123
- const inset = frozenInsets(position.scale);
124
- return constrainGrid({ ...position, x: position.x - inset.x, y: position.y - inset.y },
125
- { width: viewport.width - inset.x, height: viewport.height - inset.y }, content);
126
- }
127
- function update(next: Position) {
128
- if (next.x === current.current.x && next.y === current.current.y && next.scale === current.current.scale) return false;
129
- current.current = next;
130
- setPosition(next);
131
- return true;
132
- }
133
- const { handlers: nativeGestures, stopInertia } = useNativeContacts(gridViewport, !web && viewport.width > 0, (previous, next) => {
134
- const before = current.current;
135
- const after = constrainInViewport(panAndPinch(viewportPosition(before), previous, next));
136
- update(after);
137
- if (after.scale !== before.scale) onZoom(after.scale);
138
- }, ({ x, y }) => {
139
- const position = viewportPosition(current.current);
140
- return update(constrainInViewport({ ...position, x: position.x + x, y: position.y + y }));
141
- }, trackTouch);
142
- useLayoutEffect(() => {
143
- if (web) return;
144
- stopInertia();
145
- if (findOpen) beforeFind.current ??= current.current;
146
- const saved = findOpen ? undefined : beforeFind.current;
147
- beforeFind.current = findOpen ? beforeFind.current : undefined;
148
- const anchor = { x: viewport.width / 2, y: viewport.height / 2 };
149
- update(constrainInViewport(zoomAround(viewportPosition(saved ?? current.current), scale, anchor)));
150
- }, [web, viewport, content, scale, stopInertia, frozenRowSize, frozenColumnSize, findOpen]);
151
- useLayoutEffect(() => {
152
- const pending = webZoom.current;
153
- webZoom.current = undefined;
154
- if (!pending || pending.scale !== scale) return;
155
- horizontal.current?.scrollTo({ x: pending.x, animated: false });
156
- vertical.current?.scrollTo({ y: pending.y, animated: false });
157
- }, [scale]);
158
- function zoomWeb(factor: number | undefined, anchor: Point, scroll: Point) {
159
- const previous = webZoom.current ?? { ...scroll, scale };
160
- const next = factor === undefined ? 1 : boundZoom(previous.scale * factor);
161
- if (next === previous.scale) return;
162
- webZoom.current = zoomGridScroll(previous, next, anchor, viewport,
163
- { width: width / scale, height: height / scale },
164
- { width: frozenColumnSize / scale, height: frozenRowSize / scale });
165
- onZoom(next);
166
- }
167
- const focusGeometry = useRef({ columns, rows, frozenWidth, frozenHeight, frozenRow, frozenColumn, scrollLeft, scrollTop });
168
- focusGeometry.current = { columns, rows, frozenWidth, frozenHeight, frozenRow, frozenColumn, scrollLeft, scrollTop };
169
- useLayoutEffect(() => {
170
- if (!focus || !viewport.width || !viewport.height || focus.row >= sheet.rows.length || focus.column >= sheet.columns.length) return;
171
- const { columns, rows, frozenWidth, frozenHeight, frozenRow, frozenColumn, scrollLeft, scrollTop } = focusGeometry.current;
172
- stopInertia();
173
- const atScale = web ? 1 : current.current.scale;
174
- const x = focus.column === frozenColumn ? scrollLeft : columns[focus.column] * atScale;
175
- const y = focus.row === frozenRow ? scrollTop
176
- : Math.max(0, rows[focus.row] * atScale - (viewport.height - frozenHeight) * 0.35);
177
- if (web) {
178
- horizontal.current?.scrollTo({ x, animated: false });
179
- vertical.current?.scrollTo({ y, animated: false });
180
- } else {
181
- update(constrainGrid({ ...current.current, x: -x, y: -y },
182
- { width: viewport.width - frozenWidth, height: viewport.height - frozenHeight }, content));
183
- }
184
- }, [focus, viewport, web, sheet, stopInertia]);
185
- const cellIndex = useMemo(() => {
186
- const byRow = new Map<number, Map<number, Worksheet["cells"][number]>>();
187
- for (const cell of sheet.cells) {
188
- const [row, column] = cell;
189
- const cells = byRow.get(row) ?? new Map();
190
- cells.set(column, cell);
191
- byRow.set(row, cells);
192
- }
193
- return byRow;
194
- }, [sheet.cells]);
195
- useLayoutEffect(() => {
196
- setPicked(undefined);
197
- closeMenu();
198
- return () => { clearTimeout(press.current?.timer); press.current = undefined; };
199
- }, [sheet, closeMenu]);
200
- const gridActions = useRef({ open: openCellMenu, dragMode, zoom: zoomWeb });
201
- gridActions.current = { open: openCellMenu, dragMode, zoom: zoomWeb };
202
- useLayoutEffect(() => {
203
- if (web && tabActive) return bindWorksheetGrid(gridViewport.current, {
204
- open: (point) => gridActions.current.open(point),
205
- dragMode: () => gridActions.current.dragMode,
206
- shortcuts: () => shortcuts.current,
207
- zoom: (...args) => gridActions.current.zoom(...args),
208
- });
209
- }, [tabActive, web, shortcuts]);
210
- useLayoutEffect(() => {
211
- if (web && tabActive) setWebCursor(gridViewport.current, dragMode ? "grab" : "");
212
- }, [dragMode, tabActive, web]);
213
- function addressAt({ x, y }: Point): CellAddress | undefined {
214
- if (x < 0 || y < 0 || x >= viewport.width || y >= viewport.height) return;
215
- const column = frozenColumn !== undefined && x < frozenWidth ? frozenColumn
216
- : upperOffset(columns, (x - frozenWidth + scrollLeft) / zoom) - 1;
217
- const row = frozenRow !== undefined && y < frozenHeight ? frozenRow
218
- : upperOffset(rows, (y - frozenHeight + scrollTop) / zoom) - 1;
219
- if (sheet.rows[row] && sheet.columns[column]) return { row, column };
220
- }
221
- function openCellMenu(point: Point) {
222
- const address = addressAt(point);
223
- if (!address) return false;
224
- setMenu({ address, point });
225
- return true;
226
- }
227
- function pickCell(point: Point) {
228
- const address = addressAt(point);
229
- if (!address) return setPicked(undefined);
230
- const { row, column } = address;
231
- const merge = sheet.merges.find(([firstRow, firstColumn, lastRow, lastColumn]) =>
232
- row >= firstRow && row <= lastRow && column >= firstColumn && column <= lastColumn);
233
- const cell = cellIndex.get(merge?.[0] ?? row)?.get(merge?.[1] ?? column);
234
- setPicked(cell?.[2] ? cell : undefined);
235
- }
236
- function measureContact(contact: Contact, action: (point: Point) => void) {
237
- gridViewport.current?.measure((_left, _top, _width, _height, x, y) => action({ x: contact.x - x, y: contact.y - y }));
238
- }
239
- function trackTouch(_visible: Contact[], contacts: Contact[]) {
240
- const [point] = contacts;
241
- const start = press.current;
242
- if (!point) {
243
- clearTimeout(start?.timer);
244
- press.current = undefined;
245
- if (start?.held) return true;
246
- if (!start) return false;
247
- measureContact(start.contact, pickCell);
248
- return true;
249
- }
250
- if (start?.held) return true;
251
- if (contacts.length > 1 || start && (point.id !== start.contact.id || Math.hypot(point.x - start.contact.x, point.y - start.contact.y) > 7)) {
252
- clearTimeout(start?.timer);
253
- press.current = null;
254
- } else if (start === undefined) {
255
- const timer = setTimeout(() => {
256
- if (!press.current) return;
257
- press.current.held = true;
258
- measureContact(point, (target) => gridActions.current.open(target));
259
- }, 500);
260
- press.current = { contact: point, timer, held: false };
261
- }
262
- return false;
263
- }
264
- const copyPicked = async (value: string) => {
265
- try {
266
- await copyText(value);
267
- notify?.(t("copied"));
268
- } catch {
269
- notify?.(t("textCopyError"), true);
270
- }
271
- };
272
- const selected = useMemo(() => picked && { row: picked[0], column: picked[1] }, [picked]);
273
- const decoration = useMemo(() => ({ focus, selected, matches, active }), [focus, selected, matches, active]);
274
- const gridColor = theme.colors.border;
275
- const header = {
276
- position: "absolute", justifyContent: "center", alignItems: "center",
277
- backgroundColor: theme.colors.surface1, borderRightWidth: 1, borderBottomWidth: 1, borderColor: gridColor,
278
- } as const;
279
- const headerText = { color: theme.colors.foregroundMuted, fontSize: 12 };
280
- const rowNumbers = [];
281
- const columnLabels = [];
282
- const cells = useMemo(() => renderCells(
283
- sheet, cellIndex, rows, columns, { firstRow, endRow, firstColumn, endColumn }, cellScale, theme, decoration,
284
- ), [sheet, cellIndex, rows, columns, firstRow, endRow, firstColumn, endColumn, cellScale, theme, decoration]);
285
- const pinnedCells = useMemo(() => {
286
- const render = (rows: number[], columns: number[], firstRow: number, endRow: number, firstColumn: number, endColumn: number) =>
287
- renderCells(sheet, cellIndex, rows, columns, { firstRow, endRow, firstColumn, endColumn }, cellScale, theme, decoration);
288
- return {
289
- row: frozenRow === undefined ? null : render(fullRows, columns, frozenRow, frozenRow + 1, firstColumn, endColumn),
290
- column: frozenColumn === undefined ? null : render(rows, fullColumns, firstRow, endRow, frozenColumn, frozenColumn + 1),
291
- corner: frozenRow === undefined || frozenColumn === undefined ? null
292
- : render(fullRows, fullColumns, frozenRow, frozenRow + 1, frozenColumn, frozenColumn + 1),
293
- };
294
- }, [frozenRow, frozenColumn, firstRow, endRow, firstColumn, endColumn, sheet, cellIndex,
295
- rows, columns, fullRows, fullColumns, cellScale, theme, decoration]);
296
- for (let column = firstColumn; column < endColumn; column++) {
297
- const size = (columns[column + 1] - columns[column]) * zoom;
298
- if (size <= 0) continue;
299
- columnLabels.push(
300
- <View key={column} style={{ ...header, left: frozenWidth + columns[column] * zoom - scrollLeft, width: size, height: headingHeight }}>
301
- <Text style={headerText}>{columnName(column)}</Text>
302
- </View>,
303
- );
304
- }
305
- for (let row = firstRow; row < endRow; row++) {
306
- const size = (rows[row + 1] - rows[row]) * zoom;
307
- if (size <= 0) continue;
308
- rowNumbers.push(
309
- <View key={row} style={{ ...header, top: frozenHeight + rows[row] * zoom - scrollTop, width: gutter, height: size }}>
310
- <Text style={headerText}>{row + 1}</Text>
311
- </View>,
312
- );
313
- }
314
-
315
- return (
316
- <View testID="merong-worksheet-grid" style={{ flex: 1, minHeight: 0, overflow: "hidden" }}>
317
- <View style={{ height: headingHeight, marginLeft: gutter, overflow: "hidden", backgroundColor: theme.colors.surface1 }}>
318
- {columnLabels}
319
- {frozenColumn !== undefined && frozenWidth > 0 && (
320
- <View style={{ ...header, left: 0, top: 0, width: frozenWidth, height: headingHeight, borderColor: theme.colors.accent }}>
321
- <Text style={headerText}>{columnName(frozenColumn)}</Text>
322
- </View>
323
- )}
324
- </View>
325
- <View
326
- ref={gridViewport}
327
- testID="merong-worksheet-viewport"
328
- collapsable={web}
329
- tabIndex={web && tabActive ? 0 : undefined}
330
- {...nativeGestures}
331
- style={{ flex: 1, minHeight: 0, marginLeft: gutter, overflow: "hidden" }}
332
- onLayout={({ nativeEvent }) => {
333
- const { width, height } = nativeEvent.layout;
334
- setViewport((previous) => previous.width === width && previous.height === height ? previous : { width, height });
335
- }}
336
- >
337
- {web ? (
338
- <ScrollView ref={horizontal} horizontal nestedScrollEnabled scrollEventThrottle={16}
339
- testID="merong-worksheet-horizontal" onScroll={({ nativeEvent }) => setLeft(Math.max(0, nativeEvent.contentOffset.x))}>
340
- <ScrollView ref={vertical} nestedScrollEnabled scrollEventThrottle={16}
341
- style={{ width: Math.max(viewport.width, width + frozenWidth), height: viewport.height }}
342
- testID="merong-worksheet-vertical" onScroll={({ nativeEvent }) => setTop(Math.max(0, nativeEvent.contentOffset.y))}>
343
- <View style={{ width: width + frozenWidth, height: height + frozenHeight }}>
344
- <View style={{ position: "absolute", left: frozenWidth, top: frozenHeight, width, height }}>{cells}</View>
345
- </View>
346
- </ScrollView>
347
- </ScrollView>
348
- ) : (
349
- <View testID="merong-worksheet-touch" style={{
350
- position: "absolute", left: frozenWidth, top: frozenHeight, width, height, transformOrigin: [0, 0, 0],
351
- transform: [{ translateX: position.x }, { translateY: position.y }, { scale: zoom }],
352
- }}>{cells}</View>
353
- )}
354
- {frozenRow !== undefined && frozenHeight > 0 && <View testID="merong-worksheet-frozen-row" pointerEvents={web ? "auto" : "none"}
355
- style={{ position: "absolute", top: 0, left: frozenWidth, right: 0,
356
- height: frozenHeight, overflow: "hidden", backgroundColor: theme.colors.surface0, borderBottomWidth: 1, borderColor: theme.colors.accent }}>
357
- <View style={{ position: "absolute", width, height: fullRows.at(-1), transformOrigin: [0, 0, 0],
358
- transform: [{ translateX: -scrollLeft }, { translateY: -fullRows[frozenRow] * zoom }, { scale: zoom }] }}>{pinnedCells.row}</View>
359
- </View>}
360
- {frozenColumn !== undefined && frozenWidth > 0 && <View testID="merong-worksheet-frozen-column" pointerEvents={web ? "auto" : "none"}
361
- style={{ position: "absolute", top: frozenHeight, bottom: 0,
362
- left: 0, width: frozenWidth, overflow: "hidden", backgroundColor: theme.colors.surface0, borderRightWidth: 1, borderColor: theme.colors.accent }}>
363
- <View style={{ position: "absolute", width: fullColumns.at(-1), height, transformOrigin: [0, 0, 0],
364
- transform: [{ translateX: -fullColumns[frozenColumn] * zoom }, { translateY: -scrollTop }, { scale: zoom }] }}>{pinnedCells.column}</View>
365
- </View>}
366
- {frozenRow !== undefined && frozenColumn !== undefined && frozenHeight > 0 && frozenWidth > 0 && (
367
- <View testID="merong-worksheet-frozen-corner" pointerEvents={web ? "auto" : "none"}
368
- style={{ position: "absolute", top: 0, left: 0, width: frozenWidth, height: frozenHeight, overflow: "hidden",
369
- backgroundColor: theme.colors.surface0, borderBottomWidth: 1, borderRightWidth: 1, borderColor: theme.colors.accent }}>
370
- <View style={{ position: "absolute", width: fullColumns.at(-1), height: fullRows.at(-1), transformOrigin: [0, 0, 0],
371
- transform: [{ translateX: -fullColumns[frozenColumn] * zoom }, { translateY: -fullRows[frozenRow] * zoom }, { scale: zoom }] }}>{pinnedCells.corner}</View>
372
- </View>
373
- )}
374
- </View>
375
- <View pointerEvents="none" style={{ position: "absolute", top: headingHeight, bottom: 0, left: 0, width: gutter,
376
- overflow: "hidden", backgroundColor: theme.colors.surface1 }}>
377
- {rowNumbers}
378
- {frozenRow !== undefined && frozenHeight > 0 && (
379
- <View style={{ ...header, top: 0, width: gutter, height: frozenHeight, borderColor: theme.colors.accent }}>
380
- <Text style={headerText}>{frozenRow + 1}</Text>
381
- </View>
382
- )}
383
- </View>
384
- <View pointerEvents="none" style={{ ...header, top: 0, left: 0, width: gutter, height: headingHeight }} />
385
- {!!picked?.[2] && <View style={[{ position: "absolute", right: 8,
386
- borderWidth: 1, borderRadius: 7, borderColor: theme.colors.border, backgroundColor: theme.colors.surface1 },
387
- findOpen ? { bottom: 8 } : { top: headingHeight + 8 }]}>
388
- <Control title={t("copyCell")} icon="Copy" theme={theme} compact={compact} onPress={() => { void copyPicked(picked[2]); }} />
389
- </View>}
390
- {menu && <WorksheetCellMenu {...{ menu, pinned, viewport, theme, onPin }} close={closeMenu} />}
391
- </View>
392
- );
393
- }
394
-
395
- function WorksheetCellMenu({ menu, pinned, viewport, theme, onPin, close }: {
396
- menu: CellMenu; pinned: FrozenAxes; viewport: Size; theme: Theme;
397
- onPin: (axis: keyof CellAddress, index: number) => void; close: () => void;
398
- }) {
399
- const { t } = useTranslation(messages);
400
- const web = Platform.OS === "web";
401
- const ref = useRef<View>(null);
402
- const shortcuts = useReaderShortcuts();
403
- const [height, setHeight] = useState(120);
404
- useLayoutEffect(() => {
405
- if (web) return bindWorksheetMenuDismiss(ref.current, close, () => shortcuts.current);
406
- }, [web, close, shortcuts]);
407
- const { address: { row, column }, point } = menu;
408
- const width = Math.min(220, viewport.width - 8);
409
- const columnLabel = columnName(column);
410
- const actions = [
411
- { axis: "row", index: row, label: t(pinned.row === row ? "unfreezeRow" : "freezeRow", { row: row + 1 }) },
412
- { axis: "column", index: column, label: t(pinned.column === column ? "unfreezeColumn" : "freezeColumn", { column: columnLabel }) },
413
- ] as const;
414
- return (
415
- <View pointerEvents="box-none" style={{ position: "absolute", inset: 0, zIndex: 3 }}>
416
- {!web && <Pressable accessible={false} onPress={close} style={{ position: "absolute", inset: 0 }} />}
417
- <View ref={ref} testID="merong-worksheet-cell-menu" accessibilityRole="menu" accessibilityLabel={t("cellActions")}
418
- tabIndex={web ? -1 : undefined} onAccessibilityEscape={close}
419
- onLayout={({ nativeEvent }) => setHeight(nativeEvent.layout.height)} style={{
420
- position: "absolute", left: gutter + clamp(point.x, 4, viewport.width - width - 4),
421
- top: headingHeight + clamp(point.y, 4, viewport.height - height - 4),
422
- width, padding: 4, borderRadius: 8, borderWidth: 1, borderColor: theme.colors.border, backgroundColor: theme.colors.surface1,
423
- }}>
424
- <Text style={{ color: theme.colors.foregroundMuted, paddingHorizontal: 8, paddingVertical: 4, fontSize: 12 }}>
425
- {columnLabel}{row + 1}
426
- </Text>
427
- {actions.map(({ axis, index, label }) => (
428
- <Pressable key={axis} accessibilityRole="menuitem" onPress={() => { onPin(axis, index); close(); }}
429
- style={({ pressed, hovered }: { pressed: boolean; hovered?: boolean }) => ({
430
- minHeight: web ? 32 : 40, paddingHorizontal: 8, paddingVertical: 4,
431
- borderRadius: 4, flexDirection: "row", alignItems: "center", gap: 8,
432
- backgroundColor: pressed || hovered ? theme.colors.surface2 : "transparent",
433
- })}>
434
- <Icon name={pinned[axis] === index ? "PinOff" : "Pin"} size={15} color={theme.colors.foregroundMuted} />
435
- <Text style={{ flexShrink: 1, color: theme.colors.foreground, fontSize: 13 }}>{label}</Text>
436
- </Pressable>
437
- ))}
438
- </View>
439
- </View>
440
- );
441
- }
442
-
443
- function renderCells(
444
- sheet: Worksheet,
445
- cellIndex: Map<number, Map<number, Worksheet["cells"][number]>>,
446
- rows: number[],
447
- columns: number[],
448
- { firstRow, endRow, firstColumn, endColumn }: { firstRow: number; endRow: number; firstColumn: number; endColumn: number },
449
- scale: number,
450
- theme: Theme,
451
- { focus, selected, matches, active }: {
452
- focus?: CellAddress; selected?: CellAddress; matches: ReadonlyMap<string, WorksheetMatch[]>; active?: WorksheetMatch;
453
- },
454
- ) {
455
- const cells = [];
456
- const covered = new Set<number>();
457
- const columnCount = sheet.columns.length;
458
- const web = Platform.OS === "web";
459
- const renderCell = (row: number, column: number, lastRow = row, lastColumn = column) => {
460
- const cell = cellIndex.get(row)?.get(column);
461
- const style = cell ? sheet.styles[cell[3]] : undefined;
462
- const fontSize = (style?.fontSize ?? 14) * scale;
463
- const cellWidth = columns[lastColumn + 1] - columns[column];
464
- const cellHeight = rows[lastRow + 1] - rows[row];
465
- const contains = (address?: CellAddress) =>
466
- address && address.row >= row && address.row <= lastRow && address.column >= column && address.column <= lastColumn;
467
- const focused = contains(focus);
468
- const highlighted = focused || contains(selected);
469
- const hits = matches.get(`${row}:${column}`);
470
- if (cellWidth <= 0 || cellHeight <= 0) return null;
471
- return (
472
- <View key={`${row}:${column}`} testID={focused && !active ? "merong-worksheet-address-match" : undefined} style={{
473
- position: "absolute", left: columns[column], top: rows[row], width: cellWidth, height: cellHeight,
474
- justifyContent: "center", paddingHorizontal: 4 * scale, overflow: "hidden",
475
- backgroundColor: style?.fill ?? theme.colors.surface0,
476
- borderRightWidth: 1, borderBottomWidth: 1, borderColor: theme.colors.border,
477
- ...(highlighted ? { borderWidth: 2, borderColor: theme.colors.accent } : {}),
478
- }}>
479
- {cell?.[2] ? (
480
- <Text selectable {...(web ? { dataSet: { worksheetCellText: "" } } : {})}
481
- ref={web ? (node) => applyWebTitle(node, cell[2]) : undefined}
482
- style={[{
483
- color: style?.color ?? (style?.fill ? "#181818" : theme.colors.foreground),
484
- textAlign: style?.align ?? (cell[4] ? "right" : "left"),
485
- fontSize, lineHeight: fontSize * 1.22,
486
- fontWeight: style?.bold ? "700" : "400", fontStyle: style?.italic ? "italic" : "normal",
487
- fontVariant: ["tabular-nums"],
488
- }, web && webCellText]}>
489
- {hits ? <CellMatches value={cell[2]} hits={hits} active={active} theme={theme} /> : cell[2]}
490
- </Text>
491
- ) : null}
492
- </View>
493
- );
494
- };
495
- for (const [row, column, lastRow, lastColumn] of sheet.merges) {
496
- if (lastRow < firstRow || row >= endRow || lastColumn < firstColumn || column >= endColumn) continue;
497
- cells.push(renderCell(row, column, lastRow, lastColumn));
498
- for (let rowIndex = Math.max(row, firstRow); rowIndex <= Math.min(lastRow, endRow - 1); rowIndex++) {
499
- for (let colIndex = Math.max(column, firstColumn); colIndex <= Math.min(lastColumn, endColumn - 1); colIndex++) {
500
- covered.add(rowIndex * columnCount + colIndex);
501
- }
502
- }
503
- }
504
- for (let row = firstRow; row < endRow; row++) {
505
- if (rows[row] === rows[row + 1]) continue;
506
- for (let column = firstColumn; column < endColumn; column++) {
507
- if (!covered.has(row * columnCount + column)) cells.push(renderCell(row, column));
508
- }
509
- }
510
- return cells;
511
- }
512
-
513
- function CellMatches({ value, hits, active, theme }: {
514
- value: string; hits: WorksheetMatch[]; active?: WorksheetMatch; theme: Theme;
515
- }) {
516
- let offset = 0;
517
- return <>{hits.map((hit) => {
518
- const [, , start, end] = hit;
519
- const before = value.slice(offset, start);
520
- offset = end;
521
- const selected = hit === active;
522
- return <Text key={start}>{before}
523
- <Text testID={selected ? "merong-worksheet-find-active" : undefined} style={{
524
- backgroundColor: selected ? theme.colors.accent : theme.colors.surface2,
525
- color: selected ? theme.colors.accentForeground : theme.colors.foreground,
526
- }}>{value.slice(start, end)}</Text>
527
- </Text>;
528
- })}{value.slice(offset)}</>;
529
- }
530
-
531
- export function WorksheetPanel(props: PluginFilePanelProps) {
532
- const { file, host, workspaceId, theme, layout: { compact } } = props;
533
- const { t } = useTranslation(messages);
534
- const rpc = useRpc(readWorksheet);
535
- const searchText = useRpc(findWorksheetText);
536
- const generation = useFileGeneration(file);
537
- const panel = useRef<View>(null);
538
- const web = Platform.OS === "web";
539
- const tabActive = isTabActive(props.tab);
540
- const [selected, setSelected] = useState(0);
541
- const [scale, setScale] = useState(1);
542
- const [dragMode, setDragMode] = useState(false);
543
- const { findOpen, showFind, hideFind } = useReaderFindVisibility();
544
- const [addressOnly, setAddressOnly] = useState(false);
545
- const [pinnedSheets, setPinnedSheets] = useState<Partial<Record<number, FrozenAxes>>>({});
546
- const pinned = pinnedSheets[selected] ?? noPins;
547
- const onPin = (axis: keyof CellAddress, index: number) => setPinnedSheets((sheets) => {
548
- const existing = sheets[selected];
549
- return { ...sheets, [selected]: { ...existing, [axis]: existing?.[axis] === index ? undefined : index } };
550
- });
551
- const fileKey = ["merong-docs", "worksheet", host.id, workspaceId, file.path, file.modifiedAt, generation, selected] as const;
552
- const result = useQuery({
553
- queryKey: fileKey,
554
- queryFn: () => rpc({ workspaceId, path: file.path, sheet: selected }),
555
- placeholderData: (previous) => previous,
556
- staleTime: Infinity, gcTime: 30_000, retry: false,
557
- });
558
- const sheet = result.isPlaceholderData ? undefined : result.data?.sheet;
559
- const names = result.data?.names ?? [];
560
- const find = useFindResults<WorksheetHit>([...fileKey, addressOnly], !!sheet && tabActive && findOpen,
561
- async (criteria) => {
562
- const address = cellAddress(criteria.query);
563
- const targets: WorksheetHit[] = address && sheet?.rows[address.row] && sheet.columns[address.column]
564
- ? [[address.row, address.column]] : [];
565
- if (addressOnly) return { matches: targets, limited: false, invalidPattern: false };
566
- const text = await searchText({ workspaceId, path: file.path, sheet: selected, ...criteria });
567
- return targets.length ? { ...text, matches: [...targets, ...text.matches] } : text;
568
- });
569
- const matches = useMemo(() => {
570
- const grouped = new Map<string, WorksheetMatch[]>();
571
- for (const hit of find.matches) {
572
- if (hit.length !== 4) continue;
573
- const key = `${hit[0]}:${hit[1]}`;
574
- const cell = grouped.get(key);
575
- if (cell) cell.push(hit);
576
- else grouped.set(key, [hit]);
577
- }
578
- return grouped;
579
- }, [find.matches]);
580
- const searchFocus = useMemo(() => find.active && { row: find.active[0], column: find.active[1] }, [find.active]);
581
- const openFind = () => {
582
- if (findOpen) return focusReaderFind(panel.current, findId);
583
- const selected = web ? readerSelection(panel.current) : "";
584
- if (selected && !selected.includes("\n")) find.changeQuery(selected.slice(0, 256));
585
- showFind();
586
- };
587
- useReaderFindShortcuts(panel, findId, web && tabActive && !!sheet,
588
- { open: openFind, close: hideFind, move: find.move, isOpen: () => findOpen });
589
- const zoomControls = <ZoomControls {...{ scale, theme, compact }} disabled={!sheet}
590
- stepZoom={(factor) => setScale((previous) => boundZoom(previous * factor))} setZoom={setScale} />;
591
- return (
592
- <View ref={panel} tabIndex={web ? 0 : undefined} style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface0 }}>
593
- <Toolbar theme={theme} filePanel={props} nativePrimary={!web && zoomControls}>
594
- {web && zoomControls}
595
- {web && <Control title={t("dragWorksheet")} icon="Hand" selected={dragMode} disabled={!sheet}
596
- theme={theme} compact={compact} onPress={() => setDragMode((enabled) => !enabled)} />}
597
- <Control title={t("find")} icon="Search" selected={findOpen} disabled={!sheet}
598
- theme={theme} compact={compact} onPress={findOpen ? hideFind : openFind} />
599
- <ExternalFileAction {...props} />
600
- </Toolbar>
601
- {sheet?.truncated && <Text style={{ padding: 8, color: theme.colors.foregroundMuted }}>{t("worksheetTruncated")}</Text>}
602
- <View style={{ flex: 1, minHeight: 0 }}>
603
- {sheet?.rows.length && sheet.columns.length ? <WorksheetGrid key={selected}
604
- {...{ sheet, scale, theme, pinned, onPin, matches, compact, findOpen, dragMode, tabActive }} focus={searchFocus}
605
- active={find.active?.length === 4 ? find.active : undefined} onZoom={setScale} />
606
- : result.isFetching ? <Loading />
607
- : result.isError ? <ReadError theme={theme} compact={compact} label={t("textError")} error={result.error}
608
- retry={t("retry")} onRetry={() => { void result.refetch(); }} />
609
- : <Text style={{ padding: 16, color: theme.colors.foregroundMuted }}>{t("empty")}</Text>}
610
- {findOpen && <ReaderFindBar testID={findId} find={find} theme={theme} compact={compact} close={hideFind}
611
- textOptions={!addressOnly} placeholder={t(addressOnly ? "addressSearch" : "worksheetSearch")}
612
- option={<Control title={t("addressesOnly")} icon="MapPin" theme={theme} compact={compact} small
613
- selected={addressOnly} onPress={() => { find.reset(); setAddressOnly((only) => !only); }} />} />}
614
- </View>
615
- {!!names.length && (
616
- <ScrollView horizontal nestedScrollEnabled
617
- style={{ flexGrow: 0, borderTopWidth: 1, borderColor: theme.colors.border }}
618
- contentContainerStyle={{ paddingHorizontal: 4, paddingVertical: 2, gap: 4 }}>
619
- {names.map((name, index) => (
620
- <Control key={index} title={name || `${t("sheet")} ${index + 1}`} theme={theme} compact={compact}
621
- selected={index === selected} onPress={() => {
622
- if (index === selected) return;
623
- setSelected(index);
624
- find.reset();
625
- }} />
626
- ))}
627
- </ScrollView>
628
- )}
629
- </View>
630
- );
631
- }
1
+ import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import { Platform, Pressable, Text, View, type ScrollView as ScrollViewInstance, type TextStyle } from "react-native";
3
+ import { useQuery } from "@tanstack/react-query";
4
+ import { useRpc, useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
5
+ import { copyText, Icon, Loading, ScrollView } from "@getpaseo/plugin/client/ui";
6
+ import { findWorksheetText, readWorksheet, type Worksheet, type WorksheetMatch } from "../shared/contracts";
7
+ import { Control, isTabActive, ReadError, Toolbar, useFileGeneration, useReaderShortcuts, type Theme } from "./controls";
8
+ import { ExternalFileAction } from "./external-file";
9
+ import { messages } from "./messages";
10
+ import { useNativeContacts } from "./native-contacts";
11
+ import { ReaderFindBar, useFindResults, useReaderFindShortcuts, useReaderFindVisibility } from "./reader-find";
12
+ import { useReaderNotice } from "./reader-notice";
13
+ import { boundZoom, clamp, constrainGrid, panAndPinch, zoomAround, zoomGridScroll, type Contact, type Point, type Position, type Size } from "./viewport-geometry";
14
+ import { applyWebTitle, bindWorksheetGrid, bindWorksheetMenuDismiss, focusReaderFind, readerSelection, setWebCursor } from "./web";
15
+ import { ZoomControls } from "./zoom-controls";
16
+
17
+ const gutter = 48;
18
+ const headingHeight = 26;
19
+ const findId = "merong-worksheet-find";
20
+ const webCellText = { overflowWrap: "anywhere", whiteSpace: "pre-wrap" } as TextStyle;
21
+ type CellAddress = { row: number; column: number };
22
+ type FrozenAxes = Partial<CellAddress>;
23
+ type CellMenu = { address: CellAddress; point: Point };
24
+ type CellPress = { contact: Contact; timer: ReturnType<typeof setTimeout>; held: boolean };
25
+ type WorksheetHit = WorksheetMatch | [row: number, column: number];
26
+ const noPins: FrozenAxes = {};
27
+
28
+ function offsets(values: number[], scale: number) {
29
+ let position = 0;
30
+ return [0, ...values.map((value) => position += value * scale)];
31
+ }
32
+
33
+ function withoutTrack(values: number[], track?: number) {
34
+ if (track === undefined) return values;
35
+ const size = values[track + 1] - values[track];
36
+ return values.map((offset, index) => index === track + 1 ? values[track] : index > track ? offset - size : offset);
37
+ }
38
+
39
+ function upperOffset(values: number[], target: number) {
40
+ let first = 0;
41
+ let end = values.length;
42
+ while (first < end) {
43
+ const middle = Math.floor((first + end) / 2);
44
+ if (values[middle] <= target) first = middle + 1;
45
+ else end = middle;
46
+ }
47
+ return first;
48
+ }
49
+
50
+ function visibleRange(values: number[], start: number, length: number) {
51
+ const last = values.length - 1;
52
+ return {
53
+ first: Math.min(last, Math.max(0, upperOffset(values, start - 80) - 1)),
54
+ end: Math.min(last, upperOffset(values, start + length + 80)),
55
+ };
56
+ }
57
+
58
+ function columnName(column: number) {
59
+ let name = "";
60
+ for (let value = column + 1; value > 0; value = Math.floor((value - 1) / 26)) {
61
+ name = String.fromCharCode(65 + (value - 1) % 26) + name;
62
+ }
63
+ return name;
64
+ }
65
+
66
+ function cellAddress(text: string): CellAddress | undefined {
67
+ const match = /^\$?([A-Z]{1,3})\$?([1-9]\d{0,6})$/.exec(text.trim().toUpperCase());
68
+ if (!match) return;
69
+ let column = 0;
70
+ for (const letter of match[1]) column = column * 26 + letter.charCodeAt(0) - 64;
71
+ return { row: Number(match[2]) - 1, column: column - 1 };
72
+ }
73
+
74
+ function WorksheetGrid({ sheet, scale, theme, onZoom, focus, pinned, onPin, matches, active, compact, findOpen, dragMode, tabActive }: {
75
+ sheet: Worksheet; scale: number; theme: Theme; onZoom: (scale: number) => void; compact: boolean;
76
+ focus?: CellAddress; pinned: FrozenAxes; onPin: (axis: keyof CellAddress, index: number) => void; findOpen: boolean;
77
+ matches: ReadonlyMap<string, WorksheetMatch[]>; active?: WorksheetMatch; dragMode: boolean; tabActive: boolean;
78
+ }) {
79
+ const { t } = useTranslation(messages);
80
+ const notify = useReaderNotice();
81
+ const web = Platform.OS === "web";
82
+ const [viewport, setViewport] = useState({ width: 0, height: 0 });
83
+ const [left, setLeft] = useState(0);
84
+ const [top, setTop] = useState(0);
85
+ const [position, setPosition] = useState<Position>({ x: 0, y: 0, scale });
86
+ const current = useRef(position);
87
+ const beforeFind = useRef<Position>(undefined);
88
+ const gridViewport = useRef<View>(null);
89
+ const shortcuts = useReaderShortcuts();
90
+ const horizontal = useRef<ScrollViewInstance>(null);
91
+ const vertical = useRef<ScrollViewInstance>(null);
92
+ const webZoom = useRef<Position>(undefined);
93
+ const [picked, setPicked] = useState<Worksheet["cells"][number]>();
94
+ const [menu, setMenu] = useState<CellMenu>();
95
+ const closeMenu = useCallback(() => setMenu(undefined), []);
96
+ const press = useRef<CellPress | null>(undefined);
97
+ const cellScale = web ? scale : 1;
98
+ const fullColumns = useMemo(() => offsets(sheet.columns, cellScale), [sheet.columns, cellScale]);
99
+ const fullRows = useMemo(() => offsets(sheet.rows, cellScale), [sheet.rows, cellScale]);
100
+ const frozenRow = pinned.row !== undefined && sheet.rows[pinned.row] ? pinned.row : undefined;
101
+ const frozenColumn = pinned.column !== undefined && sheet.columns[pinned.column] ? pinned.column : undefined;
102
+ const rows = useMemo(() => withoutTrack(fullRows, frozenRow), [fullRows, frozenRow]);
103
+ const columns = useMemo(() => withoutTrack(fullColumns, frozenColumn), [fullColumns, frozenColumn]);
104
+ const frozenRowSize = frozenRow === undefined ? 0 : fullRows[frozenRow + 1] - fullRows[frozenRow];
105
+ const frozenColumnSize = frozenColumn === undefined ? 0 : fullColumns[frozenColumn + 1] - fullColumns[frozenColumn];
106
+ const width = columns[columns.length - 1];
107
+ const height = rows[rows.length - 1];
108
+ const content = useMemo(() => ({ width, height }), [width, height]);
109
+ const zoom = web ? 1 : position.scale;
110
+ const { x: frozenWidth, y: frozenHeight } = frozenInsets(zoom);
111
+ const scrollLeft = web ? left : -position.x;
112
+ const scrollTop = web ? top : -position.y;
113
+ const { first: firstColumn, end: endColumn } = visibleRange(columns, scrollLeft / zoom, (viewport.width - frozenWidth) / zoom);
114
+ const { first: firstRow, end: endRow } = visibleRange(rows, scrollTop / zoom, (viewport.height - frozenHeight) / zoom);
115
+ function frozenInsets(scale: number) {
116
+ return { x: Math.min(frozenColumnSize * scale, viewport.width / 3), y: Math.min(frozenRowSize * scale, viewport.height / 3) };
117
+ }
118
+ function viewportPosition(position: Position) {
119
+ const inset = frozenInsets(position.scale);
120
+ return { ...position, x: position.x + inset.x, y: position.y + inset.y };
121
+ }
122
+ function constrainInViewport(position: Position) {
123
+ const inset = frozenInsets(position.scale);
124
+ return constrainGrid({ ...position, x: position.x - inset.x, y: position.y - inset.y },
125
+ { width: viewport.width - inset.x, height: viewport.height - inset.y }, content);
126
+ }
127
+ function update(next: Position) {
128
+ if (next.x === current.current.x && next.y === current.current.y && next.scale === current.current.scale) return false;
129
+ current.current = next;
130
+ setPosition(next);
131
+ return true;
132
+ }
133
+ const { handlers: nativeGestures, stopInertia } = useNativeContacts(gridViewport, !web && viewport.width > 0, (previous, next) => {
134
+ const before = current.current;
135
+ const after = constrainInViewport(panAndPinch(viewportPosition(before), previous, next));
136
+ update(after);
137
+ if (after.scale !== before.scale) onZoom(after.scale);
138
+ }, ({ x, y }) => {
139
+ const position = viewportPosition(current.current);
140
+ return update(constrainInViewport({ ...position, x: position.x + x, y: position.y + y }));
141
+ }, trackTouch);
142
+ useLayoutEffect(() => {
143
+ if (web) return;
144
+ stopInertia();
145
+ if (findOpen) beforeFind.current ??= current.current;
146
+ const saved = findOpen ? undefined : beforeFind.current;
147
+ beforeFind.current = findOpen ? beforeFind.current : undefined;
148
+ const anchor = { x: viewport.width / 2, y: viewport.height / 2 };
149
+ update(constrainInViewport(zoomAround(viewportPosition(saved ?? current.current), scale, anchor)));
150
+ }, [web, viewport, content, scale, stopInertia, frozenRowSize, frozenColumnSize, findOpen]);
151
+ useLayoutEffect(() => {
152
+ const pending = webZoom.current;
153
+ webZoom.current = undefined;
154
+ if (!pending || pending.scale !== scale) return;
155
+ horizontal.current?.scrollTo({ x: pending.x, animated: false });
156
+ vertical.current?.scrollTo({ y: pending.y, animated: false });
157
+ }, [scale]);
158
+ function zoomWeb(factor: number | undefined, anchor: Point, scroll: Point) {
159
+ const previous = webZoom.current ?? { ...scroll, scale };
160
+ const next = factor === undefined ? 1 : boundZoom(previous.scale * factor);
161
+ if (next === previous.scale) return;
162
+ webZoom.current = zoomGridScroll(previous, next, anchor, viewport,
163
+ { width: width / scale, height: height / scale },
164
+ { width: frozenColumnSize / scale, height: frozenRowSize / scale });
165
+ onZoom(next);
166
+ }
167
+ const focusGeometry = useRef({ columns, rows, frozenWidth, frozenHeight, frozenRow, frozenColumn, scrollLeft, scrollTop });
168
+ focusGeometry.current = { columns, rows, frozenWidth, frozenHeight, frozenRow, frozenColumn, scrollLeft, scrollTop };
169
+ useLayoutEffect(() => {
170
+ if (!focus || !viewport.width || !viewport.height || focus.row >= sheet.rows.length || focus.column >= sheet.columns.length) return;
171
+ const { columns, rows, frozenWidth, frozenHeight, frozenRow, frozenColumn, scrollLeft, scrollTop } = focusGeometry.current;
172
+ stopInertia();
173
+ const atScale = web ? 1 : current.current.scale;
174
+ const x = focus.column === frozenColumn ? scrollLeft : columns[focus.column] * atScale;
175
+ const y = focus.row === frozenRow ? scrollTop
176
+ : Math.max(0, rows[focus.row] * atScale - (viewport.height - frozenHeight) * 0.35);
177
+ if (web) {
178
+ horizontal.current?.scrollTo({ x, animated: false });
179
+ vertical.current?.scrollTo({ y, animated: false });
180
+ } else {
181
+ update(constrainGrid({ ...current.current, x: -x, y: -y },
182
+ { width: viewport.width - frozenWidth, height: viewport.height - frozenHeight }, content));
183
+ }
184
+ }, [focus, viewport, web, sheet, stopInertia]);
185
+ const cellIndex = useMemo(() => {
186
+ const byRow = new Map<number, Map<number, Worksheet["cells"][number]>>();
187
+ for (const cell of sheet.cells) {
188
+ const [row, column] = cell;
189
+ const cells = byRow.get(row) ?? new Map();
190
+ cells.set(column, cell);
191
+ byRow.set(row, cells);
192
+ }
193
+ return byRow;
194
+ }, [sheet.cells]);
195
+ useLayoutEffect(() => {
196
+ setPicked(undefined);
197
+ closeMenu();
198
+ return () => { clearTimeout(press.current?.timer); press.current = undefined; };
199
+ }, [sheet, closeMenu]);
200
+ const gridActions = useRef({ open: openCellMenu, dragMode, zoom: zoomWeb });
201
+ gridActions.current = { open: openCellMenu, dragMode, zoom: zoomWeb };
202
+ useLayoutEffect(() => {
203
+ if (web && tabActive) return bindWorksheetGrid(gridViewport.current, {
204
+ open: (point) => gridActions.current.open(point),
205
+ dragMode: () => gridActions.current.dragMode,
206
+ shortcuts: () => shortcuts.current,
207
+ zoom: (...args) => gridActions.current.zoom(...args),
208
+ });
209
+ }, [tabActive, web, shortcuts]);
210
+ useLayoutEffect(() => {
211
+ if (web && tabActive) setWebCursor(gridViewport.current, dragMode ? "grab" : "");
212
+ }, [dragMode, tabActive, web]);
213
+ function addressAt({ x, y }: Point): CellAddress | undefined {
214
+ if (x < 0 || y < 0 || x >= viewport.width || y >= viewport.height) return;
215
+ const column = frozenColumn !== undefined && x < frozenWidth ? frozenColumn
216
+ : upperOffset(columns, (x - frozenWidth + scrollLeft) / zoom) - 1;
217
+ const row = frozenRow !== undefined && y < frozenHeight ? frozenRow
218
+ : upperOffset(rows, (y - frozenHeight + scrollTop) / zoom) - 1;
219
+ if (sheet.rows[row] && sheet.columns[column]) return { row, column };
220
+ }
221
+ function openCellMenu(point: Point) {
222
+ const address = addressAt(point);
223
+ if (!address) return false;
224
+ setMenu({ address, point });
225
+ return true;
226
+ }
227
+ function pickCell(point: Point) {
228
+ const address = addressAt(point);
229
+ if (!address) return setPicked(undefined);
230
+ const { row, column } = address;
231
+ const merge = sheet.merges.find(([firstRow, firstColumn, lastRow, lastColumn]) =>
232
+ row >= firstRow && row <= lastRow && column >= firstColumn && column <= lastColumn);
233
+ const cell = cellIndex.get(merge?.[0] ?? row)?.get(merge?.[1] ?? column);
234
+ setPicked(cell?.[2] ? cell : undefined);
235
+ }
236
+ function measureContact(contact: Contact, action: (point: Point) => void) {
237
+ gridViewport.current?.measure((_left, _top, _width, _height, x, y) => action({ x: contact.x - x, y: contact.y - y }));
238
+ }
239
+ function trackTouch(_visible: Contact[], contacts: Contact[]) {
240
+ const [point] = contacts;
241
+ const start = press.current;
242
+ if (!point) {
243
+ clearTimeout(start?.timer);
244
+ press.current = undefined;
245
+ if (start?.held) return true;
246
+ if (!start) return false;
247
+ measureContact(start.contact, pickCell);
248
+ return true;
249
+ }
250
+ if (start?.held) return true;
251
+ if (contacts.length > 1 || start && (point.id !== start.contact.id || Math.hypot(point.x - start.contact.x, point.y - start.contact.y) > 7)) {
252
+ clearTimeout(start?.timer);
253
+ press.current = null;
254
+ } else if (start === undefined) {
255
+ const timer = setTimeout(() => {
256
+ if (!press.current) return;
257
+ press.current.held = true;
258
+ measureContact(point, (target) => gridActions.current.open(target));
259
+ }, 500);
260
+ press.current = { contact: point, timer, held: false };
261
+ }
262
+ return false;
263
+ }
264
+ const copyPicked = async (value: string) => {
265
+ try {
266
+ await copyText(value);
267
+ notify?.(t("copied"));
268
+ } catch {
269
+ notify?.(t("textCopyError"), true);
270
+ }
271
+ };
272
+ const selected = useMemo(() => picked && { row: picked[0], column: picked[1] }, [picked]);
273
+ const decoration = useMemo(() => ({ focus, selected, matches, active }), [focus, selected, matches, active]);
274
+ const gridColor = theme.colors.border;
275
+ const header = {
276
+ position: "absolute", justifyContent: "center", alignItems: "center",
277
+ backgroundColor: theme.colors.surface1, borderRightWidth: 1, borderBottomWidth: 1, borderColor: gridColor,
278
+ } as const;
279
+ const headerText = { color: theme.colors.foregroundMuted, fontSize: 12 };
280
+ const rowNumbers = [];
281
+ const columnLabels = [];
282
+ const cells = useMemo(() => renderCells(
283
+ sheet, cellIndex, rows, columns, { firstRow, endRow, firstColumn, endColumn }, cellScale, theme, decoration,
284
+ ), [sheet, cellIndex, rows, columns, firstRow, endRow, firstColumn, endColumn, cellScale, theme, decoration]);
285
+ const pinnedCells = useMemo(() => {
286
+ const render = (rows: number[], columns: number[], firstRow: number, endRow: number, firstColumn: number, endColumn: number) =>
287
+ renderCells(sheet, cellIndex, rows, columns, { firstRow, endRow, firstColumn, endColumn }, cellScale, theme, decoration);
288
+ return {
289
+ row: frozenRow === undefined ? null : render(fullRows, columns, frozenRow, frozenRow + 1, firstColumn, endColumn),
290
+ column: frozenColumn === undefined ? null : render(rows, fullColumns, firstRow, endRow, frozenColumn, frozenColumn + 1),
291
+ corner: frozenRow === undefined || frozenColumn === undefined ? null
292
+ : render(fullRows, fullColumns, frozenRow, frozenRow + 1, frozenColumn, frozenColumn + 1),
293
+ };
294
+ }, [frozenRow, frozenColumn, firstRow, endRow, firstColumn, endColumn, sheet, cellIndex,
295
+ rows, columns, fullRows, fullColumns, cellScale, theme, decoration]);
296
+ for (let column = firstColumn; column < endColumn; column++) {
297
+ const size = (columns[column + 1] - columns[column]) * zoom;
298
+ if (size <= 0) continue;
299
+ columnLabels.push(
300
+ <View key={column} style={{ ...header, left: frozenWidth + columns[column] * zoom - scrollLeft, width: size, height: headingHeight }}>
301
+ <Text style={headerText}>{columnName(column)}</Text>
302
+ </View>,
303
+ );
304
+ }
305
+ for (let row = firstRow; row < endRow; row++) {
306
+ const size = (rows[row + 1] - rows[row]) * zoom;
307
+ if (size <= 0) continue;
308
+ rowNumbers.push(
309
+ <View key={row} style={{ ...header, top: frozenHeight + rows[row] * zoom - scrollTop, width: gutter, height: size }}>
310
+ <Text style={headerText}>{row + 1}</Text>
311
+ </View>,
312
+ );
313
+ }
314
+
315
+ return (
316
+ <View testID="merong-worksheet-grid" style={{ flex: 1, minHeight: 0, overflow: "hidden" }}>
317
+ <View style={{ height: headingHeight, marginLeft: gutter, overflow: "hidden", backgroundColor: theme.colors.surface1 }}>
318
+ {columnLabels}
319
+ {frozenColumn !== undefined && frozenWidth > 0 && (
320
+ <View style={{ ...header, left: 0, top: 0, width: frozenWidth, height: headingHeight, borderColor: theme.colors.accent }}>
321
+ <Text style={headerText}>{columnName(frozenColumn)}</Text>
322
+ </View>
323
+ )}
324
+ </View>
325
+ <View
326
+ ref={gridViewport}
327
+ testID="merong-worksheet-viewport"
328
+ collapsable={web}
329
+ tabIndex={web && tabActive ? 0 : undefined}
330
+ {...nativeGestures}
331
+ style={{ flex: 1, minHeight: 0, marginLeft: gutter, overflow: "hidden" }}
332
+ onLayout={({ nativeEvent }) => {
333
+ const { width, height } = nativeEvent.layout;
334
+ setViewport((previous) => previous.width === width && previous.height === height ? previous : { width, height });
335
+ }}
336
+ >
337
+ {web ? (
338
+ <ScrollView ref={horizontal} horizontal nestedScrollEnabled scrollEventThrottle={16}
339
+ testID="merong-worksheet-horizontal" onScroll={({ nativeEvent }) => setLeft(Math.max(0, nativeEvent.contentOffset.x))}>
340
+ <ScrollView ref={vertical} nestedScrollEnabled scrollEventThrottle={16}
341
+ style={{ width: Math.max(viewport.width, width + frozenWidth), height: viewport.height }}
342
+ testID="merong-worksheet-vertical" onScroll={({ nativeEvent }) => setTop(Math.max(0, nativeEvent.contentOffset.y))}>
343
+ <View style={{ width: width + frozenWidth, height: height + frozenHeight }}>
344
+ <View style={{ position: "absolute", left: frozenWidth, top: frozenHeight, width, height }}>{cells}</View>
345
+ </View>
346
+ </ScrollView>
347
+ </ScrollView>
348
+ ) : (
349
+ <View testID="merong-worksheet-touch" style={{
350
+ position: "absolute", left: frozenWidth, top: frozenHeight, width, height, transformOrigin: [0, 0, 0],
351
+ transform: [{ translateX: position.x }, { translateY: position.y }, { scale: zoom }],
352
+ }}>{cells}</View>
353
+ )}
354
+ {frozenRow !== undefined && frozenHeight > 0 && <View testID="merong-worksheet-frozen-row" pointerEvents={web ? "auto" : "none"}
355
+ style={{ position: "absolute", top: 0, left: frozenWidth, right: 0,
356
+ height: frozenHeight, overflow: "hidden", backgroundColor: theme.colors.surface0, borderBottomWidth: 1, borderColor: theme.colors.accent }}>
357
+ <View style={{ position: "absolute", width, height: fullRows.at(-1), transformOrigin: [0, 0, 0],
358
+ transform: [{ translateX: -scrollLeft }, { translateY: -fullRows[frozenRow] * zoom }, { scale: zoom }] }}>{pinnedCells.row}</View>
359
+ </View>}
360
+ {frozenColumn !== undefined && frozenWidth > 0 && <View testID="merong-worksheet-frozen-column" pointerEvents={web ? "auto" : "none"}
361
+ style={{ position: "absolute", top: frozenHeight, bottom: 0,
362
+ left: 0, width: frozenWidth, overflow: "hidden", backgroundColor: theme.colors.surface0, borderRightWidth: 1, borderColor: theme.colors.accent }}>
363
+ <View style={{ position: "absolute", width: fullColumns.at(-1), height, transformOrigin: [0, 0, 0],
364
+ transform: [{ translateX: -fullColumns[frozenColumn] * zoom }, { translateY: -scrollTop }, { scale: zoom }] }}>{pinnedCells.column}</View>
365
+ </View>}
366
+ {frozenRow !== undefined && frozenColumn !== undefined && frozenHeight > 0 && frozenWidth > 0 && (
367
+ <View testID="merong-worksheet-frozen-corner" pointerEvents={web ? "auto" : "none"}
368
+ style={{ position: "absolute", top: 0, left: 0, width: frozenWidth, height: frozenHeight, overflow: "hidden",
369
+ backgroundColor: theme.colors.surface0, borderBottomWidth: 1, borderRightWidth: 1, borderColor: theme.colors.accent }}>
370
+ <View style={{ position: "absolute", width: fullColumns.at(-1), height: fullRows.at(-1), transformOrigin: [0, 0, 0],
371
+ transform: [{ translateX: -fullColumns[frozenColumn] * zoom }, { translateY: -fullRows[frozenRow] * zoom }, { scale: zoom }] }}>{pinnedCells.corner}</View>
372
+ </View>
373
+ )}
374
+ </View>
375
+ <View pointerEvents="none" style={{ position: "absolute", top: headingHeight, bottom: 0, left: 0, width: gutter,
376
+ overflow: "hidden", backgroundColor: theme.colors.surface1 }}>
377
+ {rowNumbers}
378
+ {frozenRow !== undefined && frozenHeight > 0 && (
379
+ <View style={{ ...header, top: 0, width: gutter, height: frozenHeight, borderColor: theme.colors.accent }}>
380
+ <Text style={headerText}>{frozenRow + 1}</Text>
381
+ </View>
382
+ )}
383
+ </View>
384
+ <View pointerEvents="none" style={{ ...header, top: 0, left: 0, width: gutter, height: headingHeight }} />
385
+ {!!picked?.[2] && <View style={[{ position: "absolute", right: 8,
386
+ borderWidth: 1, borderRadius: 7, borderColor: theme.colors.border, backgroundColor: theme.colors.surface1 },
387
+ findOpen ? { bottom: 8 } : { top: headingHeight + 8 }]}>
388
+ <Control title={t("copyCell")} icon="Copy" theme={theme} compact={compact} onPress={() => { void copyPicked(picked[2]); }} />
389
+ </View>}
390
+ {menu && <WorksheetCellMenu {...{ menu, pinned, viewport, theme, onPin }} close={closeMenu} />}
391
+ </View>
392
+ );
393
+ }
394
+
395
+ function WorksheetCellMenu({ menu, pinned, viewport, theme, onPin, close }: {
396
+ menu: CellMenu; pinned: FrozenAxes; viewport: Size; theme: Theme;
397
+ onPin: (axis: keyof CellAddress, index: number) => void; close: () => void;
398
+ }) {
399
+ const { t } = useTranslation(messages);
400
+ const web = Platform.OS === "web";
401
+ const ref = useRef<View>(null);
402
+ const shortcuts = useReaderShortcuts();
403
+ const [height, setHeight] = useState(120);
404
+ useLayoutEffect(() => {
405
+ if (web) return bindWorksheetMenuDismiss(ref.current, close, () => shortcuts.current);
406
+ }, [web, close, shortcuts]);
407
+ const { address: { row, column }, point } = menu;
408
+ const width = Math.min(220, viewport.width - 8);
409
+ const columnLabel = columnName(column);
410
+ const actions = [
411
+ { axis: "row", index: row, label: t(pinned.row === row ? "unfreezeRow" : "freezeRow", { row: row + 1 }) },
412
+ { axis: "column", index: column, label: t(pinned.column === column ? "unfreezeColumn" : "freezeColumn", { column: columnLabel }) },
413
+ ] as const;
414
+ return (
415
+ <View pointerEvents="box-none" style={{ position: "absolute", inset: 0, zIndex: 3 }}>
416
+ {!web && <Pressable accessible={false} onPress={close} style={{ position: "absolute", inset: 0 }} />}
417
+ <View ref={ref} testID="merong-worksheet-cell-menu" accessibilityRole="menu" accessibilityLabel={t("cellActions")}
418
+ tabIndex={web ? -1 : undefined} onAccessibilityEscape={close}
419
+ onLayout={({ nativeEvent }) => setHeight(nativeEvent.layout.height)} style={{
420
+ position: "absolute", left: gutter + clamp(point.x, 4, viewport.width - width - 4),
421
+ top: headingHeight + clamp(point.y, 4, viewport.height - height - 4),
422
+ width, padding: 4, borderRadius: 8, borderWidth: 1, borderColor: theme.colors.border, backgroundColor: theme.colors.surface1,
423
+ }}>
424
+ <Text style={{ color: theme.colors.foregroundMuted, paddingHorizontal: 8, paddingVertical: 4, fontSize: 12 }}>
425
+ {columnLabel}{row + 1}
426
+ </Text>
427
+ {actions.map(({ axis, index, label }) => (
428
+ <Pressable key={axis} accessibilityRole="menuitem" onPress={() => { onPin(axis, index); close(); }}
429
+ style={({ pressed, hovered }: { pressed: boolean; hovered?: boolean }) => ({
430
+ minHeight: web ? 32 : 40, paddingHorizontal: 8, paddingVertical: 4,
431
+ borderRadius: 4, flexDirection: "row", alignItems: "center", gap: 8,
432
+ backgroundColor: pressed || hovered ? theme.colors.surface2 : "transparent",
433
+ })}>
434
+ <Icon name={pinned[axis] === index ? "PinOff" : "Pin"} size={15} color={theme.colors.foregroundMuted} />
435
+ <Text style={{ flexShrink: 1, color: theme.colors.foreground, fontSize: 13 }}>{label}</Text>
436
+ </Pressable>
437
+ ))}
438
+ </View>
439
+ </View>
440
+ );
441
+ }
442
+
443
+ function renderCells(
444
+ sheet: Worksheet,
445
+ cellIndex: Map<number, Map<number, Worksheet["cells"][number]>>,
446
+ rows: number[],
447
+ columns: number[],
448
+ { firstRow, endRow, firstColumn, endColumn }: { firstRow: number; endRow: number; firstColumn: number; endColumn: number },
449
+ scale: number,
450
+ theme: Theme,
451
+ { focus, selected, matches, active }: {
452
+ focus?: CellAddress; selected?: CellAddress; matches: ReadonlyMap<string, WorksheetMatch[]>; active?: WorksheetMatch;
453
+ },
454
+ ) {
455
+ const cells = [];
456
+ const covered = new Set<number>();
457
+ const columnCount = sheet.columns.length;
458
+ const web = Platform.OS === "web";
459
+ const renderCell = (row: number, column: number, lastRow = row, lastColumn = column) => {
460
+ const cell = cellIndex.get(row)?.get(column);
461
+ const style = cell ? sheet.styles[cell[3]] : undefined;
462
+ const fontSize = (style?.fontSize ?? 14) * scale;
463
+ const cellWidth = columns[lastColumn + 1] - columns[column];
464
+ const cellHeight = rows[lastRow + 1] - rows[row];
465
+ const contains = (address?: CellAddress) =>
466
+ address && address.row >= row && address.row <= lastRow && address.column >= column && address.column <= lastColumn;
467
+ const focused = contains(focus);
468
+ const highlighted = focused || contains(selected);
469
+ const hits = matches.get(`${row}:${column}`);
470
+ if (cellWidth <= 0 || cellHeight <= 0) return null;
471
+ return (
472
+ <View key={`${row}:${column}`} testID={focused && !active ? "merong-worksheet-address-match" : undefined} style={{
473
+ position: "absolute", left: columns[column], top: rows[row], width: cellWidth, height: cellHeight,
474
+ justifyContent: "center", paddingHorizontal: 4 * scale, overflow: "hidden",
475
+ backgroundColor: style?.fill ?? theme.colors.surface0,
476
+ borderRightWidth: 1, borderBottomWidth: 1, borderColor: theme.colors.border,
477
+ ...(highlighted ? { borderWidth: 2, borderColor: theme.colors.accent } : {}),
478
+ }}>
479
+ {cell?.[2] ? (
480
+ <Text selectable {...(web ? { dataSet: { worksheetCellText: "" } } : {})}
481
+ ref={web ? (node) => applyWebTitle(node, cell[2]) : undefined}
482
+ style={[{
483
+ color: style?.color ?? (style?.fill ? "#181818" : theme.colors.foreground),
484
+ textAlign: style?.align ?? (cell[4] ? "right" : "left"),
485
+ fontSize, lineHeight: fontSize * 1.22,
486
+ fontWeight: style?.bold ? "700" : "400", fontStyle: style?.italic ? "italic" : "normal",
487
+ fontVariant: ["tabular-nums"],
488
+ }, web && webCellText]}>
489
+ {hits ? <CellMatches value={cell[2]} hits={hits} active={active} theme={theme} /> : cell[2]}
490
+ </Text>
491
+ ) : null}
492
+ </View>
493
+ );
494
+ };
495
+ for (const [row, column, lastRow, lastColumn] of sheet.merges) {
496
+ if (lastRow < firstRow || row >= endRow || lastColumn < firstColumn || column >= endColumn) continue;
497
+ cells.push(renderCell(row, column, lastRow, lastColumn));
498
+ for (let rowIndex = Math.max(row, firstRow); rowIndex <= Math.min(lastRow, endRow - 1); rowIndex++) {
499
+ for (let colIndex = Math.max(column, firstColumn); colIndex <= Math.min(lastColumn, endColumn - 1); colIndex++) {
500
+ covered.add(rowIndex * columnCount + colIndex);
501
+ }
502
+ }
503
+ }
504
+ for (let row = firstRow; row < endRow; row++) {
505
+ if (rows[row] === rows[row + 1]) continue;
506
+ for (let column = firstColumn; column < endColumn; column++) {
507
+ if (!covered.has(row * columnCount + column)) cells.push(renderCell(row, column));
508
+ }
509
+ }
510
+ return cells;
511
+ }
512
+
513
+ function CellMatches({ value, hits, active, theme }: {
514
+ value: string; hits: WorksheetMatch[]; active?: WorksheetMatch; theme: Theme;
515
+ }) {
516
+ let offset = 0;
517
+ return <>{hits.map((hit) => {
518
+ const [, , start, end] = hit;
519
+ const before = value.slice(offset, start);
520
+ offset = end;
521
+ const selected = hit === active;
522
+ return <Text key={start}>{before}
523
+ <Text testID={selected ? "merong-worksheet-find-active" : undefined} style={{
524
+ backgroundColor: selected ? theme.colors.accent : theme.colors.surface2,
525
+ color: selected ? theme.colors.accentForeground : theme.colors.foreground,
526
+ }}>{value.slice(start, end)}</Text>
527
+ </Text>;
528
+ })}{value.slice(offset)}</>;
529
+ }
530
+
531
+ export function WorksheetPanel(props: PluginFilePanelProps) {
532
+ const { file, host, workspaceId, theme, layout: { compact } } = props;
533
+ const { t } = useTranslation(messages);
534
+ const rpc = useRpc(readWorksheet);
535
+ const searchText = useRpc(findWorksheetText);
536
+ const generation = useFileGeneration(file);
537
+ const panel = useRef<View>(null);
538
+ const web = Platform.OS === "web";
539
+ const tabActive = isTabActive(props.tab);
540
+ const [selected, setSelected] = useState(0);
541
+ const [scale, setScale] = useState(1);
542
+ const [dragMode, setDragMode] = useState(false);
543
+ const { findOpen, showFind, hideFind } = useReaderFindVisibility();
544
+ const [addressOnly, setAddressOnly] = useState(false);
545
+ const [pinnedSheets, setPinnedSheets] = useState<Partial<Record<number, FrozenAxes>>>({});
546
+ const pinned = pinnedSheets[selected] ?? noPins;
547
+ const onPin = (axis: keyof CellAddress, index: number) => setPinnedSheets((sheets) => {
548
+ const existing = sheets[selected];
549
+ return { ...sheets, [selected]: { ...existing, [axis]: existing?.[axis] === index ? undefined : index } };
550
+ });
551
+ const fileKey = ["merong-docs", "worksheet", host.id, workspaceId, file.path, file.modifiedAt, generation, selected] as const;
552
+ const result = useQuery({
553
+ queryKey: fileKey,
554
+ queryFn: () => rpc({ workspaceId, path: file.path, sheet: selected }),
555
+ placeholderData: (previous) => previous,
556
+ staleTime: Infinity, gcTime: 30_000, retry: false,
557
+ });
558
+ const sheet = result.isPlaceholderData ? undefined : result.data?.sheet;
559
+ const names = result.data?.names ?? [];
560
+ const find = useFindResults<WorksheetHit>([...fileKey, addressOnly], !!sheet && tabActive && findOpen,
561
+ async (criteria) => {
562
+ const address = cellAddress(criteria.query);
563
+ const targets: WorksheetHit[] = address && sheet?.rows[address.row] && sheet.columns[address.column]
564
+ ? [[address.row, address.column]] : [];
565
+ if (addressOnly) return { matches: targets, limited: false, invalidPattern: false };
566
+ const text = await searchText({ workspaceId, path: file.path, sheet: selected, ...criteria });
567
+ return targets.length ? { ...text, matches: [...targets, ...text.matches] } : text;
568
+ });
569
+ const matches = useMemo(() => {
570
+ const grouped = new Map<string, WorksheetMatch[]>();
571
+ for (const hit of find.matches) {
572
+ if (hit.length !== 4) continue;
573
+ const key = `${hit[0]}:${hit[1]}`;
574
+ const cell = grouped.get(key);
575
+ if (cell) cell.push(hit);
576
+ else grouped.set(key, [hit]);
577
+ }
578
+ return grouped;
579
+ }, [find.matches]);
580
+ const searchFocus = useMemo(() => find.active && { row: find.active[0], column: find.active[1] }, [find.active]);
581
+ const openFind = () => {
582
+ if (findOpen) return focusReaderFind(panel.current, findId);
583
+ const selected = web ? readerSelection(panel.current) : "";
584
+ if (selected && !selected.includes("\n")) find.changeQuery(selected.slice(0, 256));
585
+ showFind();
586
+ };
587
+ useReaderFindShortcuts(panel, findId, web && tabActive && !!sheet,
588
+ { open: openFind, close: hideFind, move: find.move, isOpen: () => findOpen });
589
+ const zoomControls = <ZoomControls {...{ scale, theme, compact }} disabled={!sheet}
590
+ stepZoom={(factor) => setScale((previous) => boundZoom(previous * factor))} setZoom={setScale} />;
591
+ return (
592
+ <View ref={panel} tabIndex={web ? 0 : undefined} style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface0 }}>
593
+ <Toolbar theme={theme} filePanel={props} nativePrimary={!web && zoomControls}>
594
+ {web && zoomControls}
595
+ {web && <Control title={t("dragWorksheet")} icon="Hand" selected={dragMode} disabled={!sheet}
596
+ theme={theme} compact={compact} onPress={() => setDragMode((enabled) => !enabled)} />}
597
+ <Control title={t("find")} icon="Search" selected={findOpen} disabled={!sheet}
598
+ theme={theme} compact={compact} onPress={findOpen ? hideFind : openFind} />
599
+ <ExternalFileAction {...props} />
600
+ </Toolbar>
601
+ {sheet?.truncated && <Text style={{ padding: 8, color: theme.colors.foregroundMuted }}>{t("worksheetTruncated")}</Text>}
602
+ <View style={{ flex: 1, minHeight: 0 }}>
603
+ {sheet?.rows.length && sheet.columns.length ? <WorksheetGrid key={selected}
604
+ {...{ sheet, scale, theme, pinned, onPin, matches, compact, findOpen, dragMode, tabActive }} focus={searchFocus}
605
+ active={find.active?.length === 4 ? find.active : undefined} onZoom={setScale} />
606
+ : result.isFetching ? <Loading />
607
+ : result.isError ? <ReadError theme={theme} compact={compact} label={t("textError")} error={result.error}
608
+ retry={t("retry")} onRetry={() => { void result.refetch(); }} />
609
+ : <Text style={{ padding: 16, color: theme.colors.foregroundMuted }}>{t("empty")}</Text>}
610
+ {findOpen && <ReaderFindBar testID={findId} find={find} theme={theme} compact={compact} close={hideFind}
611
+ textOptions={!addressOnly} placeholder={t(addressOnly ? "addressSearch" : "worksheetSearch")}
612
+ option={<Control title={t("addressesOnly")} icon="MapPin" theme={theme} compact={compact} small
613
+ selected={addressOnly} onPress={() => { find.reset(); setAddressOnly((only) => !only); }} />} />}
614
+ </View>
615
+ {!!names.length && (
616
+ <ScrollView horizontal nestedScrollEnabled
617
+ style={{ flexGrow: 0, borderTopWidth: 1, borderColor: theme.colors.border }}
618
+ contentContainerStyle={{ paddingHorizontal: 4, paddingVertical: 2, gap: 4 }}>
619
+ {names.map((name, index) => (
620
+ <Control key={index} title={name || `${t("sheet")} ${index + 1}`} theme={theme} compact={compact}
621
+ selected={index === selected} onPress={() => {
622
+ if (index === selected) return;
623
+ setSelected(index);
624
+ find.reset();
625
+ }} />
626
+ ))}
627
+ </ScrollView>
628
+ )}
629
+ </View>
630
+ );
631
+ }