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