@tobyt/expo-pdf-markup 1.1.4 → 2.0.0-next.20261121193029

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 (73) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +76 -0
  3. package/android/build.gradle +3 -0
  4. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationModel.kt +12 -0
  5. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationSerializer.kt +92 -15
  6. package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationsChangeEmitter.kt +31 -0
  7. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookPager.kt +66 -0
  8. package/android/src/main/java/dev/terhoeven/expopdfmarkup/BookTurnPolicy.kt +117 -0
  9. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ContinuousPdfView.kt +370 -57
  10. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupModule.kt +8 -0
  11. package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupView.kt +105 -17
  12. package/build/ExpoPdfMarkup.types.d.ts +43 -1
  13. package/build/ExpoPdfMarkup.types.d.ts.map +1 -1
  14. package/build/ExpoPdfMarkup.types.js.map +1 -1
  15. package/build/ExpoPdfMarkupView.web.d.ts.map +1 -1
  16. package/build/ExpoPdfMarkupView.web.js +400 -69
  17. package/build/ExpoPdfMarkupView.web.js.map +1 -1
  18. package/build/index.d.ts +1 -0
  19. package/build/index.d.ts.map +1 -1
  20. package/build/index.js +1 -0
  21. package/build/index.js.map +1 -1
  22. package/build/parseAnnotations.d.ts +11 -0
  23. package/build/parseAnnotations.d.ts.map +1 -0
  24. package/build/parseAnnotations.js +49 -0
  25. package/build/parseAnnotations.js.map +1 -0
  26. package/build/web/annotationUtils.d.ts +12 -3
  27. package/build/web/annotationUtils.d.ts.map +1 -1
  28. package/build/web/annotationUtils.js +57 -12
  29. package/build/web/annotationUtils.js.map +1 -1
  30. package/build/web/bookMode.d.ts +77 -0
  31. package/build/web/bookMode.d.ts.map +1 -0
  32. package/build/web/bookMode.js +169 -0
  33. package/build/web/bookMode.js.map +1 -0
  34. package/build/web/layout.d.ts +8 -0
  35. package/build/web/layout.d.ts.map +1 -0
  36. package/build/web/layout.js +22 -0
  37. package/build/web/layout.js.map +1 -0
  38. package/build/web/types.d.ts +2 -0
  39. package/build/web/types.d.ts.map +1 -1
  40. package/build/web/types.js.map +1 -1
  41. package/docs/annotation-coordinates.md +45 -0
  42. package/docs/annotation-validation.md +117 -0
  43. package/fixtures/annotations-v1-array.json +124 -0
  44. package/fixtures/annotations-v1.json +130 -0
  45. package/fixtures/ink-cleanup-expected-array.json +95 -0
  46. package/fixtures/ink-cleanup-expected-object.json +95 -0
  47. package/fixtures/ink-cleanup-input.json +99 -0
  48. package/ios/AnnotationModels.swift +188 -30
  49. package/ios/AnnotationSerializer.swift +103 -14
  50. package/ios/ExpoPdfMarkupModule.swift +8 -0
  51. package/ios/ExpoPdfMarkupView+Book.swift +455 -0
  52. package/ios/ExpoPdfMarkupView+Ink.swift +13 -28
  53. package/ios/ExpoPdfMarkupView+Markup.swift +151 -0
  54. package/ios/ExpoPdfMarkupView+Move.swift +17 -6
  55. package/ios/ExpoPdfMarkupView.swift +84 -86
  56. package/ios/StampPDFAnnotation.swift +21 -3
  57. package/ios/Tests/AnnotationCoordinateTests.swift +424 -0
  58. package/ios/Tests/AnnotationSerializerTests.swift +201 -2
  59. package/ios/Tests/AreaMarkupTests.swift +279 -0
  60. package/ios/Tests/BookModeTests.swift +538 -0
  61. package/ios/Tests/ExpoPdfMarkupViewTests.swift +151 -0
  62. package/ios/Tests/RotatedAnnotationRenderingTests.swift +411 -0
  63. package/ios/Tests/book-sample.pdf +207 -0
  64. package/ios/Tests/single-page.pdf +52 -0
  65. package/package.json +41 -25
  66. package/src/ExpoPdfMarkup.types.ts +46 -1
  67. package/src/ExpoPdfMarkupView.web.tsx +476 -74
  68. package/src/index.ts +1 -0
  69. package/src/parseAnnotations.ts +52 -0
  70. package/src/web/annotationUtils.ts +70 -11
  71. package/src/web/bookMode.ts +186 -0
  72. package/src/web/layout.ts +30 -0
  73. package/src/web/types.ts +3 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @tobyt/expo-pdf-markup
2
2
 
3
+ ## 2.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 08d6547: Fix iOS annotation placement, moving and erasing on cropped or rotated PDFs, including stamps in thumbnails and text after reopening.
8
+
9
+ iOS annotation coordinates and `onTextInputRequested.point` now use the visible page, with `(0, 0)` at its bottom-left after rotation. Some annotations saved by older iOS versions may move; existing data is not automatically migrated. Back up saved annotations before upgrading.
10
+
11
+ Rebuild your native iOS app to apply these fixes.
12
+
13
+ - c9f8824: On iOS, drag a rectangle to highlight or underline any page, including scans. This replaces text-selection highlighting and underlining; marks no longer snap to text lines.
14
+
15
+ Switch `annotationMode` to `"none"` to scroll, zoom or turn pages by touch. Programmatic page changes and book-mode keyboard controls still work while marking.
16
+
17
+ Rebuild your native iOS app to use this behaviour.
18
+
19
+ ## 1.2.0
20
+
21
+ ### Minor Changes
22
+
23
+ - 055cf02: Add book mode. `ExpoPdfMarkupView` takes a new `displayMode` prop, `'continuous'` (the default) or `'book'`. Book mode shows one page at a time, fitted to the view, and turns pages sideways with a slide animation: swipe horizontally, tap the outer quarter of the view on either side, or press the arrow or Page Up / Page Down keys, which is what Bluetooth page-turner pedals send. Pinch to zoom still works, and while the page is zoomed in a swipe pans instead of turning. Markup tools keep working in book mode and take priority over swipes and taps, while hardware keys still turn the page. `page` and `onPageChanged` behave the same in both modes, and changing `displayMode` or rotating keeps the current page. Leaving `displayMode` out keeps today's continuous behaviour. The library adds no user-facing text: page indicators and announcements are up to your app. Book mode needs a new native build.
24
+
3
25
  ## 1.1.4
4
26
 
5
27
  ### Patch Changes
package/README.md CHANGED
@@ -136,6 +136,19 @@ annotation while the text tool is active.
136
136
 
137
137
  This module uses the [Expo Modules API](https://docs.expo.dev/modules/overview/). The `example` directory contains a test app.
138
138
 
139
+ The library development environment and example use Expo SDK 58, React 19.3, and React Native
140
+ 0.88. Use Node.js 22.13+ or 24.3+ (even-numbered releases). Install dependencies with `npm ci`
141
+ in both the root and `example` directories.
142
+
143
+ Builds and type checks use TypeScript directly. ESLint uses the public Expo flat config,
144
+ and Jest uses `jest-expo` presets for iOS, Android, Web, and Node. Test types are checked
145
+ separately with `npm run typecheck:tests`, since Jest uses Babel to transform TypeScript.
146
+ React and React DOM are pinned together for the web tests.
147
+
148
+ `expo-doctor` in `example` reports duplicate copies of native dependencies from the separate
149
+ root and example installs, including the library's peer dependencies. Their versions match;
150
+ the native builds select the example's copies. Keep both installations aligned when upgrading.
151
+
139
152
  ```sh
140
153
  # Build the module
141
154
  npm run build
@@ -160,3 +173,66 @@ npx expo start
160
173
  ## License
161
174
 
162
175
  MIT
176
+
177
+ ### Annotation coordinates and compatibility
178
+
179
+ Annotations use zero-origin visible-page coordinates, in PDF points with y increasing upward.
180
+ See [the coordinate contract and upgrade guidance](docs/annotation-coordinates.md) for cropped
181
+ and rotated pages, v1 compatibility limits, and native rebuild requirements.
182
+
183
+ ### Reading annotation JSON
184
+
185
+ Ink points in an annotation set may be stored in object form (`{"x": 40, "y": 100}`) or array
186
+ form (`[40, 100]`), and one ink stroke may mix both. Use `parseAnnotations` to read raw
187
+ annotation JSON in your own code: it accepts either form and always returns ink points as
188
+ `{ x, y }` objects, so the `AnnotationPoint` and `InkAnnotation` types are unchanged.
189
+
190
+ ```tsx
191
+ import { parseAnnotations, type InkAnnotation } from '@tobyt/expo-pdf-markup';
192
+
193
+ const { annotations } = parseAnnotations(storedJson);
194
+ const inks = annotations.filter((a): a is InkAnnotation => a.type === 'ink');
195
+ ```
196
+
197
+ Malformed ink points are skipped. `parseAnnotations` throws if the JSON can't be parsed or has
198
+ no `annotations` array, so lost data isn't mistaken for an empty set. It doesn't round values.
199
+ `AnnotationPointArray` (`[number, number]`) types raw array-form ink points.
200
+
201
+ ### Writing ink points in array form (`inkPointFormat`)
202
+
203
+ Whenever an annotation set is written, each ink coordinate is rounded to 0.1 pt and consecutive
204
+ duplicate ink points are dropped. By default ink points are still written in object form, which
205
+ every release can read. Set `inkPointFormat="array"` to write them in the shorter array form
206
+ instead; the clean-up is the same, the output is identical on iOS, Android and web, and
207
+ `version` stays at 1.
208
+
209
+ ```tsx
210
+ <ExpoPdfMarkupView
211
+ source={pdfPath}
212
+ annotations={annotations}
213
+ inkPointFormat="array"
214
+ onAnnotationsChanged={({ nativeEvent }) => setAnnotations(nativeEvent.annotations)}
215
+ />
216
+ ```
217
+
218
+ **Rollout rule:** only choose `'array'` once every version of your app that might read the
219
+ annotation set includes the release of this library with the array-form readers. Earlier
220
+ releases can't read array form: iOS rejects the whole annotation set, Android throws and web
221
+ draws `NaN`. So ship a version of your app with this release first,
222
+ and switch to `'array'` once that is the oldest version still in use.
223
+
224
+ Changing `inkPointFormat` writes nothing and doesn't fire `onAnnotationsChanged`. It applies from
225
+ the next edit, when the whole annotation set is written in the chosen form, whichever form it was
226
+ loaded in. Loading an annotation set never rewrites it.
227
+
228
+ ### Highlighting and underlining on iOS
229
+
230
+ With `annotationMode="highlight"` or `"underline"`, drag one finger to mark a rectangular area on
231
+ any page, including scanned PDFs. Highlights cover the rectangle; underlines follow its lower
232
+ edge. The tools use area selection on text-bearing pages too, without snapping to text lines.
233
+
234
+ The active tool captures touch input so marking does not scroll the page. Set
235
+ `annotationMode="none"` to scroll, pinch to zoom, or turn pages by touch, then reselect the tool.
236
+ The `page` prop and book-mode hardware keys remain available while marking; navigating cancels
237
+ an unfinished drag. Cancelling a gesture or switching tools also discards the unfinished area.
238
+ These Swift changes require a native iOS rebuild; a JavaScript-only update cannot install them.
@@ -15,6 +15,9 @@ android {
15
15
  lintOptions {
16
16
  abortOnError false
17
17
  }
18
+ sourceSets {
19
+ test.resources.srcDir '../fixtures'
20
+ }
18
21
  }
19
22
 
20
23
  dependencies {
@@ -27,3 +27,15 @@ data class AnnotationsData(
27
27
  val version: Int = 1,
28
28
  val annotations: List<AnnotationModel> = emptyList()
29
29
  )
30
+
31
+ /** How ink points are written: object form `{"x": …, "y": …}` (default) or array form `[x, y]`. */
32
+ enum class InkPointFormat {
33
+ OBJECT,
34
+ ARRAY
35
+ ;
36
+
37
+ companion object {
38
+ /** Maps the `inkPointFormat` view prop; anything other than `"array"` is object form. */
39
+ fun fromProp(value: String?): InkPointFormat = if (value == "array") ARRAY else OBJECT
40
+ }
41
+ }
@@ -20,12 +20,15 @@ object AnnotationSerializer {
20
20
  }
21
21
  }
22
22
 
23
- fun serialize(data: AnnotationsData): String {
23
+ fun serialize(
24
+ data: AnnotationsData,
25
+ inkPointFormat: InkPointFormat = InkPointFormat.OBJECT
26
+ ): String {
24
27
  val obj = JSONObject()
25
28
  obj.put("version", data.version)
26
29
  val arr = JSONArray()
27
30
  for (annotation in data.annotations) {
28
- arr.put(annotationToJson(annotation))
31
+ arr.put(annotationToJson(annotation, inkPointFormat))
29
32
  }
30
33
  obj.put("annotations", arr)
31
34
  return obj.toString()
@@ -89,19 +92,35 @@ object AnnotationSerializer {
89
92
  arr ?: return null
90
93
  val paths = mutableListOf<List<AnnotationPoint>>()
91
94
  for (i in 0 until arr.length()) {
92
- val stroke = arr.getJSONArray(i)
95
+ // A stroke that isn't an array is malformed and skipped; the rest still loads.
96
+ val stroke = arr.optJSONArray(i) ?: continue
93
97
  val points = mutableListOf<AnnotationPoint>()
94
98
  for (j in 0 until stroke.length()) {
95
- val pt = stroke.getJSONObject(j)
96
- points.add(
97
- AnnotationPoint(pt.getDouble("x").toFloat(), pt.getDouble("y").toFloat())
98
- )
99
+ readInkPoint(stroke.opt(j))?.let { points.add(it) }
99
100
  }
100
101
  paths.add(points)
101
102
  }
102
103
  return paths
103
104
  }
104
105
 
106
+ /**
107
+ * Reads one ink point in object form (`{"x": …, "y": …}`) or array form (`[x, y]`).
108
+ * Anything else is malformed and returns null, so the caller skips just that point.
109
+ */
110
+ private fun readInkPoint(value: Any?): AnnotationPoint? {
111
+ val (x, y) = when (value) {
112
+ is JSONObject -> value.opt("x") to value.opt("y")
113
+ is JSONArray -> if (value.length() == 2) value.opt(0) to value.opt(1) else return null
114
+ else -> return null
115
+ }
116
+ val xd = finiteNumber(x) ?: return null
117
+ val yd = finiteNumber(y) ?: return null
118
+ return AnnotationPoint(xd.toFloat(), yd.toFloat())
119
+ }
120
+
121
+ private fun finiteNumber(value: Any?): Double? =
122
+ (value as? Number)?.toDouble()?.takeIf { it.isFinite() }
123
+
105
124
  private fun parseBounds(obj: JSONObject?): AnnotationBounds? {
106
125
  obj ?: return null
107
126
  return AnnotationBounds(
@@ -112,7 +131,10 @@ object AnnotationSerializer {
112
131
  )
113
132
  }
114
133
 
115
- private fun annotationToJson(model: AnnotationModel): JSONObject {
134
+ private fun annotationToJson(
135
+ model: AnnotationModel,
136
+ inkPointFormat: InkPointFormat
137
+ ): JSONObject {
116
138
  val obj = JSONObject()
117
139
  obj.put("id", model.id)
118
140
  obj.put("type", model.type)
@@ -122,10 +144,12 @@ object AnnotationSerializer {
122
144
  model.alpha?.let { obj.put("alpha", it.toDouble()) }
123
145
  // Ink annotations always carry `paths`, even when empty: the JS `Annotation` type
124
146
  // declares it non-optional, so omitting the key crashes consumers that dereference it.
147
+ // Only ink points are cleaned up and follow the ink point format; any other paths are
148
+ // written as they always were.
125
149
  if (model.type == "ink") {
126
- obj.put("paths", pathsToJson(model.paths ?: emptyList()))
150
+ obj.put("paths", inkPathsToJson(model.paths ?: emptyList(), inkPointFormat))
127
151
  } else {
128
- model.paths?.let { obj.put("paths", pathsToJson(it)) }
152
+ model.paths?.let { obj.put("paths", rawPathsToJson(it)) }
129
153
  }
130
154
  model.bounds?.let { obj.put("bounds", boundsToJson(it)) }
131
155
  model.contents?.let { obj.put("contents", it) }
@@ -136,21 +160,74 @@ object AnnotationSerializer {
136
160
  return obj
137
161
  }
138
162
 
139
- private fun pathsToJson(paths: List<List<AnnotationPoint>>): JSONArray {
163
+ /**
164
+ * Writes ink strokes cleaned up: every coordinate rounded to 0.1 pt, consecutive duplicate
165
+ * points (after rounding) dropped, and a stroke that collapses from 2+ points to one kept
166
+ * as two identical points so it still draws as a dot. In-memory points are untouched.
167
+ * Each point is written in object form (`{"x": …, "y": …}`) or array form (`[x, y]`).
168
+ */
169
+ private fun inkPathsToJson(
170
+ paths: List<List<AnnotationPoint>>,
171
+ inkPointFormat: InkPointFormat
172
+ ): JSONArray {
173
+ val writePoint: (Long, Long) -> Any = when (inkPointFormat) {
174
+ InkPointFormat.OBJECT -> { x, y ->
175
+ JSONObject().put("x", tenthsToJsonNumber(x)).put("y", tenthsToJsonNumber(y))
176
+ }
177
+
178
+ InkPointFormat.ARRAY -> { x, y ->
179
+ JSONArray().put(tenthsToJsonNumber(x)).put(tenthsToJsonNumber(y))
180
+ }
181
+ }
182
+ val arr = JSONArray()
183
+ for (stroke in paths) {
184
+ val strokeArr = JSONArray()
185
+ for ((x, y) in cleanUpStroke(stroke)) strokeArr.put(writePoint(x, y))
186
+ arr.put(strokeArr)
187
+ }
188
+ return arr
189
+ }
190
+
191
+ /** Writes paths of a non-ink annotation unchanged, each point in object form. */
192
+ private fun rawPathsToJson(paths: List<List<AnnotationPoint>>): JSONArray {
140
193
  val arr = JSONArray()
141
194
  for (stroke in paths) {
142
195
  val strokeArr = JSONArray()
143
196
  for (pt in stroke) {
144
- val ptObj = JSONObject()
145
- ptObj.put("x", pt.x.toDouble())
146
- ptObj.put("y", pt.y.toDouble())
147
- strokeArr.put(ptObj)
197
+ strokeArr.put(JSONObject().put("x", pt.x.toDouble()).put("y", pt.y.toDouble()))
148
198
  }
149
199
  arr.put(strokeArr)
150
200
  }
151
201
  return arr
152
202
  }
153
203
 
204
+ /** Rounds a stroke to whole tenths of a point and drops consecutive duplicates. */
205
+ private fun cleanUpStroke(stroke: List<AnnotationPoint>): List<Pair<Long, Long>> {
206
+ val kept = mutableListOf<Pair<Long, Long>>()
207
+ for (pt in stroke) {
208
+ val rounded = toTenths(pt.x) to toTenths(pt.y)
209
+ if (kept.lastOrNull() != rounded) kept.add(rounded)
210
+ }
211
+ if (stroke.size >= 2 && kept.size == 1) kept.add(kept[0])
212
+ return kept
213
+ }
214
+
215
+ /**
216
+ * Nearest whole number of tenths, rounding the Double product with ties away from zero.
217
+ * The Float is widened to Double first; `kotlin.math.round` is half-even, so it isn't used.
218
+ */
219
+ private fun toTenths(value: Float): Long {
220
+ val scaled = value.toDouble() * 10
221
+ return (Math.signum(scaled) * Math.round(Math.abs(scaled))).toLong()
222
+ }
223
+
224
+ /**
225
+ * Whole numbers go in as Long so they print without `.0` (and negative zero as `0`);
226
+ * anything else is n / 10.0, whose shortest decimal has a single digit after the point.
227
+ */
228
+ private fun tenthsToJsonNumber(tenths: Long): Number =
229
+ if (tenths % 10 == 0L) tenths / 10 else tenths / 10.0
230
+
154
231
  private fun boundsToJson(bounds: AnnotationBounds): JSONObject {
155
232
  val obj = JSONObject()
156
233
  obj.put("x", bounds.x.toDouble())
@@ -0,0 +1,31 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ /**
4
+ * Reads the view's annotation set when it is loaded, and writes it after an edit, handing the
5
+ * JSON to [emit] (the view's `onAnnotationsChanged`). Loading never emits.
6
+ */
7
+ class AnnotationsChangeEmitter(private val emit: (String) -> Unit) {
8
+ /** Applies from the next write; setting it writes nothing by itself. */
9
+ var inkPointFormat: InkPointFormat = InkPointFormat.OBJECT
10
+
11
+ fun annotationsChanged(annotations: List<AnnotationModel>) {
12
+ emit(
13
+ AnnotationSerializer.serialize(
14
+ AnnotationsData(version = 1, annotations = annotations),
15
+ inkPointFormat
16
+ )
17
+ )
18
+ }
19
+
20
+ /**
21
+ * Reads an annotation set given to the view, keeping the last annotation with each id.
22
+ * Returns an empty list for no set, or null when [json] can't be read (keep what is shown).
23
+ * Writes nothing.
24
+ */
25
+ fun annotationsLoaded(json: String?): List<AnnotationModel>? {
26
+ if (json.isNullOrEmpty()) return emptyList()
27
+ val data = AnnotationSerializer.deserialize(json) ?: return null
28
+ val seen = mutableSetOf<String>()
29
+ return data.annotations.reversed().filter { seen.add(it.id) }.reversed()
30
+ }
31
+ }
@@ -0,0 +1,66 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ /**
4
+ * Which page book mode shows, and how a turn moves between pages. Pure Kotlin
5
+ * so the turn rules can be tested in the JVM; the view animates whatever
6
+ * [turn] returns and calls [finishSlide] when the slide has landed.
7
+ */
8
+ class BookPager(private val onPageChanged: (page: Int) -> Unit) {
9
+ sealed interface Turn {
10
+ data class Slide(val from: Int, val to: Int, val direction: BookTurnPolicy.Direction) : Turn
11
+
12
+ /** No page that way: nudge towards [direction] and spring back. Nothing wraps round. */
13
+ data class Bounce(val direction: BookTurnPolicy.Direction) : Turn
14
+ }
15
+
16
+ var pageCount = 0
17
+ private set
18
+ var currentPage = 0
19
+ private set
20
+
21
+ private var inFlight: Turn.Slide? = null
22
+
23
+ /** True while a slide has started but not landed. */
24
+ val isSliding: Boolean get() = inFlight != null
25
+
26
+ /**
27
+ * Sets the document and page without reporting a change, clamping [page]
28
+ * into the document. Used on load, mode switch, rotation and resize.
29
+ */
30
+ fun reset(pageCount: Int, page: Int) {
31
+ inFlight = null
32
+ this.pageCount = maxOf(0, pageCount)
33
+ currentPage = page.coerceIn(0, maxOf(0, this.pageCount - 1))
34
+ }
35
+
36
+ /**
37
+ * Starts a turn. A slide already in flight lands first, so rapid turns
38
+ * each count and each report once. Returns [Turn.Bounce] at either end.
39
+ */
40
+ fun turn(direction: BookTurnPolicy.Direction): Turn {
41
+ finishSlide()
42
+ val target = currentPage + direction.delta
43
+ if (target !in 0 until pageCount) return Turn.Bounce(direction)
44
+ val slide = Turn.Slide(currentPage, target, direction)
45
+ inFlight = slide
46
+ return slide
47
+ }
48
+
49
+ /** Shows [page] straight away (the `page` prop), cancelling any slide. */
50
+ fun jumpTo(page: Int): Boolean {
51
+ if (page !in 0 until pageCount) return false
52
+ inFlight = null
53
+ if (page == currentPage) return false
54
+ currentPage = page
55
+ onPageChanged(page)
56
+ return true
57
+ }
58
+
59
+ /** Lands the slide in flight, if any, and reports the new page. */
60
+ fun finishSlide() {
61
+ val slide = inFlight ?: return
62
+ inFlight = null
63
+ currentPage = slide.to
64
+ onPageChanged(currentPage)
65
+ }
66
+ }
@@ -0,0 +1,117 @@
1
+ package dev.terhoeven.expopdfmarkup
2
+
3
+ import android.view.KeyEvent
4
+
5
+ /**
6
+ * Turn decisions for book mode. Every caller is book mode only, so nothing
7
+ * here takes the display mode.
8
+ */
9
+ object BookTurnPolicy {
10
+ /** Scales within this of fit (1.0) count as "at fit", absorbing pinch rounding. */
11
+ private const val FIT_TOLERANCE = 0.01f
12
+
13
+ private const val EDGE_ZONE_FRACTION = 0.25f
14
+ private const val MIN_EDGE_ZONE_DP = 44f
15
+
16
+ /** Share of the view's width a slow swipe has to travel to turn the page. */
17
+ private const val SWIPE_TURN_FRACTION = 0.25f
18
+
19
+ enum class SwipeAction { TURN, PAN }
20
+
21
+ /** Direction of a page turn. [delta] is the change in page index. */
22
+ enum class Direction(val delta: Int) { NEXT(1), PREVIOUS(-1) }
23
+
24
+ /**
25
+ * Width of each edge tap zone: the outer quarter of the view, at least
26
+ * 44 dp, but never more than half the view so the zones can't overlap.
27
+ */
28
+ fun edgeZoneWidth(viewWidth: Float, density: Float): Float =
29
+ maxOf(viewWidth * EDGE_ZONE_FRACTION, MIN_EDGE_ZONE_DP * density)
30
+ .coerceAtMost(viewWidth / 2f)
31
+
32
+ /** The turn an edge tap at [x] asks for, or null for no turn. */
33
+ fun edgeTapTurnFor(
34
+ annotationMode: String,
35
+ scale: Float,
36
+ x: Float,
37
+ viewWidth: Float,
38
+ density: Float
39
+ ): Direction? {
40
+ if (!touchCanTurn(annotationMode, scale) || viewWidth <= 0f) return null
41
+ val zone = edgeZoneWidth(viewWidth, density)
42
+ return when {
43
+ x < zone -> Direction.PREVIOUS
44
+ x > viewWidth - zone -> Direction.NEXT
45
+ else -> null
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Whether a double-tap at [x] zooms. Where an edge tap would turn, the
51
+ * first tap of the pair has already turned the page, so the second is
52
+ * swallowed: a double-tap zooms only in the middle region, or anywhere
53
+ * while edge taps can't turn (zoomed in or with a markup tool active).
54
+ */
55
+ fun doubleTapZooms(
56
+ annotationMode: String,
57
+ scale: Float,
58
+ x: Float,
59
+ viewWidth: Float,
60
+ density: Float
61
+ ): Boolean = edgeTapTurnFor(annotationMode, scale, x, viewWidth, density) == null
62
+
63
+ /**
64
+ * Swipes and edge taps turn the page only with no markup tool active,
65
+ * while the page is not zoomed in beyond fit (scale 1).
66
+ */
67
+ fun touchCanTurn(annotationMode: String, scale: Float): Boolean =
68
+ annotationMode == "none" && scale <= 1f + FIT_TOLERANCE
69
+
70
+ /**
71
+ * The turn a released horizontal swipe asks for, or null to settle back.
72
+ * [dragX] is the finger's total horizontal travel (negative = leftwards).
73
+ * Leftwards always means next, whatever the layout direction. A fast
74
+ * fling turns in its own direction unless it flicks back against the
75
+ * drag; a slow release turns once the drag passes a quarter of the view.
76
+ */
77
+ fun swipeReleaseTurnFor(
78
+ dragX: Float,
79
+ velocityX: Float,
80
+ viewWidth: Float,
81
+ flingVelocity: Float
82
+ ): Direction? {
83
+ val fromDrag = when {
84
+ dragX <= -viewWidth * SWIPE_TURN_FRACTION -> Direction.NEXT
85
+ dragX >= viewWidth * SWIPE_TURN_FRACTION -> Direction.PREVIOUS
86
+ else -> null
87
+ }
88
+ if (kotlin.math.abs(velocityX) < flingVelocity) return fromDrag
89
+ val fromFling = if (velocityX < 0f) Direction.NEXT else Direction.PREVIOUS
90
+ val dragOpposes = (fromFling == Direction.NEXT && dragX > 0f) ||
91
+ (fromFling == Direction.PREVIOUS && dragX < 0f)
92
+ return if (dragOpposes) null else fromFling
93
+ }
94
+
95
+ /**
96
+ * The turn a hardware key (keyboard or page-turner pedal) asks for, or
97
+ * null to leave the key alone. Right, Down and Page Down go forward; Left,
98
+ * Up and Page Up go back; Space isn't mapped. Keys turn whatever the zoom
99
+ * or markup mode, but never while a text input has focus, and never with
100
+ * a modifier held.
101
+ */
102
+ fun keyTurnFor(keyCode: Int, textInputHasFocus: Boolean, hasModifiers: Boolean): Direction? {
103
+ if (textInputHasFocus || hasModifiers) return null
104
+ return when (keyCode) {
105
+ KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_PAGE_DOWN ->
106
+ Direction.NEXT
107
+
108
+ KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_PAGE_UP ->
109
+ Direction.PREVIOUS
110
+
111
+ else -> null
112
+ }
113
+ }
114
+
115
+ fun swipeActionFor(annotationMode: String, scale: Float): SwipeAction =
116
+ if (touchCanTurn(annotationMode, scale)) SwipeAction.TURN else SwipeAction.PAN
117
+ }