@tobyt/expo-pdf-markup 1.1.4 → 1.2.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 (39) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookPager.kt +66 -0
  3. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookTurnPolicy.kt +117 -0
  4. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ContinuousPdfView.kt +370 -57
  5. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupModule.kt +4 -0
  6. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupView.kt +96 -5
  7. package/build/ExpoPdfMarkup.types.d.ts +12 -0
  8. package/build/ExpoPdfMarkup.types.d.ts.map +1 -1
  9. package/build/ExpoPdfMarkup.types.js.map +1 -1
  10. package/build/ExpoPdfMarkupView.web.d.ts.map +1 -1
  11. package/build/ExpoPdfMarkupView.web.js +369 -44
  12. package/build/ExpoPdfMarkupView.web.js.map +1 -1
  13. package/build/web/bookMode.d.ts +77 -0
  14. package/build/web/bookMode.d.ts.map +1 -0
  15. package/build/web/bookMode.js +169 -0
  16. package/build/web/bookMode.js.map +1 -0
  17. package/build/web/layout.d.ts +8 -0
  18. package/build/web/layout.d.ts.map +1 -0
  19. package/build/web/layout.js +22 -0
  20. package/build/web/layout.js.map +1 -0
  21. package/build/web/types.d.ts +2 -0
  22. package/build/web/types.d.ts.map +1 -1
  23. package/build/web/types.js.map +1 -1
  24. package/docs/agents/domain.md +51 -0
  25. package/docs/agents/issue-tracker.md +46 -0
  26. package/docs/agents/triage-labels.md +15 -0
  27. package/ios/ExpoPdfMarkupModule.swift +4 -0
  28. package/ios/ExpoPdfMarkupView+Book.swift +455 -0
  29. package/ios/ExpoPdfMarkupView.swift +46 -2
  30. package/ios/Tests/BookModeTests.swift +534 -0
  31. package/ios/Tests/book-sample.pdf +207 -0
  32. package/ios/Tests/single-page.pdf +52 -0
  33. package/package.json +3 -2
  34. package/src/ExpoPdfMarkup.types.ts +13 -0
  35. package/src/ExpoPdfMarkupView.web.tsx +443 -52
  36. package/src/web/bookMode.ts +186 -0
  37. package/src/web/layout.ts +30 -0
  38. package/src/web/types.ts +3 -0
  39. package/tsconfig.test.json +10 -0
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Layout for every page. Continuous mode fits each page to the view's width. Book mode fits the
3
+ * whole page into the view, falling back to width when the height isn't known yet.
4
+ */
5
+ export function computePageMetas(sizes, viewWidth, viewHeight, displayMode, dpr) {
6
+ if (viewWidth <= 0)
7
+ return [];
8
+ return sizes.map(({ pdfWidth, pdfHeight }) => {
9
+ const widthScale = viewWidth / pdfWidth;
10
+ const scale = displayMode === 'book' && viewHeight > 0
11
+ ? Math.min(widthScale, viewHeight / pdfHeight)
12
+ : widthScale;
13
+ return {
14
+ pdfWidth,
15
+ pdfHeight,
16
+ scale,
17
+ canvasWidth: Math.round(pdfWidth * scale * dpr),
18
+ canvasHeight: Math.round(pdfHeight * scale * dpr),
19
+ };
20
+ });
21
+ }
22
+ //# sourceMappingURL=layout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"layout.js","sourceRoot":"","sources":["../../src/web/layout.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAC9B,KAAiB,EACjB,SAAiB,EACjB,UAAkB,EAClB,WAAwB,EACxB,GAAW;IAEX,IAAI,SAAS,IAAI,CAAC;QAAE,OAAO,EAAE,CAAC;IAC9B,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,EAAE,EAAE;QAC3C,MAAM,UAAU,GAAG,SAAS,GAAG,QAAQ,CAAC;QACxC,MAAM,KAAK,GACT,WAAW,KAAK,MAAM,IAAI,UAAU,GAAG,CAAC;YACtC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,UAAU,GAAG,SAAS,CAAC;YAC9C,CAAC,CAAC,UAAU,CAAC;QACjB,OAAO;YACL,QAAQ;YACR,SAAS;YACT,KAAK;YACL,WAAW,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,KAAK,GAAG,GAAG,CAAC;YAC/C,YAAY,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,GAAG,KAAK,GAAG,GAAG,CAAC;SAClD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DisplayMode } from '../ExpoPdfMarkup.types';\nimport type { PageSize, PdfPageMeta } from './types';\n\n/**\n * Layout for every page. Continuous mode fits each page to the view's width. Book mode fits the\n * whole page into the view, falling back to width when the height isn't known yet.\n */\nexport function computePageMetas(\n sizes: PageSize[],\n viewWidth: number,\n viewHeight: number,\n displayMode: DisplayMode,\n dpr: number\n): PdfPageMeta[] {\n if (viewWidth <= 0) return [];\n return sizes.map(({ pdfWidth, pdfHeight }) => {\n const widthScale = viewWidth / pdfWidth;\n const scale =\n displayMode === 'book' && viewHeight > 0\n ? Math.min(widthScale, viewHeight / pdfHeight)\n : widthScale;\n return {\n pdfWidth,\n pdfHeight,\n scale,\n canvasWidth: Math.round(pdfWidth * scale * dpr),\n canvasHeight: Math.round(pdfHeight * scale * dpr),\n };\n });\n}\n"]}
@@ -10,4 +10,6 @@ export type PdfPageMeta = {
10
10
  /** Canvas backing height in physical pixels (CSS height × devicePixelRatio) */
11
11
  canvasHeight: number;
12
12
  };
13
+ /** A page's size in PDF user-space points, as read from the document before any layout. */
14
+ export type PageSize = Pick<PdfPageMeta, 'pdfWidth' | 'pdfHeight'>;
13
15
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/web/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG;IACxB,8CAA8C;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,+CAA+C;IAC/C,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,6EAA6E;IAC7E,WAAW,EAAE,MAAM,CAAC;IACpB,+EAA+E;IAC/E,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/web/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,GAAG;IACxB,8CAA8C;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,+CAA+C;IAC/C,SAAS,EAAE,MAAM,CAAC;IAClB,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,6EAA6E;IAC7E,WAAW,EAAE,MAAM,CAAC;IACpB,+EAA+E;IAC/E,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,2FAA2F;AAC3F,MAAM,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,UAAU,GAAG,WAAW,CAAC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/web/types.ts"],"names":[],"mappings":"","sourcesContent":["export type PdfPageMeta = {\n /** PDF page width in PDF user-space points */\n pdfWidth: number;\n /** PDF page height in PDF user-space points */\n pdfHeight: number;\n /** Pixels per PDF point (containerWidth / pdfWidth) */\n scale: number;\n /** Canvas backing width in physical pixels (CSS width × devicePixelRatio) */\n canvasWidth: number;\n /** Canvas backing height in physical pixels (CSS height × devicePixelRatio) */\n canvasHeight: number;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/web/types.ts"],"names":[],"mappings":"","sourcesContent":["export type PdfPageMeta = {\n /** PDF page width in PDF user-space points */\n pdfWidth: number;\n /** PDF page height in PDF user-space points */\n pdfHeight: number;\n /** Pixels per PDF point (containerWidth / pdfWidth) */\n scale: number;\n /** Canvas backing width in physical pixels (CSS width × devicePixelRatio) */\n canvasWidth: number;\n /** Canvas backing height in physical pixels (CSS height × devicePixelRatio) */\n canvasHeight: number;\n};\n\n/** A page's size in PDF user-space points, as read from the document before any layout. */\nexport type PageSize = Pick<PdfPageMeta, 'pdfWidth' | 'pdfHeight'>;\n"]}
@@ -0,0 +1,51 @@
1
+ # Domain Docs
2
+
3
+ How the engineering skills should consume this repo's domain documentation when exploring the codebase.
4
+
5
+ ## Before exploring, read these
6
+
7
+ - **`GLOSSARY.md`** at the repo root, or
8
+ - **`GLOSSARY-MAP.md`** at the repo root if it exists: it points at one `GLOSSARY.md` per context. Read each one relevant to the topic.
9
+ - **`docs/adr/`**: read ADRs that touch the area you're about to work in. In multi-context repos, also check `src/<context>/docs/adr/` for context-scoped decisions.
10
+
11
+ If any of these files don't exist, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.
12
+
13
+ ## File structure
14
+
15
+ Single-context repo (most repos):
16
+
17
+ ```
18
+ /
19
+ ├── GLOSSARY.md
20
+ ├── docs/adr/
21
+ │ ├── 0001-event-sourced-orders.md
22
+ │ └── 0002-postgres-for-write-model.md
23
+ └── src/
24
+ ```
25
+
26
+ Multi-context repo (presence of `GLOSSARY-MAP.md` at the root):
27
+
28
+ ```
29
+ /
30
+ ├── GLOSSARY-MAP.md
31
+ ├── docs/adr/ ← system-wide decisions
32
+ └── src/
33
+ ├── ordering/
34
+ │ ├── GLOSSARY.md
35
+ │ └── docs/adr/ ← context-specific decisions
36
+ └── billing/
37
+ ├── GLOSSARY.md
38
+ └── docs/adr/
39
+ ```
40
+
41
+ ## Use the glossary's vocabulary
42
+
43
+ When your output names a domain concept (in an issue title, a refactor proposal, a hypothesis, a test name), use the term as defined in `GLOSSARY.md`. Don't drift to synonyms the glossary explicitly avoids.
44
+
45
+ If the concept you need isn't in the glossary yet, that's a signal: either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).
46
+
47
+ ## Flag ADR conflicts
48
+
49
+ If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:
50
+
51
+ > _Contradicts ADR-0007 (event-sourced orders), but worth reopening because…_
@@ -0,0 +1,46 @@
1
+ # Issue tracker: GitHub
2
+
3
+ Issues and specs for this repo live as GitHub issues. Use the `gh` CLI for all operations.
4
+
5
+ ## Conventions
6
+
7
+ - **Create an issue**: `gh issue create --title "..." --body "..."`. Use a heredoc for multi-line bodies.
8
+ - **Read an issue**: `gh issue view <number> --json number,title,body,labels,comments`.
9
+ - **List issues**: `gh issue list --state open --json number,title,body,labels,comments --jq '[.[] | {number, title, body, labels: [.labels[].name], comments: [.comments[].body]}]'` with appropriate `--label` and `--state` filters.
10
+ - **Make an issue a sub-issue of a parent**: `gh issue create --parent <parent> ...`, or `gh issue edit <parent> --add-sub-issue <child>` afterwards (`gh` 2.94+). Older `gh`: `gh api --method POST repos/<owner>/<repo>/issues/<parent>/sub_issues -F sub_issue_id=<child-db-id>` (database id, as in **Blocking** below). Without sub-issues, put `Part of #<parent>` at the top of the child body.
11
+ - **Comment on an issue**: `gh issue comment <number> --body "..."`
12
+ - **Apply / remove labels**: `gh issue edit <number> --add-label "..."` / `--remove-label "..."`
13
+ - **Close**: `gh issue close <number> --comment "..."`
14
+
15
+ Infer the repo from `git remote -v`; `gh` does this automatically when run inside a clone.
16
+
17
+ ## Pull requests as a triage surface
18
+
19
+ **PRs as a request surface: no.** _(Set to `yes` if this repo treats external PRs as feature requests; `/triage` reads this flag.)_
20
+
21
+ When set to `yes`, PRs run through the same labels and states as issues, using the `gh pr` equivalents:
22
+
23
+ - **Read a PR**: `gh pr view <number> --comments` and `gh pr diff <number>` for the diff.
24
+ - **List external PRs for triage**: `gh api --paginate 'repos/{owner}/{repo}/pulls?state=open' --jq '.[] | select(.author_association | IN("OWNER","MEMBER","COLLABORATOR") | not) | {number, title, author: .user.login, author_association, labels: [.labels[].name]}'`.
25
+ - **Comment / label / close**: `gh pr comment`, `gh pr edit --add-label`/`--remove-label`, `gh pr close`.
26
+
27
+ GitHub shares one number space across issues and PRs, so a bare `#42` may be either: resolve with `gh pr view 42` and fall back to `gh issue view 42`.
28
+
29
+ ## When a skill says "publish to the issue tracker"
30
+
31
+ Create a GitHub issue.
32
+
33
+ ## When a skill says "fetch the relevant ticket"
34
+
35
+ Read it as in **Read an issue** above.
36
+
37
+ ## Wayfinding operations
38
+
39
+ Used by `/wayfinder`. The **map** is a single issue with **child** issues as tickets.
40
+
41
+ - **Map**: a single issue labelled `wayfinder:map`, holding the Notes / Decisions-so-far / Fog body. `gh issue create --label wayfinder:map`.
42
+ - **Child ticket**: an issue linked to the map as a GitHub sub-issue (see **Make an issue a sub-issue of a parent**). Where sub-issues aren't enabled, add the child to a task list in the map body and put `Part of #<map>` at the top of the child body. Labels: `wayfinder:<type>` (`research`/`prototype`/`grilling`/`task`). Once claimed, the ticket is assigned to the driving dev.
43
+ - **Blocking**: GitHub's **native issue dependencies**, the canonical, UI-visible representation. Add an edge with `gh api --method POST repos/<owner>/<repo>/issues/<child>/dependencies/blocked_by -F issue_id=<blocker-db-id>`, where `<blocker-db-id>` is the blocker's numeric **database id** (`gh api repos/<owner>/<repo>/issues/<n> --jq .id`, _not_ the `#number` or `node_id`). GitHub reports `issue_dependencies_summary.blocked_by` (open blockers only, the live gate). Where dependencies aren't available, fall back to a `Blocked by: #<n>, #<n>` line at the top of the child body. A ticket is unblocked when every blocker is closed.
44
+ - **Frontier query**: list the map's open children (`gh issue list --state open`, scoped to the map's sub-issues / task list), drop any with an open blocker (`issue_dependencies_summary.blocked_by > 0`, or an open issue in the `Blocked by` line) or an assignee; first in map order wins.
45
+ - **Claim**: `gh issue edit <n> --add-assignee @me`, the session's first write.
46
+ - **Resolve**: `gh issue comment <n> --body "<answer>"`, then `gh issue close <n>`, then append a context pointer (gist + link) to the map's Decisions-so-far.
@@ -0,0 +1,15 @@
1
+ # Triage Labels
2
+
3
+ The skills speak in terms of five canonical triage roles. This file maps those roles to the actual label strings used in this repo's issue tracker.
4
+
5
+ | Label in mattpocock/skills | Label in our tracker | Meaning |
6
+ | -------------------------- | -------------------- | ---------------------------------------- |
7
+ | `needs-triage` | `needs-triage` | Maintainer needs to evaluate this issue |
8
+ | `needs-info` | `needs-info` | Waiting on reporter for more information |
9
+ | `ready-for-agent` | `ready-for-agent` | Fully specified, ready for an AFK agent |
10
+ | `ready-for-human` | `ready-for-human` | Requires human implementation |
11
+ | `wontfix` | `wontfix` | Will not be actioned |
12
+
13
+ When a skill mentions a role (e.g. "apply the AFK-ready triage label"), use the corresponding label string from this table.
14
+
15
+ Edit the "Label in our tracker" column to match whatever vocabulary you actually use.
@@ -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
+ }