forked from automerge/automerge-swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDocument.swift
1371 lines (1290 loc) · 58.1 KB
/
Document.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import class AutomergeUniffi.Doc
import protocol AutomergeUniffi.DocProtocol
import Foundation
/// An Automerge document that provides an interface to the document-structured data it contains.
///
/// Store your data in the document-based data structure that Automerge provides, similar to representing it with JSON.
/// Like JSON, you structure data with a combination of nested dictionaries and arrays, each of which store values or
/// other container objects.
/// For more detailed information about the types that Automerge stores, see <doc:ModelingData>.
///
/// Use methods on `Document` to save, load, fork, merge, and sync Automerge documents.
/// In addition to working with the low-level methods, this library provides ``AutomergeEncoder`` and
/// ``AutomergeDecoder``, which provide support for mapping your own `Codable` types into an Automerge document.
public final class Document: @unchecked Sendable {
private var doc: WrappedDoc
#if !os(WASI)
let lock = NSRecursiveLock()
fileprivate func lock<T>(execute work: () throws -> T) rethrows -> T {
lock.lock()
defer { lock.unlock() }
return try work()
}
#else
fileprivate func lock<T>(execute work: () throws -> T) rethrows -> T {
try work()
}
#endif
#if canImport(Combine)
private let objectDidChangeSubject: PassthroughSubject<(), Never> = .init()
/// A publisher that emits after the document has changed.
///
/// This publisher and ``objectWillChange()`` are always paired. Unlike that
/// publisher, this one fires after the document update is complete, allowing you to
/// read any changed values.
///
/// An example that uses this publisher to observe granular patch changes:
///
/// ```swift
/// var observedHeads = doc.heads()
/// doc.objectDidChange.sink {
/// let changes = doc.difference(since: observedHeads)
/// observedHeads = doc.heads()
/// if !changes.isEmpty {
/// processChanges(changes)
/// }
/// }.store(in: &cancellables)
public lazy var objectDidChange: AnyPublisher<(), Never> = {
objectDidChangeSubject.eraseToAnyPublisher()
}()
#endif
var reportingLogLevel: LogVerbosity
/// The actor ID of this document
public var actor: ActorId {
get {
lock {
ActorId(ffi: self.doc.wrapErrors { $0.actorId() })
}
}
set {
lock {
self.doc.wrapErrors { $0.setActor(actor: [UInt8](newValue.data)) }
}
}
}
/// Retrieve the current text encoding used by the document.
public var textEncoding: TextEncoding {
lock {
self.doc.wrapErrors { $0.textEncoding().textEncoding }
}
}
/// Creates an new, empty Automerge document.
/// - Parameters:
/// - textEncoding: The encoding type for text within the document. Defaults to `.unicodeCodePoint`.
/// - logLevel: The level at which to generate logs into unified logging from actions within this document.
public init(textEncoding: TextEncoding = .unicodeScalar, logLevel: LogVerbosity = .errorOnly) {
doc = WrappedDoc(Doc.newWithTextEncoding(textEncoding: textEncoding.ffi_textEncoding))
self.reportingLogLevel = logLevel
}
/// Creates a new document from the data that you provide.
///
/// Generate the data for a document by calling ``save()``,
/// The raw data format of an Automerge document is a series of changes, as such, you can concatenate multiple calls
/// of
/// ``encodeChangesSince(heads:)``, ``encodeNewChanges()``, or
/// any sequence of bytes containing valid encodings of automerge changes.
/// - Parameters:
/// - bytes: A data buffer of encoded automerge changes.
/// - logLevel: The level at which to generate logs into unified logging from actions within this document.
public init(_ bytes: Data, logLevel: LogVerbosity = .errorOnly) throws {
doc = try WrappedDoc { try Doc.load(bytes: Array(bytes)) }
self.reportingLogLevel = logLevel
}
private init(doc: Doc, logLevel: LogVerbosity = .errorOnly) {
self.doc = WrappedDoc(doc)
self.reportingLogLevel = logLevel
}
/// Set or update a value within a dictionary object you specify.
///
/// - Parameters:
/// - obj: The identifier of the dictionary object to update.
/// - key: The key of the property to update.
/// - value: The value to set for the key you provide.
///
/// If the object you update is a ``ScalarValue/Counter(_:)``, calling this function uniformly sets the value
/// and ignores any previous increments or decrements of the value. If you intent to update the counter by a fixed
/// amount,
/// use the method ``increment(obj:key:by:)`` instead.
public func put(obj: ObjId, key: String, value: ScalarValue) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.putInMap(obj: obj.bytes, key: key, value: value.toFfi())
}
}
}
/// Set or update a value within an array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object to update.
/// - index: The index value of the array to update.
/// - value: The value to set for the index you provide.
///
/// If the index position doesn't yet exist within the array, this method will throw an error.
/// To add an object that extends the array, use the method ``insert(obj:index:value:)``
///
/// If the object you update is a ``ScalarValue/Counter(_:)``, calling this function uniformly sets the value
/// and ignores any previous increments or decrements of the value. If you intent to update the counter by a fixed
/// amount,
/// use the method ``increment(obj:key:by:)`` instead.
public func put(obj: ObjId, index: UInt64, value: ScalarValue) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.putInList(obj: obj.bytes, index: index, value: value.toFfi())
}
}
}
/// Set or update an object within a dictionary object you specify.
///
/// - Parameters:
/// - obj: The identifier of the dictionary object to update.
/// - key: The key of the property to update.
/// - ty: The type of object to add to the dictionary.
/// - Returns: The object Id that references the object added.
public func putObject(obj: ObjId, key: String, ty: ObjType) throws -> ObjId {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
return try self.doc.wrapErrors {
try ObjId(bytes: $0.putObjectInMap(obj: obj.bytes, key: key, objType: ty.toFfi()))
}
}
}
/// Set or update an object within an array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object to update.
/// - index: The index value of the array to update.
/// - ty: The type of object to add to the array.
/// - Returns: The object Id that references the object added.
///
/// If the index position doesn't yet exist within the array, this method will throw an error.
/// To add an object that extends the array, use the method ``insertObject(obj:index:ty:)``.
public func putObject(obj: ObjId, index: UInt64, ty: ObjType) throws -> ObjId {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
return try self.doc.wrapErrors {
try ObjId(bytes: $0.putObjectInList(obj: obj.bytes, index: index, objType: ty.toFfi()))
}
}
}
/// Insert a value, at the index you provide, into the array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object to update.
/// - index: The index value of the array to update.
/// - value: The value to insert for the index you provide.
public func insert(obj: ObjId, index: UInt64, value: ScalarValue) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.insertInList(obj: obj.bytes, index: index, value: value.toFfi())
}
}
}
/// Insert an object, at the index you provide, into the array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object to update.
/// - index: The index value of the array to update.
/// - ty: The type of object to add to the array.
/// - Returns: The object Id that references the object added.
///
/// This method extends the array by inserting a new object.
/// If you want to change an existing index, use the ``putObject(obj:index:ty:)`` to put in an object or
/// ``put(obj:index:value:)`` to put in a value.
public func insertObject(obj: ObjId, index: UInt64, ty: ObjType) throws -> ObjId {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
return try self.doc.wrapErrors {
try ObjId(bytes: $0.insertObjectInList(obj: obj.bytes, index: index, objType: ty.toFfi()))
}
}
}
/// Deletes the key you provide, and its associated value or object, from the dictionary object you specify.
/// - Parameters:
/// - obj: The identifier of the dictionary to update.
/// - key: The key to delete.
public func delete(obj: ObjId, key: String) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.deleteInMap(obj: obj.bytes, key: key)
}
}
}
/// Deletes the object or value at the index you provide from the array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array to update.
/// - index: The index position to remove.
///
/// This method shrinks the length of the array object.
public func delete(obj: ObjId, index: UInt64) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.deleteInList(obj: obj.bytes, index: index)
}
}
}
/// Increment or decrement the counter referenced by the key you provide in the dictionary object you specify.
///
/// - Parameters:
/// - obj: The identifier of the dictionary object that holds the counter.
/// - key: The key in the dictionary object that references the counter.
/// - by: The amount to increment, or decrement, the counter.
public func increment(obj: ObjId, key: String, by: Int64) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.incrementInMap(obj: obj.bytes, key: key, by: by)
}
}
}
/// Increment or decrement a counter refrerenced at the index you provide in the array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object that holds the counter.
/// - index: The index position in the array object that references the counter.
/// - by: The amount to increment, or decrement, the counter.
public func increment(obj: ObjId, index: UInt64, by: Int64) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.incrementInList(obj: obj.bytes, index: index, by: by)
}
}
}
/// Get the value of the key you provide from the dictionary object you specify.
///
/// - Parameters:
/// - obj: The identifier of the dictionary object.
/// - key: The key within the dictionary.
/// - Returns: The value of the key, or `nil` if the key doesn't exist in the dictionary.
///
/// Inspect the ``Value`` returned to determine if the value represents an object or a scalar value.
///
/// > Tip: Note that if there are multiple conflicting values this method
/// will return one of them arbitrarily (but deterministically). If you
/// need all the conflicting values see ``getAll(obj:key:)``
public func get(obj: ObjId, key: String) throws -> Value? {
try lock {
let val = try self.doc.wrapErrors { try $0.getInMap(obj: obj.bytes, key: key) }
return val.map(Value.fromFfi)
}
}
/// Get the value at the index position you provide from the array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object.
/// - index: The index position within the array.
/// - Returns: The value of the key, or `nil` if the key doesn't exist in the dictionary.
///
/// If you request a index beyond the bounds of the array, this method throws an error.
///
/// > Tip: Note that if there are multiple conflicting values this method
/// will return one of them arbitrarily (but deterministically). If you
/// need all the conflicting values see ``getAll(obj:index:)``
public func get(obj: ObjId, index: UInt64) throws -> Value? {
try lock {
let val = try self.doc.wrapErrors { try $0.getInList(obj: obj.bytes, index: index) }
return val.map(Value.fromFfi)
}
}
/// Get the set of possibly conflicting values at the key you provide for the dictionary object that you specify.
///
/// - Parameters:
/// - obj: The identifier of the dictionary object.
/// - key: The key within the dictionary.
/// - Returns: A set of value objects.
public func getAll(obj: ObjId, key: String) throws -> Set<Value> {
try lock {
let vals = try self.doc.wrapErrors { try $0.getAllInMap(obj: obj.bytes, key: key) }
return Set(vals.map { Value.fromFfi(value: $0) })
}
}
/// Get the set of possibly conflicting values at the index you provide for the array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object.
/// - index: The index position within the array.
/// - Returns: A set of the values at that index.
///
/// If you request a index beyond the bounds of the array, this method throws an error.
public func getAll(obj: ObjId, index: UInt64) throws -> Set<Value> {
try lock {
let vals = try self.doc.wrapErrors { try $0.getAllInList(obj: obj.bytes, index: index) }
return Set(vals.map { Value.fromFfi(value: $0) })
}
}
/// Get the historical value of the key you provide, in the dictionary object and point in time you specify.
///
/// - Parameters:
/// - obj: The identifier of the dictionary object.
/// - key: The key within the dictionary.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: The value of the key at the point in time you provide, or `nil` if the key doesn't exist in the
/// dictionary.
///
/// Use the method ``heads()`` to capture a specific point in time in order to use this method.
///
/// > Tip: Note that if there are multiple conflicting values this method
/// will return one of them arbitrarily (but deterministically). If you
/// need all the conflicting values see ``getAllAt(obj:key:heads:)``
public func getAt(obj: ObjId, key: String, heads: Set<ChangeHash>) throws
-> Value?
{
try lock {
let val = try self.doc.wrapErrors {
try $0.getAtInMap(obj: obj.bytes, key: key, heads: heads.map(\.bytes))
}
return val.map(Value.fromFfi)
}
}
/// Get the historical value at of the index you provide in the array object and point in time you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object.
/// - index: The index position within the array.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: The value of the index at the point in time you provide, or `nil` if the value doesn't exist.
///
/// Use the method ``heads()`` to capture a specific point in time in order to use this method.
///
/// > Tip: Note that if there are multiple conflicting values this method
/// will return one of them arbitrarily (but deterministically). If you
/// need all the conflicting values see ``getAllAt(obj:index:heads:)``
public func getAt(obj: ObjId, index: UInt64, heads: Set<ChangeHash>) throws
-> Value?
{
try lock {
let val = try self.doc.wrapErrors {
try $0.getAtInList(obj: obj.bytes, index: index, heads: heads.map(\.bytes))
}
return val.map(Value.fromFfi)
}
}
/// Get the the historical set of possibly conflicting values of the key you provide, in the dictionary object and
/// point in time you specify.
///
/// - Parameters:
/// - obj: The identifier of the dictionary object.
/// - key: The key within the dictionary.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: The set of value for the key at the point in time you provide, or `nil` if the key doesn't exist in
/// the dictionary.
///
/// Use the method ``heads()`` to capture a specific point in time in order to use this method.
public func getAllAt(obj: ObjId, key: String, heads: Set<ChangeHash>) throws
-> Set<Value>
{
try lock {
let vals = try self.doc.wrapErrors {
try $0.getAllAtInMap(obj: obj.bytes, key: key, heads: heads.map(\.bytes))
}
return Set(vals.map { Value.fromFfi(value: $0) })
}
}
/// Get the historical value at of the index you provide, in the array object and point of time you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object.
/// - index: The index position within the array.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: The set of possibly conflicting values of the index at the point in time you provide.
///
/// Use the method ``heads()`` to capture a specific point in time in order to use this method.
public func getAllAt(obj: ObjId, index: UInt64, heads: Set<ChangeHash>)
throws -> Set<Value>
{
try lock {
let vals = try self.doc.wrapErrors {
try $0.getAllAtInList(obj: obj.bytes, index: index, heads: heads.map(\.bytes))
}
return Set(vals.map { Value.fromFfi(value: $0) })
}
}
/// Get a list of all the current keys available for the dictionary object you specify.
///
/// - Parameter obj: The identifier of the dictionary object.
/// - Returns: The keys for that dictionary.
public func keys(obj: ObjId) -> [String] {
lock {
self.doc.wrapErrors { $0.mapKeys(obj: obj.bytes) }
}
}
/// Get a historical list of the keys available for the dictionary object and point in time you specify.
///
/// - Parameters:
/// - obj: The identifier of the dictionary object.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: The set of keys for the dictionary at the point in time you specify.
///
/// Use the method ``heads()`` to capture a specific point in time in order to use this method.
public func keysAt(obj: ObjId, heads: Set<ChangeHash>) -> [String] {
lock {
self.doc.wrapErrors { $0.mapKeysAt(obj: obj.bytes, heads: heads.map(\.bytes)) }
}
}
/// Get a list of all the current values for the array or dictionary object you specify.
///
/// - Parameter obj: The identifier of an array or dictionary object.
/// - Returns: For an array object, the list of all current values.
/// For a dictionary object, the list of the values for all the keys.
public func values(obj: ObjId) throws -> [Value] {
try lock {
let vals = try self.doc.wrapErrors { try $0.values(obj: obj.bytes) }
return vals.map { Value.fromFfi(value: $0) }
}
}
/// Get a historical list of the values for the array or dictionary object and point in time you specify.
///
/// - Parameters:
/// - obj: The identifier of an array or dictionary object.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: For an array object, the list of all current values.
/// For a dictionary object, the list of the values for all the keys.
///
/// Use the method ``heads()`` to capture a specific point in time in order to use this method.
public func valuesAt(obj: ObjId, heads: Set<ChangeHash>) throws -> [Value] {
try lock {
let vals = try self.doc.wrapErrors {
try $0.valuesAt(obj: obj.bytes, heads: heads.map(\.bytes))
}
return vals.map { Value.fromFfi(value: $0) }
}
}
/// Get a list of the current key and values from the dictionary object you specify.
///
/// - Parameter obj: The identifier of the dictionary object.
/// - Returns: An array of `(String, Value)` that represents the key and value combinations of the dictionary
/// object.
public func mapEntries(obj: ObjId) throws -> [(String, Value)] {
try lock {
let entries = try self.doc.wrapErrors { try $0.mapEntries(obj: obj.bytes) }
return entries.map { ($0.key, Value.fromFfi(value: $0.value)) }
}
}
/// Get a historical list of the keys and values from the dictionary object and point in time you specify.
///
/// - Parameter obj: The identifier of the dictionary object.
/// - Parameter heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: An array of `(String, Value)` that represents the key and value combinations of the dictionary
/// object.
public func mapEntriesAt(obj: ObjId, heads: Set<ChangeHash>) throws -> [(
String, Value
)] {
try lock {
let entries = try self.doc.wrapErrors {
try $0.mapEntriesAt(obj: obj.bytes, heads: heads.map(\.bytes))
}
return entries.map { ($0.key, Value.fromFfi(value: $0.value)) }
}
}
/// Returns the current length of the array, dictionary, or text object you specify.
///
/// - Parameter obj: The identifier of an array, dictionary, or text object.
public func length(obj: ObjId) -> UInt64 {
lock {
self.doc.wrapErrors { $0.length(obj: obj.bytes) }
}
}
/// Returns the historical length of the array, dictionary, or text object and point in time you specify.
///
/// - Parameters:
/// - obj: The identifier of an array, dictionary, or text object.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
public func lengthAt(obj: ObjId, heads: Set<ChangeHash>) -> UInt64 {
lock {
self.doc.wrapErrors { $0.lengthAt(obj: obj.bytes, heads: heads.map(\.bytes)) }
}
}
/// Returns the object type for the object Id that you provide.
///
/// - Parameter obj: The identifier of an array, dictionary, or text object.
public func objectType(obj: ObjId) -> ObjType {
lock {
self.doc.wrapErrors {
ObjType.fromFfi(ty: $0.objectType(obj: obj.bytes))
}
}
}
/// Get the current value of the text object you specify.
///
/// - Parameter obj: The identifier of a text object.
/// - Returns: The current string value that the text object contains.
public func text(obj: ObjId) throws -> String {
try lock {
try self.doc.wrapErrors { try $0.text(obj: obj.bytes) }
}
}
/// Get the historical value of the text object and point in time you specify.
///
/// - Parameters:
/// - obj: The identifier of a text object.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: The string value that the text object contains at the point in time you specify.
public func textAt(obj: ObjId, heads: Set<ChangeHash>) throws -> String {
try lock {
try self.doc.wrapErrors { try $0.textAt(obj: obj.bytes, heads: heads.map(\.bytes)) }
}
}
/// Establish a cursor at the position you specify in the list or text object you provide.
///
/// In collaborative applications, maintaining stable cursor positions is crucial. Traditional index-based
/// positions can become outdated due to document modifications. This method ensures the cursor stays
/// correctly anchored regardless of changes.
///
/// `Cursor` provides a reliable way to track positions over time without being affected by document changes.
/// The cursor remains anchored to the following character, and if placed at the end of the document,
/// it will persistently stay attached to the end.
///
/// ```swift
/// "ABC" // scenario
/// "A|BC" // set cursor at `1`, cursor is attached to `B`
/// "AZ|BC" // insert `Z` at `1`
/// ```
///
/// To retrieve the original absolute index-based positions, use:
/// - ``position(obj:cursor:)``
/// - ``position(obj:cursor:heads:)``
///
/// - Parameters:
/// - obj: The object identifier of the list or text object.
/// - position: The index position in the list, or index for a text object based on ``TextEncoding``.
/// When using a position equal to or greater than the current length of the object,
/// the cursor will track the end of the document as it changes.
/// - Returns: A cursor that references the position you specified.
///
/// ### See Also
/// ``cursor(obj:position:heads:)``
///
public func cursor(obj: ObjId, position: UInt64) throws -> Cursor {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
return try Cursor(bytes: self.doc.wrapErrors { try $0.cursor(obj: obj.bytes, position: position) })
}
}
/// Establish a cursor at the position and point of time you specify in the list or text object you provide.
///
/// In collaborative applications, maintaining stable cursor positions is crucial. Traditional index-based
/// positions can become outdated due to document modifications. This method ensures the cursor stays
/// correctly anchored regardless of changes.
///
/// `Cursor` provides a reliable way to track positions over time without being affected by document changes.
/// The cursor remains anchored to the following character, and if placed at the end of the document,
/// it will persistently stay attached to the end.
///
/// ```swift
/// "ABC" // scenario
/// "A|BC" // set cursor at `1`, cursor is attached to `B`
/// "AZ|BC" // insert `Z` at `1`
/// ```
///
/// To retrieve the original absolute index-based positions, use:
/// - ``position(obj:cursor:)``
/// - ``position(obj:cursor:heads:)``
///
/// - Parameters:
/// - obj: The object identifier of the list or text object.
/// - position: The index position in the list, or index for a text object based on ``TextEncoding``.
/// When using a position equal to or greater than the object's length at the specified point in time,
/// the cursor will track the end of the document as it changes.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: A cursor that references the position and point in time you specified.
///
/// ### See Also
/// ``cursor(obj:position:)``
///
public func cursor(obj: ObjId, position: UInt64, heads: Set<ChangeHash>) throws -> Cursor {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
return try Cursor(bytes: self.doc.wrapErrors { try $0.cursorAt(
obj: obj.bytes,
position: position,
heads: heads.map(\.bytes)
) })
}
}
/// Retrieves the absolute index-based position for the list or text object you provide.
///
/// While cursors provide stable positions in a collaborative environment, this method allows you to convert
/// a cursor back into an absolute index-based position.
///
/// - Parameters:
/// - obj: The object identifier of the list or text object.
/// - cursor: The cursor created for this list or text object
/// - Returns: The index position of a list, or index for a text object based on ``TextEncoding``, of the cursor.
///
/// ### See Also
/// ``cursor(obj:position:)``
/// ``cursor(obj:position:heads:)``
///
public func position(obj: ObjId, cursor: Cursor) throws -> UInt64 {
try lock {
try self.doc.wrapErrors {
try $0.cursorPosition(obj: obj.bytes, cursor: cursor.bytes)
}
}
}
/// Retrieves the absolute index-based position for the list or text object and point in time you provide.
///
/// While cursors provide stable positions in a collaborative environment, this method allows you to convert
/// a cursor back into an absolute index-based position.
///
/// - Parameters:
/// - obj: The object identifier of the list or text object.
/// - cursor: The cursor created for this list or text object
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: The index position of a list, or index for a text object based on ``TextEncoding``, of the cursor.
///
/// ### See Also
/// ``cursor(obj:position:)``
/// ``cursor(obj:position:heads:)``
///
public func position(obj: ObjId, cursor: Cursor, heads: Set<ChangeHash>) throws -> UInt64 {
try lock {
try self.doc.wrapErrors {
try $0.cursorPositionAt(obj: obj.bytes, cursor: cursor.bytes, heads: heads.map(\.bytes))
}
}
}
/// Splice an array of values into the array object you specify.
///
/// - Parameters:
/// - obj: The identifier of the array object to update.
/// - start: The index where the splice method begins inserting or deleting.
/// - delete: The number of elements to delete from the `start` index.
/// If negative, the function deletes elements preceding `start` index, rather than following it.
/// - values: An array of values to insert after the `start` index.
public func splice(obj: ObjId, start: UInt64, delete: Int64, values: [ScalarValue]) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.splice(
obj: obj.bytes, start: start, delete: delete, values: values.map { $0.toFfi() }
)
}
}
}
/// Splice characters into the text object you specify.
///
/// - Parameters:
/// - obj: The identifier of the text object to update.
/// - start: The distance from the start of the string where the function begins inserting or deleting.
/// - delete: Text length to delete from the `start` index. It depends on the picked ``TextEncoding`` in Document creation.
/// If negative, the function deletes characters preceding `start` index, rather than following it.
/// - value: The characters to insert after the `start` index.
///
/// With `spliceText`, the `start` and `delete` parameters represent integer distances of the Swift strings. This distance will change
/// based on the text encoding chosen during at Document creation.
///
/// If you use or receive a Swift `String.Index` convert it to an index position usable by Automerge through `Foundation.String.View`
/// APIs. Indices in Automerge are based on the ``TextEncoding`` chosen at document creation.
///
/// An example of deriving the automerge start position from a Swift string's index:
/// ```swift
/// extension String {
/// /// Given: Automerge.Document(textEncoding: .unicodeScalars)
/// @inlinable func automergeIndexPosition(index: String.Index) -> UInt64? {
/// guard let unicodeScalarIndex = index.samePosition(in: self.unicodeScalars) else {
/// return nil
/// }
/// let intPositionInUnicodeScalar = self.unicodeScalars.distance(
/// from: self.unicodeScalars.startIndex,
/// to: unicodeScalarIndex)
/// return UInt64(intPositionInUnicodeScalar)
/// }
/// }
/// ```
///
/// For the length of index updates in Automerge, use the count in picked text encoding converted to `Int64`.
/// For example:
/// ```swift
/// Int64("🇬🇧".unicodeScalars.count)
/// Int64("🇬🇧".utf8.count)
/// Int64("🇬🇧".utf16.count)
/// ```
public func spliceText(obj: ObjId, start: UInt64, delete: Int64, value: String? = nil) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.spliceText(obj: obj.bytes, start: start, delete: delete, chars: value ?? "")
}
}
}
/// Updates the text object with the value you specify.
///
/// - Parameters:
/// - obj: The identifier of the text object to update.
/// - value: The string value for the text
///
/// You can use updateText as an alternative to spliceText for low-level text updates.
/// This method creates a diff of the text, using Grapheme clusters, to apply updates to change the stored text to
/// what you provide.
public func updateText(obj: ObjId, value: String) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors { doc in
try doc.updateText(obj: obj.bytes, chars: value)
}
}
}
/// Add or remove a mark to a given range of text
///
/// - Parameters:
/// - obj: The identifier of the text object to which to add the mark.
/// - start: The distance from the start of the string where the function begins inserting or deleting.
/// - end: The distance from the start of the string where the function ends the mark.
/// - expand: How the mark should expand when text is inserted at the beginning or end of the range
/// - name: The name of the mark, for example "bold".
/// - value: The scalar value to associate with the mark.
///
/// To remove an existing mark between two index positions, set the name to the same value
/// as the existing mark and set the value to the scalar value ``ScalarValue/Null``.
///
/// If you use or receive a Swift `String.Index` convert it to an index position usable by Automerge through `Foundation.String.View`
/// APIs. Indices depends on picked ``TextEncoding`` during Automerge.Document creation.
///
/// An example of deriving the automerge start position from a Swift string's index:
/// ```swift
/// extension String {
/// /// Given: Automerge.Document(textEncoding: .unicodeScalars)
/// @inlinable func automergeIndexPosition(index: String.Index) -> UInt64? {
/// guard let unicodeScalarIndex = index.samePosition(in: self.unicodeScalars) else {
/// return nil
/// }
/// let intPositionInUnicodeScalar = self.unicodeScalars.distance(
/// from: self.unicodeScalars.startIndex,
/// to: unicodeScalarIndex)
/// return UInt64(intPositionInUnicodeScalar)
/// }
/// }
/// ```
///
/// For the length of index updates in Automerge, use the count in picked text encoding converted to `UInt64`.
/// For example:
/// ```swift
/// UInt64("🇬🇧".unicodeScalars.count)
/// UInt64("🇬🇧".utf8.count)
/// UInt64("🇬🇧".utf16.count)
/// ```
public func mark(
obj: ObjId,
start: UInt64,
end: UInt64,
expand: ExpandMark,
name: String,
value: ScalarValue
) throws {
try lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
try self.doc.wrapErrors {
try $0.mark(
obj: obj.bytes,
start: start,
end: end,
expand: expand.toFfi(),
name: name,
value: value.toFfi()
)
}
}
}
/// Returns the current list of marks for a text object.
///
/// - Parameter obj: The identifier of the text object.
/// - Returns: The current list of ``Mark`` for the text object.
public func marks(obj: ObjId) throws -> [Mark] {
try lock {
try self.doc.wrapErrors {
try $0.marks(obj: obj.bytes).map(Mark.fromFfi)
}
}
}
/// Get the historical list of marks for a text object and point in time you specify.
///
/// - Parameters:
/// - obj: The identifier of the text object.
/// - heads: The set of ``ChangeHash`` that represents a point of time in the history the document.
/// - Returns: A list of ``Mark`` for the text object at the point in time you specify.
public func marksAt(obj: ObjId, heads: Set<ChangeHash>) throws -> [Mark] {
try lock {
try self.doc.wrapErrors {
try $0.marksAt(obj: obj.bytes, heads: heads.map(\.bytes)).map(Mark.fromFfi)
}
}
}
/// Retrieves the list of marks within a text object at the specified position and point in time.
///
/// This method allows you to get the marks present at a specific position in a text object.
/// Marks can represent various formatting or annotations applied to the text.
///
/// - Parameters:
/// - obj: The identifier of the text object, represented by an ``ObjId``.
/// - position: The position within the text, represented by a ``Position`` enum which can be a ``Cursor`` or an
/// `UInt64` as a fixed position.
/// - heads: A set of `ChangeHash` values that represents a point in time in the document's history.
/// - Returns: An array of `Mark` objects for the text object at the specified position.
///
/// # Example Usage
/// ```
/// let doc = Document()
/// let textId = try doc.putObject(obj: ObjId.ROOT, key: "text", ty: .Text)
///
/// let cursor = try doc.cursor(obj: textId, position: 0)
/// let marks = try doc.marksAt(obj: textId, position: .cursor(cursor), heads: doc.heads())
/// ```
///
/// ## Recommendation
///
/// Use this method to query the marks applied to a text object at a specific position.
/// This can be useful for retrieving the list of ``Automerge/Mark`` related to a character without
/// traversing the full document.
///
/// ## When to Use Cursor vs. Index
///
/// While you can specify the position either with a `Cursor` or an `Index`, there are important distinctions:
///
/// - **Cursor**: Use a `Cursor` when you need to track a position that might change over time due to edits in the
/// text object. A `Cursor` provides a way to maintain a reference to a logical position within the text even if the
/// text content changes, making it more robust in collaborative or frequently edited documents.
///
/// - **Index**: Use an `Index` when you have a fixed position and you are sure that the text content will not
/// change, or changes are irrelevant to your current operation. An index is a straightforward approach for static
/// text content.
///
/// # See Also
/// ``marksAt(obj:position:)``
/// ``marksAt(obj:heads:)``
///
public func marksAt(obj: ObjId, position: Position, heads: Set<ChangeHash>) throws -> [Mark] {
try lock {
try self.doc.wrapErrors {
try $0.marksAtPosition(
obj: obj.bytes,
position: position.toFfi(),
heads: heads.map(\.bytes)
).map(Mark.fromFfi)
}
}
}
/// Retrieves the list of marks within a text object at the specified position.
///
/// This method allows you to get the marks present at a specific position in a text object.
/// Marks can represent various formatting or annotations applied to the text.
///
/// - Parameters:
/// - obj: The identifier of the text object, represented by an ``ObjId``.
/// - position: The position within the text, represented by a ``Position`` enum which can be a ``Cursor`` or an
/// `UInt64` as a fixed position.
/// - Returns: An array of `Mark` objects for the text object at the specified position.
/// - Note: This method retrieves marks from the latest version of the document.
/// If you need to specify a point in the document's history, refer to ``marksAt(obj:position:heads:)``.
///
/// # Example Usage
/// ```
/// let doc = Document()
/// let textId = try doc.putObject(obj: ObjId.ROOT, key: "text", ty: .Text)
///
/// let cursor = try doc.cursor(obj: textId, position: 0)
/// let marks = try doc.marksAt(obj: textId, position: .cursor(cursor), heads: doc.heads())
/// ```
///
/// ## Recommendation
/// Use this method to query the marks applied to a text object at a specific position.
/// This can be useful for retrieving the list of ``Automerge/Mark`` related to a character without
/// traversing the full document.
///
/// ## When to Use Cursor vs. Index
///
/// While you can specify the position either with a `Cursor` or an `Index`, there are important distinctions:
///
/// - **Cursor**: Use a `Cursor` when you need to track a position that might change over time due to edits in the
/// text object. A `Cursor` provides a way to maintain a reference to a logical position within the text even if the
/// text content changes, making it more robust in collaborative or frequently edited documents.
///
/// - **Index**: Use an `Index` when you have a fixed position and you are sure that the text content will not
/// change, or changes are irrelevant to your current operation. An index is a straightforward approach for static
/// text content.
///
/// # See Also
/// ``marksAt(obj:position:heads:)``
/// ``marksAt(obj:heads:)``
///
public func marksAt(obj: ObjId, position: Position) throws -> [Mark] {
try marksAt(obj: obj, position: position, heads: heads())
}
/// Commit the auto-generated transaction with options.
///
/// - Parameters:
/// - message: An optional message to attach to the auto-committed change (if any).
/// - timestamp: A timestamp to attach to the auto-committed change (if any), defaulting to Date().
public func commitWith(message: String? = nil, timestamp: Date = Date()) {
lock {
sendObjectWillChange()
defer { sendObjectDidChange() }
self.doc.wrapErrors {
$0.commitWith(msg: message, time: Int64(timestamp.timeIntervalSince1970))
}
}
}