@tobyt/expo-pdf-markup 1.2.0 → 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.
@@ -15,6 +15,35 @@ final class ExpoPdfMarkupViewTests: XCTestCase {
15
15
  super.tearDown()
16
16
  }
17
17
 
18
+ @MainActor func testCommittedInkOnCroppedPageStaysUnderInputAndSerializesVisibleCoordinates() throws {
19
+ let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 800, height: 1000))
20
+ let document = try XCTUnwrap(PDFDocument(data: renderer.pdfData { context in context.beginPage() }))
21
+ let page = try XCTUnwrap(document.page(at: 0))
22
+ page.setBounds(CGRect(x: 100, y: 80, width: 600, height: 840), for: .cropBox)
23
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 700))
24
+ let controller = UIViewController()
25
+ window.rootViewController = controller
26
+ window.makeKeyAndVisible()
27
+ view.frame = controller.view.bounds
28
+ controller.view.addSubview(view)
29
+ view.pdfView.document = document
30
+ view.layoutIfNeeded()
31
+ view.pdfView.layoutDocumentView()
32
+ view.setAnnotationMode("ink")
33
+ let overlay = try XCTUnwrap(view.inkOverlayView)
34
+ let first = view.convert(view.pdfView.convert(CGPoint(x: 180, y: 200), from: page), from: view.pdfView)
35
+ let last = view.convert(view.pdfView.convert(CGPoint(x: 280, y: 200), from: page), from: view.pdfView)
36
+ overlay.onBegan?(first)
37
+ overlay.onMoved?(last)
38
+ overlay.onEnded?()
39
+ let result = try XCTUnwrap(AnnotationSerializer.deserialize(from: view.serializeCurrentAnnotations()))
40
+ XCTAssertEqual(
41
+ result.annotations.first?.decodedPaths,
42
+ [[AnnotationPoint(x: 80, y: 120), AnnotationPoint(x: 180, y: 120)]]
43
+ )
44
+ window.isHidden = true
45
+ }
46
+
18
47
  // MARK: - Initial state
19
48
 
20
49
  func testInitialState() {
@@ -0,0 +1,411 @@
1
+ @testable internal import ExpoPdfMarkup
2
+ import PDFKit
3
+ import XCTest
4
+
5
+ final class RotatedAnnotationRenderingTests: XCTestCase {
6
+ var retainedDocuments: [PDFDocument] = []
7
+ @MainActor func testLiveTextCreationEditingAndFreshReloadPreserveHorizontalVisibleGeometry() throws {
8
+ for rotation in [0, 90, 180, 270] {
9
+ let document = try AnnotationTestFixture.document(rotation: rotation)
10
+ retainedDocuments.append(document)
11
+ let page = try XCTUnwrap(document.page(at: 0))
12
+ let window = try testWindow()
13
+ let host = UIView(frame: window.bounds)
14
+ window.addSubview(host)
15
+ let view = ExpoPdfMarkupView(appContext: nil)
16
+ // These tests drive module input and custom appearances; keep PDFKit's
17
+ // built-in text-selection gestures out of this rendering harness.
18
+ if #available(iOS 16.0, *) { view.pdfView.isInMarkupMode = true }
19
+ defer {
20
+ view.pdfView.document = nil
21
+ view.removeFromSuperview()
22
+ host.removeFromSuperview()
23
+ RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1))
24
+ retainedDocuments.removeAll()
25
+ }
26
+ view.frame = host.bounds
27
+ host.addSubview(view)
28
+ view.pdfView.document = document
29
+ view.layoutIfNeeded()
30
+ view.pdfView.layoutDocumentView()
31
+ view.useJsTextDialog = true
32
+ view.annotationColor = "#FF0000"
33
+ view.annotationFontFamily = "Helvetica"
34
+ view.setAnnotationMode("text")
35
+ let tap = RenderingTestTap()
36
+ let coordinates = AnnotationCoordinates(page: page)
37
+ tap.point = view.pdfView.convert(CGPoint(x: 80, y: 320).applying(coordinates.visibleToNative), from: page)
38
+ view.handleTextTap(tap)
39
+ view.provideTextInput(text: "MMMMMMMMMM")
40
+ let created = try model(view)
41
+ XCTAssertEqual(created.color, "#FF0000")
42
+ XCTAssertEqual(created.type, "freeText")
43
+ let initialBounds = try XCTUnwrap(created.bounds?.cgRect)
44
+ XCTAssertGreaterThan(initialBounds.width, initialBounds.height * 3, "rotation \(rotation)")
45
+ XCTAssertEqual(initialBounds.minX, 80, accuracy: 0.001)
46
+ try assertHorizontalText(page, near: CGRect(x: 80, y: 290, width: 200, height: 50))
47
+ try assertLiveHorizontalText(view, on: page, within: CGRect(x: 80, y: 290, width: 200, height: 50))
48
+ let createdJSON = view.serializeCurrentAnnotations()
49
+ view.loadAnnotations(from: nil)
50
+ view.loadAnnotations(from: createdJSON)
51
+ XCTAssertEqual(try model(view), created, "created text shifted on reload at rotation \(rotation)")
52
+
53
+ let annotation = try XCTUnwrap(page.annotations.first)
54
+ tap.point = view.pdfView.convert(CGPoint(x: annotation.bounds.midX, y: annotation.bounds.midY), from: page)
55
+ view.handleTextTap(tap)
56
+ view.provideTextInput(text: "MMMMMMMMMMMMMMMM")
57
+ let edited = try model(view)
58
+ XCTAssertEqual(edited.id, created.id)
59
+ XCTAssertEqual(edited.createdAt, created.createdAt)
60
+ XCTAssertEqual(edited.color, created.color)
61
+ XCTAssertEqual(edited.fontFamily, created.fontFamily)
62
+ XCTAssertEqual(edited.fontSize, created.fontSize)
63
+ XCTAssertEqual(edited.contents, "MMMMMMMMMMMMMMMM")
64
+ XCTAssertEqual(edited.bounds?.cgRect.minX, created.bounds?.cgRect.minX)
65
+ XCTAssertEqual(edited.bounds?.cgRect.maxY, created.bounds?.cgRect.maxY)
66
+ let editedJSON = view.serializeCurrentAnnotations()
67
+ let reopened = try AnnotationTestFixture.document(rotation: rotation)
68
+ retainedDocuments.append(reopened)
69
+ view.pdfView.document = reopened
70
+ view.loadAnnotations(from: nil)
71
+ view.loadAnnotations(from: editedJSON)
72
+ XCTAssertEqual(try model(view), edited, "edited text shifted on fresh reopen at rotation \(rotation)")
73
+ try assertHorizontalText(XCTUnwrap(reopened.page(at: 0)), near: CGRect(x: 80, y: 290, width: 300, height: 50))
74
+ view.layoutIfNeeded()
75
+ try assertLiveHorizontalText(view, on: XCTUnwrap(reopened.page(at: 0)),
76
+ within: CGRect(x: 80, y: 290, width: 300, height: 50))
77
+ let attachment = try XCTAttachment(image: UIImage(cgImage: snapshot(view)))
78
+ attachment.name = "Live text rotation \(rotation) after fresh reopen"
79
+ attachment.lifetime = .keepAlways
80
+ add(attachment)
81
+ }
82
+ }
83
+
84
+ @MainActor func testLiveAndThumbnailStampGlyphsStayAtVisibleBoundsForEveryRotation() throws {
85
+ for rotation in [0, 90, 180, 270] {
86
+ let document = try AnnotationTestFixture.document(rotation: rotation)
87
+ retainedDocuments.append(document)
88
+ let page = try XCTUnwrap(document.page(at: 0))
89
+ let coordinates = AnnotationCoordinates(page: page)
90
+ let window = try testWindow()
91
+ let host = UIView(frame: window.bounds)
92
+ window.addSubview(host)
93
+ let view = ExpoPdfMarkupView(appContext: nil)
94
+ // These tests drive module input and custom appearances; keep PDFKit's
95
+ // built-in text-selection gestures out of this rendering harness.
96
+ if #available(iOS 16.0, *) { view.pdfView.isInMarkupMode = true }
97
+ defer {
98
+ view.pdfView.document = nil
99
+ view.removeFromSuperview()
100
+ host.removeFromSuperview()
101
+ RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1))
102
+ retainedDocuments.removeAll()
103
+ }
104
+ view.frame = host.bounds
105
+ host.addSubview(view)
106
+ view.pdfView.document = document
107
+ view.layoutIfNeeded()
108
+ view.pdfView.layoutDocumentView()
109
+ view.annotationColor = "#FF0000"
110
+ view.setAnnotationMode("stamp")
111
+ let beforeThumbnail = try AnnotationTestFixture.thumbnail(page)
112
+ let scaledSize = CGSize(width: coordinates.visibleBounds.width / 2, height: coordinates.visibleBounds.height / 2)
113
+ let beforeScaled = try XCTUnwrap(page.thumbnail(of: scaledSize, for: .cropBox).cgImage)
114
+ let beforeLive = try snapshot(view)
115
+ let positions = [20, 270, 530]
116
+ for (index, glyph) in ["♫", "★", "🎵"].enumerated() {
117
+ view.stampText = glyph
118
+ let tap = RenderingTestTap()
119
+ tap.point = view.pdfView.convert(
120
+ CGPoint(x: positions[index] + 24, y: 84).applying(coordinates.visibleToNative), from: page
121
+ )
122
+ view.handleStampTap(tap)
123
+ }
124
+ let original = view.serializeCurrentAnnotations()
125
+ for pass in 0 ..< 2 {
126
+ let afterThumbnail = try AnnotationTestFixture.thumbnail(page)
127
+ let afterScaled = try XCTUnwrap(page.thumbnail(of: scaledSize, for: .cropBox).cgImage)
128
+ let afterLive = try snapshot(view)
129
+ for (index, x) in positions.enumerated() {
130
+ let visible = CGRect(x: x, y: 60, width: 48, height: 48)
131
+ let thumbnailRegion = CGRect(x: x, y: afterThumbnail.height - 108, width: 48, height: 48)
132
+ XCTAssertGreaterThan(try changedPixels(beforeThumbnail, afterThumbnail, within: thumbnailRegion), 30,
133
+ "thumbnail glyph \(index), rotation \(rotation), pass \(pass)")
134
+ let scale = CGFloat(afterScaled.width) / coordinates.visibleBounds.width
135
+ let scaledRegion = CGRect(x: visible.minX * scale,
136
+ y: CGFloat(afterScaled.height) - visible.maxY * scale,
137
+ width: visible.width * scale, height: visible.height * scale)
138
+ XCTAssertGreaterThan(try changedPixels(beforeScaled, afterScaled, within: scaledRegion), 8,
139
+ "scaled thumbnail glyph \(index), rotation \(rotation), pass \(pass)")
140
+ let native = visible.applying(coordinates.visibleToNative)
141
+ let liveRegion = view.convert(view.pdfView.convert(native, from: page), from: view.pdfView)
142
+ XCTAssertGreaterThan(try changedPixels(beforeLive, afterLive, within: liveRegion), 8,
143
+ "live glyph \(index), rotation \(rotation), pass \(pass)")
144
+ }
145
+ let attachment = XCTAttachment(image: UIImage(cgImage: afterLive))
146
+ attachment.name = "Stamp glyphs rotation \(rotation) pass \(pass)"
147
+ attachment.lifetime = .keepAlways
148
+ add(attachment)
149
+ view.loadAnnotations(from: nil)
150
+ view.loadAnnotations(from: original)
151
+ let reloaded = try XCTUnwrap(AnnotationSerializer.deserialize(from: view.serializeCurrentAnnotations()))
152
+ XCTAssertEqual(reloaded, AnnotationSerializer.deserialize(from: original))
153
+ }
154
+ }
155
+ }
156
+
157
+ @MainActor func testUnderlineDrawsTheVisibleLowerEdgeInLiveViewAndThumbnailAtEveryRotation() throws {
158
+ for rotation in [0, 90, 180, 270] {
159
+ let document = try AnnotationTestFixture.document(rotation: rotation)
160
+ retainedDocuments.append(document)
161
+ let page = try XCTUnwrap(document.page(at: 0))
162
+ let coordinates = AnnotationCoordinates(page: page)
163
+ let window = try testWindow()
164
+ let host = UIView(frame: window.bounds)
165
+ window.addSubview(host)
166
+ let view = ExpoPdfMarkupView(appContext: nil)
167
+ // These tests drive module input and custom appearances; keep PDFKit's
168
+ // built-in text-selection gestures out of this rendering harness.
169
+ if #available(iOS 16.0, *) { view.pdfView.isInMarkupMode = true }
170
+ defer {
171
+ view.pdfView.document = nil
172
+ view.removeFromSuperview()
173
+ host.removeFromSuperview()
174
+ RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.1))
175
+ retainedDocuments.removeAll()
176
+ }
177
+ view.frame = host.bounds
178
+ host.addSubview(view)
179
+ view.pdfView.document = document
180
+ view.layoutIfNeeded()
181
+ view.pdfView.layoutDocumentView()
182
+ let beforeThumbnail = try AnnotationTestFixture.thumbnail(page)
183
+ let scaledSize = CGSize(width: coordinates.visibleBounds.width / 2, height: coordinates.visibleBounds.height / 2)
184
+ let beforeScaled = try XCTUnwrap(page.thumbnail(of: scaledSize, for: .cropBox).cgImage)
185
+ let beforeLive = try snapshot(view)
186
+ let model = AnnotationModel(id: "underline", type: "underline", page: 0, color: "#FF0000",
187
+ bounds: AnnotationBounds(x: 80, y: 300, width: 160, height: 24), createdAt: 123)
188
+ try page.addAnnotation(XCTUnwrap(AnnotationSerializer.toPDFAnnotation(model,
189
+ pageBounds: page.bounds(for: .cropBox),
190
+ pageRotation: rotation)))
191
+ let afterThumbnail = try AnnotationTestFixture.thumbnail(page)
192
+ let afterScaled = try XCTUnwrap(page.thumbnail(of: scaledSize, for: .cropBox).cgImage)
193
+ let scale = CGFloat(afterScaled.width) / coordinates.visibleBounds.width
194
+ let scaledEdge = CGRect(x: 80 * scale, y: CGFloat(afterScaled.height) - 303 * scale,
195
+ width: 160 * scale, height: 6 * scale)
196
+ XCTAssertGreaterThan(try changedPixels(beforeScaled, afterScaled, within: scaledEdge), 30)
197
+ let afterLive = try snapshot(view)
198
+ let edge = CGRect(x: 80, y: 297, width: 160, height: 6)
199
+ let thumbnailEdge = CGRect(x: 80, y: afterThumbnail.height - 303, width: 160, height: 6)
200
+ XCTAssertGreaterThan(try changedPixels(beforeThumbnail, afterThumbnail, within: thumbnailEdge), 100,
201
+ "thumbnail lower edge, rotation \(rotation)")
202
+ let liveEdge = view.convert(
203
+ view.pdfView.convert(edge.applying(coordinates.visibleToNative), from: page),
204
+ from: view.pdfView
205
+ )
206
+ XCTAssertGreaterThan(try changedPixels(beforeLive, afterLive, within: liveEdge), 30,
207
+ "live lower edge, rotation \(rotation)")
208
+ XCTAssertEqual(AnnotationSerializer.toModel(from: page.annotations[0], page: 0), model)
209
+ let saved = view.serializeCurrentAnnotations()
210
+ view.loadAnnotations(from: nil)
211
+ view.loadAnnotations(from: saved)
212
+ XCTAssertEqual(try self.model(view), model)
213
+ view.setAnnotationMode("move")
214
+ let pan = RenderingTestPan()
215
+ pan.point = view.pdfView.convert(CGPoint(x: 160, y: 310).applying(coordinates.visibleToNative), from: page)
216
+ pan.suppliedState = .began
217
+ view.handleMovePan(pan)
218
+ pan.point = view.pdfView.convert(CGPoint(x: 180, y: 340).applying(coordinates.visibleToNative), from: page)
219
+ pan.suppliedState = .changed
220
+ view.handleMovePan(pan)
221
+ pan.suppliedState = .ended
222
+ view.handleMovePan(pan)
223
+ view.setAnnotationMode("none")
224
+ let moved = try self.model(view)
225
+ XCTAssertEqual(moved.type, "underline")
226
+ XCTAssertEqual(moved.id, model.id)
227
+ XCTAssertEqual(moved.createdAt, model.createdAt)
228
+ XCTAssertEqual(moved.color, model.color)
229
+ XCTAssertEqual(try XCTUnwrap(moved.bounds?.x), 100, accuracy: 0.001)
230
+ XCTAssertEqual(try XCTUnwrap(moved.bounds?.y), 330, accuracy: 0.001)
231
+ XCTAssertNotNil(view.hitTestAnnotation(
232
+ at: CGPoint(x: 180, y: 330).applying(coordinates.visibleToNative),
233
+ on: page
234
+ ))
235
+ let movedThumbnail = try AnnotationTestFixture.thumbnail(page)
236
+ XCTAssertGreaterThan(try changedPixels(
237
+ beforeThumbnail,
238
+ movedThumbnail,
239
+ within: CGRect(x: 100, y: movedThumbnail.height - 333, width: 160, height: 6)
240
+ ), 100)
241
+ let movedLive = try snapshot(view)
242
+ let movedEdge = CGRect(x: 100, y: 327, width: 160, height: 6)
243
+ let movedLiveEdge = view.convert(
244
+ view.pdfView.convert(movedEdge.applying(coordinates.visibleToNative), from: page),
245
+ from: view.pdfView
246
+ )
247
+ XCTAssertGreaterThan(try changedPixels(beforeLive, movedLive, within: movedLiveEdge), 30)
248
+ }
249
+ }
250
+
251
+ func testFullPageCustomAnnotationsKeepOrientationInScaledThumbnails() throws {
252
+ for type in ["underline", "stamp"] {
253
+ let document = try AnnotationTestFixture.document(rotation: 180)
254
+ let page = try XCTUnwrap(document.page(at: 0))
255
+ let sizes = [CGSize(width: 600, height: 840), CGSize(width: 300, height: 420)]
256
+ let baselines = try sizes.map { try XCTUnwrap(page.thumbnail(of: $0, for: .cropBox).cgImage) }
257
+ let model = AnnotationModel(id: type, type: type, page: 0, color: "#FF0000",
258
+ bounds: AnnotationBounds(x: 0, y: 0, width: 600, height: 840), createdAt: 123,
259
+ text: type == "stamp" ? "L" : nil)
260
+ try page.addAnnotation(XCTUnwrap(AnnotationSerializer.toPDFAnnotation(model,
261
+ pageBounds: page.bounds(for: .cropBox),
262
+ pageRotation: 180)))
263
+ XCTAssertEqual(AnnotationSerializer.toModel(from: page.annotations[0], page: 0), model)
264
+ for (index, size) in sizes.enumerated() {
265
+ let image = try XCTUnwrap(page.thumbnail(of: size, for: .cropBox).cgImage)
266
+ if type == "underline" {
267
+ let region = CGRect(x: 0, y: image.height - 3, width: image.width, height: 3)
268
+ XCTAssertGreaterThan(try changedPixels(baselines[index], image, within: region), 10,
269
+ "full-page underline must stay on the visible lower edge, render \(index)")
270
+ } else {
271
+ let glyph = try redBounds(image, within: CGRect(x: 0, y: 0, width: image.width, height: image.height))
272
+ XCTAssertFalse(glyph.isNull)
273
+ if !glyph.isNull {
274
+ let top = try redBounds(image, within: CGRect(x: glyph.minX, y: glyph.minY,
275
+ width: glyph.width, height: glyph.height * 0.2))
276
+ let bottom = try redBounds(image, within: CGRect(x: glyph.minX,
277
+ y: glyph.maxY - glyph.height * 0.2, width: glyph.width,
278
+ height: glyph.height * 0.2))
279
+ XCTAssertGreaterThan(bottom.width, top.width * 1.5, "L's wide foot belongs at the visible bottom")
280
+ }
281
+ }
282
+ }
283
+ }
284
+ }
285
+
286
+ @MainActor private func testWindow() throws -> UIWindow {
287
+ let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows)
288
+ return try XCTUnwrap(windows.first { !$0.isHidden && $0.windowLevel == .normal }
289
+ ?? windows.first { !$0.isHidden } ?? windows.first, "Native test host window must exist")
290
+ }
291
+
292
+ @MainActor private func snapshot(_ view: UIView) throws -> CGImage {
293
+ RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.2))
294
+ let format = UIGraphicsImageRendererFormat()
295
+ format.scale = 1
296
+ let image = UIGraphicsImageRenderer(size: view.bounds.size, format: format).image { _ in
297
+ view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
298
+ }
299
+ return try XCTUnwrap(image.cgImage)
300
+ }
301
+
302
+ private func changedPixels(_ before: CGImage, _ after: CGImage, within region: CGRect) throws -> Int {
303
+ let lhs = try pixelBytes(before)
304
+ let rhs = try pixelBytes(after)
305
+ XCTAssertEqual(before.width, after.width)
306
+ XCTAssertEqual(before.height, after.height)
307
+ let clipped = region.integral.intersection(CGRect(x: 0, y: 0, width: after.width, height: after.height))
308
+ guard !clipped.isNull else { return 0 }
309
+ var changed = 0
310
+ for y in Int(clipped.minY) ..< Int(clipped.maxY) {
311
+ for x in Int(clipped.minX) ..< Int(clipped.maxX) {
312
+ let offset = (y * after.width + x) * 4
313
+ if (0 ..< 3).contains(where: { abs(Int(lhs[offset + $0]) - Int(rhs[offset + $0])) > 40 }) { changed += 1 }
314
+ }
315
+ }
316
+ return changed
317
+ }
318
+
319
+ private func pixelBytes(_ image: CGImage) throws -> [UInt8] {
320
+ let context = try XCTUnwrap(CGContext(data: nil, width: image.width, height: image.height,
321
+ bitsPerComponent: 8, bytesPerRow: image.width * 4,
322
+ space: CGColorSpaceCreateDeviceRGB(),
323
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
324
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
325
+ let pixels = try XCTUnwrap(context.data).bindMemory(to: UInt8.self, capacity: image.width * image.height * 4)
326
+ return Array(UnsafeBufferPointer(start: pixels, count: image.width * image.height * 4))
327
+ }
328
+
329
+ @MainActor private func assertLiveHorizontalText(_ view: ExpoPdfMarkupView, on page: PDFPage,
330
+ within visibleRegion: CGRect, file: StaticString = #filePath,
331
+ line: UInt = #line) throws {
332
+ let nativeRegion = visibleRegion.applying(AnnotationCoordinates(page: page).visibleToNative)
333
+ let screenRegion = view.convert(view.pdfView.convert(nativeRegion, from: page), from: view.pdfView)
334
+ let image = try snapshot(view)
335
+ let painted = try redBounds(image, within: screenRegion)
336
+ XCTAssertFalse(painted.isNull, "text should paint at its live visible location", file: file, line: line)
337
+ if !painted.isNull {
338
+ XCTAssertGreaterThan(painted.width, painted.height * 3, file: file, line: line)
339
+ XCTAssertGreaterThan(painted.width, view.pdfView.scaleFactor * 100, file: file, line: line)
340
+ }
341
+ }
342
+
343
+ private func redBounds(_ image: CGImage, within region: CGRect) throws -> CGRect {
344
+ let pixels = try pixelBytes(image)
345
+ let clipped = region.integral.intersection(CGRect(x: 0, y: 0, width: image.width, height: image.height))
346
+ guard !clipped.isNull else { return .null }
347
+ var result = CGRect.null
348
+ for y in Int(clipped.minY) ..< Int(clipped.maxY) {
349
+ for x in Int(clipped.minX) ..< Int(clipped.maxX) {
350
+ let offset = (y * image.width + x) * 4
351
+ if pixels[offset] > 180, pixels[offset + 1] < 100, pixels[offset + 2] < 100 {
352
+ result = result.union(CGRect(x: x, y: y, width: 1, height: 1))
353
+ }
354
+ }
355
+ }
356
+ return result
357
+ }
358
+
359
+ private func model(_ view: ExpoPdfMarkupView) throws -> AnnotationModel {
360
+ try XCTUnwrap(AnnotationSerializer.deserialize(from: view.serializeCurrentAnnotations())?.annotations.first)
361
+ }
362
+
363
+ private func assertHorizontalText(
364
+ _ page: PDFPage,
365
+ near expected: CGRect,
366
+ file: StaticString = #filePath,
367
+ line: UInt = #line
368
+ ) throws {
369
+ let image = try AnnotationTestFixture.thumbnail(page)
370
+ let context = try XCTUnwrap(CGContext(data: nil, width: image.width, height: image.height,
371
+ bitsPerComponent: 8, bytesPerRow: image.width * 4,
372
+ space: CGColorSpaceCreateDeviceRGB(),
373
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
374
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
375
+ let pixels = try XCTUnwrap(context.data).bindMemory(to: UInt8.self, capacity: image.width * image.height * 4)
376
+ var painted = CGRect.null
377
+ for y in Int(expected.minY) ..< Int(expected.maxY) {
378
+ for x in Int(expected.minX) ..< Int(expected.maxX) {
379
+ let offset = ((image.height - y) * image.width + x) * 4
380
+ if pixels[offset] > 180, pixels[offset + 1] < 100, pixels[offset + 2] < 100 {
381
+ painted = painted.union(CGRect(x: x, y: y, width: 1, height: 1))
382
+ }
383
+ }
384
+ }
385
+ XCTAssertFalse(painted.isNull, "text should paint at the tapped visible location", file: file, line: line)
386
+ if !painted.isNull {
387
+ XCTAssertGreaterThan(painted.width, 100, file: file, line: line)
388
+ XCTAssertLessThan(painted.height, 30, file: file, line: line)
389
+ }
390
+ }
391
+ }
392
+
393
+ private final class RenderingTestTap: UITapGestureRecognizer {
394
+ var point: CGPoint = .zero
395
+ override func location(in _: UIView?) -> CGPoint {
396
+ point
397
+ }
398
+ }
399
+
400
+ private final class RenderingTestPan: UIPanGestureRecognizer {
401
+ var point: CGPoint = .zero
402
+ var suppliedState: UIGestureRecognizer.State = .possible
403
+ override var state: UIGestureRecognizer.State {
404
+ get { suppliedState }
405
+ set { suppliedState = newValue }
406
+ }
407
+
408
+ override func location(in _: UIView?) -> CGPoint {
409
+ point
410
+ }
411
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tobyt/expo-pdf-markup",
3
- "version": "1.2.0",
3
+ "version": "2.0.0",
4
4
  "description": "An Expo module for displaying and annotating PDFs",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",
@@ -1,7 +1,9 @@
1
1
  import type { StyleProp, ViewStyle } from 'react-native';
2
2
 
3
+ /** Zero-origin visible-page points after page rotation, in PDF points with y increasing upward. */
3
4
  export type AnnotationPoint = { x: number; y: number };
4
5
 
6
+ /** Visible-page rectangle; x/y locate its bottom-left corner. See docs/annotation-coordinates.md. */
5
7
  export type AnnotationBounds = { x: number; y: number; width: number; height: number };
6
8
 
7
9
  export type InkAnnotation = {
@@ -114,7 +116,11 @@ export type ExpoPdfMarkupViewProps = {
114
116
  backgroundColor?: string;
115
117
  /** Serialised {@link AnnotationsData} JSON string to load when the document opens. */
116
118
  annotations?: string;
117
- /** Active annotation tool. Defaults to `'none'` (view-only). */
119
+ /**
120
+ * Active annotation tool. Defaults to `'none'` (view-only).
121
+ * On iOS, highlight/underline use a one-finger area drag on scanned and text-bearing pages.
122
+ * Set `'none'` for touch navigation/zoom; `page` and book-mode hardware keys remain available.
123
+ */
118
124
  annotationMode?: AnnotationMode;
119
125
  /** Colour applied to new annotations, as a CSS colour string (e.g. `'#FF0000'`). */
120
126
  annotationColor?: string;
@@ -135,28 +135,35 @@ function PageView({
135
135
  React.useEffect(() => {
136
136
  let cancelled = false;
137
137
  async function render() {
138
- if (!pdfCanvasRef.current) return;
139
- renderTaskRef.current?.cancel();
140
- renderTaskRef.current = null;
141
- const page = await doc.getPage(pageIndex + 1);
142
- if (cancelled) {
143
- page.cleanup();
144
- return;
145
- }
146
- pageRef.current = page;
147
138
  const canvas = pdfCanvasRef.current;
148
139
  if (!canvas) return;
149
- canvas.width = meta.canvasWidth;
150
- canvas.height = meta.canvasHeight;
151
- const ctx = canvas.getContext('2d');
152
- if (!ctx) return;
153
- const viewport = page.getViewport({ scale: meta.scale * dpr });
154
- const task = page.render({ canvas: null, canvasContext: ctx, viewport });
155
- renderTaskRef.current = task;
140
+ canvas.dataset.pdfRenderState = 'pending';
141
+ renderTaskRef.current?.cancel();
142
+ renderTaskRef.current = null;
156
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;
157
160
  await task.promise;
158
- } catch {
159
- // 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
+ }
160
167
  }
161
168
  }
162
169
  render();
@@ -421,6 +428,8 @@ function PageView({
421
428
  >
422
429
  <canvas
423
430
  ref={pdfCanvasRef}
431
+ data-pdf-layer="pdf"
432
+ data-pdf-render-state="pending"
424
433
  style={{
425
434
  position: 'absolute',
426
435
  top: 0,
@@ -432,6 +441,7 @@ function PageView({
432
441
  />
433
442
  <canvas
434
443
  ref={annotCanvasRef}
444
+ data-pdf-layer="annotations"
435
445
  style={{
436
446
  position: 'absolute',
437
447
  top: 0,