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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
use crate::block::{EmbedPrelim, Item, ItemContent, ItemPosition, ItemPtr, Prelim};
use crate::block_iter::BlockIter;
use crate::transaction::TransactionMut;
use crate::types::text::{diff_between, TextEvent, YChange};
use crate::types::{
    event_change_set, event_keys, Branch, BranchPtr, Change, ChangeSet, Delta, Entries,
    EntryChange, MapRef, Path, RootRef, SharedRef, ToJson, TypePtr, TypeRef, Value,
};
use crate::{
    Any, ArrayRef, BranchID, DeepObservable, GetString, IndexedSequence, Map, Observable, ReadTxn,
    StickyIndex, Text, TextRef, ID,
};
use std::borrow::Borrow;
use std::cell::UnsafeCell;
use std::collections::{HashMap, HashSet};
use std::convert::{TryFrom, TryInto};
use std::fmt::Write;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::Arc;

/// Trait shared by preliminary types that can be used as XML nodes: [XmlElementPrelim],
/// [XmlFragmentPrelim] and [XmlTextPrelim].
pub trait XmlPrelim: Prelim {}

/// An return type from XML elements retrieval methods. It's an enum of all supported values, that
/// can be nested inside of [XmlElementRef]. These are other [XmlElementRef]s, [XmlFragmentRef]s
/// or [XmlTextRef] values.
#[derive(Debug, Clone)]
pub enum XmlNode {
    Element(XmlElementRef),
    Fragment(XmlFragmentRef),
    Text(XmlTextRef),
}

impl XmlNode {
    pub fn as_ptr(&self) -> BranchPtr {
        match self {
            XmlNode::Element(n) => n.0,
            XmlNode::Fragment(n) => n.0,
            XmlNode::Text(n) => n.0,
        }
    }

    pub fn id(&self) -> BranchID {
        self.as_ptr().id()
    }

    /// If current underlying [XmlNode] is wrapping a [XmlElementRef], it will be returned.
    /// Otherwise, a `None` will be returned.
    pub fn into_xml_element(self) -> Option<XmlElementRef> {
        match self {
            XmlNode::Element(n) => Some(n),
            _ => None,
        }
    }

    /// If current underlying [XmlNode] is wrapping a [XmlFragmentRef], it will be returned.
    /// Otherwise, a `None` will be returned.
    pub fn into_xml_fragment(self) -> Option<XmlFragmentRef> {
        match self {
            XmlNode::Fragment(n) => Some(n),
            _ => None,
        }
    }

    /// If current underlying [XmlNode] is wrapping a [XmlTextRef], it will be returned.
    /// Otherwise, a `None` will be returned.
    pub fn into_xml_text(self) -> Option<XmlTextRef> {
        match self {
            XmlNode::Text(n) => Some(n),
            _ => None,
        }
    }
}

impl AsRef<Branch> for XmlNode {
    fn as_ref(&self) -> &Branch {
        match self {
            XmlNode::Element(n) => n.as_ref(),
            XmlNode::Fragment(n) => n.as_ref(),
            XmlNode::Text(n) => n.as_ref(),
        }
    }
}

impl TryInto<XmlElementRef> for XmlNode {
    type Error = XmlNode;

    fn try_into(self) -> Result<XmlElementRef, Self::Error> {
        match self {
            XmlNode::Element(xml) => Ok(xml),
            other => Err(other),
        }
    }
}

impl TryInto<XmlTextRef> for XmlNode {
    type Error = XmlNode;

    fn try_into(self) -> Result<XmlTextRef, Self::Error> {
        match self {
            XmlNode::Text(xml) => Ok(xml),
            other => Err(other),
        }
    }
}

impl TryInto<XmlFragmentRef> for XmlNode {
    type Error = XmlNode;

    fn try_into(self) -> Result<XmlFragmentRef, Self::Error> {
        match self {
            XmlNode::Fragment(xml) => Ok(xml),
            other => Err(other),
        }
    }
}

impl TryFrom<BranchPtr> for XmlNode {
    type Error = BranchPtr;

    fn try_from(value: BranchPtr) -> Result<Self, Self::Error> {
        match value.type_ref {
            TypeRef::XmlElement(_) => Ok(XmlNode::Element(XmlElementRef::from(value))),
            TypeRef::XmlFragment => Ok(XmlNode::Fragment(XmlFragmentRef::from(value))),
            TypeRef::XmlText => Ok(XmlNode::Text(XmlTextRef::from(value))),
            _ => Err(value),
        }
    }
}

impl TryFrom<Value> for XmlNode {
    type Error = Value;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::YXmlElement(n) => Ok(XmlNode::Element(n)),
            Value::YXmlFragment(n) => Ok(XmlNode::Fragment(n)),
            Value::YXmlText(n) => Ok(XmlNode::Text(n)),
            other => Err(other),
        }
    }
}

/// 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
/// [XmlTextRef] type).
///
/// In terms of conflict resolution, [XmlElementRef] 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.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct XmlElementRef(BranchPtr);

impl SharedRef for XmlElementRef {}
impl Xml for XmlElementRef {}
impl XmlFragment for XmlElementRef {}
impl IndexedSequence for XmlElementRef {}

impl Into<XmlFragmentRef> for XmlElementRef {
    fn into(self) -> XmlFragmentRef {
        XmlFragmentRef(self.0)
    }
}

impl Into<ArrayRef> for XmlElementRef {
    fn into(self) -> ArrayRef {
        ArrayRef::from(self.0)
    }
}

impl Into<MapRef> for XmlElementRef {
    fn into(self) -> MapRef {
        MapRef::from(self.0)
    }
}

impl XmlElementRef {
    /// A tag name of a current top-level XML node, eg. node `<p></p>` has "p" as it's tag name.
    pub fn try_tag(&self) -> Option<&Arc<str>> {
        if let TypeRef::XmlElement(tag) = &self.0.type_ref {
            Some(tag)
        } else {
            // this could happen only if we reinterpret top level type as XmlElementRef
            None
        }
    }

    /// A tag name of a current top-level XML node, eg. node `<p></p>` has "p" as it's tag name.
    pub fn tag(&self) -> &Arc<str> {
        self.try_tag().expect("XmlElement tag was not defined")
    }
}

impl GetString for XmlElementRef {
    /// Converts current XML node into a textual representation. This representation if flat, it
    /// doesn't include any indentation.
    fn get_string<T: ReadTxn>(&self, txn: &T) -> String {
        let tag: &str = self.tag();
        let inner = self.0;
        let mut s = String::new();
        write!(&mut s, "<{}", tag).unwrap();
        let attributes = Attributes(inner.entries(txn));
        for (k, v) in attributes {
            write!(&mut s, " {}=\"{}\"", k, v).unwrap();
        }
        write!(&mut s, ">").unwrap();
        for i in inner.iter(txn) {
            if !i.is_deleted() {
                for content in i.content.get_content() {
                    write!(&mut s, "{}", content.to_string(txn)).unwrap();
                }
            }
        }
        write!(&mut s, "</{}>", tag).unwrap();
        s
    }
}

impl DeepObservable for XmlElementRef {}
impl Observable for XmlElementRef {
    type Event = XmlEvent;
}

impl AsRef<Branch> for XmlElementRef {
    fn as_ref(&self) -> &Branch {
        &self.0
    }
}

impl Eq for XmlElementRef {}
impl PartialEq for XmlElementRef {
    fn eq(&self, other: &Self) -> bool {
        self.0.id() == other.0.id()
    }
}

impl From<BranchPtr> for XmlElementRef {
    fn from(inner: BranchPtr) -> Self {
        XmlElementRef(inner)
    }
}

impl TryFrom<ItemPtr> for XmlElementRef {
    type Error = ItemPtr;

    fn try_from(value: ItemPtr) -> Result<Self, Self::Error> {
        if let Some(branch) = value.clone().as_branch() {
            Ok(Self::from(branch))
        } else {
            Err(value)
        }
    }
}

impl TryFrom<Value> for XmlElementRef {
    type Error = Value;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::YXmlElement(value) => Ok(value),
            other => Err(other),
        }
    }
}

/// A preliminary type that will be materialized into an [XmlElementRef] once it will be integrated
/// into Yrs document.
#[derive(Debug, Clone)]
pub struct XmlElementPrelim<I, T>(Arc<str>, I)
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim;

impl<I, T> XmlElementPrelim<I, T>
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim,
{
    pub fn new<S: Into<Arc<str>>>(tag: S, iter: I) -> Self {
        XmlElementPrelim(tag.into(), iter)
    }
}

impl XmlElementPrelim<Option<XmlTextPrelim<String>>, XmlTextPrelim<String>> {
    pub fn empty<S: Into<Arc<str>>>(tag: S) -> Self {
        XmlElementPrelim(tag.into(), None)
    }
}

impl<I, T> XmlPrelim for XmlElementPrelim<I, T>
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim,
{
}

impl<I, T> Prelim for XmlElementPrelim<I, T>
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim,
{
    type Return = XmlElementRef;

    fn into_content(self, _txn: &mut TransactionMut) -> (ItemContent, Option<Self>) {
        let inner = Branch::new(TypeRef::XmlElement(self.0.clone()));
        (ItemContent::Type(inner), Some(self))
    }

    fn integrate(self, txn: &mut TransactionMut, inner_ref: BranchPtr) {
        let xml = XmlElementRef::from(inner_ref);
        for value in self.1 {
            xml.push_back(txn, value);
        }
    }
}

impl<I, T: Prelim> Into<EmbedPrelim<XmlElementPrelim<I, T>>> for XmlElementPrelim<I, T>
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim,
{
    #[inline]
    fn into(self) -> EmbedPrelim<XmlElementPrelim<I, T>> {
        EmbedPrelim::Shared(self)
    }
}

/// A shared data type used for collaborative text editing, that can be used in a context of
/// [XmlElementRef] node. It enables multiple users to add and remove chunks of text in efficient
/// manner. This type is internally represented as a mutable double-linked list of text chunks
/// - an optimization occurs during [Transaction::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.
///
/// Just like [XmlElementRef], [XmlTextRef] can be marked with extra metadata in form of attributes.
///
/// [XmlTextRef] 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, [XmlTextRef] 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.
///
/// [XmlTextRef] offers a rich text editing capabilities (it's not limited to simple text operations).
/// Actions like embedding objects, binaries (eg. images) and formatting attributes are all possible
/// using [XmlTextRef].
///
/// Keep in mind that [XmlTextRef::get_string] method returns a raw string, while rendering
/// formatting attrbitues as XML tags in-text. However it doesn't include embedded elements.
/// If there's a need to include them, use [XmlTextRef::diff] method instead.
///
/// Another note worth reminding is that human-readable numeric indexes are not good for maintaining
/// cursor positions in rich text documents with real-time collaborative capabilities. In such cases
/// any concurrent update incoming and applied from the remote peer may change the order of elements
/// in current [XmlTextRef], invalidating numeric index. For such cases you can take advantage of fact
/// that [XmlTextRef] implements [IndexedSequence::sticky_index] method that returns a
/// [permanent index](crate::StickyIndex) position that sticks to the same place even when concurrent
/// updates are being made.
///
/// # Example
///
/// ```rust
/// use yrs::{Any, Array, ArrayPrelim, Doc, GetString, Text, Transact, WriteTxn, XmlFragment, XmlTextPrelim};
/// use yrs::types::Attrs;
///
/// let doc = Doc::new();
/// let mut txn = doc.transact_mut();
/// let f = txn.get_or_insert_xml_fragment("article");
/// let text = f.insert(&mut txn, 0, XmlTextPrelim::new(""));
///
/// let bold = Attrs::from([("b".into(), true.into())]);
/// let italic = Attrs::from([("i".into(), true.into())]);
///
/// text.insert(&mut txn, 0, "hello ");
/// text.insert_with_attributes(&mut txn, 6, "world", italic);
/// text.format(&mut txn, 0, 5, bold);
///
/// assert_eq!(text.get_string(&txn), "<b>hello</b> <i>world</i>");
///
/// // remove formatting
/// let remove_italic = Attrs::from([("i".into(), Any::Null)]);
/// text.format(&mut txn, 6, 5, remove_italic);
///
/// assert_eq!(text.get_string(&txn), "<b>hello</b> world");
///
/// // insert binary payload eg. images
/// let image = b"deadbeaf".to_vec();
/// text.insert_embed(&mut txn, 1, image);
///
/// // insert nested shared type eg. table as ArrayRef of ArrayRefs
/// let table = text.insert_embed(&mut txn, 5, ArrayPrelim::default());
/// let header = table.insert(&mut txn, 0, ArrayPrelim::from(["Book title", "Author"]));
/// let row = table.insert(&mut txn, 1, ArrayPrelim::from(["\"Moby-Dick\"", "Herman Melville"]));
/// ```
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct XmlTextRef(BranchPtr);

impl XmlTextRef {
    pub(crate) fn get_string_fragment(
        head: Option<ItemPtr>,
        start: Option<&StickyIndex>,
        end: Option<&StickyIndex>,
    ) -> String {
        let mut buf = String::new();
        for d in diff_between(head, start, end, YChange::identity) {
            let mut attrs = Vec::new();
            if let Some(attributes) = d.attributes.as_ref() {
                for (key, value) in attributes.iter() {
                    attrs.push((key, value));
                }
                attrs.sort_by(|x, y| x.0.cmp(y.0))
            }

            // write attributes as xml opening tags
            for (node, at) in attrs.iter() {
                write!(buf, "<{}", node).unwrap();
                if let Any::Map(at) = at {
                    for (k, v) in at.iter() {
                        write!(buf, " {}=\"{}\"", k, v).unwrap();
                    }
                }
                buf.push('>');
            }

            // write string content of delta
            if let Value::Any(any) = d.insert {
                write!(buf, "{}", any).unwrap();
            }

            // write attributes as xml closing tags
            attrs.reverse();
            for (key, _) in attrs {
                write!(buf, "</{}>", key).unwrap();
            }
        }
        buf
    }
}

impl SharedRef for XmlTextRef {}
impl Xml for XmlTextRef {}
impl Text for XmlTextRef {}
impl IndexedSequence for XmlTextRef {}
#[cfg(feature = "weak")]
impl crate::Quotable for XmlTextRef {}

impl Into<TextRef> for XmlTextRef {
    fn into(self) -> TextRef {
        TextRef::from(self.0)
    }
}

impl DeepObservable for XmlTextRef {}
impl Observable for XmlTextRef {
    type Event = XmlTextEvent;
}

impl GetString for XmlTextRef {
    fn get_string<T: ReadTxn>(&self, _txn: &T) -> String {
        XmlTextRef::get_string_fragment(self.0.start, None, None)
    }
}

impl AsRef<Branch> for XmlTextRef {
    fn as_ref(&self) -> &Branch {
        &self.0
    }
}

impl Eq for XmlTextRef {}
impl PartialEq for XmlTextRef {
    fn eq(&self, other: &Self) -> bool {
        self.0.id() == other.0.id()
    }
}

impl From<BranchPtr> for XmlTextRef {
    fn from(inner: BranchPtr) -> Self {
        XmlTextRef(inner)
    }
}

impl TryFrom<ItemPtr> for XmlTextRef {
    type Error = ItemPtr;

    fn try_from(value: ItemPtr) -> Result<Self, Self::Error> {
        if let Some(branch) = value.clone().as_branch() {
            Ok(Self::from(branch))
        } else {
            Err(value)
        }
    }
}

impl TryFrom<Value> for XmlTextRef {
    type Error = Value;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::YXmlText(value) => Ok(value),
            other => Err(other),
        }
    }
}

/// A preliminary type that will be materialized into an [XmlTextRef] once it will be integrated
/// into Yrs document.
#[derive(Debug)]
pub struct XmlTextPrelim<T: Borrow<str>>(T);

impl Default for XmlTextPrelim<String> {
    fn default() -> Self {
        XmlTextPrelim::new(String::default())
    }
}

impl<T: Borrow<str>> XmlTextPrelim<T> {
    #[inline]
    pub fn new(str: T) -> Self {
        XmlTextPrelim(str)
    }
}

impl<T: Borrow<str>> XmlPrelim for XmlTextPrelim<T> {}

impl<T: Borrow<str>> Prelim for XmlTextPrelim<T> {
    type Return = XmlTextRef;

    fn into_content(self, _txn: &mut TransactionMut) -> (ItemContent, Option<Self>) {
        let inner = Branch::new(TypeRef::XmlText);
        (ItemContent::Type(inner), Some(self))
    }

    fn integrate(self, txn: &mut TransactionMut, inner_ref: BranchPtr) {
        let s = self.0.borrow();
        if !s.is_empty() {
            let text = XmlTextRef::from(inner_ref);
            text.push(txn, s);
        }
    }
}

impl<T: Borrow<str>> Into<EmbedPrelim<XmlTextPrelim<T>>> for XmlTextPrelim<T> {
    #[inline]
    fn into(self) -> EmbedPrelim<XmlTextPrelim<T>> {
        EmbedPrelim::Shared(self)
    }
}

/// A XML fragment, which works as an untagged collection of XML nodes.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct XmlFragmentRef(BranchPtr);

impl RootRef for XmlFragmentRef {
    fn type_ref() -> TypeRef {
        TypeRef::XmlFragment
    }
}
impl SharedRef for XmlFragmentRef {}
impl XmlFragment for XmlFragmentRef {}
impl IndexedSequence for XmlFragmentRef {}

impl XmlFragmentRef {
    pub fn parent(&self) -> Option<XmlNode> {
        let item = self.as_ref().item?;
        let parent = item.parent.as_branch()?;
        XmlNode::try_from(*parent).ok()
    }
}

impl GetString for XmlFragmentRef {
    /// Converts current XML node into a textual representation. This representation if flat, it
    /// doesn't include any indentation.
    fn get_string<T: ReadTxn>(&self, txn: &T) -> String {
        let inner = self.0;
        let mut s = String::new();
        for i in inner.iter(txn) {
            if !i.is_deleted() {
                for content in i.content.get_content() {
                    write!(&mut s, "{}", content.to_string(txn)).unwrap();
                }
            }
        }
        s
    }
}

impl DeepObservable for XmlFragmentRef {}
impl Observable for XmlFragmentRef {
    type Event = XmlEvent;
}

impl AsRef<Branch> for XmlFragmentRef {
    fn as_ref(&self) -> &Branch {
        self.0.deref()
    }
}

impl Eq for XmlFragmentRef {}
impl PartialEq for XmlFragmentRef {
    fn eq(&self, other: &Self) -> bool {
        self.0.id() == other.0.id()
    }
}

impl From<BranchPtr> for XmlFragmentRef {
    fn from(inner: BranchPtr) -> Self {
        XmlFragmentRef(inner)
    }
}

impl TryFrom<ItemPtr> for XmlFragmentRef {
    type Error = ItemPtr;

    fn try_from(value: ItemPtr) -> Result<Self, Self::Error> {
        if let Some(branch) = value.clone().as_branch() {
            Ok(Self::from(branch))
        } else {
            Err(value)
        }
    }
}

impl TryFrom<Value> for XmlFragmentRef {
    type Error = Value;

    fn try_from(value: Value) -> Result<Self, Self::Error> {
        match value {
            Value::YXmlFragment(value) => Ok(value),
            other => Err(other),
        }
    }
}

/// A preliminary type that will be materialized into an [XmlFragmentRef] once it will be integrated
/// into Yrs document.
#[derive(Debug, Clone)]
pub struct XmlFragmentPrelim<I, T>(I)
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim;

impl<I, T> XmlFragmentPrelim<I, T>
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim,
{
    pub fn new(iter: I) -> Self {
        XmlFragmentPrelim(iter)
    }
}

impl<I, T> XmlPrelim for XmlFragmentPrelim<I, T>
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim,
    <T as Prelim>::Return: TryFrom<ItemPtr>,
{
}

impl<I, T> Prelim for XmlFragmentPrelim<I, T>
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim,
    <T as Prelim>::Return: TryFrom<ItemPtr>,
{
    type Return = XmlFragmentRef;

    fn into_content(self, _txn: &mut TransactionMut) -> (ItemContent, Option<Self>) {
        let inner = Branch::new(TypeRef::XmlFragment);
        (ItemContent::Type(inner), Some(self))
    }

    fn integrate(self, txn: &mut TransactionMut, inner_ref: BranchPtr) {
        let xml = XmlFragmentRef::from(inner_ref);
        for value in self.0 {
            xml.push_back(txn, value);
        }
    }
}

impl<I, T: Prelim> Into<EmbedPrelim<XmlFragmentPrelim<I, T>>> for XmlFragmentPrelim<I, T>
where
    I: IntoIterator<Item = T>,
    T: XmlPrelim,
{
    #[inline]
    fn into(self) -> EmbedPrelim<XmlFragmentPrelim<I, T>> {
        EmbedPrelim::Shared(self)
    }
}

/// (Obsolete) an Yjs-compatible XML node used for nesting Map elements.
#[derive(Debug, Clone)]
pub struct XmlHookRef(BranchPtr);

impl Map for XmlHookRef {}

impl ToJson for XmlHookRef {
    fn to_json<T: ReadTxn>(&self, txn: &T) -> Any {
        let map: MapRef = self.clone().into();
        map.to_json(txn)
    }
}

impl AsRef<Branch> for XmlHookRef {
    fn as_ref(&self) -> &Branch {
        self.0.deref()
    }
}

impl Eq for XmlHookRef {}
impl PartialEq for XmlHookRef {
    fn eq(&self, other: &Self) -> bool {
        self.0.id() == other.0.id()
    }
}

impl From<BranchPtr> for XmlHookRef {
    fn from(inner: BranchPtr) -> Self {
        XmlHookRef(inner)
    }
}

impl Into<MapRef> for XmlHookRef {
    fn into(self) -> MapRef {
        MapRef::from(self.0)
    }
}

pub trait Xml: AsRef<Branch> {
    fn parent(&self) -> Option<XmlNode> {
        let item = self.as_ref().item?;
        let parent = item.parent.as_branch()?;
        XmlNode::try_from(*parent).ok()
    }

    /// Removes an attribute recognized by an `attr_name` from a current XML element.
    fn remove_attribute<K>(&self, txn: &mut TransactionMut, attr_name: &K)
    where
        K: AsRef<str>,
    {
        self.as_ref().remove(txn, attr_name.as_ref());
    }

    /// Inserts an attribute entry into current XML element.
    fn insert_attribute<K, V>(&self, txn: &mut TransactionMut, attr_name: K, attr_value: V)
    where
        K: Into<Arc<str>>,
        V: Into<String>,
    {
        let key = attr_name.into();
        let value = attr_value.into();
        let pos = {
            let branch = self.as_ref();
            let left = branch.map.get(&key);
            ItemPosition {
                parent: BranchPtr::from(branch).into(),
                left: left.cloned(),
                right: None,
                index: 0,
                current_attrs: None,
            }
        };

        txn.create_item(&pos, value, Some(key));
    }

    /// Returns a value of an attribute given its `attr_name`. Returns `None` if no such attribute
    /// can be found inside of a current XML element.
    fn get_attribute<T: ReadTxn>(&self, txn: &T, attr_name: &str) -> Option<String> {
        let branch = self.as_ref();
        let value = branch.get(txn, attr_name)?;
        Some(value.to_string(txn))
    }

    /// Returns an unordered iterator over all attributes (key-value pairs), that can be found
    /// inside of a current XML element.
    fn attributes<'a, T: ReadTxn>(&'a self, txn: &'a T) -> Attributes<'a, &'a T, T> {
        Attributes(Entries::new(&self.as_ref().map, txn))
    }

    fn siblings<'a, T: ReadTxn>(&self, txn: &'a T) -> Siblings<'a, T> {
        let ptr = BranchPtr::from(self.as_ref());
        Siblings::new(ptr.item, txn)
    }
}

pub trait XmlFragment: AsRef<Branch> {
    fn first_child(&self) -> Option<XmlNode> {
        let first = self.as_ref().first()?;
        match &first.content {
            ItemContent::Type(c) => {
                let ptr = BranchPtr::from(c);
                XmlNode::try_from(ptr).ok()
            }
            _ => None,
        }
    }
    /// Returns a number of elements stored in current array.
    fn len<T: ReadTxn>(&self, _txn: &T) -> u32 {
        self.as_ref().len()
    }

    /// Inserts a `value` at the given `index`. Inserting at index `0` is equivalent to prepending
    /// current array with given `value`, while inserting at array length is equivalent to appending
    /// that value at the end of it.
    ///
    /// Using `index` value that's higher than current array length results in panic.
    fn insert<V>(&self, txn: &mut TransactionMut, index: u32, xml_node: V) -> V::Return
    where
        V: XmlPrelim,
    {
        let ptr = self.as_ref().insert_at(txn, index, xml_node);
        if let Ok(integrated) = V::Return::try_from(ptr) {
            integrated
        } else {
            panic!("Defect: inserted XML element returned primitive value block")
        }
    }

    /// Inserts given `value` at the end of the current array.
    fn push_back<V>(&self, txn: &mut TransactionMut, xml_node: V) -> V::Return
    where
        V: XmlPrelim,
    {
        let len = self.len(txn);
        self.insert(txn, len, xml_node)
    }

    /// Inserts given `value` at the beginning of the current array.
    fn push_front<V>(&self, txn: &mut TransactionMut, xml_node: V) -> V::Return
    where
        V: XmlPrelim,
    {
        self.insert(txn, 0, xml_node)
    }

    /// Removes a single element at provided `index`.
    fn remove(&self, txn: &mut TransactionMut, index: u32) {
        self.remove_range(txn, index, 1)
    }

    /// Removes a range of elements from current array, starting at given `index` up until
    /// a particular number described by `len` has been deleted. This method panics in case when
    /// not all expected elements were removed (due to insufficient number of elements in an array)
    /// or `index` is outside of the bounds of an array.
    fn remove_range(&self, txn: &mut TransactionMut, index: u32, len: u32) {
        let mut walker = BlockIter::new(BranchPtr::from(self.as_ref()));
        if walker.try_forward(txn, index) {
            walker.delete(txn, len)
        } else {
            panic!("Index {} is outside of the range of an array", index);
        }
    }

    /// Retrieves a value stored at a given `index`. Returns `None` when provided index was out
    /// of the range of a current array.
    fn get<T: ReadTxn>(&self, _txn: &T, index: u32) -> Option<XmlNode> {
        let branch = self.as_ref();
        let (content, _) = branch.get_at(index)?;
        if let ItemContent::Type(inner) = content {
            let ptr: BranchPtr = inner.into();
            XmlNode::try_from(ptr).ok()
        } else {
            None
        }
    }

    /// Returns an iterator that can be used to traverse over the successors of a current
    /// XML element. This includes recursive step over children of its children. The recursive
    /// iteration is depth-first.
    ///
    /// Example:
    /// ```
    /// /* construct node with a shape:
    ///    <div>
    ///       <p>Hello <b>world</b></p>
    ///       again
    ///    </div>
    /// */
    /// use yrs::{Doc, Text, Xml, XmlNode, Transact, XmlFragment, XmlElementPrelim, XmlTextPrelim, GetString};
    ///
    /// let doc = Doc::new();
    /// let mut html = doc.get_or_insert_xml_fragment("div");
    /// let mut txn = doc.transact_mut();
    /// let p = html.push_back(&mut txn, XmlElementPrelim::empty("p"));
    /// let txt = p.push_back(&mut txn, XmlTextPrelim::new("Hello "));
    /// let b = p.push_back(&mut txn, XmlElementPrelim::empty("b"));
    /// let txt = b.push_back(&mut txn, XmlTextPrelim::new("world"));
    /// let txt = html.push_back(&mut txn, XmlTextPrelim::new("again"));
    ///
    /// let mut result = Vec::new();
    /// for node in html.successors(&txn) {
    ///   let value = match node {
    ///       XmlNode::Element(elem) => elem.tag().to_string(),
    ///       XmlNode::Text(txt) => txt.get_string(&txn),
    ///       _ => panic!("shouldn't be the case here")
    ///   };
    ///   result.push(value);
    /// }
    /// assert_eq!(result, vec![
    ///   "p".to_string(),
    ///   "Hello ".to_string(),
    ///   "b".to_string(),
    ///   "world".to_string(),
    ///   "again".to_string()
    /// ]);
    /// ```
    fn successors<'a, T: ReadTxn>(&'a self, txn: &'a T) -> TreeWalker<'a, &'a T, T> {
        TreeWalker::new(self.as_ref(), txn)
    }
}

/// Iterator over the attributes (key-value pairs represented as a strings) of an [XmlElement].
pub struct Attributes<'a, B, T>(Entries<'a, B, T>);

impl<'a, B, T> Attributes<'a, B, T>
where
    B: Borrow<T>,
    T: ReadTxn,
{
    pub fn new(branch: &'a Branch, txn: B) -> Self {
        let entries = Entries::new(&branch.map, txn);
        Attributes(entries)
    }
}

impl<'a, B, T> Iterator for Attributes<'a, B, T>
where
    B: Borrow<T>,
    T: ReadTxn,
{
    type Item = (&'a str, String);

    fn next(&mut self) -> Option<Self::Item> {
        let (key, block) = self.0.next()?;
        let txn = self.0.txn.borrow();
        let value = block
            .content
            .get_last()
            .map(|v| v.to_string(txn))
            .unwrap_or(String::default());
        Some((key.as_ref(), value))
    }
}

/// An iterator over [XmlElement] successors, working in a recursive depth-first manner.
pub struct TreeWalker<'a, B, T> {
    current: Option<&'a Item>,
    root: TypePtr,
    first_call: bool,
    _txn: B,
    _marker: PhantomData<T>,
}

impl<'a, B, T: ReadTxn> TreeWalker<'a, B, T>
where
    B: Borrow<T>,
    T: ReadTxn,
{
    pub fn new(root: &'a Branch, txn: B) -> Self {
        TreeWalker {
            current: root.start.as_deref(),
            root: TypePtr::Branch(BranchPtr::from(root)),
            first_call: true,
            _txn: txn,
            _marker: PhantomData::default(),
        }
    }
}

impl<'a, B, T: ReadTxn> Iterator for TreeWalker<'a, B, T>
where
    B: Borrow<T>,
    T: ReadTxn,
{
    type Item = XmlNode;

    /// Tree walker used depth-first search to move over the xml tree.
    fn next(&mut self) -> Option<Self::Item> {
        fn try_descend(item: &Item) -> Option<&Item> {
            if let ItemContent::Type(t) = &item.content {
                let inner = t.as_ref();
                match inner.type_ref() {
                    TypeRef::XmlElement(_) | TypeRef::XmlFragment if !item.is_deleted() => {
                        return inner.start.as_deref();
                    }
                    _ => { /* do nothing */ }
                }
            }

            None
        }

        let mut result = None;
        let mut n = self.current.take();
        if let Some(current) = n {
            if !self.first_call || current.is_deleted() {
                while {
                    if let Some(current) = n {
                        if let Some(ptr) = try_descend(current) {
                            // depth-first search - try walk down the tree first
                            n = Some(ptr);
                        } else {
                            // walk right or up in the tree
                            while let Some(current) = n {
                                if let Some(right) = current.right.as_ref() {
                                    n = Some(right);
                                    break;
                                } else if current.parent == self.root {
                                    n = None;
                                } else {
                                    let ptr = current.parent.as_branch().unwrap();
                                    n = ptr.item.as_deref();
                                }
                            }
                        }
                    }
                    if let Some(current) = n {
                        current.is_deleted()
                    } else {
                        false
                    }
                } {}
            }
            self.first_call = false;
            self.current = n;
        }
        if let Some(current) = self.current {
            if let ItemContent::Type(t) = &current.content {
                result = XmlNode::try_from(BranchPtr::from(t)).ok();
            }
        }
        result
    }
}

/// Event generated by [XmlText::observe] method. Emitted during transaction commit phase.
pub struct XmlTextEvent {
    pub(crate) current_target: BranchPtr,
    target: XmlTextRef,
    delta: UnsafeCell<Option<Vec<Delta>>>,
    keys: UnsafeCell<Result<HashMap<Arc<str>, EntryChange>, HashSet<Option<Arc<str>>>>>,
}

impl XmlTextEvent {
    pub(crate) fn new(branch_ref: BranchPtr, key_changes: HashSet<Option<Arc<str>>>) -> Self {
        let current_target = branch_ref.clone();
        let target = XmlTextRef::from(branch_ref);
        XmlTextEvent {
            target,
            current_target,
            delta: UnsafeCell::new(None),
            keys: UnsafeCell::new(Err(key_changes)),
        }
    }

    /// Returns a [XmlText] instance which emitted this event.
    pub fn target(&self) -> &XmlTextRef {
        &self.target
    }

    /// Returns a path from root type down to [XmlText] instance which emitted this event.
    pub fn path(&self) -> Path {
        Branch::path(self.current_target, self.target.0)
    }

    /// Returns a summary of text changes made over corresponding [XmlText] collection within
    /// bounds of current transaction.
    pub fn delta(&self, txn: &TransactionMut) -> &[Delta] {
        let delta = unsafe { self.delta.get().as_mut().unwrap() };
        delta
            .get_or_insert_with(|| TextEvent::get_delta(self.target.0, txn))
            .as_slice()
    }

    /// Returns a summary of attribute changes made over corresponding [XmlText] collection within
    /// bounds of current transaction.
    pub fn keys(&self, txn: &TransactionMut) -> &HashMap<Arc<str>, EntryChange> {
        let keys = unsafe { self.keys.get().as_mut().unwrap() };

        match keys {
            Ok(keys) => {
                return keys;
            }
            Err(subs) => {
                let subs = event_keys(txn, self.target.0, subs);
                *keys = Ok(subs);
                if let Ok(keys) = keys {
                    keys
                } else {
                    panic!("Defect: should not happen");
                }
            }
        }
    }
}

pub struct Siblings<'a, T> {
    current: Option<ItemPtr>,
    _txn: &'a T,
}

impl<'a, T> Siblings<'a, T> {
    fn new(current: Option<ItemPtr>, txn: &'a T) -> Self {
        Siblings { current, _txn: txn }
    }
}

impl<'a, T> Iterator for Siblings<'a, T> {
    type Item = XmlNode;

    fn next(&mut self) -> Option<Self::Item> {
        while let Some(item) = self.current.as_deref() {
            self.current = item.right;
            if let Some(right) = self.current.as_deref() {
                if !right.is_deleted() {
                    if let ItemContent::Type(inner) = &right.content {
                        let ptr = BranchPtr::from(inner);
                        return XmlNode::try_from(ptr).ok();
                    }
                }
            }
        }

        None
    }
}

impl<'a, T> DoubleEndedIterator for Siblings<'a, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        while let Some(item) = self.current.as_deref() {
            self.current = item.left;
            if let Some(left) = self.current.as_deref() {
                if !left.is_deleted() {
                    if let ItemContent::Type(inner) = &left.content {
                        let ptr = BranchPtr::from(inner);
                        return XmlNode::try_from(ptr).ok();
                    }
                }
            }
        }

        None
    }
}

/// Event generated by [XmlElement::observe] method. Emitted during transaction commit phase.
pub struct XmlEvent {
    pub(crate) current_target: BranchPtr,
    target: XmlNode,
    change_set: UnsafeCell<Option<Box<ChangeSet<Change>>>>,
    keys: UnsafeCell<Result<HashMap<Arc<str>, EntryChange>, HashSet<Option<Arc<str>>>>>,
    children_changed: bool,
}

impl XmlEvent {
    pub(crate) fn new(branch_ref: BranchPtr, key_changes: HashSet<Option<Arc<str>>>) -> Self {
        let current_target = branch_ref.clone();
        let children_changed = key_changes.iter().any(Option::is_none);
        XmlEvent {
            target: XmlNode::try_from(branch_ref).unwrap(),
            current_target,
            change_set: UnsafeCell::new(None),
            keys: UnsafeCell::new(Err(key_changes)),
            children_changed,
        }
    }

    /// True if any child XML nodes have been changed within bounds of current transaction.
    pub fn children_changed(&self) -> bool {
        self.children_changed
    }

    /// Returns a [XmlElement] instance which emitted this event.
    pub fn target(&self) -> &XmlNode {
        &self.target
    }

    /// Returns a path from root type down to [XmlElement] instance which emitted this event.
    pub fn path(&self) -> Path {
        Branch::path(self.current_target, self.target.as_ptr())
    }

    /// Returns a summary of XML child nodes changed within corresponding [XmlElement] collection
    /// within bounds of current transaction.
    pub fn delta(&self, txn: &TransactionMut) -> &[Change] {
        self.changes(txn).delta.as_slice()
    }

    /// Returns a collection of block identifiers that have been added within a bounds of
    /// current transaction.
    pub fn added(&self, txn: &TransactionMut) -> &HashSet<ID> {
        &self.changes(txn).added
    }

    /// Returns a collection of block identifiers that have been removed within a bounds of
    /// current transaction.
    pub fn deleted(&self, txn: &TransactionMut) -> &HashSet<ID> {
        &self.changes(txn).deleted
    }

    /// Returns a summary of attribute changes made over corresponding [XmlElement] collection
    /// within bounds of current transaction.
    pub fn keys(&self, txn: &TransactionMut) -> &HashMap<Arc<str>, EntryChange> {
        let keys = unsafe { self.keys.get().as_mut().unwrap() };

        match keys {
            Ok(keys) => keys,
            Err(subs) => {
                let subs = event_keys(txn, self.target.as_ptr(), subs);
                *keys = Ok(subs);
                if let Ok(keys) = keys {
                    keys
                } else {
                    panic!("Defect: should not happen");
                }
            }
        }
    }

    fn changes(&self, txn: &TransactionMut) -> &ChangeSet<Change> {
        let change_set = unsafe { self.change_set.get().as_mut().unwrap() };
        change_set
            .get_or_insert_with(|| Box::new(event_change_set(txn, self.target.as_ptr().start)))
    }
}

#[cfg(test)]
mod test {
    use crate::branch::BranchPtr;
    use crate::test_utils::exchange_updates;
    use crate::transaction::ReadTxn;
    use crate::types::xml::{Xml, XmlFragment, XmlNode};
    use crate::types::{Attrs, Change, EntryChange, Value};
    use crate::updates::decoder::Decode;
    use crate::updates::encoder::{Encoder, EncoderV1};
    use crate::{
        Any, Doc, GetString, Observable, SharedRef, StateVector, Text, Transact, Update,
        XmlElementPrelim, XmlTextPrelim, XmlTextRef,
    };
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::rc::Rc;

    #[test]
    fn insert_attribute() {
        let d1 = Doc::with_client_id(1);
        let f = d1.get_or_insert_xml_fragment("xml");
        let mut t1 = d1.transact_mut();
        let xml1 = f.push_back(&mut t1, XmlElementPrelim::empty("div"));
        xml1.insert_attribute(&mut t1, "height", 10.to_string());
        assert_eq!(xml1.get_attribute(&t1, "height"), Some("10".to_string()));

        let d2 = Doc::with_client_id(1);
        let f = d2.get_or_insert_xml_fragment("xml");
        let mut t2 = d2.transact_mut();
        let xml2 = f.push_back(&mut t2, XmlElementPrelim::empty("div"));
        let u = t1.encode_state_as_update_v1(&StateVector::default());
        t2.apply_update(Update::decode_v1(u.as_slice()).unwrap());
        assert_eq!(xml2.get_attribute(&t2, "height"), Some("10".to_string()));
    }

    #[test]
    fn tree_walker() {
        let doc = Doc::with_client_id(1);
        let root = doc.get_or_insert_xml_fragment("xml");
        let mut txn = doc.transact_mut();
        /*
            <UNDEFINED>
                <p>{txt1}{txt2}</p>
                <p></p>
                <img/>
            </UNDEFINED>
        */
        let p1 = root.push_back(&mut txn, XmlElementPrelim::empty("p"));
        p1.push_back(&mut txn, XmlTextPrelim::new(""));
        p1.push_back(&mut txn, XmlTextPrelim::new(""));
        let p2 = root.push_back(&mut txn, XmlElementPrelim::empty("p"));
        root.push_back(&mut txn, XmlElementPrelim::empty("img"));

        let all_paragraphs = root.successors(&txn).filter_map(|n| match n {
            XmlNode::Element(e) if e.tag() == &"p".into() => Some(e),
            _ => None,
        });
        let actual: Vec<_> = all_paragraphs.collect();

        assert_eq!(
            actual.len(),
            2,
            "query selector should found two paragraphs"
        );
        assert_eq!(
            actual[0].hook(),
            p1.hook(),
            "query selector found 1st paragraph"
        );
        assert_eq!(
            actual[1].hook(),
            p2.hook(),
            "query selector found 2nd paragraph"
        );
    }

    #[test]
    fn text_attributes() {
        let doc = Doc::with_client_id(1);
        let f = doc.get_or_insert_xml_fragment("test");
        let mut txn = doc.transact_mut();
        let txt = f.push_back(&mut txn, XmlTextPrelim::new(""));
        txt.insert_attribute(&mut txn, "test", 42.to_string());

        assert_eq!(txt.get_attribute(&txn, "test"), Some("42".to_string()));
        let actual: Vec<_> = txt.attributes(&txn).collect();
        assert_eq!(actual, vec![("test", "42".to_string())]);
    }

    #[test]
    fn siblings() {
        let doc = Doc::with_client_id(1);
        let root = doc.get_or_insert_xml_fragment("root");
        let mut txn = doc.transact_mut();
        let first = root.push_back(&mut txn, XmlTextPrelim::new("hello"));
        let second = root.push_back(&mut txn, XmlElementPrelim::empty("p"));

        assert_eq!(
            &first.siblings(&txn).next().unwrap().id(),
            second.hook().id(),
            "first.next_sibling should point to second"
        );
        assert_eq!(
            &second.siblings(&txn).next_back().unwrap().id(),
            first.hook().id(),
            "second.prev_sibling should point to first"
        );
        assert_eq!(
            &first.parent().unwrap().id(),
            root.hook().id(),
            "first.parent should point to root"
        );
        assert!(root.parent().is_none(), "root parent should not exist");
        assert_eq!(
            &root.first_child().unwrap().id(),
            first.hook().id(),
            "root.first_child should point to first"
        );
    }

    #[test]
    fn serialization() {
        let d1 = Doc::with_client_id(1);
        let r1 = d1.get_or_insert_xml_fragment("root");
        let mut t1 = d1.transact_mut();
        let _first = r1.push_back(&mut t1, XmlTextPrelim::new("hello"));
        r1.push_back(&mut t1, XmlElementPrelim::empty("p"));

        let expected = "hello<p></p>";
        assert_eq!(r1.get_string(&t1), expected);

        let u1 = t1.encode_state_as_update_v1(&StateVector::default());

        let d2 = Doc::with_client_id(2);
        let r2 = d2.get_or_insert_xml_fragment("root");
        let mut t2 = d2.transact_mut();

        t2.apply_update(Update::decode_v1(u1.as_slice()).unwrap());
        assert_eq!(r2.get_string(&t2), expected);
    }

    #[test]
    fn serialization_compatibility() {
        let d1 = Doc::with_client_id(1);
        let r1 = d1.get_or_insert_xml_fragment("root");
        let mut t1 = d1.transact_mut();
        let _first = r1.push_back(&mut t1, XmlTextPrelim::new("hello"));
        r1.push_back(&mut t1, XmlElementPrelim::empty("p"));

        /* This binary is result of following Yjs code (matching Rust code above):
        ```js
            let d1 = new Y.Doc()
            d1.clientID = 1
            let root = d1.get('root', Y.XmlElement)
            let first = new Y.XmlText()
            first.insert(0, 'hello')
            let second = new Y.XmlElement('p')
            root.insert(0, [first,second])

            let expected = Y.encodeStateAsUpdate(d1)
        ``` */
        let expected = &[
            1, 3, 1, 0, 7, 1, 4, 114, 111, 111, 116, 6, 4, 0, 1, 0, 5, 104, 101, 108, 108, 111,
            135, 1, 0, 3, 1, 112, 0,
        ];
        let u1 = t1.encode_state_as_update_v1(&StateVector::default());
        assert_eq!(u1.as_slice(), expected);
    }

    #[test]
    fn event_observers() {
        let d1 = Doc::with_client_id(1);
        let f = d1.get_or_insert_xml_fragment("xml");
        let xml = f.insert(&mut d1.transact_mut(), 0, XmlElementPrelim::empty("test"));

        let d2 = Doc::with_client_id(2);
        let f = d2.get_or_insert_xml_fragment("xml");
        exchange_updates(&[&d1, &d2]);
        let xml2 = f
            .get(&d2.transact(), 0)
            .unwrap()
            .into_xml_element()
            .unwrap();

        let attributes = Rc::new(RefCell::new(None));
        let nodes = Rc::new(RefCell::new(None));
        let attributes_c = attributes.clone();
        let nodes_c = nodes.clone();
        let _sub = xml.observe(move |txn, e| {
            *attributes_c.borrow_mut() = Some(e.keys(txn).clone());
            *nodes_c.borrow_mut() = Some(e.delta(txn).to_vec());
        });

        // insert attribute
        {
            let mut txn = d1.transact_mut();
            xml.insert_attribute(&mut txn, "key1", "value1");
            xml.insert_attribute(&mut txn, "key2", "value2");
        }
        assert!(nodes.borrow_mut().take().unwrap().is_empty());
        assert_eq!(
            attributes.borrow_mut().take(),
            Some(HashMap::from([
                (
                    "key1".into(),
                    EntryChange::Inserted(Any::String("value1".into()).into())
                ),
                (
                    "key2".into(),
                    EntryChange::Inserted(Any::String("value2".into()).into())
                )
            ]))
        );

        // change and remove attribute
        {
            let mut txn = d1.transact_mut();
            xml.insert_attribute(&mut txn, "key1", "value11");
            xml.remove_attribute(&mut txn, &"key2");
        }
        assert!(nodes.borrow_mut().take().unwrap().is_empty());
        assert_eq!(
            attributes.borrow_mut().take(),
            Some(HashMap::from([
                (
                    "key1".into(),
                    EntryChange::Updated(
                        Any::String("value1".into()).into(),
                        Any::String("value11".into()).into()
                    )
                ),
                (
                    "key2".into(),
                    EntryChange::Removed(Any::String("value2".into()).into())
                )
            ]))
        );

        // add xml elements
        let (nested_txt, nested_xml) = {
            let mut txn = d1.transact_mut();
            let txt = xml.insert(&mut txn, 0, XmlTextPrelim::new(""));
            let xml2 = xml.insert(&mut txn, 1, XmlElementPrelim::empty("div"));
            (txt, xml2)
        };
        assert_eq!(
            nodes.borrow_mut().take(),
            Some(vec![Change::Added(vec![
                Value::YXmlText(nested_txt.clone()),
                Value::YXmlElement(nested_xml.clone())
            ])])
        );
        assert_eq!(attributes.borrow_mut().take(), Some(HashMap::new()));

        // remove and add
        let nested_xml2 = {
            let mut txn = d1.transact_mut();
            xml.remove_range(&mut txn, 1, 1);
            xml.insert(&mut txn, 1, XmlElementPrelim::empty("p"))
        };
        assert_eq!(
            nodes.borrow_mut().take(),
            Some(vec![
                Change::Retain(1),
                Change::Added(vec![Value::YXmlElement(nested_xml2.clone())]),
                Change::Removed(1),
            ])
        );
        assert_eq!(attributes.borrow_mut().take(), Some(HashMap::new()));

        // copy updates over
        let attributes = Rc::new(RefCell::new(None));
        let nodes = Rc::new(RefCell::new(None));
        let attributes_c = attributes.clone();
        let nodes_c = nodes.clone();
        let _sub = xml2.observe(move |txn, e| {
            *attributes_c.borrow_mut() = Some(e.keys(txn).clone());
            *nodes_c.borrow_mut() = Some(e.delta(txn).to_vec());
        });

        {
            let t1 = d1.transact_mut();
            let mut t2 = d2.transact_mut();
            let sv = t2.state_vector();
            let mut encoder = EncoderV1::new();
            t1.encode_diff(&sv, &mut encoder);
            t2.apply_update(Update::decode_v1(encoder.to_vec().as_slice()).unwrap());
        }
        assert_eq!(
            nodes.borrow_mut().take(),
            Some(vec![Change::Added(vec![
                Value::YXmlText(nested_txt),
                Value::YXmlElement(nested_xml2)
            ])])
        );
        assert_eq!(
            attributes.borrow_mut().take(),
            Some(HashMap::from([(
                "key1".into(),
                EntryChange::Inserted(Any::String("value11".into()).into())
            )]))
        );
    }

    #[test]
    fn xml_to_string() {
        let doc = Doc::new();
        let f = doc.get_or_insert_xml_fragment("test");
        let mut txn = doc.transact_mut();
        let div = f.push_back(&mut txn, XmlElementPrelim::empty("div"));
        div.insert_attribute(&mut txn, "class", "t-button");
        let text = div.push_back(&mut txn, XmlTextPrelim::new("hello world"));
        text.format(
            &mut txn,
            6,
            5,
            Attrs::from([(
                "a".into(),
                HashMap::from([("href".into(), "http://domain.org")]).into(),
            )]),
        );
        drop(txn);

        let str = f.get_string(&doc.transact());
        assert_eq!(
            str.as_str(),
            "<div class=\"t-button\">hello <a href=\"http://domain.org\">world</a></div>"
        )
    }

    #[test]
    fn xml_to_string_2() {
        let doc = Doc::new();
        let f = doc.get_or_insert_xml_fragment("article");
        let xml = f.insert(&mut doc.transact_mut(), 0, XmlTextPrelim::new(""));
        let mut txn = doc.transact_mut();

        let bold = Attrs::from([("b".into(), true.into())]);
        let italic = Attrs::from([("i".into(), true.into())]);

        xml.insert(&mut txn, 0, "hello ");
        xml.insert_with_attributes(&mut txn, 6, "world", italic);
        xml.format(&mut txn, 0, 5, bold);

        assert_eq!(xml.get_string(&txn), "<b>hello</b> <i>world</i>");

        let remove_italic = Attrs::from([("i".into(), Any::Null)]);
        xml.format(&mut txn, 6, 5, remove_italic);

        assert_eq!(xml.get_string(&txn), "<b>hello</b> world");
    }

    #[test]
    fn format_attributes_decode_compatibility_v1() {
        let data = &[
            1, 6, 1, 0, 6, 1, 4, 116, 101, 115, 116, 1, 105, 4, 116, 114, 117, 101, 132, 1, 0, 6,
            104, 101, 108, 108, 111, 32, 132, 1, 6, 5, 119, 111, 114, 108, 100, 134, 1, 11, 1, 105,
            4, 110, 117, 108, 108, 198, 1, 6, 1, 7, 1, 98, 4, 116, 114, 117, 101, 134, 1, 12, 1,
            98, 4, 110, 117, 108, 108, 0,
        ];
        let update = Update::decode_v1(data).unwrap();
        let doc = Doc::new();
        let txt = doc.get_or_insert_text("test");
        let txt = XmlTextRef::from(BranchPtr::from(txt.as_ref()));
        let mut txn = doc.transact_mut();

        txn.apply_update(update);
        assert_eq!(txt.get_string(&txn), "<i>hello </i><b><i>world</i></b>");

        let actual = txn.encode_state_as_update_v1(&StateVector::default());
        assert_eq!(actual, data);
    }

    #[test]
    fn format_attributes_decode_compatibility_v2() {
        let data = &[
            0, 3, 0, 3, 1, 2, 65, 5, 5, 0, 12, 10, 74, 12, 1, 14, 9, 6, 0, 132, 1, 134, 0, 198, 0,
            134, 26, 19, 116, 101, 115, 116, 105, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108,
            100, 105, 98, 98, 4, 1, 6, 5, 65, 1, 1, 1, 0, 0, 1, 6, 0, 120, 126, 120, 126, 0,
        ];
        let update = Update::decode_v2(data).unwrap();
        let doc = Doc::new();
        let txt = doc.get_or_insert_text("test");
        let txt = XmlTextRef::from(BranchPtr::from(txt.as_ref()));
        let mut txn = doc.transact_mut();

        txn.apply_update(update);
        assert_eq!(txt.get_string(&txn), "<i>hello </i><b><i>world</i></b>");

        let actual = txn.encode_state_as_update_v2(&StateVector::default());
        assert_eq!(actual, data);
    }
}