@tobyt/expo-pdf-markup 2.0.0 → 2.1.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.
- package/CHANGELOG.md +15 -0
- package/README.md +58 -0
- package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationModel.kt +12 -0
- package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationSerializer.kt +92 -15
- package/android/src/main/java/dev/terhoeven/expopdfmarkup/AnnotationsChangeEmitter.kt +31 -0
- package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupModule.kt +4 -0
- package/android/src/main/java/dev/terhoeven/expopdfmarkup/ExpoPdfMarkupView.kt +10 -13
- package/build/ExpoPdfMarkup.types.d.ts +24 -0
- package/build/ExpoPdfMarkup.types.d.ts.map +1 -1
- package/build/ExpoPdfMarkup.types.js.map +1 -1
- package/build/ExpoPdfMarkupView.web.d.ts.map +1 -1
- package/build/ExpoPdfMarkupView.web.js +5 -5
- package/build/ExpoPdfMarkupView.web.js.map +1 -1
- package/build/index.d.ts +1 -0
- package/build/index.d.ts.map +1 -1
- package/build/index.js +1 -0
- package/build/index.js.map +1 -1
- package/build/parseAnnotations.d.ts +11 -0
- package/build/parseAnnotations.d.ts.map +1 -0
- package/build/parseAnnotations.js +49 -0
- package/build/parseAnnotations.js.map +1 -0
- package/build/web/annotationUtils.d.ts +12 -3
- package/build/web/annotationUtils.d.ts.map +1 -1
- package/build/web/annotationUtils.js +57 -12
- package/build/web/annotationUtils.js.map +1 -1
- package/fixtures/annotations-v1-array.json +124 -0
- package/fixtures/ink-cleanup-expected-array.json +95 -0
- package/fixtures/ink-cleanup-expected-object.json +95 -0
- package/fixtures/ink-cleanup-input.json +99 -0
- package/ios/AnnotationModels.swift +159 -0
- package/ios/AnnotationSerializer.swift +4 -2
- package/ios/ExpoPdfMarkupModule.swift +4 -0
- package/ios/ExpoPdfMarkupView.swift +8 -2
- package/ios/Tests/AnnotationCoordinateTests.swift +87 -0
- package/ios/Tests/AnnotationSerializerTests.swift +158 -1
- package/ios/Tests/BookModeTests.swift +11 -7
- package/ios/Tests/ExpoPdfMarkupViewTests.swift +122 -0
- package/package.json +40 -25
- package/src/ExpoPdfMarkup.types.ts +26 -0
- package/src/ExpoPdfMarkupView.web.tsx +5 -4
- package/src/index.ts +1 -0
- package/src/parseAnnotations.ts +52 -0
- package/src/web/annotationUtils.ts +70 -11
- package/docs/agents/domain.md +0 -51
- package/docs/agents/issue-tracker.md +0 -46
- package/docs/agents/triage-labels.md +0 -15
- package/tsconfig.test.json +0 -10
|
@@ -47,6 +47,10 @@ struct AnnotationModel: Codable, Equatable {
|
|
|
47
47
|
var createdAt: Double?
|
|
48
48
|
var text: String?
|
|
49
49
|
|
|
50
|
+
enum CodingKeys: String, CodingKey {
|
|
51
|
+
case id, type, page, color, lineWidth, alpha, paths, bounds, contents, fontSize, fontFamily, createdAt, text
|
|
52
|
+
}
|
|
53
|
+
|
|
50
54
|
var decodedPaths: [[AnnotationPoint]] {
|
|
51
55
|
guard let paths else { return [] }
|
|
52
56
|
return paths.map { path in
|
|
@@ -66,6 +70,161 @@ struct AnnotationModel: Codable, Equatable {
|
|
|
66
70
|
}
|
|
67
71
|
}
|
|
68
72
|
|
|
73
|
+
extension AnnotationModel {
|
|
74
|
+
/// Decodes `paths` one ink stroke and one ink point at a time, so an array-form point
|
|
75
|
+
/// (`[x, y]`), a malformed point or a stroke that isn't an array never rejects the whole
|
|
76
|
+
/// annotation set: malformed strokes and points are skipped.
|
|
77
|
+
init(from decoder: Decoder) throws {
|
|
78
|
+
let container = try decoder.container(keyedBy: CodingKeys.self)
|
|
79
|
+
id = try container.decode(String.self, forKey: .id)
|
|
80
|
+
type = try container.decode(String.self, forKey: .type)
|
|
81
|
+
page = try container.decode(Int.self, forKey: .page)
|
|
82
|
+
color = try container.decode(String.self, forKey: .color)
|
|
83
|
+
lineWidth = try container.decodeIfPresent(CGFloat.self, forKey: .lineWidth)
|
|
84
|
+
alpha = try container.decodeIfPresent(CGFloat.self, forKey: .alpha)
|
|
85
|
+
paths = try container.decodeIfPresent([InkStrokeReader].self, forKey: .paths)?
|
|
86
|
+
.compactMap(\.points)
|
|
87
|
+
bounds = try container.decodeIfPresent(AnnotationBounds.self, forKey: .bounds)
|
|
88
|
+
contents = try container.decodeIfPresent(String.self, forKey: .contents)
|
|
89
|
+
fontSize = try container.decodeIfPresent(CGFloat.self, forKey: .fontSize)
|
|
90
|
+
fontFamily = try container.decodeIfPresent(String.self, forKey: .fontFamily)
|
|
91
|
+
createdAt = try container.decodeIfPresent(Double.self, forKey: .createdAt)
|
|
92
|
+
text = try container.decodeIfPresent(String.self, forKey: .text)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
extension AnnotationModel {
|
|
97
|
+
/// Writes every field as the synthesised encoder did, except that an ink annotation's points
|
|
98
|
+
/// are cleaned up and follow the ink point format (see `InkPointCleanup`). Paths on any other
|
|
99
|
+
/// type are written exactly as before. The model itself keeps full precision.
|
|
100
|
+
func encode(to encoder: Encoder) throws {
|
|
101
|
+
var container = encoder.container(keyedBy: CodingKeys.self)
|
|
102
|
+
try container.encode(id, forKey: .id)
|
|
103
|
+
try container.encode(type, forKey: .type)
|
|
104
|
+
try container.encode(page, forKey: .page)
|
|
105
|
+
try container.encode(color, forKey: .color)
|
|
106
|
+
try container.encodeIfPresent(lineWidth, forKey: .lineWidth)
|
|
107
|
+
try container.encodeIfPresent(alpha, forKey: .alpha)
|
|
108
|
+
if type == "ink", paths != nil {
|
|
109
|
+
try container.encode(InkPointCleanup.cleanedPaths(decodedPaths), forKey: .paths)
|
|
110
|
+
} else {
|
|
111
|
+
try container.encodeIfPresent(paths, forKey: .paths)
|
|
112
|
+
}
|
|
113
|
+
try container.encodeIfPresent(bounds, forKey: .bounds)
|
|
114
|
+
try container.encodeIfPresent(contents, forKey: .contents)
|
|
115
|
+
try container.encodeIfPresent(fontSize, forKey: .fontSize)
|
|
116
|
+
try container.encodeIfPresent(fontFamily, forKey: .fontFamily)
|
|
117
|
+
try container.encodeIfPresent(createdAt, forKey: .createdAt)
|
|
118
|
+
try container.encodeIfPresent(text, forKey: .text)
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/// How ink points are written: object form `{"x": …, "y": …}` (the default) or array form `[x, y]`.
|
|
123
|
+
enum InkPointFormat: String {
|
|
124
|
+
case object
|
|
125
|
+
case array
|
|
126
|
+
|
|
127
|
+
static let userInfoKey = CodingUserInfoKey(rawValue: "inkPointFormat")!
|
|
128
|
+
|
|
129
|
+
/// Maps the `inkPointFormat` view prop; anything other than `"array"` is object form.
|
|
130
|
+
init(prop: String?) {
|
|
131
|
+
self = prop == "array" ? .array : .object
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/// Ink point clean-up applied only when an annotation set is written (same rule on every
|
|
136
|
+
/// platform): each coordinate is rounded to 0.1 pt (the double `value * 10` rounded to the
|
|
137
|
+
/// nearest integer, ties away from zero), consecutive duplicates within a stroke are dropped,
|
|
138
|
+
/// and a stroke of 2+ points that collapses to one point is written as that point twice.
|
|
139
|
+
enum InkPointCleanup {
|
|
140
|
+
/// A rounded coordinate held as the integer number of tenths, so it is written from the
|
|
141
|
+
/// integer (`307.7`, `100`, `-1.3`, never `.0`, `-0` or long trailing digits).
|
|
142
|
+
struct Coordinate: Encodable, Equatable {
|
|
143
|
+
let tenths: Int
|
|
144
|
+
|
|
145
|
+
init(_ value: CGFloat) {
|
|
146
|
+
let rounded = Int((Double(value) * 10).rounded())
|
|
147
|
+
tenths = rounded == 0 ? 0 : rounded
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
func encode(to encoder: Encoder) throws {
|
|
151
|
+
var container = encoder.singleValueContainer()
|
|
152
|
+
if tenths % 10 == 0 {
|
|
153
|
+
try container.encode(tenths / 10)
|
|
154
|
+
} else {
|
|
155
|
+
// Decimal is written from its exact digits, unlike Double which JSONSerialization
|
|
156
|
+
// may print with long trailing digits.
|
|
157
|
+
try container.encode(Decimal(sign: tenths < 0 ? .minus : .plus, exponent: -1,
|
|
158
|
+
significand: Decimal(abs(tenths))))
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
struct Point: Encodable, Equatable {
|
|
164
|
+
let x: Coordinate
|
|
165
|
+
let y: Coordinate
|
|
166
|
+
|
|
167
|
+
/// Object form (`{"x": …, "y": …}`) unless the encoder asks for array form (`[x, y]`).
|
|
168
|
+
func encode(to encoder: Encoder) throws {
|
|
169
|
+
if encoder.userInfo[InkPointFormat.userInfoKey] as? InkPointFormat == .array {
|
|
170
|
+
var container = encoder.unkeyedContainer()
|
|
171
|
+
try container.encode(x)
|
|
172
|
+
try container.encode(y)
|
|
173
|
+
} else {
|
|
174
|
+
var container = encoder.container(keyedBy: InkPointKeys.self)
|
|
175
|
+
try container.encode(x, forKey: .x)
|
|
176
|
+
try container.encode(y, forKey: .y)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
static func cleanedPaths(_ paths: [[AnnotationPoint]]) -> [[Point]] {
|
|
182
|
+
paths.map(cleanedStroke)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
static func cleanedStroke(_ stroke: [AnnotationPoint]) -> [Point] {
|
|
186
|
+
var kept: [Point] = []
|
|
187
|
+
for point in stroke {
|
|
188
|
+
let rounded = Point(x: Coordinate(point.x), y: Coordinate(point.y))
|
|
189
|
+
if rounded != kept.last { kept.append(rounded) }
|
|
190
|
+
}
|
|
191
|
+
if stroke.count >= 2, kept.count == 1 { kept.append(kept[0]) }
|
|
192
|
+
return kept
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/// The keys of an ink point in object form.
|
|
197
|
+
private enum InkPointKeys: String, CodingKey { case x, y }
|
|
198
|
+
|
|
199
|
+
/// Reads one ink stroke; anything that isn't an array decodes to nil `points` instead of throwing.
|
|
200
|
+
private struct InkStrokeReader: Decodable {
|
|
201
|
+
let points: [[String: CGFloat]]?
|
|
202
|
+
|
|
203
|
+
init(from decoder: Decoder) {
|
|
204
|
+
points = (try? [InkPointReader](from: decoder))?.compactMap(\.point)
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/// Reads one ink point in object form (`{"x": …, "y": …}`) or array form (`[x, y]`), straight
|
|
209
|
+
/// into the model's object-form dictionary. Anything else decodes to a nil `point` instead of throwing.
|
|
210
|
+
private struct InkPointReader: Decodable {
|
|
211
|
+
let point: [String: CGFloat]?
|
|
212
|
+
|
|
213
|
+
init(from decoder: Decoder) {
|
|
214
|
+
if let object = try? decoder.container(keyedBy: InkPointKeys.self),
|
|
215
|
+
let x = try? object.decode(CGFloat.self, forKey: .x),
|
|
216
|
+
let y = try? object.decode(CGFloat.self, forKey: .y) {
|
|
217
|
+
point = ["x": x, "y": y]
|
|
218
|
+
} else if var array = try? decoder.unkeyedContainer(), array.count == 2,
|
|
219
|
+
let x = try? array.decode(CGFloat.self),
|
|
220
|
+
let y = try? array.decode(CGFloat.self) {
|
|
221
|
+
point = ["x": x, "y": y]
|
|
222
|
+
} else {
|
|
223
|
+
point = nil
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
69
228
|
struct AnnotationsData: Codable, Equatable {
|
|
70
229
|
let version: Int
|
|
71
230
|
let annotations: [AnnotationModel]
|
|
@@ -11,8 +11,10 @@ enum AnnotationSerializer {
|
|
|
11
11
|
return try? JSONDecoder().decode(AnnotationsData.self, from: data)
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
static func serialize(_ annotationsData: AnnotationsData) -> String? {
|
|
15
|
-
|
|
14
|
+
static func serialize(_ annotationsData: AnnotationsData, inkPointFormat: InkPointFormat = .object) -> String? {
|
|
15
|
+
let encoder = JSONEncoder()
|
|
16
|
+
encoder.userInfo[InkPointFormat.userInfoKey] = inkPointFormat
|
|
17
|
+
guard let data = try? encoder.encode(annotationsData) else { return nil }
|
|
16
18
|
return String(data: data, encoding: .utf8)
|
|
17
19
|
}
|
|
18
20
|
|
|
@@ -60,6 +60,10 @@ public class ExpoPdfMarkupModule: Module {
|
|
|
60
60
|
view.useJsTextDialog = use ?? false
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
Prop("inkPointFormat") { (view: ExpoPdfMarkupView, format: String?) in
|
|
64
|
+
view.inkPointFormat = InkPointFormat(prop: format)
|
|
65
|
+
}
|
|
66
|
+
|
|
63
67
|
Events("onPageChanged", "onLoadComplete", "onError", "onAnnotationsChanged", "onTextInputRequested")
|
|
64
68
|
}
|
|
65
69
|
}
|
|
@@ -10,7 +10,10 @@ class ExpoPdfMarkupView: ExpoView, UIGestureRecognizerDelegate {
|
|
|
10
10
|
let onTextInputRequested = EventDispatcher()
|
|
11
11
|
|
|
12
12
|
private var currentSource: String?
|
|
13
|
-
|
|
13
|
+
/// The annotation set last loaded or sent in `onAnnotationsChanged`, used to skip reloading
|
|
14
|
+
/// the view's own write. Read-only outside the view (tests read it) so that only loading and
|
|
15
|
+
/// emitting can change it.
|
|
16
|
+
private(set) var currentAnnotationsJSON: String?
|
|
14
17
|
private(set) var currentMode: String = "none"
|
|
15
18
|
var annotationColor: String = "#FF0000" {
|
|
16
19
|
didSet {
|
|
@@ -21,6 +24,8 @@ class ExpoPdfMarkupView: ExpoView, UIGestureRecognizerDelegate {
|
|
|
21
24
|
var annotationLineWidth: CGFloat = 2.0
|
|
22
25
|
var annotationFontFamily: String?
|
|
23
26
|
var useJsTextDialog: Bool = false
|
|
27
|
+
/// How ink points are written from the next edit on; changing it writes nothing.
|
|
28
|
+
var inkPointFormat: InkPointFormat = .object
|
|
24
29
|
var stampText: String?
|
|
25
30
|
var stampSize: CGFloat = 48.0
|
|
26
31
|
|
|
@@ -217,7 +222,8 @@ class ExpoPdfMarkupView: ExpoView, UIGestureRecognizerDelegate {
|
|
|
217
222
|
}
|
|
218
223
|
|
|
219
224
|
let data = AnnotationsData(version: 1, annotations: models)
|
|
220
|
-
return AnnotationSerializer.serialize(data
|
|
225
|
+
return AnnotationSerializer.serialize(data, inkPointFormat: inkPointFormat)
|
|
226
|
+
?? "{\"version\":1,\"annotations\":[]}"
|
|
221
227
|
}
|
|
222
228
|
|
|
223
229
|
func emitAnnotationsChanged() {
|
|
@@ -187,6 +187,93 @@ final class AnnotationCoordinateTests: XCTestCase {
|
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
189
|
|
|
190
|
+
private func sharedFixtureJSON(_ name: String) throws -> String {
|
|
191
|
+
let url = try XCTUnwrap(Bundle(for: type(of: self)).url(forResource: name, withExtension: "json"))
|
|
192
|
+
return try String(contentsOf: url, encoding: .utf8)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/// What PDFKit actually holds for an annotation set: native ink points and bounds.
|
|
196
|
+
private func nativePlacement(of json: String, crop: CGRect, rotation: Int) throws -> [String] {
|
|
197
|
+
let document = try AnnotationTestFixture.document(crop: crop, rotation: rotation)
|
|
198
|
+
let page = try XCTUnwrap(document.page(at: 0))
|
|
199
|
+
let data = try XCTUnwrap(AnnotationSerializer.deserialize(from: json))
|
|
200
|
+
for model in data.annotations {
|
|
201
|
+
try page.addAnnotation(XCTUnwrap(AnnotationSerializer.toPDFAnnotation(
|
|
202
|
+
model, pageBounds: crop, pageRotation: rotation
|
|
203
|
+
)))
|
|
204
|
+
}
|
|
205
|
+
return page.annotations.map { annotation in
|
|
206
|
+
let strokes = (annotation.paths ?? []).map { path in
|
|
207
|
+
var points: [String] = []
|
|
208
|
+
path.cgPath.applyWithBlock { element in
|
|
209
|
+
let point = element.pointee.points[0]
|
|
210
|
+
points.append("\(point.x + annotation.bounds.minX),\(point.y + annotation.bounds.minY)")
|
|
211
|
+
}
|
|
212
|
+
return points.joined(separator: " ")
|
|
213
|
+
}
|
|
214
|
+
return "\(annotation.type ?? "") \(annotation.bounds) \(strokes)"
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
func testArrayFormFixturePlacesAnnotationsLikeObjectFormOnCroppedAndRotatedPages() throws {
|
|
219
|
+
let objectForm = try sharedFixtureJSON("annotations-v1")
|
|
220
|
+
let arrayForm = try sharedFixtureJSON("annotations-v1-array")
|
|
221
|
+
for rotation in [0, 90, 180, 270] {
|
|
222
|
+
let expected = try nativePlacement(of: objectForm, crop: AnnotationTestFixture.crop, rotation: rotation)
|
|
223
|
+
XCTAssertEqual(expected.count, 8)
|
|
224
|
+
XCTAssertEqual(
|
|
225
|
+
try nativePlacement(of: arrayForm, crop: AnnotationTestFixture.crop, rotation: rotation),
|
|
226
|
+
expected,
|
|
227
|
+
"rotation \(rotation)"
|
|
228
|
+
)
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
@MainActor func testArrayFormInkCanBeMovedAndErasedAndIsWrittenInObjectForm() throws {
|
|
233
|
+
let document = try AnnotationTestFixture.document()
|
|
234
|
+
let page = try XCTUnwrap(document.page(at: 0))
|
|
235
|
+
let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 400, height: 700))
|
|
236
|
+
let controller = UIViewController()
|
|
237
|
+
window.rootViewController = controller
|
|
238
|
+
window.makeKeyAndVisible()
|
|
239
|
+
let view = ExpoPdfMarkupView(appContext: nil)
|
|
240
|
+
view.frame = controller.view.bounds
|
|
241
|
+
controller.view.addSubview(view)
|
|
242
|
+
view.pdfView.document = document
|
|
243
|
+
view.layoutIfNeeded()
|
|
244
|
+
view.pdfView.layoutDocumentView()
|
|
245
|
+
view.loadAnnotations(from: """
|
|
246
|
+
{"version": 1, "annotations": [{"id": "array-ink", "type": "ink", "page": 0, "color": "#FF0000",
|
|
247
|
+
"lineWidth": 8, "paths": [[[80, 120], {"x": 130, "y": 120}, [180, 120]]], "createdAt": 123}]}
|
|
248
|
+
""")
|
|
249
|
+
view.setAnnotationMode("move")
|
|
250
|
+
let pan = CoordinateTestPan()
|
|
251
|
+
pan.suppliedLocation = view.pdfView.convert(CGPoint(x: 230, y: 200), from: page)
|
|
252
|
+
pan.suppliedState = .began
|
|
253
|
+
view.handleMovePan(pan)
|
|
254
|
+
pan.suppliedLocation = view.pdfView.convert(CGPoint(x: 250, y: 230), from: page)
|
|
255
|
+
pan.suppliedState = .changed
|
|
256
|
+
view.handleMovePan(pan)
|
|
257
|
+
pan.suppliedState = .ended
|
|
258
|
+
view.handleMovePan(pan)
|
|
259
|
+
|
|
260
|
+
let moved = view.serializeCurrentAnnotations()
|
|
261
|
+
let written = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(moved.utf8)) as? [String: Any])
|
|
262
|
+
let annotation = try XCTUnwrap((written["annotations"] as? [[String: Any]])?.first)
|
|
263
|
+
let stroke = try XCTUnwrap((annotation["paths"] as? [[Any]])?.first as? [[String: Double]])
|
|
264
|
+
XCTAssertEqual(stroke.count, 3)
|
|
265
|
+
for (point, expected) in zip(stroke, [(100.0, 150.0), (150, 150), (200, 150)]) {
|
|
266
|
+
XCTAssertEqual(try XCTUnwrap(point["x"]), expected.0, accuracy: 0.001)
|
|
267
|
+
XCTAssertEqual(try XCTUnwrap(point["y"]), expected.1, accuracy: 0.001)
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
let erased = try XCTUnwrap(view.hitTestAnnotation(at: CGPoint(x: 250, y: 230), on: page))
|
|
271
|
+
page.removeAnnotation(erased)
|
|
272
|
+
XCTAssertEqual(try XCTUnwrap(AnnotationSerializer.deserialize(from: view.serializeCurrentAnnotations()))
|
|
273
|
+
.annotations, [])
|
|
274
|
+
window.isHidden = true
|
|
275
|
+
}
|
|
276
|
+
|
|
190
277
|
@MainActor func testStampsAreVisibleInLivePdfViewBeforeAndAfterReopen() throws {
|
|
191
278
|
let document = try AnnotationTestFixture.document()
|
|
192
279
|
let page = try XCTUnwrap(document.page(at: 0))
|
|
@@ -112,7 +112,9 @@ final class AnnotationSerializerTests: XCTestCase {
|
|
|
112
112
|
XCTAssertEqual(annotation?.type, "FreeText")
|
|
113
113
|
XCTAssertEqual(annotation?.contents, "My note")
|
|
114
114
|
XCTAssertEqual(annotation?.font?.pointSize, 16.0)
|
|
115
|
-
|
|
115
|
+
// PDFKit may normalize a transparent background to no color on newer iOS versions.
|
|
116
|
+
let backgroundColor: UIColor? = annotation?.color
|
|
117
|
+
XCTAssertEqual(backgroundColor?.cgColor.alpha ?? 0, 0)
|
|
116
118
|
}
|
|
117
119
|
|
|
118
120
|
func testCreateFreeTextAnnotationExpandsNarrowBoundsToFitText() throws {
|
|
@@ -317,6 +319,161 @@ final class AnnotationSerializerTests: XCTestCase {
|
|
|
317
319
|
XCTAssertEqual(hex, "#FF0000")
|
|
318
320
|
}
|
|
319
321
|
|
|
322
|
+
// MARK: - Ink point forms
|
|
323
|
+
|
|
324
|
+
private func sharedFixture(_ name: String) throws -> AnnotationsData {
|
|
325
|
+
let url = try XCTUnwrap(Bundle(for: type(of: self)).url(forResource: name, withExtension: "json"))
|
|
326
|
+
return try XCTUnwrap(AnnotationSerializer.deserialize(from: String(contentsOf: url, encoding: .utf8)))
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
func testArrayFormFixtureDecodesToTheSameAnnotationsAsObjectFormFixture() throws {
|
|
330
|
+
XCTAssertEqual(try sharedFixture("annotations-v1-array"), try sharedFixture("annotations-v1"))
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
func testMalformedInkPointsAreSkippedAndTheRestOfTheSetLoads() throws {
|
|
334
|
+
let json = """
|
|
335
|
+
{"version": 1, "annotations": [
|
|
336
|
+
{"id": "ink", "type": "ink", "page": 0, "color": "#FF0000", "lineWidth": 2,
|
|
337
|
+
"paths": [[[1, 2], [3], [4, 5, 6], ["a", "b"], {"x": 7}, {"x": "8", "y": 9}, null, true, 10,
|
|
338
|
+
{"x": 11.5, "y": 12}, [13, 14.25]]]},
|
|
339
|
+
{"id": "hl", "type": "highlight", "page": 1, "color": "#FFCC00",
|
|
340
|
+
"bounds": {"x": 1, "y": 2, "width": 3, "height": 4}}
|
|
341
|
+
]}
|
|
342
|
+
"""
|
|
343
|
+
let data = try XCTUnwrap(AnnotationSerializer.deserialize(from: json))
|
|
344
|
+
XCTAssertEqual(data.annotations.map(\.id), ["ink", "hl"])
|
|
345
|
+
XCTAssertEqual(data.annotations[0].decodedPaths, [[
|
|
346
|
+
AnnotationPoint(x: 1, y: 2), AnnotationPoint(x: 11.5, y: 12), AnnotationPoint(x: 13, y: 14.25),
|
|
347
|
+
]])
|
|
348
|
+
XCTAssertEqual(data.annotations[1].bounds, AnnotationBounds(x: 1, y: 2, width: 3, height: 4))
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
func testAStrokeThatIsNotAnArrayIsSkippedAndTheRestOfTheSetLoads() throws {
|
|
352
|
+
let json = """
|
|
353
|
+
{"version": 1, "annotations": [
|
|
354
|
+
{"id": "ink", "type": "ink", "page": 0, "color": "#FF0000",
|
|
355
|
+
"paths": [[[1, 2]], "not a stroke", {"x": 5, "y": 6}, [{"x": 3, "y": 4}]]},
|
|
356
|
+
{"id": "hl", "type": "highlight", "page": 1, "color": "#FFCC00",
|
|
357
|
+
"bounds": {"x": 1, "y": 2, "width": 3, "height": 4}}
|
|
358
|
+
]}
|
|
359
|
+
"""
|
|
360
|
+
let data = try XCTUnwrap(AnnotationSerializer.deserialize(from: json))
|
|
361
|
+
XCTAssertEqual(data.annotations.map(\.id), ["ink", "hl"])
|
|
362
|
+
XCTAssertEqual(data.annotations[0].decodedPaths, [[AnnotationPoint(x: 1, y: 2)], [AnnotationPoint(x: 3, y: 4)]])
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
func testArrayFormInkIsWrittenBackInObjectForm() throws {
|
|
366
|
+
let data = try XCTUnwrap(AnnotationSerializer.deserialize(from: """
|
|
367
|
+
{"version": 1, "annotations": [{"id": "ink", "type": "ink", "page": 0, "color": "#FF0000",
|
|
368
|
+
"paths": [[[40, 100], {"x": 120, "y": 160}, [180, 130]]]}]}
|
|
369
|
+
"""))
|
|
370
|
+
let json = try XCTUnwrap(AnnotationSerializer.serialize(data))
|
|
371
|
+
let written = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
|
|
372
|
+
let annotation = try XCTUnwrap((written["annotations"] as? [[String: Any]])?.first)
|
|
373
|
+
let stroke = try XCTUnwrap((annotation["paths"] as? [[Any]])?.first as? [[String: Double]])
|
|
374
|
+
XCTAssertEqual(stroke, [["x": 40, "y": 100], ["x": 120, "y": 160], ["x": 180, "y": 130]])
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// MARK: - Ink clean-up when writing
|
|
378
|
+
|
|
379
|
+
private func fixtureText(_ name: String) throws -> String {
|
|
380
|
+
let url = try XCTUnwrap(Bundle(for: type(of: self)).url(forResource: name, withExtension: "json"))
|
|
381
|
+
return try String(contentsOf: url, encoding: .utf8)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
private func jsonObject(_ text: String) throws -> NSDictionary {
|
|
385
|
+
try XCTUnwrap(JSONSerialization.jsonObject(with: Data(text.utf8)) as? NSDictionary)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
func testWritingCleansUpInkExactlyAsTheSharedFixtureExpects() throws {
|
|
389
|
+
let input = try sharedFixture("ink-cleanup-input")
|
|
390
|
+
let written = try XCTUnwrap(AnnotationSerializer.serialize(input))
|
|
391
|
+
XCTAssertEqual(try jsonObject(written), try jsonObject(fixtureText("ink-cleanup-expected-object")))
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
func testWrittenInkCoordinatesHaveAtMostOneDecimalDigitAndNoTrailingZero() throws {
|
|
395
|
+
let written = try XCTUnwrap(AnnotationSerializer.serialize(sharedFixture("ink-cleanup-input")))
|
|
396
|
+
let tokens = inkCoordinateTokens(in: written)
|
|
397
|
+
XCTAssertEqual(tokens.count, 2 * 13, written)
|
|
398
|
+
for token in tokens {
|
|
399
|
+
XCTAssertNotNil(token.range(of: #"^-?(0|[1-9][0-9]*)(\.[1-9])?$"#, options: .regularExpression), token)
|
|
400
|
+
XCTAssertNotEqual(token, "-0")
|
|
401
|
+
}
|
|
402
|
+
for expected in ["307.7", "462.6", "1.8", "12.3", "100", "0", "-1.3", "0.1", "2.7", "10.1", "21", "200.2"] {
|
|
403
|
+
XCTAssertTrue(tokens.contains(expected), "missing \(expected) in \(tokens)")
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
func testWritingInArrayFormCleansUpInkExactlyAsTheSharedArrayFixtureExpects() throws {
|
|
408
|
+
let input = try sharedFixture("ink-cleanup-input")
|
|
409
|
+
let written = try XCTUnwrap(AnnotationSerializer.serialize(input, inkPointFormat: .array))
|
|
410
|
+
XCTAssertEqual(try jsonObject(written), try jsonObject(fixtureText("ink-cleanup-expected-array")))
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
func testArrayFormInkCoordinatesHaveAtMostOneDecimalDigitAndNoTrailingZero() throws {
|
|
414
|
+
let input = try sharedFixture("ink-cleanup-input")
|
|
415
|
+
let arrayForm = try XCTUnwrap(AnnotationSerializer.serialize(input, inkPointFormat: .array))
|
|
416
|
+
XCTAssertEqual(arrayInkCoordinateTokens(in: arrayForm), [
|
|
417
|
+
"307.7", "462.6", "1.8", "12.3", "100", "100", "0", "-1.3", "0.1", "2.7",
|
|
418
|
+
"50", "60", "50", "60", "5", "5", "5", "5", "10.1", "21",
|
|
419
|
+
"200.1", "301", "200.2", "300.9", "200.1", "301",
|
|
420
|
+
])
|
|
421
|
+
XCTAssertEqual(inkCoordinateTokens(in: arrayForm), [], arrayForm)
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
func testPathsOnANonInkAnnotationAreWrittenUncleanedInObjectForm() throws {
|
|
425
|
+
let model = AnnotationModel(
|
|
426
|
+
id: "hl", type: "highlight", page: 0, color: "#FFCC00",
|
|
427
|
+
paths: [[["x": 1.23456, "y": 2.5], ["x": 1.23456, "y": 2.5]]],
|
|
428
|
+
bounds: AnnotationBounds(x: 1, y: 2, width: 3, height: 4)
|
|
429
|
+
)
|
|
430
|
+
for format in [InkPointFormat.object, .array] {
|
|
431
|
+
let data = AnnotationsData(annotations: [model])
|
|
432
|
+
let json = try XCTUnwrap(AnnotationSerializer.serialize(data, inkPointFormat: format))
|
|
433
|
+
let written = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
|
|
434
|
+
let annotation = try XCTUnwrap((written["annotations"] as? [[String: Any]])?.first)
|
|
435
|
+
XCTAssertEqual(
|
|
436
|
+
annotation["paths"] as? [[[String: Double]]],
|
|
437
|
+
[[["x": 1.23456, "y": 2.5], ["x": 1.23456, "y": 2.5]]],
|
|
438
|
+
"\(format): \(json)"
|
|
439
|
+
)
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
func testInkPointFormatPropIsArrayOnlyForArray() {
|
|
444
|
+
XCTAssertEqual(InkPointFormat(prop: "array"), .array)
|
|
445
|
+
XCTAssertEqual(InkPointFormat(prop: "object"), .object)
|
|
446
|
+
XCTAssertEqual(InkPointFormat(prop: nil), .object)
|
|
447
|
+
XCTAssertEqual(InkPointFormat(prop: "tuple"), .object)
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/// Number tokens of every two-number `[x, y]` array in the written JSON, i.e. array-form ink points.
|
|
451
|
+
private func arrayInkCoordinateTokens(in json: String) -> [String] {
|
|
452
|
+
let pattern = #"\[([^,{}\[\]]+),([^,{}\[\]]+)\]"#
|
|
453
|
+
let regex = try? NSRegularExpression(pattern: pattern)
|
|
454
|
+
let range = NSRange(json.startIndex..., in: json)
|
|
455
|
+
return (regex?.matches(in: json, range: range) ?? []).flatMap { match in
|
|
456
|
+
[1, 2].compactMap { Range(match.range(at: $0), in: json).map { String(json[$0]) } }
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/// Number tokens of every two-key `{x, y}` object in the written JSON, i.e. ink points
|
|
461
|
+
/// (bounds have four keys and are not matched).
|
|
462
|
+
private func inkCoordinateTokens(in json: String) -> [String] {
|
|
463
|
+
let pattern = #"\{"[xy]":([^,{}\[\]]+),"[xy]":([^,{}\[\]]+)\}"#
|
|
464
|
+
let regex = try? NSRegularExpression(pattern: pattern)
|
|
465
|
+
let range = NSRange(json.startIndex..., in: json)
|
|
466
|
+
return (regex?.matches(in: json, range: range) ?? []).flatMap { match in
|
|
467
|
+
[1, 2].compactMap { Range(match.range(at: $0), in: json).map { String(json[$0]) } }
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
func testInMemoryInkKeepsFullPrecisionAfterWriting() throws {
|
|
472
|
+
let input = try sharedFixture("ink-cleanup-input")
|
|
473
|
+
_ = AnnotationSerializer.serialize(input)
|
|
474
|
+
XCTAssertEqual(input.annotations[0].decodedPaths[0][0], AnnotationPoint(x: 307.6921296296296, y: 462.6087962962961))
|
|
475
|
+
}
|
|
476
|
+
|
|
320
477
|
func testHexRoundTrip() {
|
|
321
478
|
let original = "#3366CC"
|
|
322
479
|
guard let color = AnnotationSerializer.colorFromHex(original) else {
|
|
@@ -154,7 +154,7 @@ final class BookModeTests: XCTestCase {
|
|
|
154
154
|
}
|
|
155
155
|
|
|
156
156
|
@MainActor func testPDFKitDoubleTapZoomWaitsForTheEdgeDoubleTap() throws {
|
|
157
|
-
let window = hostInWindow()
|
|
157
|
+
let window = try hostInWindow()
|
|
158
158
|
try loadBook()
|
|
159
159
|
let edgeDoubleTap = try XCTUnwrap(view.bookEdgeDoubleTapGesture)
|
|
160
160
|
XCTAssertEqual(edgeDoubleTap.numberOfTapsRequired, 2)
|
|
@@ -252,8 +252,12 @@ final class BookModeTests: XCTestCase {
|
|
|
252
252
|
|
|
253
253
|
// MARK: - Animation on screen
|
|
254
254
|
|
|
255
|
-
private func hostInWindow() -> UIWindow {
|
|
256
|
-
let
|
|
255
|
+
private func hostInWindow() throws -> UIWindow {
|
|
256
|
+
let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first,
|
|
257
|
+
"Native test host scene must exist")
|
|
258
|
+
let window = UIWindow(windowScene: scene)
|
|
259
|
+
window.frame = view.frame
|
|
260
|
+
window.rootViewController = UIViewController()
|
|
257
261
|
window.addSubview(view)
|
|
258
262
|
window.isHidden = false
|
|
259
263
|
view.layoutIfNeeded()
|
|
@@ -267,7 +271,7 @@ final class BookModeTests: XCTestCase {
|
|
|
267
271
|
}
|
|
268
272
|
|
|
269
273
|
func testAnimatedTurnSlidesAndSettlesOnTheNewPage() throws {
|
|
270
|
-
let window = hostInWindow()
|
|
274
|
+
let window = try hostInWindow()
|
|
271
275
|
try loadBook(startPage: 2)
|
|
272
276
|
let subviewsBefore = view.subviews.count
|
|
273
277
|
|
|
@@ -284,7 +288,7 @@ final class BookModeTests: XCTestCase {
|
|
|
284
288
|
}
|
|
285
289
|
|
|
286
290
|
func testAnimatedBounceReturnsToRest() throws {
|
|
287
|
-
let window = hostInWindow()
|
|
291
|
+
let window = try hostInWindow()
|
|
288
292
|
try loadBook(startPage: 5)
|
|
289
293
|
view.handleBookTap(at: CGPoint(x: 395, y: 300))
|
|
290
294
|
waitForAnimations()
|
|
@@ -496,7 +500,7 @@ final class BookModeTests: XCTestCase {
|
|
|
496
500
|
}
|
|
497
501
|
|
|
498
502
|
@MainActor func testBookModeTakesKeyFocusOnScreen() throws {
|
|
499
|
-
let window = hostInWindow()
|
|
503
|
+
let window = try hostInWindow()
|
|
500
504
|
window.makeKey()
|
|
501
505
|
try loadBook()
|
|
502
506
|
// PDFKit's own views may hold first responder, but none of them claims these keys.
|
|
@@ -510,7 +514,7 @@ final class BookModeTests: XCTestCase {
|
|
|
510
514
|
}
|
|
511
515
|
|
|
512
516
|
func testKeysAreIgnoredWhileATextInputHasFocus() throws {
|
|
513
|
-
let window = hostInWindow()
|
|
517
|
+
let window = try hostInWindow()
|
|
514
518
|
window.makeKey()
|
|
515
519
|
try loadBook(startPage: 2)
|
|
516
520
|
let field = UITextField(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
|