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,477 +1,477 @@
1
- import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
- import { Image, Keyboard, Text, TextInput, View, useWindowDimensions, type ViewStyle } from "react-native";
3
- import { useQueries, useQuery } from "@tanstack/react-query";
4
- import { useRpc, useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
5
- import { copyText, Loading } from "@getpaseo/plugin/client/ui";
6
- import {
7
- findDocumentText, readDocumentLayout, readDocumentText, renderOfficePage, renderPdfPage, type PageGlyph, type PageTextMatch,
8
- } from "../shared/contracts";
9
- import { Control, isTabActive, ReadError, Toolbar, useFileGeneration, useReaderShortcuts, useWebTitle, type Theme } from "./controls";
10
- import { StructuredPanel } from "./document-panel";
11
- import { ExternalFileAction } from "./external-file";
12
- import { messages } from "./messages";
13
- import { useNativeContacts } from "./native-contacts";
14
- import { createPageRenderQueue } from "./page-render-queue";
15
- import { PageFindOverlay, PageSelectionOverlay, usePageSelection, type TextPage } from "./page-selection";
16
- import { SlideSidebar } from "./page-tools";
17
- import { ReaderFindBar, useFindResults, useReaderFindShortcuts, useReaderFindVisibility } from "./reader-find";
18
- import { useReaderNotice } from "./reader-notice";
19
- import {
20
- constrain, fitPagePosition, fitPages, jumpToPage, pageAt, pageBounds, visiblePages, zoomAt, type PageFit, type ReaderLayout,
21
- } from "./pdf-geometry";
22
- import { boundZoom, clamp, panAndPinch, type Contact, type Point, type Position, type Size } from "./viewport-geometry";
23
- import { bindWebGestures, focusReaderFind } from "./web";
24
- import { ZoomControls } from "./zoom-controls";
25
-
26
- const initialPosition: Position = { x: 0, y: 0, scale: 1 };
27
- const pageFindId = "merong-page-find";
28
- type RenderPage = (page: number, pixels: number) => Promise<{ uri: string } | null>;
29
- type ReaderKind = "pdf" | "office";
30
-
31
- function quality(width: number) {
32
- return clamp(Math.ceil(width / 256) * 256, 256, 2560);
33
- }
34
-
35
- function createPagedPanel(kind: ReaderKind, useRender: () => (input: { workspaceId: string; path: string; page: number; pixels: number }) => Promise<{ uri: string } | null>) {
36
- return function PagedPanel(props: PluginFilePanelProps) {
37
- const render = useRender();
38
- const { workspaceId, file: { path } } = props;
39
- const renderPage = useCallback<RenderPage>((page, pixels) => render({ workspaceId, path, page, pixels }),
40
- [render, workspaceId, path]);
41
- return <PagedReader {...props} kind={kind} render={renderPage} />;
42
- };
43
- }
44
-
45
- export const PdfPanel = createPagedPanel("pdf", () => useRpc(renderPdfPage));
46
- export const OfficePanel = createPagedPanel("office", () => useRpc(renderOfficePage));
47
-
48
- interface StoredView {
49
- version: string;
50
- geometry: ReaderLayout;
51
- position: Position;
52
- fit?: PageFit;
53
- }
54
-
55
- function resolvePosition(stored: StoredView | undefined, version: string, geometry: ReaderLayout) {
56
- if (!stored || stored.version !== version) return constrain(initialPosition, geometry);
57
- if (stored.geometry.viewport.width === geometry.viewport.width &&
58
- stored.geometry.viewport.height === geometry.viewport.height) return stored.position;
59
- const { position, geometry: previous } = stored;
60
- const previousTop = -position.y / position.scale;
61
- const number = pageAt(previous, previousTop);
62
- const previousPage = pageBounds(previous, number);
63
- const page = pageBounds(geometry, Math.min(number, geometry.pageCount));
64
- const fraction = (previousTop - previousPage.top) / previousPage.height;
65
- if (stored.fit) return fitPagePosition(geometry, Math.min(number, geometry.pageCount), stored.fit, fraction);
66
- return constrain({ ...position, y: -(page.top + page.height * fraction) * position.scale }, geometry);
67
- }
68
-
69
- const PageImage = memo(function PageImage({
70
- number, kind, label, errorLabel, retryLabel, render, enqueue, fileKey, width, height, pixels, theme, compact,
71
- }: {
72
- number: number;
73
- kind: ReaderKind;
74
- label: string;
75
- errorLabel: string;
76
- retryLabel: string;
77
- render: RenderPage;
78
- enqueue: ReturnType<typeof createPageRenderQueue>;
79
- fileKey: readonly unknown[];
80
- width: number;
81
- height: number;
82
- pixels: number;
83
- theme: Theme;
84
- compact: boolean;
85
- }) {
86
- const result = useQuery({
87
- queryKey: [...fileKey, "page", number, pixels],
88
- queryFn: ({ signal }) => enqueue(signal, () => render(number, pixels)),
89
- placeholderData: (previous) => previous ?? undefined,
90
- staleTime: Infinity,
91
- gcTime: 15_000,
92
- retry: (count, error) => count === 0 && error.message.includes("Reader is busy"),
93
- });
94
- return (
95
- <View pointerEvents={result.data ? "none" : "auto"} style={{
96
- position: "absolute", left: 0, top: 0, width, height,
97
- backgroundColor: result.data ? "#ffffff" : theme.colors.surface0,
98
- }}>
99
- {result.data ? (
100
- <Image testID={`merong-${kind}-page`} accessible accessibilityRole="image" accessibilityLabel={label}
101
- source={{ uri: result.data.uri }} resizeMode="stretch" resizeMethod="scale" fadeDuration={0}
102
- style={{ width: "100%", height: "100%" }} />
103
- ) : result.isPending ? <Loading /> : (
104
- <ReadError theme={theme} compact={compact} label={errorLabel} error={result.error}
105
- retry={retryLabel} onRetry={() => { void result.refetch(); }} />
106
- )}
107
- </View>
108
- );
109
- });
110
-
111
- function PagedReader(props: PluginFilePanelProps & { kind: ReaderKind; render: RenderPage }) {
112
- const { file, workspaceId, host, layout, theme, kind, render, tab } = props;
113
- const generation = useFileGeneration(file);
114
- const readLayout = useRpc(readDocumentLayout);
115
- const readText = useRpc(readDocumentText);
116
- const findText = useRpc(findDocumentText);
117
- const { t } = useTranslation(messages);
118
- const notify = useReaderNotice();
119
- const { scale: pixelRatio } = useWindowDimensions();
120
- const { compact, platform } = layout;
121
- const web = platform === "web";
122
- const tabActive = isTabActive(tab);
123
- const slides = file.extension === "pptx";
124
- const pageFieldLabel = t(slides ? "slideNumber" : "page");
125
- const pageField = useWebTitle<TextInput>(pageFieldLabel);
126
- const errorLabel = t(kind === "pdf" ? "pdfError" : "officeError");
127
- const [viewport, setViewport] = useState<Size>({ width: 0, height: 0 });
128
- const [stored, setStored] = useState<StoredView>();
129
- const [draft, setDraft] = useState<string>();
130
- const [rasterScale, setRasterScale] = useState(1);
131
- const { findOpen, showFind, hideFind } = useReaderFindVisibility();
132
- const [slidesOpen, setSlidesOpen] = useState(slides);
133
- const [enqueue] = useState(createPageRenderQueue);
134
- const viewportRef = useRef<View>(null);
135
- const panelRef = useRef<View>(null);
136
- const shortcuts = useReaderShortcuts();
137
- const pointers = useRef<Contact[]>([]);
138
- const operations = useRef<Omit<Parameters<typeof bindWebGestures>[1], "shortcuts"> | null>(null);
139
- const current = useRef<Position | null>(null);
140
- const beforeFind = useRef<StoredView>(undefined);
141
-
142
- const version = `${file.modifiedAt}:${generation}`;
143
- const fileKey = useMemo(() => ["merong-docs", kind, host.id, workspaceId, file.path, version],
144
- [kind, host.id, workspaceId, file.path, version]);
145
- const sidebarPreview = useMemo(() => ({ fileKey, enqueue, render }), [fileKey, enqueue, render]);
146
- const query = useQuery({
147
- queryKey: [...fileKey, kind === "office" ? "office-layout" : "layout"],
148
- queryFn: async ({ signal }) => {
149
- while (!signal.aborted) {
150
- const result = await readLayout({ workspaceId, path: file.path });
151
- if (result !== "loading") return result;
152
- }
153
- throw new Error("The document preview was cancelled.");
154
- },
155
- staleTime: Infinity,
156
- gcTime: 30_000,
157
- retry: false,
158
- });
159
- const geometry = useMemo(() => query.data && viewport.width > 0 && viewport.height > 0
160
- ? fitPages(query.data, viewport)
161
- : null, [query.data, viewport]);
162
- const position = geometry ? resolvePosition(stored, version, geometry) : null;
163
- const scale = position?.scale ?? 1;
164
- const page = geometry && position ? pageAt(geometry, -position.y / scale) : 1;
165
- const pageCount = geometry?.pageCount ?? 0;
166
- const activeFit = stored?.version === version ? stored.fit : "page";
167
- const enabled = tabActive && !!position;
168
- const find = useFindResults(fileKey, enabled && findOpen,
169
- (criteria) => findText({ workspaceId, path: file.path, ...criteria }));
170
- const matchesByPage = useMemo(() => {
171
- const grouped = new Map<number, PageTextMatch[]>();
172
- for (const match of find.matches) {
173
- const page = grouped.get(match[0]);
174
- if (page) page.push(match);
175
- else grouped.set(match[0], [match]);
176
- }
177
- return grouped;
178
- }, [find.matches]);
179
- const { first, last } = geometry && position ? visiblePages(geometry, position) : { first: 1, last: 0 };
180
- const textPages = enabled ? Array.from({ length: Math.min(8, last - first + 1) }, (_, index) => first + index) : [];
181
- const matchPage = find.active?.[0];
182
- if (matchPage !== undefined && !textPages.includes(matchPage)) textPages.push(matchPage);
183
- const textQueries = useQueries({
184
- queries: textPages.map((number) => ({
185
- queryKey: [...fileKey, "text", number],
186
- queryFn: ({ signal }: { signal: AbortSignal }) => enqueue(signal, () => readText({ workspaceId, path: file.path, page: number })),
187
- staleTime: Infinity, gcTime: 30_000, retry: false,
188
- })),
189
- });
190
- const matchText = matchPage === undefined ? undefined : textQueries[textPages.indexOf(matchPage)];
191
- const findTextPage = (point: Point, number?: number): TextPage | undefined => {
192
- const view = current.current;
193
- if (!geometry || !view) return;
194
- const target = number ?? pageAt(geometry, (point.y - view.y) / view.scale);
195
- const content = textQueries[textPages.indexOf(target)]?.data;
196
- if (!content?.glyphs?.length) return;
197
- const bounds = pageBounds(geometry, target);
198
- return {
199
- number: target, text: content.text, glyphs: content.glyphs,
200
- left: view.x + (geometry.width - bounds.width) * view.scale / 2, top: view.y + bounds.top * view.scale,
201
- width: bounds.width * view.scale, height: bounds.height * view.scale,
202
- };
203
- };
204
- const selection = usePageSelection(findTextPage, version);
205
- const showCopied = () => notify?.(t("copied"));
206
- const copySelection = async (text: string) => {
207
- if (!text) return;
208
- try {
209
- await copyText(text);
210
- showCopied();
211
- } catch {
212
- notify?.(t("textCopyError"), true);
213
- }
214
- };
215
-
216
- function update(convert: (position: Position, geometry: ReaderLayout) => Position) {
217
- if (!current.current || !geometry) return false;
218
- const before = current.current;
219
- const next = convert(before, geometry);
220
- if (before.x === next.x && before.y === next.y && before.scale === next.scale) return false;
221
- current.current = next;
222
- setStored({ version, geometry, position: next, fit: next.scale === before.scale ? activeFit : undefined });
223
- return true;
224
- }
225
-
226
- function pan(previous: Contact[], next: Contact[]) {
227
- update((current, dimensions) => constrain(panAndPinch(current, previous, next), dimensions));
228
- }
229
-
230
- function track(next: Contact[], pointer: string, forcePan = false) {
231
- const previous = pointers.current;
232
- pointers.current = next;
233
- if (!forcePan && selection.track(next, pointer)) return true;
234
- pan(previous, next);
235
- }
236
- const { handlers: nativeGestures, stopInertia } = useNativeContacts(viewportRef, enabled && !web, pan, ({ x, y }) =>
237
- update((position, dimensions) => constrain({ ...position, x: position.x + x, y: position.y + y }, dimensions)),
238
- (contacts) => selection.track(contacts, "touch"));
239
-
240
- const changeZoom = (resolve: (scale: number) => number,
241
- anchor = { x: viewport.width / 2, y: Math.min(viewport.height / 2, 120) }) => {
242
- stopInertia();
243
- update((current, dimensions) => zoomAt(current, boundZoom(resolve(current.scale)), anchor, dimensions));
244
- };
245
- const stepZoom = (factor: number, anchor?: Point) => changeZoom((scale) => scale * factor, anchor);
246
- const goTo = (target: number) => {
247
- stopInertia();
248
- update((current, dimensions) => jumpToPage(current, clamp(target, 1, dimensions.pageCount), dimensions));
249
- };
250
- const fit = (mode: PageFit) => {
251
- stopInertia();
252
- const view = current.current;
253
- if (!geometry || !view) return;
254
- const number = pageAt(geometry, -view.y / view.scale);
255
- const next = fitPagePosition(geometry, number, mode);
256
- current.current = next;
257
- setStored({ version, geometry, position: next, fit: mode });
258
- };
259
- const commitPage = () => {
260
- if (draft && /^\d+$/.test(draft)) goTo(Number(draft));
261
- setDraft(undefined);
262
- };
263
- const openFind = () => {
264
- if (findOpen) return focusReaderFind(panelRef.current, pageFindId);
265
- if (!web && geometry && current.current) {
266
- stopInertia();
267
- beforeFind.current = { position: current.current, version, geometry, fit: activeFit };
268
- }
269
- const selected = selection.text();
270
- if (selected && !selected.includes("\n")) find.changeQuery(selected.slice(0, 256));
271
- showFind();
272
- };
273
- const closeFind = () => {
274
- const saved = beforeFind.current;
275
- beforeFind.current = undefined;
276
- if (saved?.version === version) {
277
- stopInertia();
278
- setStored(saved);
279
- }
280
- hideFind();
281
- };
282
- useReaderFindShortcuts(panelRef, pageFindId, web && enabled,
283
- { open: openFind, close: closeFind, move: find.move, isOpen: () => findOpen }, viewportRef);
284
- const revealMatch = useRef<(match: PageTextMatch, glyphs?: PageGlyph[]) => void>(undefined);
285
- revealMatch.current = ([number, start, end], glyphs) => {
286
- const glyph = glyphs?.find(([first, last]) => last > start && first < end);
287
- if (!glyph) {
288
- goTo(number);
289
- return;
290
- }
291
- stopInertia();
292
- update((view, dimensions) => {
293
- const bounds = pageBounds(dimensions, number);
294
- const x = ((dimensions.width - bounds.width) / 2 + glyph[2] * bounds.width) * view.scale;
295
- const y = (bounds.top + glyph[3] * bounds.height) * view.scale;
296
- const right = x + (glyph[4] - glyph[2]) * bounds.width * view.scale;
297
- const bottom = y + (glyph[5] - glyph[3]) * bounds.height * view.scale;
298
- const margin = 12;
299
- const top = y + view.y >= margin && bottom + view.y <= viewport.height - margin
300
- ? view.y : viewport.height * 0.42 - y;
301
- return constrain({
302
- ...view,
303
- x: x + view.x >= margin && right + view.x <= viewport.width - margin ? view.x : viewport.width / 2 - x,
304
- y: Math.min(top, -bounds.top * view.scale),
305
- }, dimensions);
306
- });
307
- };
308
-
309
- useLayoutEffect(() => {
310
- current.current = position;
311
- operations.current = {
312
- contacts: track,
313
- overText: selection.overText,
314
- selectedText: selection.text,
315
- onCopied: showCopied,
316
- scroll: (delta) => update((position, dimensions) =>
317
- constrain({ ...position, x: position.x - delta.x, y: position.y - delta.y }, dimensions)),
318
- zoom: stepZoom,
319
- fit: () => fit("page"),
320
- };
321
- });
322
- useLayoutEffect(() => stopInertia(), [geometry, stopInertia, version]);
323
- useEffect(() => {
324
- if (find.active && (matchText?.isSuccess || matchText?.isError)) {
325
- revealMatch.current?.(find.active, matchText.data?.glyphs);
326
- }
327
- }, [geometry, matchText?.data, matchText?.isError, matchText?.isSuccess, find.active]);
328
- useEffect(() => {
329
- if (rasterScale === scale) return;
330
- const timeout = setTimeout(() => setRasterScale(scale), 150);
331
- return () => clearTimeout(timeout);
332
- }, [rasterScale, scale]);
333
- useEffect(() => {
334
- pointers.current = [];
335
- }, [enabled, version]);
336
- useEffect(() => {
337
- if (!web || !enabled) return;
338
- return bindWebGestures(viewportRef.current, {
339
- contacts: (contacts, pointer, forced) => operations.current?.contacts(contacts, pointer, forced),
340
- shortcuts: () => shortcuts.current,
341
- overText: (point) => operations.current?.overText?.(point) ?? false,
342
- selectedText: () => operations.current?.selectedText?.() ?? "",
343
- onCopied: () => operations.current?.onCopied?.(),
344
- scroll: (delta) => operations.current?.scroll(delta),
345
- zoom: (factor, anchor) => operations.current?.zoom(factor, anchor),
346
- fit: () => operations.current?.fit(),
347
- });
348
- }, [web, enabled, shortcuts]);
349
-
350
- if (kind === "office" && query.data === null) return <StructuredPanel {...props} />;
351
- let pages: React.ReactNode;
352
- if (tabActive && geometry && position) {
353
- const numbers = Array.from({ length: Math.min(last - first + 1, 20) }, (_, index) => first + index);
354
- const before = Math.max(1, first - 1);
355
- const after = Math.min(pageCount, last + 1);
356
- if (!web && last < after) numbers.push(after);
357
- if (!web && before < first) numbers.push(before);
358
- const origin = web ? 0 : pageBounds(geometry, before).top;
359
- const pageScale = web ? scale : 1;
360
- const images = numbers.map((number) => {
361
- const bounds = pageBounds(geometry, number);
362
- const left = (geometry.width - bounds.width) * pageScale / 2 + (web ? position.x : 0);
363
- const top = (bounds.top - origin) * pageScale + (web ? position.y : 0);
364
- const width = bounds.width * pageScale;
365
- const height = bounds.height * pageScale;
366
- const range = selection.selection;
367
- const matches = matchesByPage.get(number);
368
- const layer = range?.page === number || matches ? textQueries[textPages.indexOf(number)]?.data?.glyphs : undefined;
369
- return <View key={`${version}:${number}`} pointerEvents="box-none"
370
- style={{ position: "absolute", left, top, width, height }}>
371
- <PageImage {...{
372
- number, kind, fileKey, render, enqueue, theme, compact, errorLabel, width, height,
373
- label: `${t(slides ? "slide" : "page")} ${number}`, retryLabel: t("retry"),
374
- pixels: quality(bounds.width * rasterScale * Math.min(2, pixelRatio)),
375
- }} />
376
- {layer && matches && <PageFindOverlay {...{ width, height, glyphs: layer, matches }} active={find.active} />}
377
- {layer && range?.page === number && <PageSelectionOverlay {...{ width, height, glyphs: layer, range }}
378
- handles={!web || compact} accent={theme.colors.accent} scale={web ? 1 : scale} />}
379
- </View>;
380
- });
381
- const bottom = pageBounds(geometry, after);
382
- pages = web ? images : (
383
- <View pointerEvents="box-none" style={{
384
- position: "absolute", left: 0, top: 0, width: geometry.width, height: bottom.top + bottom.height - origin,
385
- transformOrigin: [0, 0, 0],
386
- transform: [{ translateX: position.x }, { translateY: position.y + origin * scale }, { scale }],
387
- }}>{images}</View>
388
- );
389
- }
390
- const findControl = <Control title={t("find")} icon="Search" disabled={!position} selected={findOpen}
391
- onPress={findOpen ? closeFind : openFind} theme={theme} compact={compact} />;
392
- const zoomControls = <ZoomControls {...{ scale, theme, compact, stepZoom }} disabled={!position}
393
- setZoom={(scale) => changeZoom(() => scale)} />;
394
- const applyPage = draft !== undefined && <Control title={t(slides ? "goToSlide" : "goToPage")} icon="CornerDownLeft"
395
- onPress={() => { commitPage(); Keyboard.dismiss(); }} theme={theme} compact={compact} small={!web} />;
396
- const pageControls = (
397
- <View style={{ flexDirection: "row", alignItems: "center", gap: 3 }}>
398
- <Control title={t(slides ? "previousSlide" : "previous")} icon="ChevronLeft" disabled={page <= 1} onPress={() => goTo(page - 1)}
399
- theme={theme} compact={compact} small={!web} />
400
- <TextInput
401
- ref={pageField}
402
- accessibilityLabel={pageFieldLabel}
403
- testID="merong-pdf-page-number"
404
- value={draft ?? String(page)}
405
- maxLength={7}
406
- inputMode="numeric"
407
- keyboardType="number-pad"
408
- returnKeyType="go"
409
- selectTextOnFocus
410
- onChangeText={setDraft}
411
- onSubmitEditing={commitPage}
412
- onBlur={commitPage}
413
- editable={!!pageCount}
414
- style={{
415
- color: theme.colors.foreground, borderColor: theme.colors.border,
416
- borderWidth: 1, borderRadius: 5, textAlign: "center", paddingHorizontal: 4, paddingVertical: 0,
417
- width: pageCount > 999 ? web ? 62 : 50 : web ? 42 : 38, height: web && compact ? 36 : 28,
418
- }}
419
- />
420
- {web && applyPage}
421
- <Text style={{ color: theme.colors.foregroundMuted, fontSize: 13 }}>/ {pageCount || "…"}</Text>
422
- {(!web && applyPage) || <Control title={t(slides ? "nextSlide" : "next")} icon="ChevronRight" disabled={page >= pageCount}
423
- onPress={() => goTo(page + 1)} theme={theme} compact={compact} small={!web} />}
424
- </View>
425
- );
426
- return (
427
- <View ref={panelRef} testID={`merong-${kind}-reader`} style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface1 }}>
428
- <Toolbar theme={theme} filePanel={props} nativePrimary={!web && <>{pageControls}{zoomControls}</>}>
429
- {web && <>{pageControls}{zoomControls}</>}
430
- <Control title={t("fitWidth")} icon="MoveHorizontal" disabled={!position} selected={activeFit === "width"}
431
- onPress={() => fit("width")} theme={theme} compact={compact} />
432
- <Control title={t(slides ? "slideFit" : "reset")} icon="Scan" disabled={!position} selected={activeFit === "page"}
433
- onPress={() => fit("page")} theme={theme} compact={compact} />
434
- {findControl}
435
- {slides && <Control title={t("thumbnails")} icon="PanelLeft" selected={slidesOpen}
436
- onPress={() => setSlidesOpen((open) => !open)} theme={theme} compact={compact} />}
437
- <ExternalFileAction {...props} />
438
- </Toolbar>
439
- <View style={{ flex: 1, minHeight: 0, flexDirection: "row" }}>
440
- {slidesOpen && <SlideSidebar count={tabActive ? pageCount : 0} {...{ page, goTo, theme, compact }}
441
- preview={sidebarPreview} />}
442
- <View style={{ flex: 1, minHeight: 0, minWidth: 0 }}>
443
- <View
444
- ref={viewportRef}
445
- testID={`merong-${kind}-viewport`}
446
- accessibilityLabel={t("documentPages")}
447
- tabIndex={web && enabled ? 0 : undefined}
448
- onLayout={({ nativeEvent: { layout: bounds } }) => setViewport((previous) =>
449
- bounds.width === previous.width && bounds.height === previous.height
450
- ? previous
451
- : { width: bounds.width, height: bounds.height },
452
- )}
453
- {...nativeGestures}
454
- style={[
455
- { flex: 1, minHeight: 0, overflow: "hidden" },
456
- web && ({ touchAction: "none", userSelect: "none" } as ViewStyle),
457
- ]}
458
- >
459
- {!tabActive ? null : pages ?? (query.isError ? (
460
- <ReadError theme={theme} compact={compact} label={errorLabel} error={query.error}
461
- retry={t("retry")} onRetry={() => { void query.refetch(); }} />
462
- ) : <Loading />)}
463
- {tabActive && selection.text() && (
464
- <View style={[{ position: "absolute", right: 8, borderWidth: 1, borderRadius: 7,
465
- borderColor: theme.colors.border, backgroundColor: theme.colors.surface1 },
466
- findOpen ? { bottom: 8 } : { top: 8 }]}>
467
- <Control title={t("copySelection")} icon="Copy" onPress={() => { void copySelection(selection.text()); }}
468
- theme={theme} compact={compact} />
469
- </View>
470
- )}
471
- </View>
472
- {findOpen && <ReaderFindBar testID={pageFindId} find={find} theme={theme} compact={compact} close={closeFind} />}
473
- </View>
474
- </View>
475
- </View>
476
- );
477
- }
1
+ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import { Image, Keyboard, Text, TextInput, View, useWindowDimensions, type ViewStyle } from "react-native";
3
+ import { useQueries, useQuery } from "@tanstack/react-query";
4
+ import { useRpc, useTranslation, type PluginFilePanelProps } from "@getpaseo/plugin/client";
5
+ import { copyText, Loading } from "@getpaseo/plugin/client/ui";
6
+ import {
7
+ findDocumentText, readDocumentLayout, readDocumentText, renderOfficePage, renderPdfPage, type PageGlyph, type PageTextMatch,
8
+ } from "../shared/contracts";
9
+ import { Control, isTabActive, ReadError, Toolbar, useFileGeneration, useReaderShortcuts, useWebTitle, type Theme } from "./controls";
10
+ import { StructuredPanel } from "./document-panel";
11
+ import { ExternalFileAction } from "./external-file";
12
+ import { messages } from "./messages";
13
+ import { useNativeContacts } from "./native-contacts";
14
+ import { createPageRenderQueue } from "./page-render-queue";
15
+ import { PageFindOverlay, PageSelectionOverlay, usePageSelection, type TextPage } from "./page-selection";
16
+ import { SlideSidebar } from "./page-tools";
17
+ import { ReaderFindBar, useFindResults, useReaderFindShortcuts, useReaderFindVisibility } from "./reader-find";
18
+ import { useReaderNotice } from "./reader-notice";
19
+ import {
20
+ constrain, fitPagePosition, fitPages, jumpToPage, pageAt, pageBounds, visiblePages, zoomAt, type PageFit, type ReaderLayout,
21
+ } from "./pdf-geometry";
22
+ import { boundZoom, clamp, panAndPinch, type Contact, type Point, type Position, type Size } from "./viewport-geometry";
23
+ import { bindWebGestures, focusReaderFind } from "./web";
24
+ import { ZoomControls } from "./zoom-controls";
25
+
26
+ const initialPosition: Position = { x: 0, y: 0, scale: 1 };
27
+ const pageFindId = "merong-page-find";
28
+ type RenderPage = (page: number, pixels: number) => Promise<{ uri: string } | null>;
29
+ type ReaderKind = "pdf" | "office";
30
+
31
+ function quality(width: number) {
32
+ return clamp(Math.ceil(width / 256) * 256, 256, 2560);
33
+ }
34
+
35
+ function createPagedPanel(kind: ReaderKind, useRender: () => (input: { workspaceId: string; path: string; page: number; pixels: number }) => Promise<{ uri: string } | null>) {
36
+ return function PagedPanel(props: PluginFilePanelProps) {
37
+ const render = useRender();
38
+ const { workspaceId, file: { path } } = props;
39
+ const renderPage = useCallback<RenderPage>((page, pixels) => render({ workspaceId, path, page, pixels }),
40
+ [render, workspaceId, path]);
41
+ return <PagedReader {...props} kind={kind} render={renderPage} />;
42
+ };
43
+ }
44
+
45
+ export const PdfPanel = createPagedPanel("pdf", () => useRpc(renderPdfPage));
46
+ export const OfficePanel = createPagedPanel("office", () => useRpc(renderOfficePage));
47
+
48
+ interface StoredView {
49
+ version: string;
50
+ geometry: ReaderLayout;
51
+ position: Position;
52
+ fit?: PageFit;
53
+ }
54
+
55
+ function resolvePosition(stored: StoredView | undefined, version: string, geometry: ReaderLayout) {
56
+ if (!stored || stored.version !== version) return constrain(initialPosition, geometry);
57
+ if (stored.geometry.viewport.width === geometry.viewport.width &&
58
+ stored.geometry.viewport.height === geometry.viewport.height) return stored.position;
59
+ const { position, geometry: previous } = stored;
60
+ const previousTop = -position.y / position.scale;
61
+ const number = pageAt(previous, previousTop);
62
+ const previousPage = pageBounds(previous, number);
63
+ const page = pageBounds(geometry, Math.min(number, geometry.pageCount));
64
+ const fraction = (previousTop - previousPage.top) / previousPage.height;
65
+ if (stored.fit) return fitPagePosition(geometry, Math.min(number, geometry.pageCount), stored.fit, fraction);
66
+ return constrain({ ...position, y: -(page.top + page.height * fraction) * position.scale }, geometry);
67
+ }
68
+
69
+ const PageImage = memo(function PageImage({
70
+ number, kind, label, errorLabel, retryLabel, render, enqueue, fileKey, width, height, pixels, theme, compact,
71
+ }: {
72
+ number: number;
73
+ kind: ReaderKind;
74
+ label: string;
75
+ errorLabel: string;
76
+ retryLabel: string;
77
+ render: RenderPage;
78
+ enqueue: ReturnType<typeof createPageRenderQueue>;
79
+ fileKey: readonly unknown[];
80
+ width: number;
81
+ height: number;
82
+ pixels: number;
83
+ theme: Theme;
84
+ compact: boolean;
85
+ }) {
86
+ const result = useQuery({
87
+ queryKey: [...fileKey, "page", number, pixels],
88
+ queryFn: ({ signal }) => enqueue(signal, () => render(number, pixels)),
89
+ placeholderData: (previous) => previous ?? undefined,
90
+ staleTime: Infinity,
91
+ gcTime: 15_000,
92
+ retry: (count, error) => count === 0 && error.message.includes("Reader is busy"),
93
+ });
94
+ return (
95
+ <View pointerEvents={result.data ? "none" : "auto"} style={{
96
+ position: "absolute", left: 0, top: 0, width, height,
97
+ backgroundColor: result.data ? "#ffffff" : theme.colors.surface0,
98
+ }}>
99
+ {result.data ? (
100
+ <Image testID={`merong-${kind}-page`} accessible accessibilityRole="image" accessibilityLabel={label}
101
+ source={{ uri: result.data.uri }} resizeMode="stretch" resizeMethod="scale" fadeDuration={0}
102
+ style={{ width: "100%", height: "100%" }} />
103
+ ) : result.isPending ? <Loading /> : (
104
+ <ReadError theme={theme} compact={compact} label={errorLabel} error={result.error}
105
+ retry={retryLabel} onRetry={() => { void result.refetch(); }} />
106
+ )}
107
+ </View>
108
+ );
109
+ });
110
+
111
+ function PagedReader(props: PluginFilePanelProps & { kind: ReaderKind; render: RenderPage }) {
112
+ const { file, workspaceId, host, layout, theme, kind, render, tab } = props;
113
+ const generation = useFileGeneration(file);
114
+ const readLayout = useRpc(readDocumentLayout);
115
+ const readText = useRpc(readDocumentText);
116
+ const findText = useRpc(findDocumentText);
117
+ const { t } = useTranslation(messages);
118
+ const notify = useReaderNotice();
119
+ const { scale: pixelRatio } = useWindowDimensions();
120
+ const { compact, platform } = layout;
121
+ const web = platform === "web";
122
+ const tabActive = isTabActive(tab);
123
+ const slides = file.extension === "pptx";
124
+ const pageFieldLabel = t(slides ? "slideNumber" : "page");
125
+ const pageField = useWebTitle<TextInput>(pageFieldLabel);
126
+ const errorLabel = t(kind === "pdf" ? "pdfError" : "officeError");
127
+ const [viewport, setViewport] = useState<Size>({ width: 0, height: 0 });
128
+ const [stored, setStored] = useState<StoredView>();
129
+ const [draft, setDraft] = useState<string>();
130
+ const [rasterScale, setRasterScale] = useState(1);
131
+ const { findOpen, showFind, hideFind } = useReaderFindVisibility();
132
+ const [slidesOpen, setSlidesOpen] = useState(slides);
133
+ const [enqueue] = useState(createPageRenderQueue);
134
+ const viewportRef = useRef<View>(null);
135
+ const panelRef = useRef<View>(null);
136
+ const shortcuts = useReaderShortcuts();
137
+ const pointers = useRef<Contact[]>([]);
138
+ const operations = useRef<Omit<Parameters<typeof bindWebGestures>[1], "shortcuts"> | null>(null);
139
+ const current = useRef<Position | null>(null);
140
+ const beforeFind = useRef<StoredView>(undefined);
141
+
142
+ const version = `${file.modifiedAt}:${generation}`;
143
+ const fileKey = useMemo(() => ["merong-docs", kind, host.id, workspaceId, file.path, version],
144
+ [kind, host.id, workspaceId, file.path, version]);
145
+ const sidebarPreview = useMemo(() => ({ fileKey, enqueue, render }), [fileKey, enqueue, render]);
146
+ const query = useQuery({
147
+ queryKey: [...fileKey, kind === "office" ? "office-layout" : "layout"],
148
+ queryFn: async ({ signal }) => {
149
+ while (!signal.aborted) {
150
+ const result = await readLayout({ workspaceId, path: file.path });
151
+ if (result !== "loading") return result;
152
+ }
153
+ throw new Error("The document preview was cancelled.");
154
+ },
155
+ staleTime: Infinity,
156
+ gcTime: 30_000,
157
+ retry: false,
158
+ });
159
+ const geometry = useMemo(() => query.data && viewport.width > 0 && viewport.height > 0
160
+ ? fitPages(query.data, viewport)
161
+ : null, [query.data, viewport]);
162
+ const position = geometry ? resolvePosition(stored, version, geometry) : null;
163
+ const scale = position?.scale ?? 1;
164
+ const page = geometry && position ? pageAt(geometry, -position.y / scale) : 1;
165
+ const pageCount = geometry?.pageCount ?? 0;
166
+ const activeFit = stored?.version === version ? stored.fit : "page";
167
+ const enabled = tabActive && !!position;
168
+ const find = useFindResults(fileKey, enabled && findOpen,
169
+ (criteria) => findText({ workspaceId, path: file.path, ...criteria }));
170
+ const matchesByPage = useMemo(() => {
171
+ const grouped = new Map<number, PageTextMatch[]>();
172
+ for (const match of find.matches) {
173
+ const page = grouped.get(match[0]);
174
+ if (page) page.push(match);
175
+ else grouped.set(match[0], [match]);
176
+ }
177
+ return grouped;
178
+ }, [find.matches]);
179
+ const { first, last } = geometry && position ? visiblePages(geometry, position) : { first: 1, last: 0 };
180
+ const textPages = enabled ? Array.from({ length: Math.min(8, last - first + 1) }, (_, index) => first + index) : [];
181
+ const matchPage = find.active?.[0];
182
+ if (matchPage !== undefined && !textPages.includes(matchPage)) textPages.push(matchPage);
183
+ const textQueries = useQueries({
184
+ queries: textPages.map((number) => ({
185
+ queryKey: [...fileKey, "text", number],
186
+ queryFn: ({ signal }: { signal: AbortSignal }) => enqueue(signal, () => readText({ workspaceId, path: file.path, page: number })),
187
+ staleTime: Infinity, gcTime: 30_000, retry: false,
188
+ })),
189
+ });
190
+ const matchText = matchPage === undefined ? undefined : textQueries[textPages.indexOf(matchPage)];
191
+ const findTextPage = (point: Point, number?: number): TextPage | undefined => {
192
+ const view = current.current;
193
+ if (!geometry || !view) return;
194
+ const target = number ?? pageAt(geometry, (point.y - view.y) / view.scale);
195
+ const content = textQueries[textPages.indexOf(target)]?.data;
196
+ if (!content?.glyphs?.length) return;
197
+ const bounds = pageBounds(geometry, target);
198
+ return {
199
+ number: target, text: content.text, glyphs: content.glyphs,
200
+ left: view.x + (geometry.width - bounds.width) * view.scale / 2, top: view.y + bounds.top * view.scale,
201
+ width: bounds.width * view.scale, height: bounds.height * view.scale,
202
+ };
203
+ };
204
+ const selection = usePageSelection(findTextPage, version);
205
+ const showCopied = () => notify?.(t("copied"));
206
+ const copySelection = async (text: string) => {
207
+ if (!text) return;
208
+ try {
209
+ await copyText(text);
210
+ showCopied();
211
+ } catch {
212
+ notify?.(t("textCopyError"), true);
213
+ }
214
+ };
215
+
216
+ function update(convert: (position: Position, geometry: ReaderLayout) => Position) {
217
+ if (!current.current || !geometry) return false;
218
+ const before = current.current;
219
+ const next = convert(before, geometry);
220
+ if (before.x === next.x && before.y === next.y && before.scale === next.scale) return false;
221
+ current.current = next;
222
+ setStored({ version, geometry, position: next, fit: next.scale === before.scale ? activeFit : undefined });
223
+ return true;
224
+ }
225
+
226
+ function pan(previous: Contact[], next: Contact[]) {
227
+ update((current, dimensions) => constrain(panAndPinch(current, previous, next), dimensions));
228
+ }
229
+
230
+ function track(next: Contact[], pointer: string, forcePan = false) {
231
+ const previous = pointers.current;
232
+ pointers.current = next;
233
+ if (!forcePan && selection.track(next, pointer)) return true;
234
+ pan(previous, next);
235
+ }
236
+ const { handlers: nativeGestures, stopInertia } = useNativeContacts(viewportRef, enabled && !web, pan, ({ x, y }) =>
237
+ update((position, dimensions) => constrain({ ...position, x: position.x + x, y: position.y + y }, dimensions)),
238
+ (contacts) => selection.track(contacts, "touch"));
239
+
240
+ const changeZoom = (resolve: (scale: number) => number,
241
+ anchor = { x: viewport.width / 2, y: Math.min(viewport.height / 2, 120) }) => {
242
+ stopInertia();
243
+ update((current, dimensions) => zoomAt(current, boundZoom(resolve(current.scale)), anchor, dimensions));
244
+ };
245
+ const stepZoom = (factor: number, anchor?: Point) => changeZoom((scale) => scale * factor, anchor);
246
+ const goTo = (target: number) => {
247
+ stopInertia();
248
+ update((current, dimensions) => jumpToPage(current, clamp(target, 1, dimensions.pageCount), dimensions));
249
+ };
250
+ const fit = (mode: PageFit) => {
251
+ stopInertia();
252
+ const view = current.current;
253
+ if (!geometry || !view) return;
254
+ const number = pageAt(geometry, -view.y / view.scale);
255
+ const next = fitPagePosition(geometry, number, mode);
256
+ current.current = next;
257
+ setStored({ version, geometry, position: next, fit: mode });
258
+ };
259
+ const commitPage = () => {
260
+ if (draft && /^\d+$/.test(draft)) goTo(Number(draft));
261
+ setDraft(undefined);
262
+ };
263
+ const openFind = () => {
264
+ if (findOpen) return focusReaderFind(panelRef.current, pageFindId);
265
+ if (!web && geometry && current.current) {
266
+ stopInertia();
267
+ beforeFind.current = { position: current.current, version, geometry, fit: activeFit };
268
+ }
269
+ const selected = selection.text();
270
+ if (selected && !selected.includes("\n")) find.changeQuery(selected.slice(0, 256));
271
+ showFind();
272
+ };
273
+ const closeFind = () => {
274
+ const saved = beforeFind.current;
275
+ beforeFind.current = undefined;
276
+ if (saved?.version === version) {
277
+ stopInertia();
278
+ setStored(saved);
279
+ }
280
+ hideFind();
281
+ };
282
+ useReaderFindShortcuts(panelRef, pageFindId, web && enabled,
283
+ { open: openFind, close: closeFind, move: find.move, isOpen: () => findOpen }, viewportRef);
284
+ const revealMatch = useRef<(match: PageTextMatch, glyphs?: PageGlyph[]) => void>(undefined);
285
+ revealMatch.current = ([number, start, end], glyphs) => {
286
+ const glyph = glyphs?.find(([first, last]) => last > start && first < end);
287
+ if (!glyph) {
288
+ goTo(number);
289
+ return;
290
+ }
291
+ stopInertia();
292
+ update((view, dimensions) => {
293
+ const bounds = pageBounds(dimensions, number);
294
+ const x = ((dimensions.width - bounds.width) / 2 + glyph[2] * bounds.width) * view.scale;
295
+ const y = (bounds.top + glyph[3] * bounds.height) * view.scale;
296
+ const right = x + (glyph[4] - glyph[2]) * bounds.width * view.scale;
297
+ const bottom = y + (glyph[5] - glyph[3]) * bounds.height * view.scale;
298
+ const margin = 12;
299
+ const top = y + view.y >= margin && bottom + view.y <= viewport.height - margin
300
+ ? view.y : viewport.height * 0.42 - y;
301
+ return constrain({
302
+ ...view,
303
+ x: x + view.x >= margin && right + view.x <= viewport.width - margin ? view.x : viewport.width / 2 - x,
304
+ y: Math.min(top, -bounds.top * view.scale),
305
+ }, dimensions);
306
+ });
307
+ };
308
+
309
+ useLayoutEffect(() => {
310
+ current.current = position;
311
+ operations.current = {
312
+ contacts: track,
313
+ overText: selection.overText,
314
+ selectedText: selection.text,
315
+ onCopied: showCopied,
316
+ scroll: (delta) => update((position, dimensions) =>
317
+ constrain({ ...position, x: position.x - delta.x, y: position.y - delta.y }, dimensions)),
318
+ zoom: stepZoom,
319
+ fit: () => fit("page"),
320
+ };
321
+ });
322
+ useLayoutEffect(() => stopInertia(), [geometry, stopInertia, version]);
323
+ useEffect(() => {
324
+ if (find.active && (matchText?.isSuccess || matchText?.isError)) {
325
+ revealMatch.current?.(find.active, matchText.data?.glyphs);
326
+ }
327
+ }, [geometry, matchText?.data, matchText?.isError, matchText?.isSuccess, find.active]);
328
+ useEffect(() => {
329
+ if (rasterScale === scale) return;
330
+ const timeout = setTimeout(() => setRasterScale(scale), 150);
331
+ return () => clearTimeout(timeout);
332
+ }, [rasterScale, scale]);
333
+ useEffect(() => {
334
+ pointers.current = [];
335
+ }, [enabled, version]);
336
+ useEffect(() => {
337
+ if (!web || !enabled) return;
338
+ return bindWebGestures(viewportRef.current, {
339
+ contacts: (contacts, pointer, forced) => operations.current?.contacts(contacts, pointer, forced),
340
+ shortcuts: () => shortcuts.current,
341
+ overText: (point) => operations.current?.overText?.(point) ?? false,
342
+ selectedText: () => operations.current?.selectedText?.() ?? "",
343
+ onCopied: () => operations.current?.onCopied?.(),
344
+ scroll: (delta) => operations.current?.scroll(delta),
345
+ zoom: (factor, anchor) => operations.current?.zoom(factor, anchor),
346
+ fit: () => operations.current?.fit(),
347
+ });
348
+ }, [web, enabled, shortcuts]);
349
+
350
+ if (kind === "office" && query.data === null) return <StructuredPanel {...props} />;
351
+ let pages: React.ReactNode;
352
+ if (tabActive && geometry && position) {
353
+ const numbers = Array.from({ length: Math.min(last - first + 1, 20) }, (_, index) => first + index);
354
+ const before = Math.max(1, first - 1);
355
+ const after = Math.min(pageCount, last + 1);
356
+ if (!web && last < after) numbers.push(after);
357
+ if (!web && before < first) numbers.push(before);
358
+ const origin = web ? 0 : pageBounds(geometry, before).top;
359
+ const pageScale = web ? scale : 1;
360
+ const images = numbers.map((number) => {
361
+ const bounds = pageBounds(geometry, number);
362
+ const left = (geometry.width - bounds.width) * pageScale / 2 + (web ? position.x : 0);
363
+ const top = (bounds.top - origin) * pageScale + (web ? position.y : 0);
364
+ const width = bounds.width * pageScale;
365
+ const height = bounds.height * pageScale;
366
+ const range = selection.selection;
367
+ const matches = matchesByPage.get(number);
368
+ const layer = range?.page === number || matches ? textQueries[textPages.indexOf(number)]?.data?.glyphs : undefined;
369
+ return <View key={`${version}:${number}`} pointerEvents="box-none"
370
+ style={{ position: "absolute", left, top, width, height }}>
371
+ <PageImage {...{
372
+ number, kind, fileKey, render, enqueue, theme, compact, errorLabel, width, height,
373
+ label: `${t(slides ? "slide" : "page")} ${number}`, retryLabel: t("retry"),
374
+ pixels: quality(bounds.width * rasterScale * Math.min(2, pixelRatio)),
375
+ }} />
376
+ {layer && matches && <PageFindOverlay {...{ width, height, glyphs: layer, matches }} active={find.active} />}
377
+ {layer && range?.page === number && <PageSelectionOverlay {...{ width, height, glyphs: layer, range }}
378
+ handles={!web || compact} accent={theme.colors.accent} scale={web ? 1 : scale} />}
379
+ </View>;
380
+ });
381
+ const bottom = pageBounds(geometry, after);
382
+ pages = web ? images : (
383
+ <View pointerEvents="box-none" style={{
384
+ position: "absolute", left: 0, top: 0, width: geometry.width, height: bottom.top + bottom.height - origin,
385
+ transformOrigin: [0, 0, 0],
386
+ transform: [{ translateX: position.x }, { translateY: position.y + origin * scale }, { scale }],
387
+ }}>{images}</View>
388
+ );
389
+ }
390
+ const findControl = <Control title={t("find")} icon="Search" disabled={!position} selected={findOpen}
391
+ onPress={findOpen ? closeFind : openFind} theme={theme} compact={compact} />;
392
+ const zoomControls = <ZoomControls {...{ scale, theme, compact, stepZoom }} disabled={!position}
393
+ setZoom={(scale) => changeZoom(() => scale)} />;
394
+ const applyPage = draft !== undefined && <Control title={t(slides ? "goToSlide" : "goToPage")} icon="CornerDownLeft"
395
+ onPress={() => { commitPage(); Keyboard.dismiss(); }} theme={theme} compact={compact} small={!web} />;
396
+ const pageControls = (
397
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 3 }}>
398
+ <Control title={t(slides ? "previousSlide" : "previous")} icon="ChevronLeft" disabled={page <= 1} onPress={() => goTo(page - 1)}
399
+ theme={theme} compact={compact} small={!web} />
400
+ <TextInput
401
+ ref={pageField}
402
+ accessibilityLabel={pageFieldLabel}
403
+ testID="merong-pdf-page-number"
404
+ value={draft ?? String(page)}
405
+ maxLength={7}
406
+ inputMode="numeric"
407
+ keyboardType="number-pad"
408
+ returnKeyType="go"
409
+ selectTextOnFocus
410
+ onChangeText={setDraft}
411
+ onSubmitEditing={commitPage}
412
+ onBlur={commitPage}
413
+ editable={!!pageCount}
414
+ style={{
415
+ color: theme.colors.foreground, borderColor: theme.colors.border,
416
+ borderWidth: 1, borderRadius: 5, textAlign: "center", paddingHorizontal: 4, paddingVertical: 0,
417
+ width: pageCount > 999 ? web ? 62 : 50 : web ? 42 : 38, height: web && compact ? 36 : 28,
418
+ }}
419
+ />
420
+ {web && applyPage}
421
+ <Text style={{ color: theme.colors.foregroundMuted, fontSize: 13 }}>/ {pageCount || "…"}</Text>
422
+ {(!web && applyPage) || <Control title={t(slides ? "nextSlide" : "next")} icon="ChevronRight" disabled={page >= pageCount}
423
+ onPress={() => goTo(page + 1)} theme={theme} compact={compact} small={!web} />}
424
+ </View>
425
+ );
426
+ return (
427
+ <View ref={panelRef} testID={`merong-${kind}-reader`} style={{ flex: 1, minHeight: 0, backgroundColor: theme.colors.surface1 }}>
428
+ <Toolbar theme={theme} filePanel={props} nativePrimary={!web && <>{pageControls}{zoomControls}</>}>
429
+ {web && <>{pageControls}{zoomControls}</>}
430
+ <Control title={t("fitWidth")} icon="MoveHorizontal" disabled={!position} selected={activeFit === "width"}
431
+ onPress={() => fit("width")} theme={theme} compact={compact} />
432
+ <Control title={t(slides ? "slideFit" : "reset")} icon="Scan" disabled={!position} selected={activeFit === "page"}
433
+ onPress={() => fit("page")} theme={theme} compact={compact} />
434
+ {findControl}
435
+ {slides && <Control title={t("thumbnails")} icon="PanelLeft" selected={slidesOpen}
436
+ onPress={() => setSlidesOpen((open) => !open)} theme={theme} compact={compact} />}
437
+ <ExternalFileAction {...props} />
438
+ </Toolbar>
439
+ <View style={{ flex: 1, minHeight: 0, flexDirection: "row" }}>
440
+ {slidesOpen && <SlideSidebar count={tabActive ? pageCount : 0} {...{ page, goTo, theme, compact }}
441
+ preview={sidebarPreview} />}
442
+ <View style={{ flex: 1, minHeight: 0, minWidth: 0 }}>
443
+ <View
444
+ ref={viewportRef}
445
+ testID={`merong-${kind}-viewport`}
446
+ accessibilityLabel={t("documentPages")}
447
+ tabIndex={web && enabled ? 0 : undefined}
448
+ onLayout={({ nativeEvent: { layout: bounds } }) => setViewport((previous) =>
449
+ bounds.width === previous.width && bounds.height === previous.height
450
+ ? previous
451
+ : { width: bounds.width, height: bounds.height },
452
+ )}
453
+ {...nativeGestures}
454
+ style={[
455
+ { flex: 1, minHeight: 0, overflow: "hidden" },
456
+ web && ({ touchAction: "none", userSelect: "none" } as ViewStyle),
457
+ ]}
458
+ >
459
+ {!tabActive ? null : pages ?? (query.isError ? (
460
+ <ReadError theme={theme} compact={compact} label={errorLabel} error={query.error}
461
+ retry={t("retry")} onRetry={() => { void query.refetch(); }} />
462
+ ) : <Loading />)}
463
+ {tabActive && selection.text() && (
464
+ <View style={[{ position: "absolute", right: 8, borderWidth: 1, borderRadius: 7,
465
+ borderColor: theme.colors.border, backgroundColor: theme.colors.surface1 },
466
+ findOpen ? { bottom: 8 } : { top: 8 }]}>
467
+ <Control title={t("copySelection")} icon="Copy" onPress={() => { void copySelection(selection.text()); }}
468
+ theme={theme} compact={compact} />
469
+ </View>
470
+ )}
471
+ </View>
472
+ {findOpen && <ReaderFindBar testID={pageFindId} find={find} theme={theme} compact={compact} close={closeFind} />}
473
+ </View>
474
+ </View>
475
+ </View>
476
+ );
477
+ }