-
Notifications
You must be signed in to change notification settings - Fork 22
/
y_py.pyi
1207 lines (1042 loc) · 44.4 KB
/
y_py.pyi
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
from typing import (Any, Callable, Dict, Iterable, Iterator, List, Literal,
Optional, Tuple, TypedDict, Union)
class SubscriptionId:
"""
Tracks an observer callback. Pass this to the `unobserve` method to cancel
its associated callback.
"""
Event = Union[YTextEvent, YArrayEvent, YMapEvent, YXmlTextEvent, YXmlElementEvent]
class YDoc:
"""
A Ypy document type. Documents are most important units of collaborative resources management.
All shared collections live within a scope of their corresponding documents. All updates are
generated on per document basis (rather than individual shared type). All operations on shared
collections happen via YTransaction, which lifetime is also bound to a document.
Document manages so called root types, which are top-level shared types definitions (as opposed
to recursively nested types).
Example::
from y_py import YDoc
doc = YDoc()
with doc.begin_transaction() as txn:
text = txn.get_text('name')
text.extend(txn, 'hello world')
print(str(text))
"""
client_id: int
def __init__(
self,
client_id: Optional[int] = None,
offset_kind: str = "utf8",
skip_gc: bool = False,
):
"""
Creates a new Ypy document. If `client_id` parameter was passed it will be used as this
document globally unique identifier (it's up to caller to ensure that requirement).
Otherwise it will be assigned a randomly generated number.
"""
def begin_transaction(self) -> YTransaction:
"""
Returns:
A new transaction for this document. Ypy shared data types execute their
operations in a context of a given transaction. Each document can have only one active
transaction at the time - subsequent attempts will cause exception to be thrown.
Transactions started with `doc.begin_transaction` can be released by deleting the transaction object
method.
Example::
from y_py import YDoc
doc = YDoc()
text = doc.get_text('name')
with doc.begin_transaction() as txn:
text.insert(txn, 0, 'hello world')
"""
def transact(self, callback: Callable[[YTransaction]]): ...
def get_map(self, name: str) -> YMap:
"""
Returns:
A `YMap` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YMap` instance.
"""
def get_xml_element(self, name: str) -> YXmlElement:
"""
Returns:
A `YXmlElement` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YXmlElement` instance.
"""
def get_xml_text(self, name: str) -> YXmlText:
"""
Returns:
A `YXmlText` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YXmlText` instance.
"""
def get_xml_fragment(self, name: str) -> YXmlFragment:
"""
Returns:
A `YXmlFragment` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YXmlFragment` instance.
"""
def get_array(self, name: str) -> YArray:
"""
Returns:
A `YArray` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YArray` instance.
"""
def get_text(self, name: str) -> YText:
"""
Args:
name: The identifier for retreiving the text
Returns:
A `YText` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YText` instance.
"""
def observe_after_transaction(
self, callback: Callable[[AfterTransactionEvent]]
) -> SubscriptionId:
"""
Subscribe callback function to updates on the YDoc. The callback will receive encoded state updates and
deletions when a document transaction is committed.
Args:
callback: A function that receives YDoc state information affected by the transaction.
Returns:
A subscription identifier that can be used to cancel the callback.
"""
EncodedStateVector = bytes
EncodedDeleteSet = bytes
YDocUpdate = bytes
class AfterTransactionEvent:
"""
Holds transaction update information from a commit after state vectors have been compressed.
"""
before_state: EncodedStateVector
"""
Encoded state of YDoc before the transaction.
"""
after_state: EncodedStateVector
"""
Encoded state of the YDoc after the transaction.
"""
delete_set: EncodedDeleteSet
"""
Elements deleted by the associated transaction.
"""
def get_update(self) -> YDocUpdate:
"""
Returns:
Encoded payload of all updates produced by the transaction.
"""
def encode_state_vector(doc: YDoc) -> EncodedStateVector:
"""
Encodes a state vector of a given Ypy document into its binary representation using lib0 v1
encoding. State vector is a compact representation of updates performed on a given document and
can be used by `encode_state_as_update` on remote peer to generate a delta update payload to
synchronize changes between peers.
Example::
from y_py import YDoc, encode_state_vector, encode_state_as_update, apply_update from y_py
# document on machine A
local_doc = YDoc()
local_sv = encode_state_vector(local_doc)
# document on machine B
remote_doc = YDoc()
remote_delta = encode_state_as_update(remote_doc, local_sv)
apply_update(local_doc, remote_delta)
"""
def encode_state_as_update(
doc: YDoc, vector: Optional[Union[EncodedStateVector, List[int]]] = None
) -> YDocUpdate:
"""
Encodes all updates that have happened since a given version `vector` into a compact delta
representation using lib0 v1 encoding. If `vector` parameter has not been provided, generated
delta payload will contain all changes of a current Ypy document, working effectively as its
state snapshot.
Example::
from y_py import YDoc, encode_state_vector, encode_state_as_update, apply_update
# document on machine A
local_doc = YDoc()
local_sv = encode_state_vector(local_doc)
# document on machine B
remote_doc = YDoc()
remote_delta = encode_state_as_update(remote_doc, local_sv)
apply_update(local_doc, remote_delta)
"""
def apply_update(doc: YDoc, diff: Union[YDocUpdate, List[int]]):
"""
Applies delta update generated by the remote document replica to a current document. This
method assumes that a payload maintains lib0 v1 encoding format.
Example::
from y_py import YDoc, encode_state_vector, encode_state_as_update, apply_update
# document on machine A
local_doc = YDoc()
local_sv = encode_state_vector(local_doc)
# document on machine B
remote_doc = YDoc()
remote_delta = encode_state_as_update(remote_doc, local_sv)
apply_update(local_doc, remote_delta)
"""
class YTransaction:
"""
A transaction that serves as a proxy to document block store. Ypy shared data types execute
their operations in a context of a given transaction. Each document can have only one active
transaction at the time - subsequent attempts will cause exception to be thrown.
Transactions started with `doc.begin_transaction` can be released by deleting the transaction object
method.
Example::
from y_py import YDoc
doc = YDoc()
text = doc.get_text('name')
with doc.begin_transaction() as txn:
text.insert(txn, 0, 'hello world')
"""
before_state: Dict[int, int]
def get_text(self, name: str) -> YText:
"""
Returns:
A `YText` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YText` instance.
"""
def get_array(self, name: str) -> YArray:
"""
Returns:
A `YArray` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YArray` instance.
"""
def get_map(self, name: str) -> YMap:
"""
Returns:
A `YMap` shared data type, that's accessible for subsequent accesses using given `name`.
If there was no instance with this name before, it will be created and then returned.
If there was an instance with this name, but it was of different type, it will be projected
onto `YMap` instance.
"""
def commit(self):
"""
Triggers a post-update series of operations without `free`ing the transaction. This includes
compaction and optimization of internal representation of updates, triggering events etc.
Ypy transactions are auto-committed when they are `free`d.
"""
def state_vector_v1(self) -> EncodedStateVector:
"""
Encodes a state vector of a given transaction document into its binary representation using
lib0 v1 encoding. State vector is a compact representation of updates performed on a given
document and can be used by `encode_state_as_update` on remote peer to generate a delta
update payload to synchronize changes between peers.
Example::
from y_py import YDoc
# document on machine A
local_doc = YDoc()
local_txn = local_doc.begin_transaction()
# document on machine B
remote_doc = YDoc()
remote_txn = local_doc.begin_transaction()
try:
local_sv = local_txn.state_vector_v1()
remote_delta = remote_txn.diff_v1(local_sv)
local_txn.apply_v1(remote_delta)
finally:
del local_txn
del remote_txn
"""
def diff_v1(self, vector: Optional[EncodedStateVector] = None) -> YDocUpdate:
"""
Encodes all updates that have happened since a given version `vector` into a compact delta
representation using lib0 v1 encoding. If `vector` parameter has not been provided, generated
delta payload will contain all changes of a current Ypy document, working effectively as
its state snapshot.
Example::
from y_py import YDoc
# document on machine A
local_doc = YDoc()
local_txn = local_doc.begin_transaction()
# document on machine B
remote_doc = YDoc()
remote_txn = local_doc.begin_transaction()
try:
local_sv = local_txn.state_vector_v1()
remote_delta = remote_txn.diff_v1(local_sv)
local_txn.apply_v1(remote_delta)
finally:
del local_txn
del remote_txn
"""
def apply_v1(self, diff: YDocUpdate):
"""
Applies delta update generated by the remote document replica to a current transaction's
document. This method assumes that a payload maintains lib0 v1 encoding format.
Example::
from y_py import YDoc
# document on machine A
local_doc = YDoc()
local_txn = local_doc.begin_transaction()
# document on machine B
remote_doc = YDoc()
remote_txn = local_doc.begin_transaction()
try:
local_sv = local_txn.state_vector_v1()
remote_delta = remote_txn.diff_v1(local_sv)
local_txn.apply_v1(remote_delta)
finally:
del local_txn
del remote_txn
"""
def __enter__() -> YTransaction: ...
def __exit__() -> bool: ...
class YText:
"""
A shared data type used for collaborative text editing. It enables multiple users to add and
remove chunks of text in efficient manner. This type is internally represented as able
double-linked list of text chunks - an optimization occurs during `YTransaction.commit`, which
allows to squash multiple consecutively inserted characters together as a single chunk of text
even between transaction boundaries in order to preserve more efficient memory model.
`YText` structure internally uses UTF-8 encoding and its length is described in a number of
bytes rather than individual characters (a single UTF-8 code point can consist of many bytes).
Like all Yrs shared data types, `YText` is resistant to the problem of interleaving (situation
when characters inserted one after another may interleave with other peers concurrent inserts
after merging all updates together). In case of Yrs conflict resolution is solved by using
unique document id to determine correct and consistent ordering.
"""
prelim: bool
"""True if this element has not been integrated into a YDoc."""
def __init__(self, init: str = ""):
"""
Creates a new preliminary instance of a `YText` shared data type, with its state initialized
to provided parameter.
Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
Once a preliminary instance has been inserted this way, it becomes integrated into Ypy
document store and cannot be nested again: attempt to do so will result in an exception.
"""
def __str__(self) -> str:
"""
Returns:
The underlying shared string stored in this data type.
"""
def __repr__(self) -> str:
"""
Returns:
The string representation wrapped in 'YText()'
"""
def __len__(self) -> int:
"""
Returns:
The length of an underlying string stored in this `YText` instance, understood as a number of UTF-8 encoded bytes.
"""
def to_json(self) -> str:
"""
Returns:
The underlying shared string stored in this data type.
"""
def insert(
self,
txn: YTransaction,
index: int,
chunk: str,
attributes: Dict[str, Any] = {},
):
"""
Inserts a string of text into the `YText` instance starting at a given `index`.
Attributes are optional style modifiers (`{"bold": True}`) that can be attached to the inserted string.
Attributes are only supported for a `YText` instance which already has been integrated into document store.
"""
def insert_embed(
self,
txn: YTransaction,
index: int,
embed: Any,
attributes: Dict[str, Any] = {},
):
"""
Inserts embedded content into the YText at the provided index. Attributes are user-defined metadata associated with the embedded content.
Attributes are only supported for a `YText` instance which already has been integrated into document store.
"""
def format(
self, txn: YTransaction, index: int, length: int, attributes: Dict[str, Any]
):
"""
Wraps an existing piece of text within a range described by `index`-`length` parameters with
formatting blocks containing provided `attributes` metadata. This method only works for
`YText` instances that already have been integrated into document store
"""
def extend(self, txn: YTransaction, chunk: str):
"""
Appends a given `chunk` of text at the end of current `YText` instance.
"""
def delete(self, txn: YTransaction, index: int):
"""
Deletes the character at the specified `index`.
"""
def delete_range(self, txn: YTransaction, index: int, length: int):
"""
Deletes a specified range of of characters, starting at a given `index`.
Both `index` and `length` are counted in terms of a number of UTF-8 character bytes.
"""
def observe(self, f: Callable[[YTextEvent]]) -> SubscriptionId:
"""
Assigns a callback function to listen to YText updates.
Args:
f: Callback function that runs when the text object receives an update.
Returns:
A reference to the callback subscription.
"""
def observe_deep(self, f: Callable[[List[Event]]]) -> SubscriptionId:
"""
Assigns a callback function to listen to the updates of the YText instance and those of its nested attributes.
Currently, this listens to the same events as YText.observe, but in the future this will also listen to
the events of embedded values.
Args:
f: Callback function that runs when the text object or its nested attributes receive an update.
Returns:
A reference to the callback subscription.
"""
def unobserve(self, subscription_id: SubscriptionId):
"""
Cancels the observer callback associated with the `subscripton_id`.
Args:
subscription_id: reference to a subscription provided by the `observe` method.
"""
class YTextEvent:
"""
Communicates updates that occurred during a transaction for an instance of `YText`.
The `target` references the `YText` element that receives the update.
The `delta` is a list of updates applied by the transaction.
"""
target: YText
delta: List[YTextDelta]
def path(self) -> List[Union[int, str]]:
"""
Returns:
Array of keys and indexes creating a path from root type down to current instance of shared type (accessible via `target` getter).
"""
YTextDelta = Union[YTextChangeInsert, YTextChangeDelete, YTextChangeRetain]
class YTextChangeInsert(TypedDict):
insert: str
attributes: Optional[Any]
class YTextChangeDelete(TypedDict):
delete: int
class YTextChangeRetain(TypedDict):
retain: int
attributes: Optional[Any]
class YArray:
prelim: bool
"""True if this element has not been integrated into a YDoc."""
def __init__(init: Optional[Iterable[Any]] = None):
"""
Creates a new preliminary instance of a `YArray` shared data type, with its state
initialized to provided parameter.
Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
Once a preliminary instance has been inserted this way, it becomes integrated into Ypy
document store and cannot be nested again: attempt to do so will result in an exception.
"""
def __len__(self) -> int:
"""
Returns:
Number of elements in the `YArray`
"""
def __str__(self) -> str:
"""
Returns:
The string representation of YArray
"""
def __repr__(self) -> str:
"""
Returns:
The string representation of YArray wrapped in `YArray()`
"""
def to_json(self) -> str:
"""
Converts an underlying contents of this `YArray` instance into their JSON representation.
"""
def insert(self, txn: YTransaction, index: int, item: Any):
"""
Inserts an item at the provided index in the `YArray`.
"""
def insert_range(self, txn: YTransaction, index: int, items: Iterable):
"""
Inserts a given range of `items` into this `YArray` instance, starting at given `index`.
"""
def append(self, txn: YTransaction, item: Any):
"""
Adds a single item to the end of the `YArray`
"""
def extend(self, txn: YTransaction, items: Iterable):
"""
Appends a sequence of `items` at the end of this `YArray` instance.
"""
def delete(self, txn: YTransaction, index: int):
"""
Deletes a single item from the array
Args:
txn: The transaction where the array is being modified.
index: The index of the element to be deleted.
"""
def delete_range(self, txn: YTransaction, index: int, length: int):
"""
Deletes a range of items of given `length` from current `YArray` instance,
starting from given `index`.
"""
def move_to(self, txn: YTransaction, source: int, target: int):
"""
Moves a single item found at `source` index into `target` index position.
Args:
txn: The transaction where the array is being modified.
source: The index of the element to be moved.
target: The new position of the element.
"""
def move_range_to(self, txn: YTransaction, start: int, end: int, target: int):
"""
Moves all elements found within `start`..`end` indexes range (both side inclusive) into
new position pointed by `target` index. All elements inserted concurrently by other peers
inside of moved range will be moved as well after synchronization (although it make take
more than one sync roundtrip to achieve convergence).
Args:
txn: The transaction where the array is being modified.
start: The index of the first element of the range (inclusive).
end: The index of the last element of the range (inclusive).
target: The new position of the element.
Example:
```
import y_py as Y
doc = Y.Doc();
array = doc.get_array('array')
with doc.begin_transaction() as t:
array.insert_range(t, 0, [1,2,3,4]);
// move elements 2 and 3 after the 4
with doc.begin_transaction() as t:
array.move_range_to(t, 1, 2, 4);
```
"""
def __getitem__(self, index: Union[int, slice]) -> Any:
"""
Returns:
The element stored under given `index` or a new list of elements from the slice range.
"""
def __iter__(self) -> Iterator:
"""
Returns:
An iterator that can be used to traverse over the values stored withing this instance of `YArray`.
Example::
from y_py import YDoc
# document on machine A
doc = YDoc()
array = doc.get_array('name')
for item in array:
print(item)
"""
def observe(self, f: Callable[[YArrayEvent]]) -> SubscriptionId:
"""
Assigns a callback function to listen to YArray updates.
Args:
f: Callback function that runs when the array object receives an update.
Returns:
An identifier associated with the callback subscription.
"""
def observe_deep(self, f: Callable[[List[Event]]]) -> SubscriptionId:
"""
Assigns a callback function to listen to the aggregated updates of the YArray and its child elements.
Args:
f: Callback function that runs when the array object or components receive an update.
Returns:
An identifier associated with the callback subscription.
"""
def unobserve(self, subscription_id: SubscriptionId):
"""
Cancels the observer callback associated with the `subscripton_id`.
Args:
subscription_id: reference to a subscription provided by the `observe` method.
"""
YArrayObserver = Any
class YArrayEvent:
"""
Communicates updates that occurred during a transaction for an instance of `YArray`.
The `target` references the `YArray` element that receives the update.
The `delta` is a list of updates applied by the transaction.
"""
target: YArray
delta: List[ArrayDelta]
def path(self) -> List[Union[int, str]]:
"""
Returns:
Array of keys and indexes creating a path from root type down to current instance of shared type (accessible via `target` getter).
"""
ArrayDelta = Union[ArrayChangeInsert, ArrayChangeDelete, ArrayChangeRetain]
"""A modification to a YArray during a transaction."""
class ArrayChangeInsert(TypedDict):
"""Update message that elements were inserted in a YArray."""
insert: List[Any]
class ArrayChangeDelete:
"""Update message that elements were deleted in a YArray."""
delete: int
class ArrayChangeRetain:
"""Update message that elements were left unmodified in a YArray."""
retain: int
class YMap:
prelim: bool
"""True if this element has not been integrated into a YDoc."""
def __init__(dict: dict):
"""
Creates a new preliminary instance of a `YMap` shared data type, with its state
initialized to provided parameter.
Preliminary instances can be nested into other shared data types such as `YArray` and `YMap`.
Once a preliminary instance has been inserted this way, it becomes integrated into Ypy
document store and cannot be nested again: attempt to do so will result in an exception.
"""
def __len__(self) -> int:
"""
Returns:
The number of entries stored within this instance of `YMap`.
"""
def __str__(self) -> str:
"""
Returns:
The string representation of the `YMap`.
"""
def __dict__(self) -> dict:
"""
Returns:
Contents of the `YMap` inside a Python dictionary.
"""
def __repr__(self) -> str:
"""
Returns:
The string representation of the `YMap` wrapped in 'YMap()'
"""
def to_json(self) -> str:
"""
Converts contents of this `YMap` instance into a JSON representation.
"""
def set(self, txn: YTransaction, key: str, value: Any):
"""
Sets a given `key`-`value` entry within this instance of `YMap`. If another entry was
already stored under given `key`, it will be overridden with new `value`.
"""
def update(
self, txn: YTransaction, items: Union[Iterable[Tuple[str, Any]], Dict[str, Any]]
):
"""
Updates `YMap` with the contents of items.
Args:
txn: A transaction to perform the insertion updates.
items: An iterable object that produces key value tuples to insert into the YMap
"""
def pop(self, txn: YTransaction, key: str, fallback: Optional[Any] = None) -> Any:
"""
Removes an entry identified by a given `key` from this instance of `YMap`, if such exists.
Throws a KeyError if the key does not exist and fallback value is not provided.
Args:
txn: The current transaction from a YDoc.
key: Identifier of the requested item.
fallback: Returns this value if the key doesn't exist in the YMap
Returns:
The item at the key.
"""
def get(self, key: str, fallback: Any) -> Any | None:
"""
Args:
key: The identifier for the requested data.
fallback: If the key doesn't exist in the map, this fallback value will be returned.
Returns:
Requested data or the provided fallback value.
"""
def __getitem__(self, key: str) -> Any:
"""
Args:
key: The identifier for the requested data.
Returns:
Value of an entry stored under given `key` within this instance of `YMap`. Will throw a `KeyError` if the provided key is unassigned.
"""
def __iter__(self) -> Iterator[str]:
"""
Returns:
An iterator that traverses all keys of the `YMap` in an unspecified order.
"""
def items(self) -> YMapItemsView:
"""
Returns:
A view that can be used to iterate over all entries stored within this instance of `YMap`. Order of entry is not specified.
Example::
from y_py import YDoc
# document on machine A
doc = YDoc()
map = doc.get_map('name')
with doc.begin_transaction() as txn:
map.set(txn, 'key1', 'value1')
map.set(txn, 'key2', true)
for (key, value) in map.items()):
print(key, value)
"""
def keys(self) -> YMapKeysView:
"""
Returns:
A view of all key identifiers in the YMap. The order of keys is not stable.
"""
def values(self) -> YMapValuesView:
"""
Returns:
A view of all values in the YMap. The order of values is not stable.
"""
def observe(self, f: Callable[[YMapEvent]]) -> SubscriptionId:
"""
Assigns a callback function to listen to YMap updates.
Args:
f: Callback function that runs when the map object receives an update.
Returns:
A reference to the callback subscription. Delete this observer in order to erase the associated callback function.
"""
def observe_deep(self, f: Callable[[List[Event]]]) -> SubscriptionId:
"""
Assigns a callback function to listen to YMap and child element updates.
Args:
f: Callback function that runs when the map object or any of its tracked elements receive an update.
Returns:
A reference to the callback subscription. Delete this observer in order to erase the associated callback function.
"""
def unobserve(self, subscription_id: SubscriptionId):
"""
Cancels the observer callback associated with the `subscripton_id`.
Args:
subscription_id: reference to a subscription provided by the `observe` method.
"""
class YMapItemsView:
"""Tracks key/values inside a YMap. Similar functionality to dict_items for a Python dict"""
def __iter__() -> Iterator[Tuple[str, Any]]:
"""Produces key value tuples of elements inside the view"""
def __contains__() -> bool:
"""Checks membership of kv tuples in the view"""
def __len__() -> int:
"""Checks number of items in the view."""
class YMapKeysView:
"""Tracks key identifiers inside of a YMap"""
def __iter__() -> Iterator[str]:
"""Produces keys of the view"""
def __contains__() -> bool:
"""Checks membership of keys in the view"""
def __len__() -> int:
"""Checks number of keys in the view."""
class YMapValuesView:
"""Tracks values inside of a YMap"""
def __iter__() -> Iterator[Any]:
"""Produces values of the view"""
def __contains__() -> bool:
"""Checks membership of values in the view"""
def __len__() -> int:
"""Checks number of values in the view."""
class YMapEvent:
"""
Communicates updates that occurred during a transaction for an instance of `YMap`.
The `target` references the `YMap` element that receives the update.
The `delta` is a list of updates applied by the transaction.
The `keys` are a list of changed values for a specific key.
"""
target: YMap
"""The element modified during this event."""
keys: Dict[str, YMapEventKeyChange]
"""A list of modifications to the YMap by key.
Includes the type of modification along with the before and after state."""
def path(self) -> List[Union[int, str]]:
"""
Returns:
Path to this element from the root if this YMap is nested inside another data structure.
"""
class YMapEventKeyChange(TypedDict):
action: Literal["add", "update", "delete"]
oldValue: Optional[Any]
newValue: Optional[Any]
YXmlAttributes = Iterator[Tuple[str, str]]
"""Generates a sequence of key/value properties for an XML Element"""
Xml = Union[YXmlElement, YXmlText]
YXmlTreeWalker = Iterator[Xml]
"""Visits elements in an Xml tree"""
EntryChange = Dict[Literal["action", "newValue", "oldValue"], Any]
class YXmlElementEvent:
target: YXmlElement
keys: Dict[str, EntryChange]
delta: List[Dict]
def path(self) -> List[Union[int, str]]:
"""
Returns a current shared type instance, that current event changes refer to.
"""
class YXmlElement:
"""
XML element data type. It represents an XML node, which can contain key-value attributes
(interpreted as strings) as well as other nested XML elements or rich text (represented by
`YXmlText` type).
In terms of conflict resolution, `YXmlElement` uses following rules:
- Attribute updates use logical last-write-wins principle, meaning the past updates are
automatically overridden and discarded by newer ones, while concurrent updates made by
different peers are resolved into a single value using document id seniority to establish
an order.
- Child node insertion uses sequencing rules from other Yrs collections - elements are inserted
using interleave-resistant algorithm, where order of concurrent inserts at the same index
is established using peer's document id seniority.
"""
name: str
first_child: Optional[Xml]
next_sibling: Optional[Xml]
prev_sibling: Optional[Xml]
parent: Optional[YXmlElement]
def __len__(self) -> int:
"""
Returns a number of child XML nodes stored within this `YXMlElement` instance.
"""
def insert_xml_element(
self,
txn: YTransaction,
index: int,
name: str,
) -> YXmlElement:
"""
Inserts a new instance of `YXmlElement` as a child of this XML node and returns it.
"""
def insert_xml_text(self, txn: YTransaction, index: int) -> YXmlText:
"""
Inserts a new instance of `YXmlText` as a child of this XML node and returns it.
"""
def delete(self, txn: YTransaction, index: int, length: int):
"""
Removes a range of children XML nodes from this `YXmlElement` instance,
starting at given `index`.
"""
def push_xml_element(self, txn: YTransaction, name: str) -> YXmlElement:
"""
Appends a new instance of `YXmlElement` as the last child of this XML node and returns it.
"""
def push_xml_text(self, txn: YTransaction) -> YXmlText:
"""
Appends a new instance of `YXmlText` as the last child of this XML node and returns it.
"""
def __str__(self) -> str:
"""
Returns:
A string representation of this XML node.
"""
def __repr__(self) -> str:
"""
Returns:
A string representation wrapped in YXmlElement
"""
def set_attribute(self, txn: YTransaction, name: str, value: str):
"""
Sets a `name` and `value` as new attribute for this XML node. If an attribute with the same
`name` already existed on that node, its value with be overridden with a provided one.
"""
def get_attribute(self, name: str) -> Optional[str]:
"""
Returns a value of an attribute given its `name`. If no attribute with such name existed,
`null` will be returned.
"""
def remove_attribute(self, txn: YTransaction, name: str):
"""
Removes an attribute from this XML node, given its `name`.
"""
def attributes(self) -> YXmlAttributes:
"""
Returns an iterator that enables to traverse over all attributes of this XML node in
unspecified order.
"""
def tree_walker(self) -> YXmlTreeWalker:
"""