@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
@@ -2,6 +2,8 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import * as pdfjs from 'pdfjs-dist';
3
3
  import * as React from 'react';
4
4
  import { clampAnnotationTranslation, canvasRectToPdfBounds, canvasToPdf, drawAnnotationsOnCanvas, hitTestAnnotation, newAnnotationId, parseAnnotations, serializeAnnotations, translateAnnotation, } from './web/annotationUtils';
5
+ import { BOUNCE_PX, EDGE_RESISTANCE, TAP_SLOP_PX, isViewShown, ownsArrowKeys, keyTurnFor, canGestureTurn, classifySwipe, classifyTap, releaseVelocityX, resolveTurn, slideOffsetFor, } from './web/bookMode';
6
+ import { computePageMetas } from './web/layout';
5
7
  // Configure pdfjs worker once at module level (consumers can override before mounting)
6
8
  if (!pdfjs.GlobalWorkerOptions.workerSrc) {
7
9
  // Default: served from public/ by withPdfMarkup() in metro.js.
@@ -49,32 +51,38 @@ function PageView({ doc, pageIndex, meta, annotations, annotationMode, annotatio
49
51
  React.useEffect(() => {
50
52
  let cancelled = false;
51
53
  async function render() {
52
- if (!pdfCanvasRef.current)
53
- return;
54
- renderTaskRef.current?.cancel();
55
- renderTaskRef.current = null;
56
- const page = await doc.getPage(pageIndex + 1);
57
- if (cancelled) {
58
- page.cleanup();
59
- return;
60
- }
61
- pageRef.current = page;
62
54
  const canvas = pdfCanvasRef.current;
63
55
  if (!canvas)
64
56
  return;
65
- canvas.width = meta.canvasWidth;
66
- canvas.height = meta.canvasHeight;
67
- const ctx = canvas.getContext('2d');
68
- if (!ctx)
69
- return;
70
- const viewport = page.getViewport({ scale: meta.scale * dpr });
71
- const task = page.render({ canvas: null, canvasContext: ctx, viewport });
72
- renderTaskRef.current = task;
57
+ canvas.dataset.pdfRenderState = 'pending';
58
+ renderTaskRef.current?.cancel();
59
+ renderTaskRef.current = null;
73
60
  try {
61
+ const page = await doc.getPage(pageIndex + 1);
62
+ if (cancelled) {
63
+ page.cleanup();
64
+ return;
65
+ }
66
+ pageRef.current = page;
67
+ canvas.width = meta.canvasWidth;
68
+ canvas.height = meta.canvasHeight;
69
+ const ctx = canvas.getContext('2d');
70
+ if (!ctx) {
71
+ canvas.dataset.pdfRenderState = 'error';
72
+ return;
73
+ }
74
+ const viewport = page.getViewport({ scale: meta.scale * dpr });
75
+ const task = page.render({ canvas: null, canvasContext: ctx, viewport });
76
+ renderTaskRef.current = task;
74
77
  await task.promise;
78
+ if (!cancelled)
79
+ canvas.dataset.pdfRenderState = 'complete';
75
80
  }
76
- catch {
77
- // Render cancelled — ignore
81
+ catch (error) {
82
+ if (!cancelled) {
83
+ canvas.dataset.pdfRenderState = 'error';
84
+ console.error('PDF page rendering failed', error);
85
+ }
78
86
  }
79
87
  }
80
88
  render();
@@ -325,14 +333,14 @@ function PageView({ doc, pageIndex, meta, annotations, annotationMode, annotatio
325
333
  : annotationMode === 'stamp'
326
334
  ? 'copy'
327
335
  : 'crosshair';
328
- return (_jsxs("div", { ref: containerRef, style: { position: 'relative', width: cssWidth, height: cssHeight, margin: '0 auto' }, children: [_jsx("canvas", { ref: pdfCanvasRef, style: {
336
+ return (_jsxs("div", { ref: containerRef, "data-pdf-page": pageIndex, style: { position: 'relative', width: cssWidth, height: cssHeight, margin: '0 auto' }, children: [_jsx("canvas", { ref: pdfCanvasRef, "data-pdf-layer": "pdf", "data-pdf-render-state": "pending", style: {
329
337
  position: 'absolute',
330
338
  top: 0,
331
339
  left: 0,
332
340
  width: cssWidth,
333
341
  height: cssHeight,
334
342
  pointerEvents: 'none',
335
- } }), _jsx("canvas", { ref: annotCanvasRef, style: {
343
+ } }), _jsx("canvas", { ref: annotCanvasRef, "data-pdf-layer": "annotations", style: {
336
344
  position: 'absolute',
337
345
  top: 0,
338
346
  left: 0,
@@ -345,12 +353,16 @@ function PageView({ doc, pageIndex, meta, annotations, annotationMode, annotatio
345
353
  // ---------------------------------------------------------------------------
346
354
  // Main component
347
355
  // ---------------------------------------------------------------------------
356
+ /** Duration of the book mode slide, in ms. */
357
+ const TURN_DURATION_MS = 250;
348
358
  export default function ExpoPdfMarkupView(props) {
349
- const { source, page: propPage, backgroundColor = '#f0f0f0', annotations: annotationsProp, annotationMode = 'none', annotationColor = '#FF0000', annotationLineWidth = 2, annotationFontFamily, stampText, stampSize = 48, onPageChanged, onLoadComplete, onError, onAnnotationsChanged, onTextInputRequested, style, } = props;
359
+ const { source, displayMode = 'continuous', page: propPage, backgroundColor = '#f0f0f0', annotations: annotationsProp, annotationMode = 'none', annotationColor = '#FF0000', annotationLineWidth = 2, annotationFontFamily, stampText, stampSize = 48, onPageChanged, onLoadComplete, onError, onAnnotationsChanged, onTextInputRequested, style, } = props;
360
+ const isBook = displayMode === 'book';
350
361
  const scrollContainerRef = React.useRef(null);
351
- const [containerWidth, setContainerWidth] = React.useState(0);
362
+ const [containerSize, setContainerSize] = React.useState({ width: 0, height: 0 });
363
+ const containerWidth = containerSize.width;
352
364
  const [doc, setDoc] = React.useState(null);
353
- const [pageMetas, setPageMetas] = React.useState([]);
365
+ const [pageSizes, setPageSizes] = React.useState([]);
354
366
  const [annotations, setAnnotations] = React.useState([]);
355
367
  const lastAnnotationsJsonRef = React.useRef(undefined);
356
368
  const pageContainerRefs = React.useRef([]);
@@ -358,7 +370,40 @@ export default function ExpoPdfMarkupView(props) {
358
370
  const loadingSourceRef = React.useRef(null);
359
371
  const [zoomLevel, setZoomLevel] = React.useState(1);
360
372
  const zoomRef = React.useRef(1);
361
- // ResizeObserver → containerWidth
373
+ // The page the reader is on, shared by both modes so switching mode keeps it. The ref is read
374
+ // by the turn path, so quick turns in a row see the latest page before React re-renders.
375
+ const [currentPage, setCurrentPage] = React.useState(0);
376
+ const currentPageRef = React.useRef(0);
377
+ const lastReportedPageRef = React.useRef(-1);
378
+ // Book mode slide: horizontal offset of the page strip, and whether it animates there.
379
+ const [slide, setSlide] = React.useState({ offset: 0, animated: false });
380
+ const slideOffsetRef = React.useRef(0);
381
+ const turnTimerRef = React.useRef(null);
382
+ const turnFrameRef = React.useRef(null);
383
+ const pendingTurnRef = React.useRef(null);
384
+ const gestureRef = React.useRef(null);
385
+ const activePointersRef = React.useRef(new Set());
386
+ const dpr = typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1;
387
+ // Continuous mode ignores the view's height, so a height change doesn't re-lay it out.
388
+ const fitHeight = isBook ? containerSize.height : 0;
389
+ const pageMetas = React.useMemo(() => computePageMetas(pageSizes, containerWidth, fitHeight, displayMode, dpr), [pageSizes, containerWidth, fitHeight, displayMode, dpr]);
390
+ const pageCount = doc ? pageMetas.length : 0;
391
+ /** Records the reader's page and fires `onPageChanged` once per change. */
392
+ const reportPage = React.useCallback((page) => {
393
+ currentPageRef.current = page;
394
+ setCurrentPage(page);
395
+ if (!doc || page === lastReportedPageRef.current)
396
+ return;
397
+ lastReportedPageRef.current = page;
398
+ onPageChanged?.({
399
+ nativeEvent: {
400
+ page,
401
+ pageCount: doc.numPages,
402
+ pageWidth: pageSizes[page]?.pdfWidth ?? 0,
403
+ pageHeight: pageSizes[page]?.pdfHeight ?? 0,
404
+ },
405
+ });
406
+ }, [doc, pageSizes, onPageChanged]);
362
407
  const applyAnnotations = React.useCallback((updater) => {
363
408
  setAnnotations((prev) => {
364
409
  const next = updater(prev);
@@ -368,13 +413,16 @@ export default function ExpoPdfMarkupView(props) {
368
413
  return next;
369
414
  });
370
415
  }, [onAnnotationsChanged]);
416
+ // ResizeObserver → containerSize
371
417
  React.useEffect(() => {
372
418
  const el = scrollContainerRef.current;
373
419
  if (!el)
374
420
  return;
375
421
  const ro = new ResizeObserver((entries) => {
376
- const width = entries[0]?.contentRect.width ?? 0;
377
- setContainerWidth(width);
422
+ const rect = entries[0]?.contentRect;
423
+ const width = rect?.width ?? 0;
424
+ const height = rect?.height ?? 0;
425
+ setContainerSize((prev) => prev.width === width && prev.height === height ? prev : { width, height });
378
426
  });
379
427
  ro.observe(el);
380
428
  return () => ro.disconnect();
@@ -450,9 +498,13 @@ export default function ExpoPdfMarkupView(props) {
450
498
  el.removeEventListener('touchcancel', onTouchEnd);
451
499
  };
452
500
  }, []);
453
- // Load PDF when source or containerWidth changes
501
+ // Load the PDF once the view has a size. Page layout is derived from the page sizes, so
502
+ // resizing the view re-lays out the pages without reloading the document, even when it comes
503
+ // back from zero size (e.g. a screen that was display: none in a back stack).
504
+ const hasSize = containerWidth > 0;
505
+ const loadedSourceRef = React.useRef(null);
454
506
  React.useEffect(() => {
455
- if (!source || containerWidth <= 0)
507
+ if (!source || !hasSize || loadedSourceRef.current === source)
456
508
  return;
457
509
  let cancelled = false;
458
510
  loadingSourceRef.current = source;
@@ -464,8 +516,7 @@ export default function ExpoPdfMarkupView(props) {
464
516
  loadedDoc.loadingTask.destroy();
465
517
  return;
466
518
  }
467
- const metas = [];
468
- const dpr = window.devicePixelRatio ?? 1;
519
+ const sizes = [];
469
520
  for (let i = 1; i <= loadedDoc.numPages; i++) {
470
521
  const pg = await loadedDoc.getPage(i);
471
522
  if (cancelled) {
@@ -474,21 +525,17 @@ export default function ExpoPdfMarkupView(props) {
474
525
  return;
475
526
  }
476
527
  const viewport = pg.getViewport({ scale: 1 });
477
- const scale = containerWidth / viewport.width;
478
- const cssHeight = viewport.height * scale;
479
- metas.push({
480
- pdfWidth: viewport.width,
481
- pdfHeight: viewport.height,
482
- scale,
483
- canvasWidth: Math.round(containerWidth * dpr),
484
- canvasHeight: Math.round(cssHeight * dpr),
485
- });
528
+ sizes.push({ pdfWidth: viewport.width, pdfHeight: viewport.height });
486
529
  pg.cleanup();
487
530
  }
488
531
  docRef.current?.loadingTask.destroy();
489
532
  docRef.current = loadedDoc;
533
+ loadedSourceRef.current = source;
534
+ currentPageRef.current = 0;
535
+ lastReportedPageRef.current = -1;
536
+ setCurrentPage(0);
490
537
  setDoc(loadedDoc);
491
- setPageMetas(metas);
538
+ setPageSizes(sizes);
492
539
  pageContainerRefs.current = new Array(loadedDoc.numPages).fill(null);
493
540
  onLoadComplete?.({ nativeEvent: { pageCount: loadedDoc.numPages } });
494
541
  }
@@ -504,7 +551,24 @@ export default function ExpoPdfMarkupView(props) {
504
551
  return () => {
505
552
  cancelled = true;
506
553
  };
507
- }, [source, containerWidth]); // intentionally omit callbacks — they should not re-trigger a PDF load
554
+ }, [source, hasSize]); // intentionally omit callbacks — they should not re-trigger a PDF load
555
+ // Continuous mode keeps the events it had in 1.1.4, when a width change reloaded the document:
556
+ // `onLoadComplete` fires again and the page in view is reported afresh. The document now loads
557
+ // once, so those events are replayed here instead. Book mode, and switching mode, fire neither.
558
+ const laidOutRef = React.useRef({
559
+ doc: null,
560
+ width: 0,
561
+ });
562
+ React.useEffect(() => {
563
+ const last = laidOutRef.current;
564
+ laidOutRef.current = { doc, width: containerWidth };
565
+ if (!doc || isBook || last.doc !== doc)
566
+ return;
567
+ if (containerWidth <= 0 || containerWidth === last.width)
568
+ return;
569
+ lastReportedPageRef.current = -1;
570
+ onLoadComplete?.({ nativeEvent: { pageCount: doc.numPages } });
571
+ }, [doc, containerWidth, isBook]); // intentionally omit callbacks — only a resize fires these
508
572
  // Sync annotations prop → state (guard round-trips)
509
573
  React.useEffect(() => {
510
574
  if (annotationsProp === lastAnnotationsJsonRef.current)
@@ -513,21 +577,171 @@ export default function ExpoPdfMarkupView(props) {
513
577
  const parsed = parseAnnotations(annotationsProp);
514
578
  setAnnotations(parsed.annotations);
515
579
  }, [annotationsProp]);
516
- // Scroll to propPage
580
+ // -------------------------------------------------------------------------
581
+ // Book mode turns
582
+ // -------------------------------------------------------------------------
583
+ const setSlideOffset = React.useCallback((offset, animated) => {
584
+ slideOffsetRef.current = offset;
585
+ setSlide((prev) => prev.offset === offset && prev.animated === animated ? prev : { offset, animated });
586
+ }, []);
587
+ const clearTurnTimer = React.useCallback(() => {
588
+ if (turnTimerRef.current != null)
589
+ clearTimeout(turnTimerRef.current);
590
+ turnTimerRef.current = null;
591
+ if (turnFrameRef.current != null)
592
+ cancelAnimationFrame(turnFrameRef.current);
593
+ turnFrameRef.current = null;
594
+ }, []);
595
+ const resetZoom = React.useCallback(() => {
596
+ if (zoomRef.current === 1)
597
+ return;
598
+ zoomRef.current = 1;
599
+ setZoomLevel(1);
600
+ const el = scrollContainerRef.current;
601
+ if (el) {
602
+ el.scrollLeft = 0;
603
+ el.scrollTop = 0;
604
+ }
605
+ }, []);
606
+ /** Shows `page` straight away, with no slide, and reports it. */
607
+ const showBookPage = React.useCallback((page) => {
608
+ clearTurnTimer();
609
+ pendingTurnRef.current = null;
610
+ setSlideOffset(0, false);
611
+ reportPage(page);
612
+ }, [clearTurnTimer, reportPage, setSlideOffset]);
613
+ /** Lands a slide that is still running, so a new turn starts from the page it was going to. */
614
+ const finishPendingTurn = React.useCallback(() => {
615
+ const pending = pendingTurnRef.current;
616
+ if (pending != null)
617
+ showBookPage(pending);
618
+ else
619
+ clearTurnTimer();
620
+ }, [clearTurnTimer, showBookPage]);
621
+ /** Slides the page back to rest. From rest it nudges towards `direction` first: the bounce. */
622
+ const bounce = React.useCallback((direction) => {
623
+ clearTurnTimer();
624
+ if (slideOffsetRef.current === 0) {
625
+ setSlideOffset(slideOffsetFor(direction, BOUNCE_PX), true);
626
+ turnTimerRef.current = setTimeout(() => {
627
+ setSlideOffset(0, true);
628
+ turnTimerRef.current = null;
629
+ }, TURN_DURATION_MS / 2);
630
+ }
631
+ else {
632
+ setSlideOffset(0, true);
633
+ }
634
+ }, [clearTurnTimer, setSlideOffset]);
635
+ /**
636
+ * The one turn path for book mode. Swipes and edge taps call it once the turn policy allows
637
+ * them; hardware keys can call it directly. It resets zoom to fit, slides the page in
638
+ * `direction` (or bounces at either end) and fires `onPageChanged` once the turn lands.
639
+ */
640
+ const turnPage = React.useCallback((direction) => {
641
+ if (!isBook || pageCount === 0)
642
+ return;
643
+ finishPendingTurn();
644
+ const wasZoomed = zoomRef.current !== 1;
645
+ resetZoom();
646
+ const target = resolveTurn(currentPageRef.current, direction, pageCount);
647
+ if (target == null) {
648
+ bounce(direction);
649
+ return;
650
+ }
651
+ pendingTurnRef.current = target;
652
+ const slideAway = () => {
653
+ turnFrameRef.current = null;
654
+ setSlideOffset(slideOffsetFor(direction, containerWidth), true);
655
+ turnTimerRef.current = setTimeout(() => showBookPage(target), TURN_DURATION_MS);
656
+ };
657
+ if (!wasZoomed) {
658
+ slideAway();
659
+ return;
660
+ }
661
+ // A zoomed page shows on its own, so the strip of neighbours only comes back with this
662
+ // render. Let it paint at rest first, or the slide would jump instead of animating.
663
+ setSlideOffset(0, false);
664
+ turnFrameRef.current = requestAnimationFrame(() => {
665
+ turnFrameRef.current = requestAnimationFrame(slideAway);
666
+ });
667
+ }, [
668
+ isBook,
669
+ pageCount,
670
+ containerWidth,
671
+ finishPendingTurn,
672
+ resetZoom,
673
+ bounce,
674
+ setSlideOffset,
675
+ showBookPage,
676
+ ]);
677
+ React.useEffect(() => clearTurnTimer, [clearTurnTimer]);
678
+ // Hardware keys and page-turner pedals turn the page in book mode.
679
+ React.useEffect(() => {
680
+ if (!isBook)
681
+ return;
682
+ function onKeyDown(e) {
683
+ // A modified arrow belongs to the browser or the host app (Alt+Left is Back, Shift selects).
684
+ if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey)
685
+ return;
686
+ const direction = keyTurnFor(e.key);
687
+ if (!direction)
688
+ return;
689
+ // Keys pressed in a text field or an arrow-key control anywhere on the page are its own.
690
+ if (ownsArrowKeys(e.target) || ownsArrowKeys(document.activeElement)) {
691
+ return;
692
+ }
693
+ // A view that isn't on screen (hidden, or a screen left mounted in a back stack) keeps out.
694
+ if (!isViewShown(scrollContainerRef.current, containerSize.width, containerSize.height)) {
695
+ return;
696
+ }
697
+ e.preventDefault();
698
+ turnPage(direction);
699
+ }
700
+ document.addEventListener('keydown', onKeyDown);
701
+ return () => document.removeEventListener('keydown', onKeyDown);
702
+ }, [isBook, turnPage, containerSize]);
703
+ // Switching mode keeps the reader's page and starts it at fit.
704
+ React.useLayoutEffect(() => {
705
+ if (!doc)
706
+ return;
707
+ finishPendingTurn();
708
+ resetZoom();
709
+ if (!isBook) {
710
+ pageContainerRefs.current[currentPageRef.current]?.scrollIntoView({
711
+ behavior: 'instant',
712
+ });
713
+ }
714
+ // Only a mode switch should move the page; the other dependencies are stable per document.
715
+ }, [isBook]);
716
+ // In book mode, report the page shown when the document opens.
717
+ React.useEffect(() => {
718
+ if (isBook && doc && pageCount > 0)
719
+ reportPage(currentPageRef.current);
720
+ }, [isBook, doc, pageCount, reportPage]);
721
+ // Go to propPage
517
722
  React.useEffect(() => {
518
723
  if (propPage == null || !doc)
519
724
  return;
725
+ if (isBook) {
726
+ if (propPage < 0 || propPage >= pageSizes.length)
727
+ return;
728
+ // `page` is a one-shot command, so acting on it here is the event, not derived state.
729
+ resetZoom();
730
+ // eslint-disable-next-line react-hooks/set-state-in-effect
731
+ showBookPage(propPage);
732
+ return;
733
+ }
520
734
  const el = pageContainerRefs.current[propPage];
521
735
  el?.scrollIntoView({ behavior: 'instant' });
736
+ // Only a new `page` (or document) is a jump; switching mode keeps the current page instead.
522
737
  }, [propPage, doc]);
523
- // IntersectionObserver → onPageChanged
738
+ // IntersectionObserver → onPageChanged (continuous mode)
524
739
  React.useEffect(() => {
525
- if (!doc || pageMetas.length === 0)
740
+ if (isBook || !doc || pageMetas.length === 0)
526
741
  return;
527
742
  const els = pageContainerRefs.current.filter(Boolean);
528
743
  if (els.length === 0)
529
744
  return;
530
- let lastReported = -1;
531
745
  const io = new IntersectionObserver((entries) => {
532
746
  let topPage = -1;
533
747
  let topY = Infinity;
@@ -540,22 +754,103 @@ export default function ExpoPdfMarkupView(props) {
540
754
  }
541
755
  }
542
756
  }
543
- if (topPage !== -1 && topPage !== lastReported) {
544
- lastReported = topPage;
545
- onPageChanged?.({
546
- nativeEvent: {
547
- page: topPage,
548
- pageCount: doc.numPages,
549
- pageWidth: pageMetas[topPage]?.pdfWidth ?? 0,
550
- pageHeight: pageMetas[topPage]?.pdfHeight ?? 0,
551
- },
552
- });
553
- }
757
+ if (topPage !== -1)
758
+ reportPage(topPage);
554
759
  }, { root: scrollContainerRef.current, threshold: 0.1 });
555
760
  for (const el of els)
556
761
  io.observe(el);
557
762
  return () => io.disconnect();
558
- }, [doc, pageMetas, onPageChanged]);
763
+ }, [isBook, doc, pageMetas, reportPage]);
764
+ // -------------------------------------------------------------------------
765
+ // Book mode gestures: swipes and edge taps
766
+ // -------------------------------------------------------------------------
767
+ function cancelBookGesture() {
768
+ const gesture = gestureRef.current;
769
+ gestureRef.current = null;
770
+ if (gesture?.kind === 'turn' && slideOffsetRef.current !== 0 && turnTimerRef.current == null) {
771
+ setSlideOffset(0, true);
772
+ }
773
+ }
774
+ function handleBookPointerDown(e) {
775
+ activePointersRef.current.add(e.pointerId);
776
+ if (activePointersRef.current.size > 1) {
777
+ // A second finger means a pinch, never a turn.
778
+ cancelBookGesture();
779
+ return;
780
+ }
781
+ if (e.button !== 0 || annotationMode !== 'none')
782
+ return;
783
+ const kind = canGestureTurn(annotationMode, zoomRef.current) ? 'turn' : 'pan';
784
+ if (kind === 'turn')
785
+ finishPendingTurn();
786
+ gestureRef.current = {
787
+ startX: e.clientX,
788
+ startY: e.clientY,
789
+ lastX: e.clientX,
790
+ lastY: e.clientY,
791
+ kind,
792
+ moved: false,
793
+ samples: [{ x: e.clientX, t: e.timeStamp }],
794
+ };
795
+ try {
796
+ e.currentTarget.setPointerCapture(e.pointerId);
797
+ }
798
+ catch {
799
+ // The pointer may already be gone (e.g. a synthetic event); the drag still works without capture.
800
+ }
801
+ }
802
+ function handleBookPointerMove(e) {
803
+ const gesture = gestureRef.current;
804
+ if (!gesture)
805
+ return;
806
+ const dx = e.clientX - gesture.startX;
807
+ const dy = e.clientY - gesture.startY;
808
+ if (!gesture.moved && Math.hypot(dx, dy) >= TAP_SLOP_PX)
809
+ gesture.moved = true;
810
+ if (gesture.kind === 'pan') {
811
+ const el = scrollContainerRef.current;
812
+ if (el) {
813
+ el.scrollLeft -= e.clientX - gesture.lastX;
814
+ el.scrollTop -= e.clientY - gesture.lastY;
815
+ }
816
+ }
817
+ else if (gesture.moved) {
818
+ // Past either end the page follows the finger only part of the way.
819
+ const blocked = resolveTurn(currentPageRef.current, dx < 0 ? 'next' : 'previous', pageCount);
820
+ setSlideOffset(blocked == null ? dx * EDGE_RESISTANCE : dx, false);
821
+ }
822
+ gesture.lastX = e.clientX;
823
+ gesture.lastY = e.clientY;
824
+ gesture.samples.push({ x: e.clientX, t: e.timeStamp });
825
+ if (gesture.samples.length > 20)
826
+ gesture.samples.shift();
827
+ }
828
+ function handleBookPointerUp(e) {
829
+ activePointersRef.current.delete(e.pointerId);
830
+ const gesture = gestureRef.current;
831
+ gestureRef.current = null;
832
+ if (!gesture || gesture.kind === 'pan')
833
+ return;
834
+ const dx = e.clientX - gesture.startX;
835
+ const dy = e.clientY - gesture.startY;
836
+ if (!gesture.moved) {
837
+ const rect = e.currentTarget.getBoundingClientRect();
838
+ const direction = classifyTap(e.clientX - rect.left, containerWidth);
839
+ if (direction)
840
+ turnPage(direction);
841
+ return;
842
+ }
843
+ gesture.samples.push({ x: e.clientX, t: e.timeStamp });
844
+ const direction = classifySwipe(dx, dy, containerWidth, releaseVelocityX(gesture.samples));
845
+ if (direction)
846
+ turnPage(direction);
847
+ else if (slideOffsetRef.current !== 0)
848
+ setSlideOffset(0, true);
849
+ }
850
+ function handleBookPointerCancel(e) {
851
+ activePointersRef.current.delete(e.pointerId);
852
+ cancelBookGesture();
853
+ }
559
854
  const handleAnnotationAdded = React.useCallback((annotation) => {
560
855
  applyAnnotations((prev) => [...prev, annotation]);
561
856
  }, [applyAnnotations]);
@@ -608,15 +903,51 @@ export default function ExpoPdfMarkupView(props) {
608
903
  onTextInputRequested,
609
904
  ]);
610
905
  const styleObj = style;
611
- return (_jsx("div", { ref: scrollContainerRef, style: {
612
- overflowY: 'scroll',
613
- overflowX: 'auto',
906
+ const pageViewProps = {
907
+ annotations,
908
+ annotationMode,
909
+ annotationColor,
910
+ annotationLineWidth,
911
+ stampText,
912
+ stampSize,
913
+ zoomLevel,
914
+ onAnnotationAdded: handleAnnotationAdded,
915
+ onAnnotationRemoved: handleAnnotationRemoved,
916
+ onAnnotationUpdated: handleAnnotationUpdated,
917
+ onTextInputRequested: handleTextInputRequested,
918
+ };
919
+ const { width, height } = containerSize;
920
+ const zoomed = zoomLevel > 1;
921
+ // Book mode: one slot per page, each the size of the view with the page centred in it. At fit,
922
+ // the current page sits between its neighbours on a strip that slides sideways. Zoomed in,
923
+ // only the current page is shown, and the view scrolls over it.
924
+ const slotStyle = {
925
+ width,
926
+ height,
927
+ flex: 'none',
928
+ display: 'flex',
929
+ alignItems: 'center',
930
+ justifyContent: 'center',
931
+ };
932
+ const bookSlots = zoomed ? [currentPage] : [currentPage - 1, currentPage, currentPage + 1];
933
+ // The root element stays the same across modes, so the size and zoom listeners stay attached.
934
+ return (_jsx("div", { ref: scrollContainerRef, "data-display-mode": displayMode, "data-page": isBook ? currentPage : undefined, style: {
614
935
  backgroundColor,
615
936
  height: '100%',
937
+ ...(isBook
938
+ ? { overflow: zoomed ? 'auto' : 'hidden', touchAction: 'none', userSelect: 'none' }
939
+ : { overflowY: 'scroll', overflowX: 'auto' }),
616
940
  ...styleObj,
617
- }, children: _jsx("div", { style: { zoom: zoomLevel }, children: doc &&
618
- pageMetas.map((meta, i) => (_jsxs(React.Fragment, { children: [_jsx(PageView, { doc: doc, pageIndex: i, meta: meta, annotations: annotations, annotationMode: annotationMode, annotationColor: annotationColor, annotationLineWidth: annotationLineWidth, stampText: stampText, stampSize: stampSize, zoomLevel: zoomLevel, onAnnotationAdded: handleAnnotationAdded, onAnnotationRemoved: handleAnnotationRemoved, onAnnotationUpdated: handleAnnotationUpdated, onTextInputRequested: handleTextInputRequested, containerRef: (el) => {
941
+ }, onPointerDown: isBook ? handleBookPointerDown : undefined, onPointerMove: isBook ? handleBookPointerMove : undefined, onPointerUp: isBook ? handleBookPointerUp : undefined, onPointerCancel: isBook ? handleBookPointerCancel : undefined, children: _jsx("div", { style: { zoom: zoomLevel }, children: isBook ? (_jsx("div", { style: {
942
+ display: 'flex',
943
+ width: width * bookSlots.length,
944
+ transform: zoomed ? undefined : `translateX(${slide.offset - width}px)`,
945
+ transition: slide.animated ? `transform ${TURN_DURATION_MS}ms ease-out` : 'none',
946
+ }, children: bookSlots.map((i) => (_jsx("div", { style: slotStyle, "aria-hidden": i === currentPage ? undefined : true, "data-book-slot": i, children: doc && pageMetas[i] && (_jsx(PageView, { ...pageViewProps, doc: doc, pageIndex: i, meta: pageMetas[i], containerRef: (el) => {
947
+ pageContainerRefs.current[i] = el;
948
+ } })) }, i))) })) : (doc &&
949
+ pageMetas.map((meta, i) => (_jsxs(React.Fragment, { children: [_jsx(PageView, { ...pageViewProps, doc: doc, pageIndex: i, meta: meta, containerRef: (el) => {
619
950
  pageContainerRefs.current[i] = el;
620
- } }), i < pageMetas.length - 1 && _jsx("div", { style: { height: 8 }, "aria-hidden": true })] }, i))) }) }));
951
+ } }), i < pageMetas.length - 1 && _jsx("div", { style: { height: 8 }, "aria-hidden": true })] }, i)))) }) }));
621
952
  }
622
953
  //# sourceMappingURL=ExpoPdfMarkupView.web.js.map