@tobyt/expo-pdf-markup 0.2.2 → 0.3.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 (40) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +85 -4
  3. package/build/ExpoPdfMarkup.types.d.ts +1 -1
  4. package/build/ExpoPdfMarkup.types.d.ts.map +1 -1
  5. package/build/ExpoPdfMarkup.types.js.map +1 -1
  6. package/build/ExpoPdfMarkupView.web.d.ts +3 -1
  7. package/build/ExpoPdfMarkupView.web.d.ts.map +1 -1
  8. package/build/ExpoPdfMarkupView.web.js +410 -4
  9. package/build/ExpoPdfMarkupView.web.js.map +1 -1
  10. package/build/index.d.ts +1 -0
  11. package/build/index.d.ts.map +1 -1
  12. package/build/index.js +1 -0
  13. package/build/index.js.map +1 -1
  14. package/build/pdfjs.d.ts +2 -0
  15. package/build/pdfjs.d.ts.map +1 -0
  16. package/build/pdfjs.js +6 -0
  17. package/build/pdfjs.js.map +1 -0
  18. package/build/pdfjs.web.d.ts +2 -0
  19. package/build/pdfjs.web.d.ts.map +1 -0
  20. package/build/pdfjs.web.js +2 -0
  21. package/build/pdfjs.web.js.map +1 -0
  22. package/build/web/annotationUtils.d.ts +37 -0
  23. package/build/web/annotationUtils.d.ts.map +1 -0
  24. package/build/web/annotationUtils.js +213 -0
  25. package/build/web/annotationUtils.js.map +1 -0
  26. package/build/web/types.d.ts +13 -0
  27. package/build/web/types.d.ts.map +1 -0
  28. package/build/web/types.js +2 -0
  29. package/build/web/types.js.map +1 -0
  30. package/ios/ExpoPdfMarkup.podspec +1 -1
  31. package/metro.d.ts +5 -0
  32. package/metro.js +90 -0
  33. package/package.json +8 -1
  34. package/src/ExpoPdfMarkup.types.ts +1 -1
  35. package/src/ExpoPdfMarkupView.web.tsx +512 -5
  36. package/src/index.ts +1 -0
  37. package/src/pdfjs.ts +5 -0
  38. package/src/pdfjs.web.ts +1 -0
  39. package/src/web/annotationUtils.ts +257 -0
  40. package/src/web/types.ts +12 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @tobyt/expo-pdf-markup
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - PDF rendering and markup is now also supported on Web.
8
+
9
+ ### Patch Changes
10
+
11
+ - 4dafaf4: Fixed documentation for the source prop - it only accepts absolute local file paths; remote URLs are not supported. Updated the README usage example to reflect real-world usage (loading a bundled asset via expo-asset) and demonstrate key props like annotationMode, annotationColor, annotationLineWidth, annotations, and the event callbacks.
12
+
13
+ ## 0.2.3
14
+
15
+ ### Patch Changes
16
+
17
+ - fix: exclude ios/Tests from podspec source_files to prevent XCTest
18
+
3
19
  ## 0.2.2
4
20
 
5
21
  ### Patch Changes
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  An Expo module for displaying and annotating PDFs, with support for iOS, Android, and Web.
9
9
 
10
- > **Status:** Early development — actively being tested. Web support is planned and will be added soon.
10
+ > **Status:** Early development — actively being tested.
11
11
 
12
12
  ## Platform support
13
13
 
@@ -15,7 +15,7 @@ An Expo module for displaying and annotating PDFs, with support for iOS, Android
15
15
  | -------- | ------------- | ----------- |
16
16
  | iOS | ✅ | ✅ |
17
17
  | Android | ✅ | ✅ |
18
- | Web | 🔜 | 🔜 |
18
+ | Web | ✅ | ✅ |
19
19
 
20
20
  ## Installation
21
21
 
@@ -29,15 +29,96 @@ npm install @tobyt/expo-pdf-markup
29
29
  npx pod-install
30
30
  ```
31
31
 
32
+ ### Web
33
+
34
+ Web rendering uses [pdfjs-dist](https://github.com/mozilla/pdfjs-dist). Install it as a dependency:
35
+
36
+ ```sh
37
+ npm install pdfjs-dist
38
+ ```
39
+
40
+ Then add the Metro config plugin to your `metro.config.js`:
41
+
42
+ ```js
43
+ const { getDefaultConfig } = require('expo/metro-config');
44
+ const { withPdfMarkup } = require('@tobyt/expo-pdf-markup/metro');
45
+
46
+ const config = getDefaultConfig(__dirname);
47
+ module.exports = withPdfMarkup(config);
48
+ ```
49
+
50
+ `withPdfMarkup` does two things automatically:
51
+
52
+ 1. **Patches `import.meta`** in pdfjs-dist so Metro can bundle it (pdfjs-dist v4 uses ESM syntax in a Node.js-only code path that is otherwise unreachable in a browser).
53
+ 2. **Copies the pdfjs worker** to `public/pdf.worker.min.mjs` in your project root so it is served at `/pdf.worker.min.mjs` (same-origin, no CORS issues).
54
+
55
+ The `public/pdf.worker.min.mjs` file is regenerated on each Metro start if missing, so you can add it to `.gitignore`:
56
+
57
+ ```
58
+ public/pdf.worker.min.mjs
59
+ ```
60
+
61
+ #### Using a different worker URL
62
+
63
+ If you are not using Metro (e.g. Webpack or a custom CDN), set the worker URL before mounting the view:
64
+
65
+ ```ts
66
+ import { setPdfJsWorkerSrc } from '@tobyt/expo-pdf-markup';
67
+
68
+ setPdfJsWorkerSrc('https://your-cdn.example.com/pdf.worker.min.mjs');
69
+ ```
70
+
71
+ #### Asset loading on web
72
+
73
+ `expo-asset` returns a full URL on web (`https://…` or `http://…`), not a local path. Pass it directly to `source` — pdfjs accepts URLs:
74
+
75
+ ```ts
76
+ // asset.localUri on web is already a URL; the .replace() is a no-op
77
+ setPdfPath(asset.localUri.replace('file://', ''));
78
+ ```
79
+
32
80
  ## Usage
33
81
 
34
82
  Full API reference is available at **[tobyt42.github.io/expo-pdf-markup](https://tobyt42.github.io/expo-pdf-markup/types/ExpoPdfMarkupViewProps.html)**.
35
83
 
36
84
  ```tsx
37
85
  import { ExpoPdfMarkupView } from '@tobyt/expo-pdf-markup';
86
+ import type { AnnotationMode } from '@tobyt/expo-pdf-markup';
87
+ import { Asset } from 'expo-asset';
88
+ import { useEffect, useState } from 'react';
89
+ import { StyleSheet } from 'react-native';
38
90
 
39
91
  export default function App() {
40
- return <ExpoPdfMarkupView source={{ uri: 'https://example.com/document.pdf' }} />;
92
+ const [pdfPath, setPdfPath] = useState<string | null>(null);
93
+ const [annotations, setAnnotations] = useState(JSON.stringify({ version: 1, annotations: [] }));
94
+
95
+ useEffect(() => {
96
+ async function preparePdf() {
97
+ const asset = Asset.fromModule(require('./assets/document.pdf'));
98
+ await asset.downloadAsync();
99
+ if (asset.localUri) setPdfPath(asset.localUri.replace('file://', ''));
100
+ }
101
+ preparePdf();
102
+ }, []);
103
+
104
+ if (!pdfPath) return null;
105
+
106
+ return (
107
+ <ExpoPdfMarkupView
108
+ source={pdfPath}
109
+ style={StyleSheet.absoluteFill}
110
+ annotationMode="ink"
111
+ annotationColor="#FF0000"
112
+ annotationLineWidth={3}
113
+ annotations={annotations}
114
+ onLoadComplete={({ nativeEvent: { pageCount } }) => console.log(`Loaded ${pageCount} pages`)}
115
+ onPageChanged={({ nativeEvent: { page, pageCount } }) =>
116
+ console.log(`Page ${page + 1} of ${pageCount}`)
117
+ }
118
+ onAnnotationsChanged={({ nativeEvent }) => setAnnotations(nativeEvent.annotations)}
119
+ onError={({ nativeEvent: { message } }) => console.error(message)}
120
+ />
121
+ );
41
122
  }
42
123
  ```
43
124
 
@@ -54,7 +135,7 @@ cd example
54
135
  npx expo start
55
136
  ```
56
137
 
57
- ## Core Team ✨
138
+ ## Core Team
58
139
 
59
140
  <table>
60
141
  <tr>
@@ -52,7 +52,7 @@ export type AnnotationsData = {
52
52
  };
53
53
  export type AnnotationMode = 'none' | 'ink' | 'highlight' | 'underline' | 'text' | 'eraser';
54
54
  export type ExpoPdfMarkupViewProps = {
55
- /** Local file path or remote URL of the PDF to display. */
55
+ /** Absolute local file path of the PDF to display. */
56
56
  source: string;
57
57
  /** 0-based page number to display. Can be used to restore scroll position on orientation change. */
58
58
  page?: number;
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoPdfMarkup.types.d.ts","sourceRoot":"","sources":["../src/ExpoPdfMarkup.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzD,MAAM,MAAM,eAAe,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CA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;YAAC,SAAS,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,KAAK,IAAI,CAAC;IACtF,oDAAoD;IACpD,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,WAAW,EAAE;YAAE,SAAS,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,KAAK,IAAI,CAAC;IACzE,6CAA6C;IAC7C,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,WAAW,EAAE;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,KAAK,IAAI,CAAC;IAChE,wHAAwH;IACxH,oBAAoB,CAAC,EAAE,CAAC,KAAK,EAAE;QAAE,WAAW,EAAE;YAAE,WAAW,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,KAAK,IAAI,CAAC;IACjF,KAAK,CAAC,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;CAC9B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoPdfMarkup.types.js","sourceRoot":"","sources":["../src/ExpoPdfMarkup.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { StyleProp, ViewStyle } from 'react-native';\n\nexport type AnnotationPoint = { x: number; y: number };\n\nexport type AnnotationBounds = { x: number; y: number; width: number; height: number };\n\nexport type InkAnnotation = {\n id: string;\n type: 'ink';\n page: number;\n color: string;\n lineWidth: number;\n paths: AnnotationPoint[][];\n createdAt?: number;\n};\n\nexport type HighlightAnnotation = {\n id: string;\n type: 'highlight';\n page: number;\n color: string;\n alpha?: number;\n bounds: AnnotationBounds;\n createdAt?: number;\n};\n\nexport type UnderlineAnnotation = {\n id: string;\n type: 'underline';\n page: number;\n color: string;\n bounds: AnnotationBounds;\n createdAt?: number;\n};\n\nexport type TextAnnotation = {\n id: string;\n type: 'text' | 'freeText';\n page: number;\n color: string;\n bounds: AnnotationBounds;\n contents?: string;\n fontSize?: number;\n createdAt?: number;\n};\n\nexport type Annotation = InkAnnotation | HighlightAnnotation | UnderlineAnnotation | TextAnnotation;\n\nexport type AnnotationsData = {\n version: 1;\n annotations: Annotation[];\n};\n\nexport type AnnotationMode = 'none' | 'ink' | 'highlight' | 'underline' | 'text' | 'eraser';\n\nexport type ExpoPdfMarkupViewProps = {\n /** Local file path or remote URL of the PDF to display. */\n source: string;\n /** 0-based page number to display. Can be used to restore scroll position on orientation change. */\n page?: number;\n /** Background colour shown behind the PDF pages. */\n backgroundColor?: string;\n /** Serialised {@link AnnotationsData} JSON string to load when the document opens. */\n annotations?: string;\n /** Active annotation tool. Defaults to `'none'` (view-only). */\n annotationMode?: AnnotationMode;\n /** Colour applied to new annotations, as a CSS colour string (e.g. `'#FF0000'`). */\n annotationColor?: string;\n /** Stroke width in points applied to new ink annotations. */\n annotationLineWidth?: number;\n /** Fired when the visible page changes. */\n onPageChanged?: (event: { nativeEvent: { page: number; pageCount: number } }) => void;\n /** Fired once the document has finished loading. */\n onLoadComplete?: (event: { nativeEvent: { pageCount: number } }) => void;\n /** Fired when the document fails to load. */\n onError?: (event: { nativeEvent: { message: string } }) => void;\n /** Fired after annotations are created or edited. `annotations` is a serialised {@link AnnotationsData} JSON string. */\n onAnnotationsChanged?: (event: { nativeEvent: { annotations: string } }) => void;\n style?: StyleProp<ViewStyle>;\n};\n"]}
1
+ {"version":3,"file":"ExpoPdfMarkup.types.js","sourceRoot":"","sources":["../src/ExpoPdfMarkup.types.ts"],"names":[],"mappings":"","sourcesContent":["import type { StyleProp, ViewStyle } from 'react-native';\n\nexport type AnnotationPoint = { x: number; y: number };\n\nexport type AnnotationBounds = { x: number; y: number; width: number; height: number };\n\nexport type InkAnnotation = {\n id: string;\n type: 'ink';\n page: number;\n color: string;\n lineWidth: number;\n paths: AnnotationPoint[][];\n createdAt?: number;\n};\n\nexport type HighlightAnnotation = {\n id: string;\n type: 'highlight';\n page: number;\n color: string;\n alpha?: number;\n bounds: AnnotationBounds;\n createdAt?: number;\n};\n\nexport type UnderlineAnnotation = {\n id: string;\n type: 'underline';\n page: number;\n color: string;\n bounds: AnnotationBounds;\n createdAt?: number;\n};\n\nexport type TextAnnotation = {\n id: string;\n type: 'text' | 'freeText';\n page: number;\n color: string;\n bounds: AnnotationBounds;\n contents?: string;\n fontSize?: number;\n createdAt?: number;\n};\n\nexport type Annotation = InkAnnotation | HighlightAnnotation | UnderlineAnnotation | TextAnnotation;\n\nexport type AnnotationsData = {\n version: 1;\n annotations: Annotation[];\n};\n\nexport type AnnotationMode = 'none' | 'ink' | 'highlight' | 'underline' | 'text' | 'eraser';\n\nexport type ExpoPdfMarkupViewProps = {\n /** Absolute local file path of the PDF to display. */\n source: string;\n /** 0-based page number to display. Can be used to restore scroll position on orientation change. */\n page?: number;\n /** Background colour shown behind the PDF pages. */\n backgroundColor?: string;\n /** Serialised {@link AnnotationsData} JSON string to load when the document opens. */\n annotations?: string;\n /** Active annotation tool. Defaults to `'none'` (view-only). */\n annotationMode?: AnnotationMode;\n /** Colour applied to new annotations, as a CSS colour string (e.g. `'#FF0000'`). */\n annotationColor?: string;\n /** Stroke width in points applied to new ink annotations. */\n annotationLineWidth?: number;\n /** Fired when the visible page changes. */\n onPageChanged?: (event: { nativeEvent: { page: number; pageCount: number } }) => void;\n /** Fired once the document has finished loading. */\n onLoadComplete?: (event: { nativeEvent: { pageCount: number } }) => void;\n /** Fired when the document fails to load. */\n onError?: (event: { nativeEvent: { message: string } }) => void;\n /** Fired after annotations are created or edited. `annotations` is a serialised {@link AnnotationsData} JSON string. */\n onAnnotationsChanged?: (event: { nativeEvent: { annotations: string } }) => void;\n style?: StyleProp<ViewStyle>;\n};\n"]}
@@ -1,4 +1,6 @@
1
1
  import * as React from 'react';
2
- import { ExpoPdfMarkupViewProps } from './ExpoPdfMarkup.types';
2
+ import type { ExpoPdfMarkupViewProps } from './ExpoPdfMarkup.types';
3
+ /** Allow consumers to override the pdfjs worker URL before mounting the view. */
4
+ export declare function setPdfJsWorkerSrc(url: string): void;
3
5
  export default function ExpoPdfMarkupView(props: ExpoPdfMarkupViewProps): React.JSX.Element;
4
6
  //# sourceMappingURL=ExpoPdfMarkupView.web.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ExpoPdfMarkupView.web.d.ts","sourceRoot":"","sources":["../src/ExpoPdfMarkupView.web.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAG/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAE/D,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,KAAK,EAAE,sBAAsB,qBAMtE"}
1
+ {"version":3,"file":"ExpoPdfMarkupView.web.d.ts","sourceRoot":"","sources":["../src/ExpoPdfMarkupView.web.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,KAAK,EAIV,sBAAsB,EACvB,MAAM,uBAAuB,CAAC;AAmB/B,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEnD;AAsQD,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,KAAK,EAAE,sBAAsB,qBAiOtE"}
@@ -1,8 +1,414 @@
1
+ import * as pdfjs from 'pdfjs-dist';
1
2
  import * as React from 'react';
2
- import { Text, View } from 'react-native';
3
+ import { canvasRectToPdfBounds, canvasToPdf, drawAnnotationsOnCanvas, hitTestAnnotation, newAnnotationId, parseAnnotations, serializeAnnotations, } from './web/annotationUtils';
4
+ // Configure pdfjs worker once at module level (consumers can override before mounting)
5
+ if (!pdfjs.GlobalWorkerOptions.workerSrc) {
6
+ // Default: served from public/ by withPdfMarkup() in metro.js.
7
+ // Override with setPdfJsWorkerSrc() if using a different bundler or CDN.
8
+ pdfjs.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs';
9
+ }
10
+ /** Allow consumers to override the pdfjs worker URL before mounting the view. */
11
+ export function setPdfJsWorkerSrc(url) {
12
+ pdfjs.GlobalWorkerOptions.workerSrc = url;
13
+ }
14
+ function PageView({ doc, pageIndex, meta, annotations, annotationMode, annotationColor, annotationLineWidth, onAnnotationAdded, onAnnotationRemoved, onTextInputRequested, containerRef, }) {
15
+ const pdfCanvasRef = React.useRef(null);
16
+ const annotCanvasRef = React.useRef(null);
17
+ const pageRef = React.useRef(null);
18
+ const renderTaskRef = React.useRef(null);
19
+ const pointerDownRef = React.useRef(false);
20
+ const inkPointsRef = React.useRef([]);
21
+ const dragStartRef = React.useRef(null);
22
+ const dragCurrentRef = React.useRef(null);
23
+ const dpr = typeof window !== 'undefined' ? window.devicePixelRatio ?? 1 : 1;
24
+ const cssWidth = meta.canvasWidth / dpr;
25
+ const cssHeight = meta.canvasHeight / dpr;
26
+ // Render PDF page onto pdfCanvas
27
+ React.useEffect(() => {
28
+ let cancelled = false;
29
+ async function render() {
30
+ if (!pdfCanvasRef.current)
31
+ return;
32
+ renderTaskRef.current?.cancel();
33
+ renderTaskRef.current = null;
34
+ const page = await doc.getPage(pageIndex + 1);
35
+ if (cancelled) {
36
+ page.cleanup();
37
+ return;
38
+ }
39
+ pageRef.current = page;
40
+ const canvas = pdfCanvasRef.current;
41
+ if (!canvas)
42
+ return;
43
+ canvas.width = meta.canvasWidth;
44
+ canvas.height = meta.canvasHeight;
45
+ const ctx = canvas.getContext('2d');
46
+ if (!ctx)
47
+ return;
48
+ const viewport = page.getViewport({ scale: meta.scale * dpr });
49
+ const task = page.render({ canvasContext: ctx, viewport });
50
+ renderTaskRef.current = task;
51
+ try {
52
+ await task.promise;
53
+ }
54
+ catch {
55
+ // Render cancelled — ignore
56
+ }
57
+ }
58
+ render();
59
+ return () => {
60
+ cancelled = true;
61
+ renderTaskRef.current?.cancel();
62
+ };
63
+ }, [doc, pageIndex, meta, dpr]);
64
+ // Draw annotations on annotCanvas
65
+ const redrawAnnotations = React.useCallback((liveInkPoints, dragRect) => {
66
+ const canvas = annotCanvasRef.current;
67
+ if (!canvas)
68
+ return;
69
+ canvas.width = meta.canvasWidth;
70
+ canvas.height = meta.canvasHeight;
71
+ const ctx = canvas.getContext('2d');
72
+ if (!ctx)
73
+ return;
74
+ ctx.scale(dpr, dpr);
75
+ drawAnnotationsOnCanvas(ctx, annotations, pageIndex, meta);
76
+ // Live ink preview
77
+ if (liveInkPoints && liveInkPoints.length > 1) {
78
+ ctx.save();
79
+ ctx.strokeStyle = annotationColor;
80
+ ctx.lineWidth = annotationLineWidth * meta.scale;
81
+ ctx.lineCap = 'round';
82
+ ctx.lineJoin = 'round';
83
+ ctx.beginPath();
84
+ for (let i = 0; i < liveInkPoints.length; i++) {
85
+ const pt = liveInkPoints[i];
86
+ if (i === 0)
87
+ ctx.moveTo(pt.x, pt.y);
88
+ else
89
+ ctx.lineTo(pt.x, pt.y);
90
+ }
91
+ ctx.stroke();
92
+ ctx.restore();
93
+ }
94
+ // Live drag rect preview (highlight/underline)
95
+ if (dragRect) {
96
+ ctx.save();
97
+ ctx.strokeStyle = annotationColor;
98
+ ctx.lineWidth = 1;
99
+ ctx.setLineDash([4, 4]);
100
+ ctx.strokeRect(dragRect.x, dragRect.y, dragRect.width, dragRect.height);
101
+ ctx.restore();
102
+ }
103
+ }, [annotations, pageIndex, meta, dpr, annotationColor, annotationLineWidth]);
104
+ React.useEffect(() => {
105
+ redrawAnnotations();
106
+ }, [redrawAnnotations]);
107
+ function getCanvasPoint(e) {
108
+ const rect = e.currentTarget.getBoundingClientRect();
109
+ return { x: e.clientX - rect.left, y: e.clientY - rect.top };
110
+ }
111
+ function handlePointerDown(e) {
112
+ if (annotationMode === 'none')
113
+ return;
114
+ e.currentTarget.setPointerCapture(e.pointerId);
115
+ const pt = getCanvasPoint(e);
116
+ pointerDownRef.current = true;
117
+ if (annotationMode === 'ink') {
118
+ inkPointsRef.current = [pt];
119
+ }
120
+ else if (annotationMode === 'highlight' || annotationMode === 'underline') {
121
+ dragStartRef.current = pt;
122
+ dragCurrentRef.current = pt;
123
+ }
124
+ }
125
+ function handlePointerMove(e) {
126
+ if (!pointerDownRef.current)
127
+ return;
128
+ const pt = getCanvasPoint(e);
129
+ if (annotationMode === 'ink') {
130
+ inkPointsRef.current.push(pt);
131
+ redrawAnnotations(inkPointsRef.current);
132
+ }
133
+ else if (annotationMode === 'highlight' || annotationMode === 'underline') {
134
+ dragCurrentRef.current = pt;
135
+ const start = dragStartRef.current;
136
+ const minX = Math.min(start.x, pt.x);
137
+ const minY = Math.min(start.y, pt.y);
138
+ const w = Math.abs(pt.x - start.x);
139
+ const h = Math.abs(pt.y - start.y);
140
+ redrawAnnotations(undefined, new DOMRect(minX, minY, w, h));
141
+ }
142
+ }
143
+ function handlePointerUp(e) {
144
+ if (!pointerDownRef.current && annotationMode !== 'text' && annotationMode !== 'eraser')
145
+ return;
146
+ pointerDownRef.current = false;
147
+ const pt = getCanvasPoint(e);
148
+ const { scale, pdfHeight } = meta;
149
+ if (annotationMode === 'ink') {
150
+ const cssPoints = inkPointsRef.current;
151
+ inkPointsRef.current = [];
152
+ if (cssPoints.length === 0)
153
+ return;
154
+ const pdfPoints = cssPoints.map((p) => canvasToPdf(p.x, p.y, scale, pdfHeight));
155
+ onAnnotationAdded({
156
+ id: newAnnotationId(),
157
+ type: 'ink',
158
+ page: pageIndex,
159
+ color: annotationColor,
160
+ lineWidth: annotationLineWidth,
161
+ paths: [pdfPoints],
162
+ createdAt: Date.now(),
163
+ });
164
+ }
165
+ else if (annotationMode === 'highlight' || annotationMode === 'underline') {
166
+ const start = dragStartRef.current;
167
+ dragStartRef.current = null;
168
+ dragCurrentRef.current = null;
169
+ if (!start)
170
+ return;
171
+ const minX = Math.min(start.x, pt.x);
172
+ const minY = Math.min(start.y, pt.y);
173
+ const maxX = Math.max(start.x, pt.x);
174
+ const maxY = Math.max(start.y, pt.y);
175
+ if (maxX - minX < 2 || maxY - minY < 2)
176
+ return;
177
+ const bounds = canvasRectToPdfBounds(minX, minY, maxX, maxY, scale, pdfHeight);
178
+ if (annotationMode === 'highlight') {
179
+ onAnnotationAdded({
180
+ id: newAnnotationId(),
181
+ type: 'highlight',
182
+ page: pageIndex,
183
+ color: annotationColor,
184
+ alpha: 0.5,
185
+ bounds,
186
+ createdAt: Date.now(),
187
+ });
188
+ }
189
+ else {
190
+ onAnnotationAdded({
191
+ id: newAnnotationId(),
192
+ type: 'underline',
193
+ page: pageIndex,
194
+ color: annotationColor,
195
+ bounds,
196
+ createdAt: Date.now(),
197
+ });
198
+ }
199
+ }
200
+ else if (annotationMode === 'text') {
201
+ const pdfPoint = canvasToPdf(pt.x, pt.y, scale, pdfHeight);
202
+ onTextInputRequested(pageIndex, pdfPoint);
203
+ }
204
+ else if (annotationMode === 'eraser') {
205
+ const pdfPoint = canvasToPdf(pt.x, pt.y, scale, pdfHeight);
206
+ const hit = hitTestAnnotation(pdfPoint, annotations, pageIndex);
207
+ if (hit)
208
+ onAnnotationRemoved(hit.id);
209
+ }
210
+ }
211
+ const pointerEvents = annotationMode === 'none' ? 'none' : 'auto';
212
+ return (<div ref={containerRef} style={{ position: 'relative', width: cssWidth, height: cssHeight, margin: '0 auto' }}>
213
+ <canvas ref={pdfCanvasRef} style={{
214
+ position: 'absolute',
215
+ top: 0,
216
+ left: 0,
217
+ width: cssWidth,
218
+ height: cssHeight,
219
+ pointerEvents: 'none',
220
+ }}/>
221
+ <canvas ref={annotCanvasRef} style={{
222
+ position: 'absolute',
223
+ top: 0,
224
+ left: 0,
225
+ width: cssWidth,
226
+ height: cssHeight,
227
+ cursor: 'crosshair',
228
+ pointerEvents,
229
+ }} onPointerDown={handlePointerDown} onPointerMove={handlePointerMove} onPointerUp={handlePointerUp}/>
230
+ </div>);
231
+ }
232
+ // ---------------------------------------------------------------------------
233
+ // Main component
234
+ // ---------------------------------------------------------------------------
3
235
  export default function ExpoPdfMarkupView(props) {
4
- return (<View style={[{ flex: 1, alignItems: 'center', justifyContent: 'center' }, props.style]}>
5
- <Text>PDF viewing is not yet supported on web.</Text>
6
- </View>);
236
+ const { source, page: propPage, backgroundColor = '#f0f0f0', annotations: annotationsProp, annotationMode = 'none', annotationColor = '#FF0000', annotationLineWidth = 2, onPageChanged, onLoadComplete, onError, onAnnotationsChanged, style, } = props;
237
+ const scrollContainerRef = React.useRef(null);
238
+ const [containerWidth, setContainerWidth] = React.useState(0);
239
+ const [doc, setDoc] = React.useState(null);
240
+ const [pageMetas, setPageMetas] = React.useState([]);
241
+ const [annotations, setAnnotations] = React.useState([]);
242
+ const lastAnnotationsJsonRef = React.useRef(undefined);
243
+ const pageContainerRefs = React.useRef([]);
244
+ const docRef = React.useRef(null);
245
+ const loadingSourceRef = React.useRef(null);
246
+ // ResizeObserver → containerWidth
247
+ React.useEffect(() => {
248
+ const el = scrollContainerRef.current;
249
+ if (!el)
250
+ return;
251
+ const ro = new ResizeObserver((entries) => {
252
+ const width = entries[0]?.contentRect.width ?? 0;
253
+ setContainerWidth(width);
254
+ });
255
+ ro.observe(el);
256
+ return () => ro.disconnect();
257
+ }, []);
258
+ // Load PDF when source or containerWidth changes
259
+ React.useEffect(() => {
260
+ if (!source || containerWidth <= 0)
261
+ return;
262
+ let cancelled = false;
263
+ loadingSourceRef.current = source;
264
+ async function load() {
265
+ try {
266
+ const task = pdfjs.getDocument(source);
267
+ const loadedDoc = await task.promise;
268
+ if (cancelled || loadingSourceRef.current !== source) {
269
+ loadedDoc.destroy();
270
+ return;
271
+ }
272
+ const metas = [];
273
+ const dpr = window.devicePixelRatio ?? 1;
274
+ for (let i = 1; i <= loadedDoc.numPages; i++) {
275
+ const pg = await loadedDoc.getPage(i);
276
+ if (cancelled) {
277
+ pg.cleanup();
278
+ loadedDoc.destroy();
279
+ return;
280
+ }
281
+ const viewport = pg.getViewport({ scale: 1 });
282
+ const scale = containerWidth / viewport.width;
283
+ const cssHeight = viewport.height * scale;
284
+ metas.push({
285
+ pdfWidth: viewport.width,
286
+ pdfHeight: viewport.height,
287
+ scale,
288
+ canvasWidth: Math.round(containerWidth * dpr),
289
+ canvasHeight: Math.round(cssHeight * dpr),
290
+ });
291
+ pg.cleanup();
292
+ }
293
+ docRef.current?.destroy();
294
+ docRef.current = loadedDoc;
295
+ setDoc(loadedDoc);
296
+ setPageMetas(metas);
297
+ pageContainerRefs.current = new Array(loadedDoc.numPages).fill(null);
298
+ onLoadComplete?.({ nativeEvent: { pageCount: loadedDoc.numPages } });
299
+ }
300
+ catch (err) {
301
+ if (!cancelled) {
302
+ onError?.({
303
+ nativeEvent: { message: err instanceof Error ? err.message : String(err) },
304
+ });
305
+ }
306
+ }
307
+ }
308
+ load();
309
+ return () => {
310
+ cancelled = true;
311
+ };
312
+ }, [source, containerWidth]); // intentionally omit callbacks — they should not re-trigger a PDF load
313
+ // Sync annotations prop → state (guard round-trips)
314
+ React.useEffect(() => {
315
+ if (annotationsProp === lastAnnotationsJsonRef.current)
316
+ return;
317
+ lastAnnotationsJsonRef.current = annotationsProp;
318
+ const parsed = parseAnnotations(annotationsProp);
319
+ setAnnotations(parsed.annotations);
320
+ }, [annotationsProp]);
321
+ // Scroll to propPage
322
+ React.useEffect(() => {
323
+ if (propPage == null || !doc)
324
+ return;
325
+ const el = pageContainerRefs.current[propPage];
326
+ el?.scrollIntoView({ behavior: 'instant' });
327
+ }, [propPage, doc]);
328
+ // IntersectionObserver → onPageChanged
329
+ React.useEffect(() => {
330
+ if (!doc || pageMetas.length === 0)
331
+ return;
332
+ const els = pageContainerRefs.current.filter(Boolean);
333
+ if (els.length === 0)
334
+ return;
335
+ let lastReported = -1;
336
+ const io = new IntersectionObserver((entries) => {
337
+ let topPage = -1;
338
+ let topY = Infinity;
339
+ for (const entry of entries) {
340
+ if (entry.isIntersecting) {
341
+ const idx = els.indexOf(entry.target);
342
+ if (idx !== -1 && entry.boundingClientRect.top < topY) {
343
+ topY = entry.boundingClientRect.top;
344
+ topPage = idx;
345
+ }
346
+ }
347
+ }
348
+ if (topPage !== -1 && topPage !== lastReported) {
349
+ lastReported = topPage;
350
+ onPageChanged?.({ nativeEvent: { page: topPage, pageCount: doc.numPages } });
351
+ }
352
+ }, { root: scrollContainerRef.current, threshold: 0.1 });
353
+ for (const el of els)
354
+ io.observe(el);
355
+ return () => io.disconnect();
356
+ }, [doc, pageMetas, onPageChanged]);
357
+ const handleAnnotationAdded = React.useCallback((annotation) => {
358
+ setAnnotations((prev) => {
359
+ const next = [...prev, annotation];
360
+ const json = serializeAnnotations({ version: 1, annotations: next });
361
+ lastAnnotationsJsonRef.current = json;
362
+ onAnnotationsChanged?.({ nativeEvent: { annotations: json } });
363
+ return next;
364
+ });
365
+ }, [onAnnotationsChanged]);
366
+ const handleAnnotationRemoved = React.useCallback((id) => {
367
+ setAnnotations((prev) => {
368
+ const next = prev.filter((a) => a.id !== id);
369
+ const json = serializeAnnotations({ version: 1, annotations: next });
370
+ lastAnnotationsJsonRef.current = json;
371
+ onAnnotationsChanged?.({ nativeEvent: { annotations: json } });
372
+ return next;
373
+ });
374
+ }, [onAnnotationsChanged]);
375
+ const handleTextInputRequested = React.useCallback((pageIndex, pdfPoint) => {
376
+ const text = window.prompt('Enter annotation text:');
377
+ if (!text)
378
+ return;
379
+ const fontSize = 16;
380
+ const estimatedWidth = text.length * fontSize * 0.6;
381
+ const bounds = {
382
+ x: pdfPoint.x,
383
+ y: pdfPoint.y,
384
+ width: estimatedWidth,
385
+ height: fontSize * 1.5,
386
+ };
387
+ handleAnnotationAdded({
388
+ id: newAnnotationId(),
389
+ type: 'text',
390
+ page: pageIndex,
391
+ color: annotationColor,
392
+ bounds,
393
+ contents: text,
394
+ fontSize,
395
+ createdAt: Date.now(),
396
+ });
397
+ }, [annotationColor, handleAnnotationAdded]);
398
+ const styleObj = style;
399
+ return (<div ref={scrollContainerRef} style={{
400
+ overflowY: 'scroll',
401
+ backgroundColor,
402
+ height: '100%',
403
+ ...styleObj,
404
+ }}>
405
+ {doc &&
406
+ pageMetas.map((meta, i) => (<React.Fragment key={i}>
407
+ <div style={{ height: 8 }} aria-hidden/>
408
+ <PageView doc={doc} pageIndex={i} meta={meta} annotations={annotations} annotationMode={annotationMode} annotationColor={annotationColor} annotationLineWidth={annotationLineWidth} onAnnotationAdded={handleAnnotationAdded} onAnnotationRemoved={handleAnnotationRemoved} onTextInputRequested={handleTextInputRequested} containerRef={(el) => {
409
+ pageContainerRefs.current[i] = el;
410
+ }}/>
411
+ </React.Fragment>))}
412
+ </div>);
7
413
  }
8
414
  //# sourceMappingURL=ExpoPdfMarkupView.web.js.map