@tobyt/expo-pdf-markup 1.1.4 → 2.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 (55) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +18 -0
  3. package/android/build.gradle +3 -0
  4. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookPager.kt +66 -0
  5. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookTurnPolicy.kt +117 -0
  6. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ContinuousPdfView.kt +370 -57
  7. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupModule.kt +4 -0
  8. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupView.kt +96 -5
  9. package/build/ExpoPdfMarkup.types.d.ts +19 -1
  10. package/build/ExpoPdfMarkup.types.d.ts.map +1 -1
  11. package/build/ExpoPdfMarkup.types.js.map +1 -1
  12. package/build/ExpoPdfMarkupView.web.d.ts.map +1 -1
  13. package/build/ExpoPdfMarkupView.web.js +396 -65
  14. package/build/ExpoPdfMarkupView.web.js.map +1 -1
  15. package/build/web/bookMode.d.ts +77 -0
  16. package/build/web/bookMode.d.ts.map +1 -0
  17. package/build/web/bookMode.js +169 -0
  18. package/build/web/bookMode.js.map +1 -0
  19. package/build/web/layout.d.ts +8 -0
  20. package/build/web/layout.d.ts.map +1 -0
  21. package/build/web/layout.js +22 -0
  22. package/build/web/layout.js.map +1 -0
  23. package/build/web/types.d.ts +2 -0
  24. package/build/web/types.d.ts.map +1 -1
  25. package/build/web/types.js.map +1 -1
  26. package/docs/agents/domain.md +51 -0
  27. package/docs/agents/issue-tracker.md +46 -0
  28. package/docs/agents/triage-labels.md +15 -0
  29. package/docs/annotation-coordinates.md +45 -0
  30. package/docs/annotation-validation.md +117 -0
  31. package/fixtures/annotations-v1.json +130 -0
  32. package/ios/AnnotationModels.swift +29 -30
  33. package/ios/AnnotationSerializer.swift +99 -12
  34. package/ios/ExpoPdfMarkupModule.swift +4 -0
  35. package/ios/ExpoPdfMarkupView+Book.swift +455 -0
  36. package/ios/ExpoPdfMarkupView+Ink.swift +13 -28
  37. package/ios/ExpoPdfMarkupView+Markup.swift +151 -0
  38. package/ios/ExpoPdfMarkupView+Move.swift +17 -6
  39. package/ios/ExpoPdfMarkupView.swift +76 -84
  40. package/ios/StampPDFAnnotation.swift +21 -3
  41. package/ios/Tests/AnnotationCoordinateTests.swift +337 -0
  42. package/ios/Tests/AnnotationSerializerTests.swift +43 -1
  43. package/ios/Tests/AreaMarkupTests.swift +279 -0
  44. package/ios/Tests/BookModeTests.swift +534 -0
  45. package/ios/Tests/ExpoPdfMarkupViewTests.swift +29 -0
  46. package/ios/Tests/RotatedAnnotationRenderingTests.swift +411 -0
  47. package/ios/Tests/book-sample.pdf +207 -0
  48. package/ios/Tests/single-page.pdf +52 -0
  49. package/package.json +3 -2
  50. package/src/ExpoPdfMarkup.types.ts +20 -1
  51. package/src/ExpoPdfMarkupView.web.tsx +471 -70
  52. package/src/web/bookMode.ts +186 -0
  53. package/src/web/layout.ts +30 -0
  54. package/src/web/types.ts +3 -0
  55. package/tsconfig.test.json +10 -0
@@ -20,7 +20,24 @@ import {
20
20
  serializeAnnotations,
21
21
  translateAnnotation,
22
22
  } from './web/annotationUtils';
23
- import type { PdfPageMeta } from './web/types';
23
+ import {
24
+ BOUNCE_PX,
25
+ EDGE_RESISTANCE,
26
+ TAP_SLOP_PX,
27
+ isViewShown,
28
+ ownsArrowKeys,
29
+ keyTurnFor,
30
+ canGestureTurn,
31
+ classifySwipe,
32
+ classifyTap,
33
+ releaseVelocityX,
34
+ resolveTurn,
35
+ slideOffsetFor,
36
+ type PointerSample,
37
+ type TurnDirection,
38
+ } from './web/bookMode';
39
+ import { computePageMetas } from './web/layout';
40
+ import type { PageSize, PdfPageMeta } from './web/types';
24
41
 
25
42
  // Configure pdfjs worker once at module level (consumers can override before mounting)
26
43
  if (!pdfjs.GlobalWorkerOptions.workerSrc) {
@@ -118,28 +135,35 @@ function PageView({
118
135
  React.useEffect(() => {
119
136
  let cancelled = false;
120
137
  async function render() {
121
- if (!pdfCanvasRef.current) return;
122
- renderTaskRef.current?.cancel();
123
- renderTaskRef.current = null;
124
- const page = await doc.getPage(pageIndex + 1);
125
- if (cancelled) {
126
- page.cleanup();
127
- return;
128
- }
129
- pageRef.current = page;
130
138
  const canvas = pdfCanvasRef.current;
131
139
  if (!canvas) return;
132
- canvas.width = meta.canvasWidth;
133
- canvas.height = meta.canvasHeight;
134
- const ctx = canvas.getContext('2d');
135
- if (!ctx) return;
136
- const viewport = page.getViewport({ scale: meta.scale * dpr });
137
- const task = page.render({ canvas: null, canvasContext: ctx, viewport });
138
- renderTaskRef.current = task;
140
+ canvas.dataset.pdfRenderState = 'pending';
141
+ renderTaskRef.current?.cancel();
142
+ renderTaskRef.current = null;
139
143
  try {
144
+ const page = await doc.getPage(pageIndex + 1);
145
+ if (cancelled) {
146
+ page.cleanup();
147
+ return;
148
+ }
149
+ pageRef.current = page;
150
+ canvas.width = meta.canvasWidth;
151
+ canvas.height = meta.canvasHeight;
152
+ const ctx = canvas.getContext('2d');
153
+ if (!ctx) {
154
+ canvas.dataset.pdfRenderState = 'error';
155
+ return;
156
+ }
157
+ const viewport = page.getViewport({ scale: meta.scale * dpr });
158
+ const task = page.render({ canvas: null, canvasContext: ctx, viewport });
159
+ renderTaskRef.current = task;
140
160
  await task.promise;
141
- } catch {
142
- // Render cancelled — ignore
161
+ if (!cancelled) canvas.dataset.pdfRenderState = 'complete';
162
+ } catch (error) {
163
+ if (!cancelled) {
164
+ canvas.dataset.pdfRenderState = 'error';
165
+ console.error('PDF page rendering failed', error);
166
+ }
143
167
  }
144
168
  }
145
169
  render();
@@ -399,10 +423,13 @@ function PageView({
399
423
  return (
400
424
  <div
401
425
  ref={containerRef}
426
+ data-pdf-page={pageIndex}
402
427
  style={{ position: 'relative', width: cssWidth, height: cssHeight, margin: '0 auto' }}
403
428
  >
404
429
  <canvas
405
430
  ref={pdfCanvasRef}
431
+ data-pdf-layer="pdf"
432
+ data-pdf-render-state="pending"
406
433
  style={{
407
434
  position: 'absolute',
408
435
  top: 0,
@@ -414,6 +441,7 @@ function PageView({
414
441
  />
415
442
  <canvas
416
443
  ref={annotCanvasRef}
444
+ data-pdf-layer="annotations"
417
445
  style={{
418
446
  position: 'absolute',
419
447
  top: 0,
@@ -435,9 +463,25 @@ function PageView({
435
463
  // Main component
436
464
  // ---------------------------------------------------------------------------
437
465
 
466
+ /** Duration of the book mode slide, in ms. */
467
+ const TURN_DURATION_MS = 250;
468
+
469
+ type BookGesture = {
470
+ startX: number;
471
+ startY: number;
472
+ lastX: number;
473
+ lastY: number;
474
+ /** `'turn'` drags the page sideways; `'pan'` scrolls a zoomed page. */
475
+ kind: 'turn' | 'pan';
476
+ moved: boolean;
477
+ /** Recent positions, oldest first, for the speed at release. */
478
+ samples: PointerSample[];
479
+ };
480
+
438
481
  export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
439
482
  const {
440
483
  source,
484
+ displayMode = 'continuous',
441
485
  page: propPage,
442
486
  backgroundColor = '#f0f0f0',
443
487
  annotations: annotationsProp,
@@ -455,10 +499,12 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
455
499
  style,
456
500
  } = props;
457
501
 
502
+ const isBook = displayMode === 'book';
458
503
  const scrollContainerRef = React.useRef<HTMLDivElement>(null);
459
- const [containerWidth, setContainerWidth] = React.useState(0);
504
+ const [containerSize, setContainerSize] = React.useState({ width: 0, height: 0 });
505
+ const containerWidth = containerSize.width;
460
506
  const [doc, setDoc] = React.useState<PDFDocumentProxy | null>(null);
461
- const [pageMetas, setPageMetas] = React.useState<PdfPageMeta[]>([]);
507
+ const [pageSizes, setPageSizes] = React.useState<PageSize[]>([]);
462
508
  const [annotations, setAnnotations] = React.useState<Annotation[]>([]);
463
509
  const lastAnnotationsJsonRef = React.useRef<string | undefined>(undefined);
464
510
  const pageContainerRefs = React.useRef<(HTMLDivElement | null)[]>([]);
@@ -467,7 +513,48 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
467
513
  const [zoomLevel, setZoomLevel] = React.useState(1);
468
514
  const zoomRef = React.useRef(1);
469
515
 
470
- // ResizeObserver → containerWidth
516
+ // The page the reader is on, shared by both modes so switching mode keeps it. The ref is read
517
+ // by the turn path, so quick turns in a row see the latest page before React re-renders.
518
+ const [currentPage, setCurrentPage] = React.useState(0);
519
+ const currentPageRef = React.useRef(0);
520
+ const lastReportedPageRef = React.useRef(-1);
521
+ // Book mode slide: horizontal offset of the page strip, and whether it animates there.
522
+ const [slide, setSlide] = React.useState({ offset: 0, animated: false });
523
+ const slideOffsetRef = React.useRef(0);
524
+ const turnTimerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
525
+ const turnFrameRef = React.useRef<number | null>(null);
526
+ const pendingTurnRef = React.useRef<number | null>(null);
527
+ const gestureRef = React.useRef<BookGesture | null>(null);
528
+ const activePointersRef = React.useRef(new Set<number>());
529
+
530
+ const dpr = typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1;
531
+ // Continuous mode ignores the view's height, so a height change doesn't re-lay it out.
532
+ const fitHeight = isBook ? containerSize.height : 0;
533
+ const pageMetas = React.useMemo(
534
+ () => computePageMetas(pageSizes, containerWidth, fitHeight, displayMode, dpr),
535
+ [pageSizes, containerWidth, fitHeight, displayMode, dpr]
536
+ );
537
+ const pageCount = doc ? pageMetas.length : 0;
538
+
539
+ /** Records the reader's page and fires `onPageChanged` once per change. */
540
+ const reportPage = React.useCallback(
541
+ (page: number) => {
542
+ currentPageRef.current = page;
543
+ setCurrentPage(page);
544
+ if (!doc || page === lastReportedPageRef.current) return;
545
+ lastReportedPageRef.current = page;
546
+ onPageChanged?.({
547
+ nativeEvent: {
548
+ page,
549
+ pageCount: doc.numPages,
550
+ pageWidth: pageSizes[page]?.pdfWidth ?? 0,
551
+ pageHeight: pageSizes[page]?.pdfHeight ?? 0,
552
+ },
553
+ });
554
+ },
555
+ [doc, pageSizes, onPageChanged]
556
+ );
557
+
471
558
  const applyAnnotations = React.useCallback(
472
559
  (updater: (prev: Annotation[]) => Annotation[]) => {
473
560
  setAnnotations((prev) => {
@@ -481,12 +568,17 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
481
568
  [onAnnotationsChanged]
482
569
  );
483
570
 
571
+ // ResizeObserver → containerSize
484
572
  React.useEffect(() => {
485
573
  const el = scrollContainerRef.current;
486
574
  if (!el) return;
487
575
  const ro = new ResizeObserver((entries) => {
488
- const width = entries[0]?.contentRect.width ?? 0;
489
- setContainerWidth(width);
576
+ const rect = entries[0]?.contentRect;
577
+ const width = rect?.width ?? 0;
578
+ const height = rect?.height ?? 0;
579
+ setContainerSize((prev) =>
580
+ prev.width === width && prev.height === height ? prev : { width, height }
581
+ );
490
582
  });
491
583
  ro.observe(el);
492
584
  return () => ro.disconnect();
@@ -566,9 +658,13 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
566
658
  };
567
659
  }, []);
568
660
 
569
- // Load PDF when source or containerWidth changes
661
+ // Load the PDF once the view has a size. Page layout is derived from the page sizes, so
662
+ // resizing the view re-lays out the pages without reloading the document, even when it comes
663
+ // back from zero size (e.g. a screen that was display: none in a back stack).
664
+ const hasSize = containerWidth > 0;
665
+ const loadedSourceRef = React.useRef<string | null>(null);
570
666
  React.useEffect(() => {
571
- if (!source || containerWidth <= 0) return;
667
+ if (!source || !hasSize || loadedSourceRef.current === source) return;
572
668
  let cancelled = false;
573
669
  loadingSourceRef.current = source;
574
670
 
@@ -580,8 +676,7 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
580
676
  loadedDoc.loadingTask.destroy();
581
677
  return;
582
678
  }
583
- const metas: PdfPageMeta[] = [];
584
- const dpr = window.devicePixelRatio ?? 1;
679
+ const sizes: PageSize[] = [];
585
680
  for (let i = 1; i <= loadedDoc.numPages; i++) {
586
681
  const pg = await loadedDoc.getPage(i);
587
682
  if (cancelled) {
@@ -590,21 +685,17 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
590
685
  return;
591
686
  }
592
687
  const viewport = pg.getViewport({ scale: 1 });
593
- const scale = containerWidth / viewport.width;
594
- const cssHeight = viewport.height * scale;
595
- metas.push({
596
- pdfWidth: viewport.width,
597
- pdfHeight: viewport.height,
598
- scale,
599
- canvasWidth: Math.round(containerWidth * dpr),
600
- canvasHeight: Math.round(cssHeight * dpr),
601
- });
688
+ sizes.push({ pdfWidth: viewport.width, pdfHeight: viewport.height });
602
689
  pg.cleanup();
603
690
  }
604
691
  docRef.current?.loadingTask.destroy();
605
692
  docRef.current = loadedDoc;
693
+ loadedSourceRef.current = source;
694
+ currentPageRef.current = 0;
695
+ lastReportedPageRef.current = -1;
696
+ setCurrentPage(0);
606
697
  setDoc(loadedDoc);
607
- setPageMetas(metas);
698
+ setPageSizes(sizes);
608
699
  pageContainerRefs.current = new Array(loadedDoc.numPages).fill(null);
609
700
  onLoadComplete?.({ nativeEvent: { pageCount: loadedDoc.numPages } });
610
701
  } catch (err) {
@@ -619,7 +710,23 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
619
710
  return () => {
620
711
  cancelled = true;
621
712
  };
622
- }, [source, containerWidth]); // intentionally omit callbacks — they should not re-trigger a PDF load
713
+ }, [source, hasSize]); // intentionally omit callbacks — they should not re-trigger a PDF load
714
+
715
+ // Continuous mode keeps the events it had in 1.1.4, when a width change reloaded the document:
716
+ // `onLoadComplete` fires again and the page in view is reported afresh. The document now loads
717
+ // once, so those events are replayed here instead. Book mode, and switching mode, fire neither.
718
+ const laidOutRef = React.useRef<{ doc: PDFDocumentProxy | null; width: number }>({
719
+ doc: null,
720
+ width: 0,
721
+ });
722
+ React.useEffect(() => {
723
+ const last = laidOutRef.current;
724
+ laidOutRef.current = { doc, width: containerWidth };
725
+ if (!doc || isBook || last.doc !== doc) return;
726
+ if (containerWidth <= 0 || containerWidth === last.width) return;
727
+ lastReportedPageRef.current = -1;
728
+ onLoadComplete?.({ nativeEvent: { pageCount: doc.numPages } });
729
+ }, [doc, containerWidth, isBook]); // intentionally omit callbacks — only a resize fires these
623
730
 
624
731
  // Sync annotations prop → state (guard round-trips)
625
732
  React.useEffect(() => {
@@ -629,19 +736,179 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
629
736
  setAnnotations(parsed.annotations);
630
737
  }, [annotationsProp]);
631
738
 
632
- // Scroll to propPage
739
+ // -------------------------------------------------------------------------
740
+ // Book mode turns
741
+ // -------------------------------------------------------------------------
742
+
743
+ const setSlideOffset = React.useCallback((offset: number, animated: boolean) => {
744
+ slideOffsetRef.current = offset;
745
+ setSlide((prev) =>
746
+ prev.offset === offset && prev.animated === animated ? prev : { offset, animated }
747
+ );
748
+ }, []);
749
+
750
+ const clearTurnTimer = React.useCallback(() => {
751
+ if (turnTimerRef.current != null) clearTimeout(turnTimerRef.current);
752
+ turnTimerRef.current = null;
753
+ if (turnFrameRef.current != null) cancelAnimationFrame(turnFrameRef.current);
754
+ turnFrameRef.current = null;
755
+ }, []);
756
+
757
+ const resetZoom = React.useCallback(() => {
758
+ if (zoomRef.current === 1) return;
759
+ zoomRef.current = 1;
760
+ setZoomLevel(1);
761
+ const el = scrollContainerRef.current;
762
+ if (el) {
763
+ el.scrollLeft = 0;
764
+ el.scrollTop = 0;
765
+ }
766
+ }, []);
767
+
768
+ /** Shows `page` straight away, with no slide, and reports it. */
769
+ const showBookPage = React.useCallback(
770
+ (page: number) => {
771
+ clearTurnTimer();
772
+ pendingTurnRef.current = null;
773
+ setSlideOffset(0, false);
774
+ reportPage(page);
775
+ },
776
+ [clearTurnTimer, reportPage, setSlideOffset]
777
+ );
778
+
779
+ /** Lands a slide that is still running, so a new turn starts from the page it was going to. */
780
+ const finishPendingTurn = React.useCallback(() => {
781
+ const pending = pendingTurnRef.current;
782
+ if (pending != null) showBookPage(pending);
783
+ else clearTurnTimer();
784
+ }, [clearTurnTimer, showBookPage]);
785
+
786
+ /** Slides the page back to rest. From rest it nudges towards `direction` first: the bounce. */
787
+ const bounce = React.useCallback(
788
+ (direction: TurnDirection) => {
789
+ clearTurnTimer();
790
+ if (slideOffsetRef.current === 0) {
791
+ setSlideOffset(slideOffsetFor(direction, BOUNCE_PX), true);
792
+ turnTimerRef.current = setTimeout(() => {
793
+ setSlideOffset(0, true);
794
+ turnTimerRef.current = null;
795
+ }, TURN_DURATION_MS / 2);
796
+ } else {
797
+ setSlideOffset(0, true);
798
+ }
799
+ },
800
+ [clearTurnTimer, setSlideOffset]
801
+ );
802
+
803
+ /**
804
+ * The one turn path for book mode. Swipes and edge taps call it once the turn policy allows
805
+ * them; hardware keys can call it directly. It resets zoom to fit, slides the page in
806
+ * `direction` (or bounces at either end) and fires `onPageChanged` once the turn lands.
807
+ */
808
+ const turnPage = React.useCallback(
809
+ (direction: TurnDirection) => {
810
+ if (!isBook || pageCount === 0) return;
811
+ finishPendingTurn();
812
+ const wasZoomed = zoomRef.current !== 1;
813
+ resetZoom();
814
+ const target = resolveTurn(currentPageRef.current, direction, pageCount);
815
+ if (target == null) {
816
+ bounce(direction);
817
+ return;
818
+ }
819
+ pendingTurnRef.current = target;
820
+ const slideAway = () => {
821
+ turnFrameRef.current = null;
822
+ setSlideOffset(slideOffsetFor(direction, containerWidth), true);
823
+ turnTimerRef.current = setTimeout(() => showBookPage(target), TURN_DURATION_MS);
824
+ };
825
+ if (!wasZoomed) {
826
+ slideAway();
827
+ return;
828
+ }
829
+ // A zoomed page shows on its own, so the strip of neighbours only comes back with this
830
+ // render. Let it paint at rest first, or the slide would jump instead of animating.
831
+ setSlideOffset(0, false);
832
+ turnFrameRef.current = requestAnimationFrame(() => {
833
+ turnFrameRef.current = requestAnimationFrame(slideAway);
834
+ });
835
+ },
836
+ [
837
+ isBook,
838
+ pageCount,
839
+ containerWidth,
840
+ finishPendingTurn,
841
+ resetZoom,
842
+ bounce,
843
+ setSlideOffset,
844
+ showBookPage,
845
+ ]
846
+ );
847
+
848
+ React.useEffect(() => clearTurnTimer, [clearTurnTimer]);
849
+
850
+ // Hardware keys and page-turner pedals turn the page in book mode.
851
+ React.useEffect(() => {
852
+ if (!isBook) return;
853
+ function onKeyDown(e: KeyboardEvent) {
854
+ // A modified arrow belongs to the browser or the host app (Alt+Left is Back, Shift selects).
855
+ if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return;
856
+ const direction = keyTurnFor(e.key);
857
+ if (!direction) return;
858
+ // Keys pressed in a text field or an arrow-key control anywhere on the page are its own.
859
+ if (ownsArrowKeys(e.target as Element | null) || ownsArrowKeys(document.activeElement)) {
860
+ return;
861
+ }
862
+ // A view that isn't on screen (hidden, or a screen left mounted in a back stack) keeps out.
863
+ if (!isViewShown(scrollContainerRef.current, containerSize.width, containerSize.height)) {
864
+ return;
865
+ }
866
+ e.preventDefault();
867
+ turnPage(direction);
868
+ }
869
+ document.addEventListener('keydown', onKeyDown);
870
+ return () => document.removeEventListener('keydown', onKeyDown);
871
+ }, [isBook, turnPage, containerSize]);
872
+
873
+ // Switching mode keeps the reader's page and starts it at fit.
874
+ React.useLayoutEffect(() => {
875
+ if (!doc) return;
876
+ finishPendingTurn();
877
+ resetZoom();
878
+ if (!isBook) {
879
+ pageContainerRefs.current[currentPageRef.current]?.scrollIntoView({
880
+ behavior: 'instant' as ScrollBehavior,
881
+ });
882
+ }
883
+ // Only a mode switch should move the page; the other dependencies are stable per document.
884
+ }, [isBook]);
885
+
886
+ // In book mode, report the page shown when the document opens.
887
+ React.useEffect(() => {
888
+ if (isBook && doc && pageCount > 0) reportPage(currentPageRef.current);
889
+ }, [isBook, doc, pageCount, reportPage]);
890
+
891
+ // Go to propPage
633
892
  React.useEffect(() => {
634
893
  if (propPage == null || !doc) return;
894
+ if (isBook) {
895
+ if (propPage < 0 || propPage >= pageSizes.length) return;
896
+ // `page` is a one-shot command, so acting on it here is the event, not derived state.
897
+ resetZoom();
898
+ // eslint-disable-next-line react-hooks/set-state-in-effect
899
+ showBookPage(propPage);
900
+ return;
901
+ }
635
902
  const el = pageContainerRefs.current[propPage];
636
903
  el?.scrollIntoView({ behavior: 'instant' as ScrollBehavior });
904
+ // Only a new `page` (or document) is a jump; switching mode keeps the current page instead.
637
905
  }, [propPage, doc]);
638
906
 
639
- // IntersectionObserver → onPageChanged
907
+ // IntersectionObserver → onPageChanged (continuous mode)
640
908
  React.useEffect(() => {
641
- if (!doc || pageMetas.length === 0) return;
909
+ if (isBook || !doc || pageMetas.length === 0) return;
642
910
  const els = pageContainerRefs.current.filter(Boolean) as HTMLDivElement[];
643
911
  if (els.length === 0) return;
644
- let lastReported = -1;
645
912
  const io = new IntersectionObserver(
646
913
  (entries) => {
647
914
  let topPage = -1;
@@ -655,23 +922,98 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
655
922
  }
656
923
  }
657
924
  }
658
- if (topPage !== -1 && topPage !== lastReported) {
659
- lastReported = topPage;
660
- onPageChanged?.({
661
- nativeEvent: {
662
- page: topPage,
663
- pageCount: doc.numPages,
664
- pageWidth: pageMetas[topPage]?.pdfWidth ?? 0,
665
- pageHeight: pageMetas[topPage]?.pdfHeight ?? 0,
666
- },
667
- });
668
- }
925
+ if (topPage !== -1) reportPage(topPage);
669
926
  },
670
927
  { root: scrollContainerRef.current, threshold: 0.1 }
671
928
  );
672
929
  for (const el of els) io.observe(el);
673
930
  return () => io.disconnect();
674
- }, [doc, pageMetas, onPageChanged]);
931
+ }, [isBook, doc, pageMetas, reportPage]);
932
+
933
+ // -------------------------------------------------------------------------
934
+ // Book mode gestures: swipes and edge taps
935
+ // -------------------------------------------------------------------------
936
+
937
+ function cancelBookGesture() {
938
+ const gesture = gestureRef.current;
939
+ gestureRef.current = null;
940
+ if (gesture?.kind === 'turn' && slideOffsetRef.current !== 0 && turnTimerRef.current == null) {
941
+ setSlideOffset(0, true);
942
+ }
943
+ }
944
+
945
+ function handleBookPointerDown(e: React.PointerEvent<HTMLDivElement>) {
946
+ activePointersRef.current.add(e.pointerId);
947
+ if (activePointersRef.current.size > 1) {
948
+ // A second finger means a pinch, never a turn.
949
+ cancelBookGesture();
950
+ return;
951
+ }
952
+ if (e.button !== 0 || annotationMode !== 'none') return;
953
+ const kind = canGestureTurn(annotationMode, zoomRef.current) ? 'turn' : 'pan';
954
+ if (kind === 'turn') finishPendingTurn();
955
+ gestureRef.current = {
956
+ startX: e.clientX,
957
+ startY: e.clientY,
958
+ lastX: e.clientX,
959
+ lastY: e.clientY,
960
+ kind,
961
+ moved: false,
962
+ samples: [{ x: e.clientX, t: e.timeStamp }],
963
+ };
964
+ try {
965
+ e.currentTarget.setPointerCapture(e.pointerId);
966
+ } catch {
967
+ // The pointer may already be gone (e.g. a synthetic event); the drag still works without capture.
968
+ }
969
+ }
970
+
971
+ function handleBookPointerMove(e: React.PointerEvent<HTMLDivElement>) {
972
+ const gesture = gestureRef.current;
973
+ if (!gesture) return;
974
+ const dx = e.clientX - gesture.startX;
975
+ const dy = e.clientY - gesture.startY;
976
+ if (!gesture.moved && Math.hypot(dx, dy) >= TAP_SLOP_PX) gesture.moved = true;
977
+ if (gesture.kind === 'pan') {
978
+ const el = scrollContainerRef.current;
979
+ if (el) {
980
+ el.scrollLeft -= e.clientX - gesture.lastX;
981
+ el.scrollTop -= e.clientY - gesture.lastY;
982
+ }
983
+ } else if (gesture.moved) {
984
+ // Past either end the page follows the finger only part of the way.
985
+ const blocked = resolveTurn(currentPageRef.current, dx < 0 ? 'next' : 'previous', pageCount);
986
+ setSlideOffset(blocked == null ? dx * EDGE_RESISTANCE : dx, false);
987
+ }
988
+ gesture.lastX = e.clientX;
989
+ gesture.lastY = e.clientY;
990
+ gesture.samples.push({ x: e.clientX, t: e.timeStamp });
991
+ if (gesture.samples.length > 20) gesture.samples.shift();
992
+ }
993
+
994
+ function handleBookPointerUp(e: React.PointerEvent<HTMLDivElement>) {
995
+ activePointersRef.current.delete(e.pointerId);
996
+ const gesture = gestureRef.current;
997
+ gestureRef.current = null;
998
+ if (!gesture || gesture.kind === 'pan') return;
999
+ const dx = e.clientX - gesture.startX;
1000
+ const dy = e.clientY - gesture.startY;
1001
+ if (!gesture.moved) {
1002
+ const rect = e.currentTarget.getBoundingClientRect();
1003
+ const direction = classifyTap(e.clientX - rect.left, containerWidth);
1004
+ if (direction) turnPage(direction);
1005
+ return;
1006
+ }
1007
+ gesture.samples.push({ x: e.clientX, t: e.timeStamp });
1008
+ const direction = classifySwipe(dx, dy, containerWidth, releaseVelocityX(gesture.samples));
1009
+ if (direction) turnPage(direction);
1010
+ else if (slideOffsetRef.current !== 0) setSlideOffset(0, true);
1011
+ }
1012
+
1013
+ function handleBookPointerCancel(e: React.PointerEvent<HTMLDivElement>) {
1014
+ activePointersRef.current.delete(e.pointerId);
1015
+ cancelBookGesture();
1016
+ }
675
1017
 
676
1018
  const handleAnnotationAdded = React.useCallback(
677
1019
  (annotation: Annotation) => {
@@ -752,43 +1094,102 @@ export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps) {
752
1094
 
753
1095
  const styleObj = style as React.CSSProperties | undefined;
754
1096
 
1097
+ const pageViewProps = {
1098
+ annotations,
1099
+ annotationMode,
1100
+ annotationColor,
1101
+ annotationLineWidth,
1102
+ stampText,
1103
+ stampSize,
1104
+ zoomLevel,
1105
+ onAnnotationAdded: handleAnnotationAdded,
1106
+ onAnnotationRemoved: handleAnnotationRemoved,
1107
+ onAnnotationUpdated: handleAnnotationUpdated,
1108
+ onTextInputRequested: handleTextInputRequested,
1109
+ };
1110
+
1111
+ const { width, height } = containerSize;
1112
+ const zoomed = zoomLevel > 1;
1113
+ // Book mode: one slot per page, each the size of the view with the page centred in it. At fit,
1114
+ // the current page sits between its neighbours on a strip that slides sideways. Zoomed in,
1115
+ // only the current page is shown, and the view scrolls over it.
1116
+ const slotStyle: React.CSSProperties = {
1117
+ width,
1118
+ height,
1119
+ flex: 'none',
1120
+ display: 'flex',
1121
+ alignItems: 'center',
1122
+ justifyContent: 'center',
1123
+ };
1124
+ const bookSlots = zoomed ? [currentPage] : [currentPage - 1, currentPage, currentPage + 1];
1125
+
1126
+ // The root element stays the same across modes, so the size and zoom listeners stay attached.
755
1127
  return (
756
1128
  <div
757
1129
  ref={scrollContainerRef}
1130
+ data-display-mode={displayMode}
1131
+ data-page={isBook ? currentPage : undefined}
758
1132
  style={{
759
- overflowY: 'scroll',
760
- overflowX: 'auto',
761
1133
  backgroundColor,
762
1134
  height: '100%',
1135
+ ...(isBook
1136
+ ? { overflow: zoomed ? 'auto' : 'hidden', touchAction: 'none', userSelect: 'none' }
1137
+ : { overflowY: 'scroll', overflowX: 'auto' }),
763
1138
  ...styleObj,
764
1139
  }}
1140
+ onPointerDown={isBook ? handleBookPointerDown : undefined}
1141
+ onPointerMove={isBook ? handleBookPointerMove : undefined}
1142
+ onPointerUp={isBook ? handleBookPointerUp : undefined}
1143
+ onPointerCancel={isBook ? handleBookPointerCancel : undefined}
765
1144
  >
766
1145
  <div style={{ zoom: zoomLevel }}>
767
- {doc &&
1146
+ {isBook ? (
1147
+ <div
1148
+ style={{
1149
+ display: 'flex',
1150
+ width: width * bookSlots.length,
1151
+ transform: zoomed ? undefined : `translateX(${slide.offset - width}px)`,
1152
+ transition: slide.animated ? `transform ${TURN_DURATION_MS}ms ease-out` : 'none',
1153
+ }}
1154
+ >
1155
+ {bookSlots.map((i) => (
1156
+ <div
1157
+ key={i}
1158
+ style={slotStyle}
1159
+ aria-hidden={i === currentPage ? undefined : true}
1160
+ data-book-slot={i}
1161
+ >
1162
+ {doc && pageMetas[i] && (
1163
+ <PageView
1164
+ {...pageViewProps}
1165
+ doc={doc}
1166
+ pageIndex={i}
1167
+ meta={pageMetas[i]}
1168
+ containerRef={(el) => {
1169
+ pageContainerRefs.current[i] = el;
1170
+ }}
1171
+ />
1172
+ )}
1173
+ </div>
1174
+ ))}
1175
+ </div>
1176
+ ) : (
1177
+ doc &&
768
1178
  pageMetas.map((meta, i) => (
769
1179
  <React.Fragment key={i}>
770
1180
  <PageView
1181
+ {...pageViewProps}
771
1182
  doc={doc}
772
1183
  pageIndex={i}
773
1184
  meta={meta}
774
- annotations={annotations}
775
- annotationMode={annotationMode}
776
- annotationColor={annotationColor}
777
- annotationLineWidth={annotationLineWidth}
778
- stampText={stampText}
779
- stampSize={stampSize}
780
- zoomLevel={zoomLevel}
781
- onAnnotationAdded={handleAnnotationAdded}
782
- onAnnotationRemoved={handleAnnotationRemoved}
783
- onAnnotationUpdated={handleAnnotationUpdated}
784
- onTextInputRequested={handleTextInputRequested}
785
1185
  containerRef={(el) => {
786
1186
  pageContainerRefs.current[i] = el;
787
1187
  }}
788
1188
  />
789
1189
  {i < pageMetas.length - 1 && <div style={{ height: 8 }} aria-hidden />}
790
1190
  </React.Fragment>
791
- ))}
1191
+ ))
1192
+ )}
792
1193
  </div>
793
1194
  </div>
794
1195
  );