@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
@@ -0,0 +1,337 @@
1
+ @testable internal import ExpoPdfMarkup
2
+ import PDFKit
3
+ import XCTest
4
+
5
+ /// Project-owned synthetic PDFs: a raster-only page with asymmetric colored anchors,
6
+ /// plus an optional text-bearing control. No third-party document content is used.
7
+ enum AnnotationTestFixture {
8
+ static let crop = CGRect(x: 100, y: 80, width: 600, height: 840)
9
+
10
+ static func document(crop: CGRect = crop, rotation: Int = 0, text: Bool = false) throws -> PDFDocument {
11
+ let media = CGRect(x: 0, y: 0, width: 800, height: 1000)
12
+ let raster = UIGraphicsImageRenderer(size: media.size).image { context in
13
+ UIColor.white.setFill()
14
+ context.fill(media)
15
+ UIColor.blue.setFill()
16
+ context.fill(CGRect(x: 150, y: 170, width: 30, height: 50))
17
+ UIColor.green.setFill()
18
+ context.fill(CGRect(x: 490, y: 650, width: 60, height: 20))
19
+ }
20
+ let data = UIGraphicsPDFRenderer(bounds: media).pdfData { context in
21
+ context.beginPage()
22
+ raster.draw(in: media)
23
+ if text { ("Selectable synthetic text" as NSString).draw(
24
+ at: CGPoint(x: 220, y: 330),
25
+ withAttributes: [.font: UIFont.systemFont(ofSize: 20)]
26
+ ) }
27
+ }
28
+ let document = try XCTUnwrap(PDFDocument(data: data))
29
+ let page = try XCTUnwrap(document.page(at: 0))
30
+ page.setBounds(crop, for: .cropBox)
31
+ page.rotation = rotation
32
+ return document
33
+ }
34
+
35
+ static func thumbnail(_ page: PDFPage) throws -> CGImage {
36
+ let box = page.bounds(for: .cropBox)
37
+ let size = page.rotation % 180 == 0 ? box.size : CGSize(width: box.height, height: box.width)
38
+ return try XCTUnwrap(page.thumbnail(of: size, for: .cropBox).cgImage)
39
+ }
40
+
41
+ static func assertRed(_ image: CGImage, x: Int, y: Int, file: StaticString = #filePath, line: UInt = #line) throws {
42
+ let context = try XCTUnwrap(CGContext(data: nil, width: image.width, height: image.height,
43
+ bitsPerComponent: 8, bytesPerRow: image.width * 4,
44
+ space: CGColorSpaceCreateDeviceRGB(),
45
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
46
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
47
+ let pixels = try XCTUnwrap(context.data).bindMemory(to: UInt8.self, capacity: image.width * image.height * 4)
48
+ let offset = ((image.height - y) * image.width + x) * 4
49
+ XCTAssertGreaterThan(pixels[offset], 200, file: file, line: line)
50
+ XCTAssertLessThan(pixels[offset + 1], 80, file: file, line: line)
51
+ XCTAssertLessThan(pixels[offset + 2], 80, file: file, line: line)
52
+ }
53
+ }
54
+
55
+ final class AnnotationCoordinateTests: XCTestCase {
56
+ func testRotatedTextBoundsDoNotGrowOnRepeatedRoundTrips() throws {
57
+ let document = try AnnotationTestFixture.document(rotation: 90)
58
+ let page = try XCTUnwrap(document.page(at: 0))
59
+ let expected = AnnotationModel(id: "rotated-text", type: "text", page: 0, color: "#FF0000",
60
+ bounds: AnnotationBounds(x: 80, y: 120, width: 240, height: 40),
61
+ contents: "Visible page note",
62
+ fontSize: 16, fontFamily: "Helvetica", createdAt: 123)
63
+ var model = expected
64
+ for _ in 0 ..< 3 {
65
+ let annotation = try XCTUnwrap(AnnotationSerializer.toPDFAnnotation(
66
+ model,
67
+ pageBounds: page.bounds(for: .cropBox),
68
+ pageRotation: page.rotation
69
+ ))
70
+ page.addAnnotation(annotation)
71
+ model = try XCTUnwrap(AnnotationSerializer.toModel(from: annotation, page: 0))
72
+ XCTAssertEqual(model, expected)
73
+ page.removeAnnotation(annotation)
74
+ }
75
+ }
76
+
77
+ @MainActor func testTextInputRequestReportsVisiblePagePoint() throws {
78
+ let document = try AnnotationTestFixture.document()
79
+ let page = try XCTUnwrap(document.page(at: 0))
80
+ let view = ExpoPdfMarkupView(appContext: nil)
81
+ view.frame = CGRect(x: 0, y: 0, width: 400, height: 700)
82
+ view.pdfView.document = document
83
+ view.layoutIfNeeded()
84
+ view.pdfView.layoutDocumentView()
85
+ view.useJsTextDialog = true
86
+ view.setAnnotationMode("text")
87
+ var requestedPoint: [String: CGFloat]?
88
+ view.onTextInputRequested.onEventSent = { payload in requestedPoint = payload["point"] as? [String: CGFloat] }
89
+ let tap = CoordinateTestTap()
90
+ tap.suppliedLocation = view.pdfView.convert(CGPoint(x: 180, y: 200), from: page)
91
+ view.handleTextTap(tap)
92
+ XCTAssertEqual(try XCTUnwrap(requestedPoint?["x"]), 80, accuracy: 0.001)
93
+ XCTAssertEqual(try XCTUnwrap(requestedPoint?["y"]), 120, accuracy: 0.001)
94
+ }
95
+
96
+ func testVisibleInkPlacementWithZeroOriginAndRightTopCrops() throws {
97
+ for crop in [
98
+ CGRect(x: 0, y: 0, width: 800, height: 1000),
99
+ CGRect(x: 0, y: 0, width: 600, height: 840),
100
+ AnnotationTestFixture.crop,
101
+ ] {
102
+ for rotation in [0, 90, 180, 270] {
103
+ let document = try AnnotationTestFixture.document(crop: crop, rotation: rotation)
104
+ let page = try XCTUnwrap(document.page(at: 0))
105
+ let model = AnnotationModel(id: "control", type: "ink", page: 0, color: "#FF0000", lineWidth: 8,
106
+ paths: [[["x": 80, "y": 120], ["x": 180, "y": 120]]], createdAt: 123)
107
+ try page.addAnnotation(XCTUnwrap(AnnotationSerializer.toPDFAnnotation(
108
+ model,
109
+ pageBounds: crop,
110
+ pageRotation: rotation
111
+ )))
112
+ try AnnotationTestFixture.assertRed(AnnotationTestFixture.thumbnail(page), x: 130, y: 120)
113
+ XCTAssertEqual(AnnotationSerializer.toModel(from: page.annotations[0], page: 0), model)
114
+ }
115
+ }
116
+ }
117
+
118
+ @MainActor func testMoveAndOutlineUseVisibleInkGeometryAfterZoomAndScroll() throws {
119
+ let document = try AnnotationTestFixture.document()
120
+ let page = try XCTUnwrap(document.page(at: 0))
121
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 700))
122
+ let controller = UIViewController()
123
+ window.rootViewController = controller
124
+ window.makeKeyAndVisible()
125
+ let view = ExpoPdfMarkupView(appContext: nil)
126
+ view.frame = controller.view.bounds
127
+ controller.view.addSubview(view)
128
+ view.pdfView.document = document
129
+ view.layoutIfNeeded()
130
+ view.pdfView.layoutDocumentView()
131
+ let model = AnnotationModel(id: "moving", type: "ink", page: 0, color: "#FF0000", lineWidth: 8,
132
+ paths: [[["x": 80, "y": 120], ["x": 180, "y": 120]]], createdAt: 123)
133
+ let json = try XCTUnwrap(AnnotationSerializer.serialize(AnnotationsData(annotations: [model])))
134
+ view.loadAnnotations(from: json)
135
+ view.pdfView.scaleFactor *= 1.5
136
+ view.pdfScrollView?.contentOffset = CGPoint(x: 20, y: 40)
137
+ view.setAnnotationMode("move")
138
+ let pan = CoordinateTestPan()
139
+ pan.suppliedLocation = view.pdfView.convert(CGPoint(x: 230, y: 200), from: page)
140
+ pan.suppliedState = .began
141
+ view.handleMovePan(pan)
142
+ pan.suppliedLocation = view.pdfView.convert(CGPoint(x: 250, y: 230), from: page)
143
+ pan.suppliedState = .changed
144
+ view.handleMovePan(pan)
145
+ pan.suppliedState = .ended
146
+ view.handleMovePan(pan)
147
+ let result = try XCTUnwrap(AnnotationSerializer.deserialize(from: view.serializeCurrentAnnotations())
148
+ .flatMap(\.annotations.first))
149
+ let stroke = try XCTUnwrap(result.decodedPaths.first)
150
+ XCTAssertEqual(result.id, "moving")
151
+ XCTAssertEqual(stroke[0].x, 100, accuracy: 0.001)
152
+ XCTAssertEqual(stroke[0].y, 150, accuracy: 0.001)
153
+ try AnnotationTestFixture.assertRed(AnnotationTestFixture.thumbnail(page), x: 150, y: 150)
154
+ XCTAssertNotNil(view.hitTestAnnotation(at: CGPoint(x: 250, y: 230), on: page))
155
+ XCTAssertNil(view.hitTestAnnotation(at: CGPoint(x: 150, y: 150), on: page))
156
+ let documentView = try XCTUnwrap(view.pdfView.documentView)
157
+ let expected = documentView.convert(
158
+ view.pdfView.convert(CGRect(x: 190, y: 220, width: 120, height: 20), from: page),
159
+ from: view.pdfView
160
+ )
161
+ let outline = try XCTUnwrap(view.editingOverlayLayer?.path).boundingBoxOfPath
162
+ XCTAssertEqual(outline.minX, expected.minX, accuracy: 0.01)
163
+ XCTAssertEqual(outline.minY, expected.minY, accuracy: 0.01)
164
+ XCTAssertEqual(outline.width, expected.width, accuracy: 0.01)
165
+ XCTAssertEqual(outline.height, expected.height, accuracy: 0.01)
166
+ window.isHidden = true
167
+ }
168
+
169
+ func testSharedV1AnnotationsRoundTripWithoutChangingVisiblePlacementOrStyle() throws {
170
+ let url = try XCTUnwrap(Bundle(for: type(of: self)).url(forResource: "annotations-v1", withExtension: "json"))
171
+ let fixture = try XCTUnwrap(AnnotationSerializer.deserialize(from: String(contentsOf: url, encoding: .utf8)))
172
+ let document = try AnnotationTestFixture.document()
173
+ let page = try XCTUnwrap(document.page(at: 0))
174
+ var models = fixture.annotations
175
+ for _ in 0 ..< 3 {
176
+ for annotation in page.annotations {
177
+ page.removeAnnotation(annotation)
178
+ }
179
+ for model in models {
180
+ try page.addAnnotation(XCTUnwrap(AnnotationSerializer.toPDFAnnotation(
181
+ model,
182
+ pageBounds: page.bounds(for: .cropBox)
183
+ )))
184
+ }
185
+ models = page.annotations.compactMap { AnnotationSerializer.toModel(from: $0, page: 0) }
186
+ XCTAssertEqual(models, fixture.annotations)
187
+ }
188
+ }
189
+
190
+ @MainActor func testStampsAreVisibleInLivePdfViewBeforeAndAfterReopen() throws {
191
+ let document = try AnnotationTestFixture.document()
192
+ let page = try XCTUnwrap(document.page(at: 0))
193
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 700))
194
+ let controller = UIViewController()
195
+ window.rootViewController = controller
196
+ window.makeKeyAndVisible()
197
+ let view = ExpoPdfMarkupView(appContext: nil)
198
+ view.frame = controller.view.bounds
199
+ controller.view.addSubview(view)
200
+ view.pdfView.document = document
201
+ view.layoutIfNeeded()
202
+ view.pdfView.layoutDocumentView()
203
+ for (index, glyph) in ["♫", "★", "🎵"].enumerated() {
204
+ let model = AnnotationModel(id: glyph, type: "stamp", page: 0, color: "#FF0000",
205
+ bounds: AnnotationBounds(x: CGFloat(20 + index * 240), y: 60, width: 48, height: 48),
206
+ text: glyph)
207
+ try page.addAnnotation(XCTUnwrap(AnnotationSerializer.toPDFAnnotation(
208
+ model,
209
+ pageBounds: page.bounds(for: .cropBox)
210
+ )))
211
+ }
212
+ for pass in 0 ..< 2 {
213
+ view.pdfView.setNeedsDisplay()
214
+ RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.2))
215
+ let format = UIGraphicsImageRendererFormat()
216
+ format.scale = 1
217
+ let snapshot = UIGraphicsImageRenderer(size: view.bounds.size, format: format).image { _ in
218
+ view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
219
+ }
220
+ let attachment = XCTAttachment(image: snapshot)
221
+ attachment.name = "Cropped stamps live view pass \(pass)"
222
+ attachment.lifetime = .keepAlways
223
+ add(attachment)
224
+ let image = try XCTUnwrap(snapshot.cgImage)
225
+ let context = try XCTUnwrap(CGContext(data: nil, width: image.width, height: image.height,
226
+ bitsPerComponent: 8, bytesPerRow: image.width * 4,
227
+ space: CGColorSpaceCreateDeviceRGB(),
228
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
229
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
230
+ let pixels = try XCTUnwrap(context.data).bindMemory(to: UInt8.self, capacity: image.width * image.height * 4)
231
+ for index in 0 ..< 3 {
232
+ let native = CGRect(x: 120 + index * 240, y: 140, width: 48, height: 48)
233
+ let rect = view.convert(view.pdfView.convert(native, from: page), from: view.pdfView).integral
234
+ var painted = 0
235
+ for y in max(0, Int(rect.minY)) ..< min(image.height, Int(rect.maxY)) {
236
+ for x in max(0, Int(rect.minX)) ..< min(image.width, Int(rect.maxX)) {
237
+ let offset = (y * image.width + x) * 4
238
+ if pixels[offset + 1] < 180 || pixels[offset + 2] < 180 { painted += 1 }
239
+ }
240
+ }
241
+ XCTAssertGreaterThan(painted, 10, "live glyph \(index), pass \(pass)")
242
+ }
243
+ let json = view.serializeCurrentAnnotations()
244
+ view.loadAnnotations(from: nil)
245
+ view.loadAnnotations(from: json)
246
+ }
247
+ window.isHidden = true
248
+ }
249
+
250
+ func testStampGlyphsRenderAtTheirVisibleBoundsOnCroppedPage() throws {
251
+ for glyph in ["♫", "★", "🎵"] {
252
+ let document = try AnnotationTestFixture.document()
253
+ let page = try XCTUnwrap(document.page(at: 0))
254
+ let model = AnnotationModel(id: glyph, type: "stamp", page: 0, color: "#FF0000",
255
+ bounds: AnnotationBounds(x: 20, y: 60, width: 48, height: 48), text: glyph)
256
+ let annotation = try XCTUnwrap(AnnotationSerializer.toPDFAnnotation(
257
+ model,
258
+ pageBounds: page.bounds(for: .cropBox)
259
+ ))
260
+ page.addAnnotation(annotation)
261
+ let image = try AnnotationTestFixture.thumbnail(page)
262
+ let context = try XCTUnwrap(CGContext(data: nil, width: image.width, height: image.height,
263
+ bitsPerComponent: 8, bytesPerRow: image.width * 4,
264
+ space: CGColorSpaceCreateDeviceRGB(),
265
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
266
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
267
+ let pixels = try XCTUnwrap(context.data).bindMemory(to: UInt8.self, capacity: image.width * image.height * 4)
268
+ var painted = 0
269
+ for y in 60 ..< 108 {
270
+ for x in 20 ..< 68 {
271
+ let offset = ((image.height - y) * image.width + x) * 4
272
+ if pixels[offset + 1] < 200 || pixels[offset + 2] < 200 { painted += 1 }
273
+ }
274
+ }
275
+ XCTAssertGreaterThan(painted, 30, "\(glyph) should paint within its intended bounds")
276
+ }
277
+ }
278
+
279
+ @MainActor func testInkRenderingEditingAndSerializationOnRotatedCroppedPages() throws {
280
+ let nativeInputs: [(Int, CGPoint, CGPoint)] = [
281
+ (0, CGPoint(x: 180, y: 200), CGPoint(x: 280, y: 200)),
282
+ (90, CGPoint(x: 580, y: 160), CGPoint(x: 580, y: 260)),
283
+ (180, CGPoint(x: 620, y: 800), CGPoint(x: 520, y: 800)),
284
+ (270, CGPoint(x: 220, y: 840), CGPoint(x: 220, y: 740)),
285
+ ]
286
+ for (rotation, start, end) in nativeInputs {
287
+ let document = try AnnotationTestFixture.document(rotation: rotation)
288
+ let page = try XCTUnwrap(document.page(at: 0))
289
+ let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 700))
290
+ let controller = UIViewController()
291
+ window.rootViewController = controller
292
+ window.makeKeyAndVisible()
293
+ let view = ExpoPdfMarkupView(appContext: nil)
294
+ view.frame = controller.view.bounds
295
+ controller.view.addSubview(view)
296
+ view.pdfView.document = document
297
+ view.layoutIfNeeded()
298
+ view.pdfView.layoutDocumentView()
299
+ view.annotationLineWidth = 8
300
+ view.setAnnotationMode("ink")
301
+ let overlay = try XCTUnwrap(view.inkOverlayView)
302
+ overlay.onBegan?(view.convert(view.pdfView.convert(start, from: page), from: view.pdfView))
303
+ overlay.onMoved?(view.convert(view.pdfView.convert(end, from: page), from: view.pdfView))
304
+ overlay.onEnded?()
305
+ let result = try XCTUnwrap(AnnotationSerializer.deserialize(from: view.serializeCurrentAnnotations()))
306
+ let stroke = try XCTUnwrap(result.annotations.first?.decodedPaths.first)
307
+ XCTAssertEqual(stroke.count, 2)
308
+ XCTAssertEqual(stroke[0].x, 80, accuracy: 0.001)
309
+ XCTAssertEqual(stroke[0].y, 120, accuracy: 0.001)
310
+ XCTAssertEqual(stroke[1].x, 180, accuracy: 0.001)
311
+ XCTAssertEqual(stroke[1].y, 120, accuracy: 0.001)
312
+ try AnnotationTestFixture.assertRed(AnnotationTestFixture.thumbnail(page), x: 130, y: 120)
313
+ XCTAssertNotNil(view.hitTestAnnotation(at: CGPoint(x: (start.x + end.x) / 2, y: (start.y + end.y) / 2), on: page))
314
+ window.isHidden = true
315
+ }
316
+ }
317
+ }
318
+
319
+ private final class CoordinateTestPan: UIPanGestureRecognizer {
320
+ var suppliedLocation: CGPoint = .zero
321
+ var suppliedState: UIGestureRecognizer.State = .possible
322
+ override var state: UIGestureRecognizer.State {
323
+ get { suppliedState }
324
+ set { suppliedState = newValue }
325
+ }
326
+
327
+ override func location(in _: UIView?) -> CGPoint {
328
+ suppliedLocation
329
+ }
330
+ }
331
+
332
+ private final class CoordinateTestTap: UITapGestureRecognizer {
333
+ var suppliedLocation: CGPoint = .zero
334
+ override func location(in _: UIView?) -> CGPoint {
335
+ suppliedLocation
336
+ }
337
+ }
@@ -3,6 +3,48 @@ import PDFKit
3
3
  import XCTest
4
4
 
5
5
  final class AnnotationSerializerTests: XCTestCase {
6
+ func testCroppedPageInkRendersAtVisiblePageCoordinates() throws {
7
+ let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 800, height: 1000))
8
+ let document = try XCTUnwrap(PDFDocument(data: renderer.pdfData { context in
9
+ context.beginPage()
10
+ UIColor.white.setFill()
11
+ context.fill(CGRect(x: 0, y: 0, width: 800, height: 1000))
12
+ }))
13
+ let page = try XCTUnwrap(document.page(at: 0))
14
+ page.setBounds(CGRect(x: 100, y: 80, width: 600, height: 840), for: .cropBox)
15
+ let model = AnnotationModel(
16
+ id: "crop-ink", type: "ink", page: 0, color: "#FF0000", lineWidth: 8,
17
+ paths: [[["x": 80, "y": 120], ["x": 180, "y": 120]]], createdAt: 123
18
+ )
19
+ let annotation = try XCTUnwrap(AnnotationSerializer.toPDFAnnotation(model, pageBounds: page.bounds(for: .cropBox)))
20
+ page.addAnnotation(annotation)
21
+ let image = try XCTUnwrap(page.thumbnail(of: CGSize(width: 600, height: 840), for: .cropBox).cgImage)
22
+ let context = try XCTUnwrap(CGContext(data: nil, width: image.width, height: image.height,
23
+ bitsPerComponent: 8, bytesPerRow: image.width * 4,
24
+ space: CGColorSpaceCreateDeviceRGB(),
25
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
26
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
27
+ let pixels = try XCTUnwrap(context.data).bindMemory(to: UInt8.self, capacity: image.width * image.height * 4)
28
+ // The midpoint is 130 pt from the visible left and 120 pt from the visible bottom.
29
+ let offset = ((image.height - 120) * image.width + 130) * 4
30
+ XCTAssertGreaterThan(pixels[offset], 200)
31
+ XCTAssertLessThan(pixels[offset + 1], 80)
32
+ XCTAssertLessThan(pixels[offset + 2], 80)
33
+ }
34
+
35
+ func testRectangularModelsUseVisiblePageCoordinatesOnCroppedPages() throws {
36
+ let crop = CGRect(x: 100, y: 80, width: 600, height: 840)
37
+ for type in ["highlight", "underline", "freeText", "stamp"] {
38
+ let model = AnnotationModel(id: "crop-\(type)", type: type, page: 0, color: "#FF0000",
39
+ bounds: AnnotationBounds(x: 80, y: 120, width: 100, height: 48), contents: "A",
40
+ text: "♫")
41
+ let annotation = try XCTUnwrap(AnnotationSerializer.toPDFAnnotation(model, pageBounds: crop))
42
+ let contentBounds = (annotation as? AreaUnderlinePDFAnnotation)?
43
+ .contentBounds ?? (annotation as? StampPDFAnnotation)?.contentBounds ?? annotation.bounds
44
+ XCTAssertEqual(contentBounds, CGRect(x: 180, y: 200, width: 100, height: 48), type)
45
+ }
46
+ }
47
+
6
48
  // MARK: - PDFAnnotation creation
7
49
 
8
50
  func testCreateInkAnnotation() throws {
@@ -51,7 +93,7 @@ final class AnnotationSerializerTests: XCTestCase {
51
93
 
52
94
  let annotation = AnnotationSerializer.toPDFAnnotation(model)
53
95
  XCTAssertNotNil(annotation)
54
- XCTAssertEqual(annotation?.type, "Underline")
96
+ XCTAssertEqual(annotation.flatMap { AnnotationSerializer.toModel(from: $0, page: 0) }?.type, "underline")
55
97
  }
56
98
 
57
99
  func testCreateFreeTextAnnotation() {
@@ -0,0 +1,279 @@
1
+ @testable internal import ExpoPdfMarkup
2
+ import PDFKit
3
+ import XCTest
4
+
5
+ final class AreaMarkupTests: XCTestCase {
6
+ @MainActor func testImageOnlyHighlightDragCreatesVisibleSerializedAreaWithoutScrolling() throws {
7
+ let view = try makeView()
8
+ let page = try XCTUnwrap(view.pdfView.document?.page(at: 0))
9
+ XCTAssertTrue(page.string?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true)
10
+ view.setAnnotationMode("highlight")
11
+ let scroll = try XCTUnwrap(view.pdfScrollView)
12
+ let offset = scroll.contentOffset
13
+ XCTAssertFalse(scroll.isScrollEnabled)
14
+ let overlay = try XCTUnwrap(view.subviews.compactMap { $0 as? InkOverlayView }.first,
15
+ "Highlight must accept an area drag without PDFKit text selection")
16
+ overlay.onBegan?(display(CGPoint(x: 180, y: 200), on: page, in: view))
17
+ overlay.onMoved?(display(CGPoint(x: 280, y: 240), on: page, in: view))
18
+ overlay.onEnded?()
19
+ let result = try XCTUnwrap(AnnotationSerializer.deserialize(from: view.serializeCurrentAnnotations()))
20
+ let model = try XCTUnwrap(result.annotations.first)
21
+ XCTAssertEqual(result.annotations.count, 1)
22
+ XCTAssertEqual(model.type, "highlight")
23
+ XCTAssertEqual(model.bounds?.x ?? -1, 80, accuracy: 0.001)
24
+ XCTAssertEqual(model.bounds?.y ?? -1, 120, accuracy: 0.001)
25
+ XCTAssertEqual(model.bounds?.width ?? -1, 100, accuracy: 0.001)
26
+ XCTAssertEqual(model.bounds?.height ?? -1, 40, accuracy: 0.001)
27
+ XCTAssertEqual(scroll.contentOffset, offset)
28
+ try assertRedTint(AnnotationTestFixture.thumbnail(page), x: 130, y: 140)
29
+ }
30
+
31
+ @MainActor func testUnderlineFollowsDisplayedBottomEdgeOnEveryRotationAndReopen() throws {
32
+ for rotation in [0, 90, 180, 270] {
33
+ let view = try makeView(rotation: rotation)
34
+ let page = try XCTUnwrap(view.pdfView.document?.page(at: 0))
35
+ view.setAnnotationMode("underline")
36
+ let overlay = try XCTUnwrap(view.markupOverlayView)
37
+ let coordinates = AnnotationCoordinates(page: page)
38
+ overlay.onBegan?(display(CGPoint(x: 80, y: 120).applying(coordinates.visibleToNative), on: page, in: view))
39
+ overlay.onMoved?(display(CGPoint(x: 180, y: 160).applying(coordinates.visibleToNative), on: page, in: view))
40
+ overlay.onEnded?()
41
+ let json = view.serializeCurrentAnnotations()
42
+ let result = try XCTUnwrap(AnnotationSerializer.deserialize(from: json)?.annotations.first)
43
+ XCTAssertEqual(result.type, "underline")
44
+ XCTAssertEqual(result.bounds?.x ?? -1, 80, accuracy: 0.001)
45
+ XCTAssertEqual(result.bounds?.y ?? -1, 120, accuracy: 0.001)
46
+ XCTAssertEqual(result.bounds?.width ?? -1, 100, accuracy: 0.001)
47
+ XCTAssertEqual(result.bounds?.height ?? -1, 40, accuracy: 0.001)
48
+ for _ in 0 ..< 2 {
49
+ XCTAssertNotNil(view.hitTestAnnotation(at: CGPoint(x: 130, y: 120)
50
+ .applying(coordinates.visibleToNative), on: page), "hit the actual underline at rotation \(rotation)")
51
+ let image = try AnnotationTestFixture.thumbnail(page)
52
+ XCTAssertGreaterThan(try redPixelCount(image, rect: CGRect(x: 110, y: 115, width: 40, height: 15)),
53
+ 20, "rotation \(rotation) should underline the displayed bottom edge")
54
+ XCTAssertEqual(try redPixelCount(image, rect: CGRect(x: 110, y: 150, width: 40, height: 10)),
55
+ 0, "rotation \(rotation) should not underline the displayed top")
56
+ view.loadAnnotations(from: nil)
57
+ view.loadAnnotations(from: json)
58
+ }
59
+ }
60
+ }
61
+
62
+ func testUnderlineRemainsVisibleAtRotatedCropEdge() throws {
63
+ let document = try AnnotationTestFixture.document(rotation: 180)
64
+ let page = try XCTUnwrap(document.page(at: 0))
65
+ let model = AnnotationModel(id: "edge-underline", type: "underline", page: 0, color: "#FF0000",
66
+ bounds: AnnotationBounds(x: 80, y: 1, width: 100, height: 40))
67
+ try page.addAnnotation(XCTUnwrap(AnnotationSerializer.toPDFAnnotation(
68
+ model, pageBounds: page.bounds(for: .cropBox), pageRotation: page.rotation
69
+ )))
70
+ XCTAssertGreaterThan(try redPixelCount(AnnotationTestFixture.thumbnail(page),
71
+ rect: CGRect(x: 110, y: 1, width: 40, height: 8)), 20)
72
+ }
73
+
74
+ @MainActor func testCancellationAndToolChangesDiscardAreaAndRestoreNavigation() throws {
75
+ let view = try makeView()
76
+ let page = try XCTUnwrap(view.pdfView.document?.page(at: 0))
77
+ let scroll = try XCTUnwrap(view.pdfScrollView)
78
+ let enabled = UITapGestureRecognizer()
79
+ let disabled = UITapGestureRecognizer()
80
+ disabled.isEnabled = false
81
+ view.pdfView.addGestureRecognizer(enabled)
82
+ view.pdfView.addGestureRecognizer(disabled)
83
+ view.setAnnotationMode("highlight")
84
+ let overlay = try XCTUnwrap(view.markupOverlayView)
85
+ overlay.onBegan?(display(CGPoint(x: 180, y: 200), on: page, in: view))
86
+ overlay.onMoved?(display(CGPoint(x: 280, y: 240), on: page, in: view))
87
+ overlay.onCancelled?()
88
+ overlay.onEnded?()
89
+ XCTAssertTrue(page.annotations.isEmpty)
90
+ XCTAssertNil(view.markupPreviewLayer?.path)
91
+ for mode in ["underline", "ink", "text", "stamp", "move", "eraser", "none"] {
92
+ view.setAnnotationMode("highlight")
93
+ let active = try XCTUnwrap(view.markupOverlayView)
94
+ active.onBegan?(display(CGPoint(x: 180, y: 200), on: page, in: view))
95
+ active.onMoved?(display(CGPoint(x: 280, y: 240), on: page, in: view))
96
+ view.setAnnotationMode(mode)
97
+ active.onEnded?()
98
+ XCTAssertTrue(page.annotations.isEmpty, "switching to \(mode) must discard the area")
99
+ XCTAssertNil(view.markupPreviewLayer?.path)
100
+ }
101
+ XCTAssertNil(view.markupOverlayView)
102
+ XCTAssertTrue(scroll.isScrollEnabled)
103
+ XCTAssertTrue(enabled.isEnabled)
104
+ XCTAssertFalse(disabled.isEnabled)
105
+ scroll.isScrollEnabled = false
106
+ view.setAnnotationMode("highlight")
107
+ view.setAnnotationMode("none")
108
+ XCTAssertFalse(scroll.isScrollEnabled, "restore the previous navigation state")
109
+ scroll.isScrollEnabled = true
110
+ view.setAnnotationMode("underline")
111
+ let final = try XCTUnwrap(view.markupOverlayView)
112
+ final.onBegan?(display(CGPoint(x: 180, y: 200), on: page, in: view))
113
+ final.onMoved?(display(CGPoint(x: 280, y: 240), on: page, in: view))
114
+ final.onEnded?()
115
+ XCTAssertEqual(page.annotations.count, 1, "a subsequent drag must still work")
116
+ }
117
+
118
+ @MainActor func testAreaMarkupOnTextAndScanControlsSurvivesZoomMoveAndReopen() throws {
119
+ for crop in [CGRect(x: 0, y: 0, width: 800, height: 1000),
120
+ CGRect(x: 0, y: 0, width: 600, height: 840), AnnotationTestFixture.crop] {
121
+ for text in [false, true] {
122
+ for mode in ["highlight", "underline"] {
123
+ let view = try makeView(crop: crop, text: text)
124
+ let page = try XCTUnwrap(view.pdfView.document?.page(at: 0))
125
+ XCTAssertEqual(!(page.string?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true), text)
126
+ view.pdfView.scaleFactor *= 1.5
127
+ view.pdfScrollView?.contentOffset = CGPoint(x: 20, y: 40)
128
+ view.setAnnotationMode(mode)
129
+ let overlay = try XCTUnwrap(view.markupOverlayView)
130
+ overlay.onBegan?(display(CGPoint(x: crop.minX + 80, y: crop.minY + 400), on: page, in: view))
131
+ overlay.onMoved?(display(CGPoint(x: crop.minX + 180, y: crop.minY + 440), on: page, in: view))
132
+ overlay.onEnded?()
133
+ let data = AnnotationSerializer.deserialize(from: view.serializeCurrentAnnotations())
134
+ let model = try XCTUnwrap(data?.annotations.first)
135
+ XCTAssertEqual(model.bounds?.x ?? -1, 80, accuracy: 0.001)
136
+ XCTAssertEqual(model.bounds?.y ?? -1, 400, accuracy: 0.001)
137
+ XCTAssertEqual(model.bounds?.width ?? -1, 100, accuracy: 0.001)
138
+ XCTAssertEqual(model.bounds?.height ?? -1, 40, accuracy: 0.001)
139
+ let target = CGPoint(x: crop.minX + 130, y: crop.minY + (mode == "highlight" ? 420 : 400))
140
+ XCTAssertNotNil(view.hitTestAnnotation(at: target, on: page))
141
+ view.setAnnotationMode("move")
142
+ let pan = AreaMarkupPan()
143
+ pan.suppliedLocation = view.pdfView.convert(target, from: page)
144
+ pan.suppliedState = .began
145
+ view.handleMovePan(pan)
146
+ pan.suppliedLocation = view.pdfView.convert(CGPoint(x: target.x + 20, y: target.y + 30), from: page)
147
+ pan.suppliedState = .changed
148
+ view.handleMovePan(pan)
149
+ pan.suppliedState = .ended
150
+ view.handleMovePan(pan)
151
+ let json = view.serializeCurrentAnnotations()
152
+ let moved = try XCTUnwrap(AnnotationSerializer.deserialize(from: json)?.annotations.first)
153
+ XCTAssertEqual(moved.id, model.id)
154
+ XCTAssertEqual(moved.bounds?.x ?? -1, 100, accuracy: 0.001)
155
+ XCTAssertEqual(moved.bounds?.y ?? -1, 430, accuracy: 0.001)
156
+ XCTAssertEqual(moved.color, model.color)
157
+ XCTAssertEqual(moved.alpha, model.alpha)
158
+ XCTAssertNotNil(view.editingOverlayLayer?.path)
159
+ let reopened = try makeView(crop: crop, text: text)
160
+ reopened.loadAnnotations(from: json)
161
+ let reopenedData = AnnotationSerializer.deserialize(from: reopened.serializeCurrentAnnotations())
162
+ XCTAssertEqual(reopenedData?.annotations, [moved])
163
+ let reopenedPage = try XCTUnwrap(reopened.pdfView.document?.page(at: 0))
164
+ let image = try AnnotationTestFixture.thumbnail(reopenedPage)
165
+ let paintedY = mode == "highlight" ? 450 : 430
166
+ let visibleLine = CGRect(x: 130, y: paintedY - 1, width: 40, height: 3)
167
+ XCTAssertGreaterThan(try redPixelCount(image, rect: visibleLine), 20)
168
+ let reopenedTarget = CGPoint(x: crop.minX + 150, y: crop.minY + CGFloat(paintedY))
169
+ XCTAssertNotNil(reopened.hitTestAnnotation(at: reopenedTarget, on: reopenedPage))
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ @MainActor func testPageKeysSourceChangesAndNoneModeDiscardStaleDrags() throws {
176
+ let view = try makeView()
177
+ let document = try XCTUnwrap(view.pdfView.document)
178
+ let first = try XCTUnwrap(document.page(at: 0))
179
+ let second = try XCTUnwrap(first.copy() as? PDFPage)
180
+ document.insert(second, at: 1)
181
+ view.setDisplayMode("book")
182
+ view.goToPage(0)
183
+ view.setAnnotationMode("highlight")
184
+ let overlay = try XCTUnwrap(view.markupOverlayView)
185
+ func begin() {
186
+ overlay.onBegan?(display(CGPoint(x: 180, y: 200), on: first, in: view))
187
+ overlay.onMoved?(display(CGPoint(x: 280, y: 240), on: first, in: view))
188
+ }
189
+ begin()
190
+ view.handleBookTap(at: CGPoint(x: view.bounds.maxX - 1, y: view.bounds.midY))
191
+ XCTAssertTrue(view.pdfView.currentPage === first, "area tools block touch page turns")
192
+ let command = try XCTUnwrap(view.keyCommands?.first { $0.input == UIKeyCommand.inputRightArrow })
193
+ try view.perform(XCTUnwrap(command.action), with: command)
194
+ XCTAssertTrue(view.pdfView.currentPage === second, "hardware navigation remains available")
195
+ overlay.onEnded?()
196
+ XCTAssertTrue(first.annotations.isEmpty)
197
+ XCTAssertTrue(second.annotations.isEmpty)
198
+ XCTAssertNil(view.markupPreviewLayer?.path)
199
+ view.goToPage(0)
200
+ begin()
201
+ view.goToPage(1)
202
+ overlay.onEnded?()
203
+ XCTAssertTrue(first.annotations.isEmpty, "page prop navigation cancels the held drag")
204
+ view.goToPage(0)
205
+ begin()
206
+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("area-source-\(UUID().uuidString).pdf")
207
+ defer { try? FileManager.default.removeItem(at: url) }
208
+ XCTAssertTrue(try AnnotationTestFixture.document(text: true).write(to: url))
209
+ view.loadPdf(from: url.path)
210
+ overlay.onEnded?()
211
+ XCTAssertTrue(try XCTUnwrap(view.pdfView.document?.page(at: 0)).annotations.isEmpty)
212
+ XCTAssertNil(view.markupPreviewLayer?.path)
213
+ XCTAssertFalse(try XCTUnwrap(view.pdfScrollView).isScrollEnabled)
214
+ view.pdfView.document = document
215
+ view.goToPage(0)
216
+ view.setAnnotationMode("none")
217
+ XCTAssertTrue(try XCTUnwrap(view.pdfScrollView).isScrollEnabled)
218
+ view.handleBookTap(at: CGPoint(x: view.bounds.maxX - 1, y: view.bounds.midY))
219
+ XCTAssertTrue(view.pdfView.currentPage === second, "touch page turning resumes after leaving the tool")
220
+ }
221
+
222
+ private func redPixelCount(_ image: CGImage, rect: CGRect) throws -> Int {
223
+ let context = try XCTUnwrap(CGContext(data: nil, width: image.width, height: image.height,
224
+ bitsPerComponent: 8, bytesPerRow: image.width * 4,
225
+ space: CGColorSpaceCreateDeviceRGB(),
226
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
227
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
228
+ let pixels = try XCTUnwrap(context.data).bindMemory(to: UInt8.self, capacity: image.width * image.height * 4)
229
+ var count = 0
230
+ for y in Int(rect.minY) ..< Int(rect.maxY) {
231
+ for x in Int(rect.minX) ..< Int(rect.maxX) {
232
+ let index = ((image.height - 1 - y) * image.width + x) * 4
233
+ if pixels[index] > 200, pixels[index + 1] < 220, pixels[index + 2] < 220 { count += 1 }
234
+ }
235
+ }
236
+ return count
237
+ }
238
+
239
+ @MainActor private func makeView(crop: CGRect = AnnotationTestFixture.crop,
240
+ rotation: Int = 0, text: Bool = false) throws -> ExpoPdfMarkupView {
241
+ let view = ExpoPdfMarkupView(appContext: nil)
242
+ view.frame = UIScreen.main.bounds
243
+ view.pdfView.document = try AnnotationTestFixture.document(crop: crop, rotation: rotation, text: text)
244
+ view.layoutIfNeeded()
245
+ view.pdfView.layoutDocumentView()
246
+ return view
247
+ }
248
+
249
+ @MainActor private func display(_ point: CGPoint, on page: PDFPage, in view: ExpoPdfMarkupView) -> CGPoint {
250
+ view.convert(view.pdfView.convert(point, from: page), from: view.pdfView)
251
+ }
252
+
253
+ private func assertRedTint(_ image: CGImage, x: Int, y: Int,
254
+ file: StaticString = #filePath, line: UInt = #line) throws {
255
+ let context = try XCTUnwrap(CGContext(data: nil, width: image.width, height: image.height,
256
+ bitsPerComponent: 8, bytesPerRow: image.width * 4,
257
+ space: CGColorSpaceCreateDeviceRGB(),
258
+ bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
259
+ context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))
260
+ let pixels = try XCTUnwrap(context.data).bindMemory(to: UInt8.self, capacity: image.width * image.height * 4)
261
+ let index = ((image.height - 1 - y) * image.width + x) * 4
262
+ XCTAssertGreaterThan(pixels[index], 200, file: file, line: line)
263
+ XCTAssertLessThan(pixels[index + 1], 220, file: file, line: line)
264
+ XCTAssertLessThan(pixels[index + 2], 220, file: file, line: line)
265
+ }
266
+ }
267
+
268
+ private final class AreaMarkupPan: UIPanGestureRecognizer {
269
+ var suppliedLocation: CGPoint = .zero
270
+ var suppliedState: UIGestureRecognizer.State = .possible
271
+ override var state: UIGestureRecognizer.State {
272
+ get { suppliedState }
273
+ set { suppliedState = newValue }
274
+ }
275
+
276
+ override func location(in _: UIView?) -> CGPoint {
277
+ suppliedLocation
278
+ }
279
+ }