@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
@@ -18,7 +18,20 @@ enum AnnotationSerializer {
18
18
 
19
19
  // MARK: - PDFAnnotation ↔ AnnotationModel
20
20
 
21
- static func toPDFAnnotation(_ model: AnnotationModel, pageBounds: CGRect? = nil) -> PDFAnnotation? {
21
+ static func toPDFAnnotation(_ model: AnnotationModel, pageBounds: CGRect? = nil,
22
+ pageRotation: Int = 0) -> PDFAnnotation? {
23
+ let coordinates = AnnotationCoordinates(bounds: pageBounds ?? .zero, rotation: pageRotation)
24
+ var visibleModel = model
25
+ if model.type == "text" || model.type == "freeText", let bounds = model.bounds {
26
+ let size = model.fontSize ?? 16
27
+ let font = UIFont(name: model.fontFamily ?? "", size: size) ?? UIFont.systemFont(ofSize: size)
28
+ visibleModel.bounds = AnnotationBounds(normalizedFreeTextBounds(
29
+ bounds: bounds.cgRect,
30
+ text: model.contents ?? "",
31
+ font: font
32
+ ))
33
+ }
34
+ let model = coordinates.transform(visibleModel, using: coordinates.visibleToNative)
22
35
  let color = colorFromHex(model.color) ?? .red
23
36
 
24
37
  switch model.type {
@@ -46,7 +59,8 @@ enum AnnotationSerializer {
46
59
  forAnnotationKey: PDFAnnotationKey(rawValue: "_createdAt")
47
60
  ) as? Double ?? Date().timeIntervalSince1970
48
61
 
49
- guard let type = modelType(for: annotation.type) else { return nil }
62
+ guard let nativeType = modelType(for: annotation.type) else { return nil }
63
+ let type = annotation.value(forAnnotationKey: PDFAnnotationKey(rawValue: "_modelType")) as? String ?? nativeType
50
64
  var model = AnnotationModel(
51
65
  id: id,
52
66
  type: type,
@@ -56,8 +70,8 @@ enum AnnotationSerializer {
56
70
  )
57
71
 
58
72
  populateModelDetails(&model, from: annotation)
59
-
60
- return model
73
+ let coordinates = annotation.page.map { AnnotationCoordinates(page: $0) } ?? AnnotationCoordinates(bounds: .zero)
74
+ return coordinates.transform(model, using: coordinates.nativeToVisible)
61
75
  }
62
76
 
63
77
  private static func modelType(for annotationType: String?) -> String? {
@@ -101,12 +115,12 @@ enum AnnotationSerializer {
101
115
  // type declares it non-optional, and `JSONEncoder` drops nil keys entirely, so a
102
116
  // nil here reaches consumers as a missing property rather than an empty stroke list.
103
117
  model.paths = (annotation.paths ?? []).map { path in
104
- pointsFromBezierPath(path).map { ["x": $0.x, "y": $0.y] }
118
+ pointsFromBezierPath(path).map { ["x": $0.x + annotation.bounds.minX, "y": $0.y + annotation.bounds.minY] }
105
119
  }
106
120
  case "highlight", "underline":
107
- model.bounds = AnnotationBounds(annotation.bounds)
121
+ model.bounds = AnnotationBounds((annotation as? AreaUnderlinePDFAnnotation)?.contentBounds ?? annotation.bounds)
108
122
  if model.type == "highlight" {
109
- model.alpha = 0.5
123
+ model.alpha = annotation.color.cgColor.alpha
110
124
  }
111
125
  case "text", "freeText":
112
126
  model.bounds = AnnotationBounds(annotation.bounds)
@@ -116,7 +130,7 @@ enum AnnotationSerializer {
116
130
  model.fontFamily = font.fontName
117
131
  }
118
132
  case "stamp":
119
- model.bounds = AnnotationBounds(annotation.bounds)
133
+ model.bounds = AnnotationBounds((annotation as? StampPDFAnnotation)?.contentBounds ?? annotation.bounds)
120
134
  if let stamp = annotation as? StampPDFAnnotation {
121
135
  model.text = stamp.stampText
122
136
  }
@@ -221,9 +235,9 @@ enum AnnotationSerializer {
221
235
  let bezierPath = UIBezierPath()
222
236
  for (index, point) in path.enumerated() {
223
237
  if index == 0 {
224
- bezierPath.move(to: CGPoint(x: point.x, y: point.y))
238
+ bezierPath.move(to: CGPoint(x: point.x - annotationBounds.minX, y: point.y - annotationBounds.minY))
225
239
  } else {
226
- bezierPath.addLine(to: CGPoint(x: point.x, y: point.y))
240
+ bezierPath.addLine(to: CGPoint(x: point.x - annotationBounds.minX, y: point.y - annotationBounds.minY))
227
241
  }
228
242
  }
229
243
  annotation.add(bezierPath)
@@ -240,7 +254,14 @@ enum AnnotationSerializer {
240
254
  subtype: PDFAnnotationSubtype
241
255
  ) -> PDFAnnotation? {
242
256
  guard let bounds = model.bounds else { return nil }
243
- let annotation = PDFAnnotation(bounds: bounds.cgRect, forType: subtype, withProperties: nil)
257
+ let annotation: PDFAnnotation = subtype == .underline
258
+ ? AreaUnderlinePDFAnnotation(bounds: bounds.cgRect, forType: .stamp, withProperties: nil)
259
+ : PDFAnnotation(bounds: bounds.cgRect, forType: subtype, withProperties: nil)
260
+ if subtype == .underline {
261
+ // PDFKit's live underline view bypasses draw(with:in:). A custom stamp
262
+ // appearance invokes our renderer while the shared model remains underline.
263
+ annotation.setValue("underline", forAnnotationKey: PDFAnnotationKey(rawValue: "_modelType"))
264
+ }
244
265
  let alpha = model.alpha ?? (subtype == .highlight ? 0.5 : 1.0)
245
266
  annotation.color = color.withAlphaComponent(alpha)
246
267
 
@@ -255,7 +276,7 @@ enum AnnotationSerializer {
255
276
  let font = UIFont(name: model.fontFamily ?? "", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)
256
277
  let contents = model.contents ?? ""
257
278
  let annotation = PDFAnnotation(
258
- bounds: normalizedFreeTextBounds(bounds: bounds.cgRect, text: contents, font: font),
279
+ bounds: bounds.cgRect,
259
280
  forType: .freeText,
260
281
  withProperties: nil
261
282
  )
@@ -263,6 +284,7 @@ enum AnnotationSerializer {
263
284
  annotation.fontColor = color
264
285
  annotation.color = .clear
265
286
  annotation.contents = contents
287
+ annotation.setValue(model.type, forAnnotationKey: PDFAnnotationKey(rawValue: "_modelType"))
266
288
 
267
289
  let createdAt = model.createdAt ?? Date().timeIntervalSince1970
268
290
  tagAsModuleManaged(annotation, id: model.id, createdAt: createdAt, colorHex: model.color)
@@ -316,3 +338,68 @@ enum AnnotationSerializer {
316
338
  return points
317
339
  }
318
340
  }
341
+
342
+ /// Interchange coordinates are zero-origin, y-up points on the visible, rotated page.
343
+ /// PDFKit uses unrotated page coordinates; ink paths additionally use annotation-local points.
344
+ struct AnnotationCoordinates {
345
+ /// Separate the live appearance clip from its content, including full-page marks.
346
+ static let appearancePadding: CGFloat = 2
347
+ private let nativeBounds: CGRect
348
+ let nativeToVisible: CGAffineTransform
349
+ var visibleToNative: CGAffineTransform {
350
+ nativeToVisible.inverted()
351
+ }
352
+
353
+ let visibleBounds: CGRect
354
+
355
+ init(page: PDFPage) {
356
+ self.init(bounds: page.bounds(for: .cropBox), rotation: page.rotation)
357
+ }
358
+
359
+ init(bounds: CGRect, rotation: Int = 0) {
360
+ nativeBounds = bounds
361
+ switch (rotation % 360 + 360) % 360 {
362
+ case 90:
363
+ nativeToVisible = CGAffineTransform(a: 0, b: -1, c: 1, d: 0, tx: -bounds.minY, ty: bounds.maxX)
364
+ visibleBounds = CGRect(x: 0, y: 0, width: bounds.height, height: bounds.width)
365
+ case 180:
366
+ nativeToVisible = CGAffineTransform(a: -1, b: 0, c: 0, d: -1, tx: bounds.maxX, ty: bounds.maxY)
367
+ visibleBounds = CGRect(origin: .zero, size: bounds.size)
368
+ case 270:
369
+ nativeToVisible = CGAffineTransform(a: 0, b: 1, c: -1, d: 0, tx: bounds.maxY, ty: -bounds.minX)
370
+ visibleBounds = CGRect(x: 0, y: 0, width: bounds.height, height: bounds.width)
371
+ default:
372
+ nativeToVisible = CGAffineTransform(translationX: -bounds.minX, y: -bounds.minY)
373
+ visibleBounds = CGRect(origin: .zero, size: bounds.size)
374
+ }
375
+ }
376
+
377
+ /// PDFKit clips a recorded live appearance to the native, crop-relative annotation
378
+ /// rectangle. Whole-page renderers instead clip to the visible page. Match that
379
+ /// geometry before adapting custom drawing; do not call bitmap-only context APIs
380
+ /// on PDFKit's vector appearance contexts.
381
+ func prepareForDrawing(in context: CGContext, annotationBounds: CGRect) {
382
+ let clip = context.boundingBoxOfClipPath
383
+ let localBounds = annotationBounds.offsetBy(dx: -nativeBounds.minX, dy: -nativeBounds.minY)
384
+ let tolerance: CGFloat = 1
385
+ guard localBounds.insetBy(dx: -tolerance, dy: -tolerance).contains(clip),
386
+ clip.insetBy(dx: -tolerance, dy: -tolerance).contains(localBounds) else { return }
387
+ context.concatenate(visibleToNative.concatenating(
388
+ CGAffineTransform(translationX: -nativeBounds.minX, y: -nativeBounds.minY)
389
+ ))
390
+ }
391
+
392
+ func transform(_ model: AnnotationModel, using transform: CGAffineTransform) -> AnnotationModel {
393
+ var result = model
394
+ if let bounds = model.bounds { result.bounds = AnnotationBounds(bounds.cgRect.applying(transform)) }
395
+ if model.paths != nil {
396
+ result.paths = model.encodedPaths(from: model.decodedPaths.map { stroke in
397
+ stroke.map { point in
398
+ let converted = CGPoint(x: point.x, y: point.y).applying(transform)
399
+ return AnnotationPoint(x: converted.x, y: converted.y)
400
+ }
401
+ })
402
+ }
403
+ return result
404
+ }
405
+ }
@@ -28,6 +28,10 @@ public class ExpoPdfMarkupModule: Module {
28
28
  view.loadAnnotations(from: json)
29
29
  }
30
30
 
31
+ Prop("displayMode") { (view: ExpoPdfMarkupView, mode: String?) in
32
+ view.setDisplayMode(mode ?? "continuous")
33
+ }
34
+
31
35
  Prop("annotationMode") { (view: ExpoPdfMarkupView, mode: String?) in
32
36
  view.setAnnotationMode(mode ?? "none")
33
37
  }
@@ -0,0 +1,455 @@
1
+ import PDFKit
2
+ import UIKit
3
+
4
+ /// Which way a book mode turn goes. `next` is always the page after, whatever the layout direction.
5
+ enum BookTurnDirection {
6
+ case previous
7
+ case next
8
+
9
+ var step: Int {
10
+ self == .next ? 1 : -1
11
+ }
12
+ }
13
+
14
+ /// What asked for a turn. The turn policy treats touch input and hardware keys differently.
15
+ enum BookTurnInput {
16
+ case swipe
17
+ case edgeTap
18
+ /// Hardware keys (#98): turn in book mode whatever the zoom or markup mode.
19
+ case key
20
+ }
21
+
22
+ /// Book mode tuning. The names follow the web (`src/web/bookMode.ts`) and Android
23
+ /// (`BookTurnPolicy`, `ContinuousPdfView`) constants, and the turn thresholds have the same values
24
+ /// on every platform. Only the bounce nudge distance differs.
25
+ enum BookMode {
26
+ /// Share of the view's width that each edge tap zone covers.
27
+ static let edgeZoneFraction: CGFloat = 0.25
28
+ /// Minimum width of an edge tap zone, in points.
29
+ static let minEdgeZone: CGFloat = 44
30
+ /// Share of the view's width a slow swipe has to travel to turn the page.
31
+ static let swipeTurnFraction: CGFloat = 0.25
32
+ /// A release faster than this (points per second) turns the page even after a short drag.
33
+ static let flingVelocity: CGFloat = 500
34
+ /// How much of the finger's travel the page follows where there's no page to turn to.
35
+ static let edgeResistance: CGFloat = 0.3
36
+ /// How far (points) the page nudges when a tap or key bounces at either end.
37
+ static let bouncePoints: CGFloat = 32
38
+ /// Scales within this share of fit count as "at fit", absorbing pinch rounding.
39
+ static let fitTolerance: CGFloat = 0.01
40
+ /// Duration of the slide to the next or previous page, in seconds.
41
+ static let turnDuration: TimeInterval = 0.25
42
+ /// Duration of each half of the bounce at either end, in seconds.
43
+ static let bounceDuration: TimeInterval = 0.12
44
+ }
45
+
46
+ extension ExpoPdfMarkupView {
47
+ // MARK: - Book mode presentation
48
+
49
+ var isBookMode: Bool {
50
+ displayMode == "book"
51
+ }
52
+
53
+ /// Switches PDFKit between the continuous scroll and the one-page-at-a-time book layout,
54
+ /// keeping the page the reader is on.
55
+ func applyDisplayMode() {
56
+ let keptPage = pdfView.currentPage
57
+
58
+ if isBookMode {
59
+ pdfView.displayMode = .singlePage
60
+ pdfView.displayDirection = .horizontal
61
+ pdfView.pageBreakMargins = .zero
62
+ installBookGestures()
63
+ } else {
64
+ removeBookGestures()
65
+ if isFirstResponder {
66
+ resignFirstResponder()
67
+ }
68
+ pdfView.displayMode = .singlePageContinuous
69
+ pdfView.displayDirection = .vertical
70
+ pdfView.pageBreakMargins = UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0)
71
+ }
72
+ pdfView.autoScales = true
73
+
74
+ if let keptPage {
75
+ pdfView.go(to: keptPage)
76
+ }
77
+ claimBookKeyFocus()
78
+ }
79
+
80
+ // MARK: - Hardware keys
81
+
82
+ /// The turn a hardware key asks for: Right, Down and Page Down go forward; Left, Up and
83
+ /// Page Up go back. Space isn't mapped.
84
+ func bookTurnDirection(forKey input: String) -> BookTurnDirection? {
85
+ switch input {
86
+ case UIKeyCommand.inputRightArrow, UIKeyCommand.inputDownArrow, UIKeyCommand.inputPageDown:
87
+ .next
88
+ case UIKeyCommand.inputLeftArrow, UIKeyCommand.inputUpArrow, UIKeyCommand.inputPageUp:
89
+ .previous
90
+ default:
91
+ nil
92
+ }
93
+ }
94
+
95
+ /// Key commands for keyboards and page-turner pedals, offered to UIKit only in book mode.
96
+ /// Unmodified keys only, and ahead of the system's own arrow-key scrolling.
97
+ var bookKeyCommands: [UIKeyCommand] {
98
+ [
99
+ UIKeyCommand.inputRightArrow, UIKeyCommand.inputDownArrow, UIKeyCommand.inputPageDown,
100
+ UIKeyCommand.inputLeftArrow, UIKeyCommand.inputUpArrow, UIKeyCommand.inputPageUp,
101
+ ].map { input in
102
+ let command = UIKeyCommand(input: input, modifierFlags: [], action: #selector(handleBookKeyCommand(_:)))
103
+ command.wantsPriorityOverSystemBehavior = true
104
+ return command
105
+ }
106
+ }
107
+
108
+ @objc func handleBookKeyCommand(_ command: UIKeyCommand) {
109
+ guard let input = command.input, let direction = bookTurnDirection(forKey: input) else { return }
110
+ // Keys typed into a text input (including the host's text annotation input) are its own.
111
+ guard !isTextInputActive else { return }
112
+ turnBookPage(direction, from: .key)
113
+ }
114
+
115
+ /// Whether a text input outside this view is first responder, so keys belong to it.
116
+ /// PDFKit's own views inside this one don't count.
117
+ var isTextInputActive: Bool {
118
+ guard let responder = UIResponder.currentFirstResponder, responder is UITextInput else { return false }
119
+ return !((responder as? UIView)?.isDescendant(of: self) ?? false)
120
+ }
121
+
122
+ /// Becomes first responder in book mode while on screen, so a pedal or keyboard turns the page
123
+ /// without the host app doing anything. Never takes focus from a text input, and leaves it
124
+ /// alone when it's already with this view or PDFKit's views inside it.
125
+ func claimBookKeyFocus() {
126
+ guard isBookMode, window != nil, !isTextInputActive else { return }
127
+ if let current = UIResponder.currentFirstResponder as? UIView, current.isDescendant(of: self) {
128
+ return
129
+ }
130
+ becomeFirstResponder()
131
+ }
132
+
133
+ @objc func handleTextEditingEnded() {
134
+ // Wait for the responder change to settle before taking the keys back.
135
+ DispatchQueue.main.async { [weak self] in
136
+ self?.claimBookKeyFocus()
137
+ }
138
+ }
139
+
140
+ // MARK: - Turn path
141
+
142
+ /// The single entry point for every book mode turn: swipes, edge taps and hardware keys.
143
+ /// Applies the turn policy, then either slides to the neighbouring page (one `onPageChanged`)
144
+ /// or bounces at the first and last page.
145
+ ///
146
+ /// `dragOffset` is how far a swipe has already dragged the page, so the slide carries on from there.
147
+ @discardableResult
148
+ func turnBookPage(_ direction: BookTurnDirection, from input: BookTurnInput, dragOffset: CGFloat = 0) -> Bool {
149
+ guard allowsBookTurn(from: input) else {
150
+ springBookPageBack()
151
+ return false
152
+ }
153
+ guard let target = bookNeighbour(direction) else {
154
+ if dragOffset == 0 {
155
+ animateBookBounce(direction)
156
+ } else {
157
+ springBookPageBack()
158
+ }
159
+ return false
160
+ }
161
+ showBookPage(target, direction: direction, dragOffset: dragOffset)
162
+ return true
163
+ }
164
+
165
+ /// Spec turn policy: touch input turns only with no markup tool active and the page at fit.
166
+ /// Keys turn in book mode regardless.
167
+ func allowsBookTurn(from input: BookTurnInput) -> Bool {
168
+ guard isBookMode else { return false }
169
+ switch input {
170
+ case .key:
171
+ return true
172
+ case .swipe, .edgeTap:
173
+ return currentMode == "none" && !isZoomedBeyondFit
174
+ }
175
+ }
176
+
177
+ var isZoomedBeyondFit: Bool {
178
+ pdfView.scaleFactor > pdfView.scaleFactorForSizeToFit * (1 + BookMode.fitTolerance)
179
+ }
180
+
181
+ func bookNeighbour(_ direction: BookTurnDirection) -> PDFPage? {
182
+ guard let document = pdfView.document, let current = pdfView.currentPage else { return nil }
183
+ let index = document.index(for: current) + direction.step
184
+ guard index >= 0, index < document.pageCount else { return nil }
185
+ return document.page(at: index)
186
+ }
187
+
188
+ private func showBookPage(_ page: PDFPage, direction: BookTurnDirection, dragOffset: CGFloat = 0) {
189
+ let width = max(pdfView.bounds.width, 1)
190
+ let outgoing = pdfView.snapshotView(afterScreenUpdates: false)
191
+ finishBookAnimation()
192
+
193
+ pdfView.transform = .identity
194
+ pdfView.go(to: page)
195
+ resetBookPageToFit()
196
+
197
+ guard window != nil else { return }
198
+
199
+ if let outgoing {
200
+ outgoing.frame = pdfView.frame.offsetBy(dx: dragOffset, dy: 0)
201
+ addSubview(outgoing)
202
+ bookTurnSnapshot = outgoing
203
+ }
204
+ // Next slides in from the right, previous from the left.
205
+ let incomingStart = direction == .next ? width + dragOffset : -width + dragOffset
206
+ pdfView.transform = CGAffineTransform(translationX: incomingStart, y: 0)
207
+ UIView.animate(withDuration: BookMode.turnDuration, delay: 0, options: [.curveEaseOut, .allowUserInteraction]) {
208
+ self.pdfView.transform = .identity
209
+ outgoing?.transform = CGAffineTransform(translationX: direction == .next ? -width : width, y: 0)
210
+ } completion: { _ in
211
+ outgoing?.removeFromSuperview()
212
+ if self.bookTurnSnapshot === outgoing {
213
+ self.bookTurnSnapshot = nil
214
+ }
215
+ }
216
+ }
217
+
218
+ /// Jumps straight to `page` with no slide, as the `page` prop does, and starts it at fit.
219
+ /// `go(to:)` fires the one `onPageChanged`.
220
+ func jumpToBookPage(_ page: PDFPage) {
221
+ finishBookAnimation()
222
+ pdfView.transform = .identity
223
+ pdfView.go(to: page)
224
+ resetBookPageToFit()
225
+ }
226
+
227
+ private func resetBookPageToFit() {
228
+ pdfView.scaleFactor = pdfView.scaleFactorForSizeToFit
229
+ pdfView.autoScales = true
230
+ }
231
+
232
+ private func animateBookBounce(_ direction: BookTurnDirection) {
233
+ guard window != nil else { return }
234
+ let nudge = direction == .next ? -BookMode.bouncePoints : BookMode.bouncePoints
235
+ UIView.animate(withDuration: BookMode.bounceDuration, delay: 0, options: [.curveEaseOut, .allowUserInteraction]) {
236
+ self.pdfView.transform = CGAffineTransform(translationX: nudge, y: 0)
237
+ } completion: { _ in
238
+ self.springBookPageBack()
239
+ }
240
+ }
241
+
242
+ func springBookPageBack() {
243
+ UIView.animate(
244
+ withDuration: 0.3,
245
+ delay: 0,
246
+ usingSpringWithDamping: 0.7,
247
+ initialSpringVelocity: 0,
248
+ options: [.allowUserInteraction]
249
+ ) {
250
+ self.pdfView.transform = .identity
251
+ }
252
+ }
253
+
254
+ private func finishBookAnimation() {
255
+ pdfView.layer.removeAllAnimations()
256
+ bookTurnSnapshot?.removeFromSuperview()
257
+ bookTurnSnapshot = nil
258
+ }
259
+
260
+ // MARK: - Edge taps
261
+
262
+ /// Width of each edge tap zone: the outer quarter of the view, at least 44 pt.
263
+ var bookEdgeZoneWidth: CGFloat {
264
+ min(max(bounds.width * BookMode.edgeZoneFraction, BookMode.minEdgeZone), bounds.width / 2)
265
+ }
266
+
267
+ /// The turn a tap at `location` (in this view's coordinates) asks for: one in an edge zone while
268
+ /// the turn policy allows edge taps. `nil` in the middle, where a double-tap zooms instead.
269
+ func bookEdgeTurn(at location: CGPoint) -> BookTurnDirection? {
270
+ guard allowsBookTurn(from: .edgeTap) else { return nil }
271
+ let zone = bookEdgeZoneWidth
272
+ if location.x <= zone {
273
+ return .previous
274
+ }
275
+ if location.x >= bounds.width - zone {
276
+ return .next
277
+ }
278
+ return nil
279
+ }
280
+
281
+ /// Turns the page for a tap at `location` if it lands in an edge zone. `tapCount` is the
282
+ /// touch's tap count: the second tap of a double-tap is skipped, so a double-tap on an edge
283
+ /// turns once (as on Android, a third quick tap turns again).
284
+ func handleBookTap(at location: CGPoint, tapCount: Int = 1) {
285
+ guard tapCount % 2 == 1, let direction = bookEdgeTurn(at: location) else { return }
286
+ turnBookPage(direction, from: .edgeTap)
287
+ }
288
+
289
+ @objc func handleBookTapGesture(_ gesture: UITapGestureRecognizer) {
290
+ guard gesture.state == .ended else { return }
291
+ claimBookKeyFocus()
292
+ handleBookTap(at: gesture.location(in: self), tapCount: bookTapCount)
293
+ }
294
+
295
+ /// A double-tap on an edge: recognised only so that PDFKit's double-tap zoom, which waits for
296
+ /// it to fail, doesn't zoom there. The first tap has already turned the page.
297
+ @objc func handleBookEdgeDoubleTapGesture(_: UITapGestureRecognizer) {}
298
+
299
+ // MARK: - Swipes
300
+
301
+ @objc func handleBookPanGesture(_ gesture: UIPanGestureRecognizer) {
302
+ let translationX = gesture.translation(in: self).x
303
+ switch gesture.state {
304
+ case .changed:
305
+ // Follow the finger, with resistance where there is no page to turn to.
306
+ let direction: BookTurnDirection = translationX < 0 ? .next : .previous
307
+ let offset = bookNeighbour(direction) == nil ? translationX * BookMode.edgeResistance : translationX
308
+ pdfView.transform = CGAffineTransform(translationX: offset, y: 0)
309
+ case .ended:
310
+ endBookSwipe(translationX: translationX, velocityX: gesture.velocity(in: self).x)
311
+ case .cancelled, .failed:
312
+ springBookPageBack()
313
+ default:
314
+ break
315
+ }
316
+ }
317
+
318
+ /// Ends a horizontal swipe: turns when it went far enough (a quarter of the width) or was
319
+ /// flicked, otherwise springs back. Swipe left always means next.
320
+ func endBookSwipe(translationX: CGFloat, velocityX: CGFloat) {
321
+ let reference = translationX != 0 ? translationX : velocityX
322
+ guard reference != 0 else {
323
+ springBookPageBack()
324
+ return
325
+ }
326
+ let direction: BookTurnDirection = reference < 0 ? .next : .previous
327
+ let farEnough = abs(translationX) > bounds.width * BookMode.swipeTurnFraction
328
+ let flicked = abs(velocityX) > BookMode.flingVelocity && (velocityX < 0) == (reference < 0)
329
+ guard farEnough || flicked else {
330
+ springBookPageBack()
331
+ return
332
+ }
333
+ turnBookPage(direction, from: .swipe, dragOffset: pdfView.transform.tx)
334
+ }
335
+
336
+ /// Whether a book mode gesture may start. A pan starts only when it's mostly horizontal and the
337
+ /// turn policy allows a swipe, so while zoomed in the scroll view pans instead.
338
+ func shouldBeginBookGesture(_ gesture: UIGestureRecognizer) -> Bool {
339
+ if gesture === bookPanGesture, let pan = gesture as? UIPanGestureRecognizer {
340
+ let velocity = pan.velocity(in: self)
341
+ return allowsBookTurn(from: .swipe) && abs(velocity.x) > abs(velocity.y)
342
+ }
343
+ if gesture === bookTapGesture {
344
+ return allowsBookTurn(from: .edgeTap)
345
+ }
346
+ if gesture === bookEdgeDoubleTapGesture {
347
+ return bookEdgeTurn(at: gesture.location(in: self)) != nil
348
+ }
349
+ return true
350
+ }
351
+
352
+ /// Whether `other` has to wait for `gesture` to fail: PDFKit's own double-tap zoom waits for
353
+ /// the edge double-tap, so a double-tap zooms only in the middle region.
354
+ func bookGesture(_ gesture: UIGestureRecognizer, isRequiredToFailBy other: UIGestureRecognizer) -> Bool {
355
+ guard gesture === bookEdgeDoubleTapGesture, other !== gesture,
356
+ let tap = other as? UITapGestureRecognizer else { return false }
357
+ return tap.numberOfTapsRequired >= 2
358
+ }
359
+
360
+ // MARK: - Gestures
361
+
362
+ private func installBookGestures() {
363
+ guard bookTapGesture == nil else { return }
364
+ let delegate = BookGestureDelegate(view: self)
365
+ bookGestureDelegate = delegate
366
+
367
+ let tap = UITapGestureRecognizer(target: self, action: #selector(handleBookTapGesture(_:)))
368
+ tap.delegate = delegate
369
+ pdfView.addGestureRecognizer(tap)
370
+ bookTapGesture = tap
371
+
372
+ let edgeDoubleTap = UITapGestureRecognizer(
373
+ target: self,
374
+ action: #selector(handleBookEdgeDoubleTapGesture(_:))
375
+ )
376
+ edgeDoubleTap.numberOfTapsRequired = 2
377
+ edgeDoubleTap.delegate = delegate
378
+ pdfView.addGestureRecognizer(edgeDoubleTap)
379
+ bookEdgeDoubleTapGesture = edgeDoubleTap
380
+
381
+ let pan = UIPanGestureRecognizer(target: self, action: #selector(handleBookPanGesture(_:)))
382
+ pan.maximumNumberOfTouches = 1
383
+ pan.delegate = delegate
384
+ pdfView.addGestureRecognizer(pan)
385
+ bookPanGesture = pan
386
+ }
387
+
388
+ private func removeBookGestures() {
389
+ finishBookAnimation()
390
+ pdfView.transform = .identity
391
+ if let tap = bookTapGesture {
392
+ pdfView.removeGestureRecognizer(tap)
393
+ bookTapGesture = nil
394
+ }
395
+ if let pan = bookPanGesture {
396
+ pdfView.removeGestureRecognizer(pan)
397
+ bookPanGesture = nil
398
+ }
399
+ if let edgeDoubleTap = bookEdgeDoubleTapGesture {
400
+ pdfView.removeGestureRecognizer(edgeDoubleTap)
401
+ bookEdgeDoubleTapGesture = nil
402
+ }
403
+ bookGestureDelegate = nil
404
+ }
405
+ }
406
+
407
+ /// Gates the book mode tap and pan with the turn policy, and lets them run alongside PDFKit's
408
+ /// own gestures. Kept apart from the view's delegate so the markup gestures are unaffected.
409
+ final class BookGestureDelegate: NSObject, UIGestureRecognizerDelegate {
410
+ private weak var view: ExpoPdfMarkupView?
411
+
412
+ init(view: ExpoPdfMarkupView) {
413
+ self.view = view
414
+ }
415
+
416
+ func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
417
+ view?.shouldBeginBookGesture(gestureRecognizer) ?? false
418
+ }
419
+
420
+ func gestureRecognizer(
421
+ _: UIGestureRecognizer,
422
+ shouldRecognizeSimultaneouslyWith _: UIGestureRecognizer
423
+ ) -> Bool {
424
+ true
425
+ }
426
+
427
+ func gestureRecognizer(
428
+ _ gestureRecognizer: UIGestureRecognizer,
429
+ shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer
430
+ ) -> Bool {
431
+ view?.bookGesture(gestureRecognizer, isRequiredToFailBy: otherGestureRecognizer) ?? false
432
+ }
433
+
434
+ func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
435
+ if let view, gestureRecognizer === view.bookTapGesture {
436
+ view.bookTapCount = touch.tapCount
437
+ }
438
+ return true
439
+ }
440
+ }
441
+
442
+ extension UIResponder {
443
+ @MainActor private weak static var probedFirstResponder: UIResponder?
444
+
445
+ /// The app's current first responder, if any, found by sending an action down the responder chain.
446
+ @MainActor static var currentFirstResponder: UIResponder? {
447
+ probedFirstResponder = nil
448
+ UIApplication.shared.sendAction(#selector(probeFirstResponder), to: nil, from: nil, for: nil)
449
+ return probedFirstResponder
450
+ }
451
+
452
+ @objc private func probeFirstResponder() {
453
+ UIResponder.probedFirstResponder = self
454
+ }
455
+ }