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
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::collections::HashMap;
use std::cell::{RefCell, Ref, RefMut};
use std::fmt;
use std::rc::{Rc, Weak};
use std::str::FromStr;

use attribute::*;
use parser::parse_svg;
use write;
use super::{
    AttributeId,
    Attributes,
    ElementId,
    Error,
    ParseOptions,
    WriteBuffer,
    WriteOptions,
    WriteToString,
};

/// Container of [`Node`](struct.Node.html)s.
pub struct Document {
    root: Node,
}

impl Document {
    /// Constructs a new `Document`.
    pub fn new() -> Document {
        Document {
            root: Document::new_node(None, NodeType::Root, None, None)
        }
    }

    /// Constructs a new `Document` from `data` using default `ParseOptions`.
    pub fn from_data(data: &[u8]) -> Result<Document, Error> {
        Document::from_data_with_opt(data, &ParseOptions::default())
    }

    /// Constructs a new `Document` from `data` using supplied `ParseOptions`.
    pub fn from_data_with_opt(data: &[u8], opt: &ParseOptions) -> Result<Document, Error> {
        parse_svg(data, opt)
    }

    /// Constructs a new `Node` with `Element` type.
    ///
    /// Constructed node do belong to this document, but not added to it tree structure.
    pub fn create_element<T>(&self, tag_name: T) -> Node
        where TagName: From<T>
    {
        let t = TagName::from(tag_name);

        // TODO: return error
        match &t {
            &TagName::Name(ref name) => debug_assert!(!name.is_empty()),
            _ => {},
        }

        Document::new_node(Some(self.root.0.clone()), NodeType::Element, Some(t), None)
    }

    /// Constructs a new `Node` using supplied `NodeType`.
    ///
    /// Constructed node do belong to this document, but not added to it tree structure.
    ///
    /// This method should be used for any non-element nodes.
    pub fn create_node(&self, node_type: NodeType, text: &str) -> Node {
        debug_assert!(node_type != NodeType::Element && node_type != NodeType::Root);
        Document::new_node(Some(self.root.0.clone()), node_type, None, Some(text.to_owned()))
    }

    /// Constructs a new element with text node.
    ///
    /// # Examples
    /// ```
    /// use svgdom::{Document, ElementId};
    ///
    /// let doc = Document::new();
    /// doc.append(&doc.create_element_with_text(ElementId::Text, "text"));
    ///
    /// assert_eq!(doc.to_string(),
    /// "<text>
    ///     text
    /// </text>
    /// ");
    /// ```
    pub fn create_element_with_text<T>(&self, tag_name: T, text: &str) -> Node
        where TagName: From<T>
    {
        let elem = self.create_element(tag_name);
        let text_node = self.create_node(NodeType::Text, text);
        elem.append(&text_node);
        elem
    }

    /// Returns root `Node`.
    pub fn root(&self) -> Node {
        self.root.clone()
    }

    /// Returns first child of the root `Node`.
    ///
    /// # Panics
    ///
    /// Panics if the root node is currently mutability borrowed.
    pub fn first_child(&self) -> Option<Node> {
        self.root().first_child()
    }

    /// Returns first child with `NodeType::Element` of the root `Node`.
    ///
    /// # Panics
    ///
    /// Panics if the root node is currently mutability borrowed.
    ///
    /// # Examples
    /// ```
    /// use svgdom::Document;
    ///
    /// let doc = Document::from_data(b"<!--comment--><svg/>").unwrap();
    ///
    /// assert_eq!(doc.first_child().unwrap().is_element(), false);
    /// assert_eq!(doc.first_element_child().unwrap().is_element(), true);
    /// ```
    pub fn first_element_child(&self) -> Option<Node> {
        for n in self.root.children() {
            if n.is_element() {
                return Some(n.clone());
            }
        }

        None
    }

    /// Returns first child with `svg` tag name of the root `Node`.
    ///
    /// In most of the cases result of this method and `first_element_child()` will be the same,
    /// but an additional check may be helpful.
    ///
    /// # Panics
    ///
    /// Panics if the root node is currently mutability borrowed.
    ///
    /// # Examples
    /// ```
    /// use svgdom::{Document, ElementId};
    ///
    /// let doc = Document::from_data(b"<!--comment--><svg/>").unwrap();
    ///
    /// assert_eq!(doc.svg_element().unwrap().is_tag_id(ElementId::Svg), true);
    /// ```
    pub fn svg_element(&self) -> Option<Node> {
        for n in self.root.children() {
            if n.is_element() && n.is_tag_id(ElementId::Svg) {
                return Some(n.clone());
            }
        }

        None
    }

    /// Appends a new child to root node, after existing children, and returns it.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed.
    ///
    /// # Examples
    /// ```
    /// use svgdom::{Document, ElementId};
    ///
    /// let doc = Document::new();
    /// doc.append(&doc.create_element(ElementId::Svg));
    ///
    /// assert_eq!(doc.to_string(), "<svg/>\n");
    /// ```
    pub fn append(&self, new_child: &Node) -> Node {
        self.root.append(new_child);
        new_child.clone()
    }

    /// Returns iterator over descendant SVG elements.
    pub fn descendants(&self) -> Descendants {
        self.root.descendants()
    }

    /// Returns iterator over descendant SVG nodes.
    pub fn descendants_all(&self) -> DescendantsAll {
        self.root.descendants_all()
    }

    fn new_node(doc: Option<Link>, node_type: NodeType, tag_name: Option<TagName>,
                text: Option<String>)
                -> Node {
        Node(Rc::new(RefCell::new(NodeData {
            doc: doc,
            parent: None,
            first_child: None,
            last_child: None,
            previous_sibling: None,
            next_sibling: None,
            node_type: node_type,
            tag_name: tag_name,
            id: String::new(),
            attributes: Attributes::new(),
            ext_attributes: HashMap::new(),
            linked_nodes: Vec::new(),
            text: text,
        })))
    }
}

impl WriteBuffer for Document {
    fn write_buf_opt(&self, opt: &WriteOptions, buf: &mut Vec<u8>) {
        write::write_dom(self, opt, buf);
    }
}

impl_display!(Document);

macro_rules! try_opt {
    ($expr: expr) => {
        match $expr {
            Some(value) => value,
            None => return None
        }
    }
}

/// Representation of an SVG node.
///
/// This is main block of the library.
///
/// It's designed as classical DOM node. We have links to parent node, first child, last child,
/// previous sibling and next sibling. So DOM nodes manipulations are very fast.
///
/// Node consist of:
///  - The `NodeType`, which indicates it's type. It can't be changed.
///  - Optional `TagName`, used only by the element nodes.
///  - Unique ID of the element node. Can be set to the nodes with other types,
///    but without any affect.
///  - List of the SVG attributes.
///  - List of the unknown attributes.
///  - Optional text data, which is used by non-element nodes.
///
/// Most of the API are designed to work with SVG elements and attributes.
/// Processing of non-SVG data is pretty hard/verbose, since it's an SVG DOM, not an XML.
pub struct Node(Rc<RefCell<NodeData>>);

impl Node {
    /// Returns a `Document` that owns this node.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn document(&self) -> Document {
        // TODO: will fail on root node
        Document { root: Node(self.0.borrow().doc.as_ref().unwrap().clone()) }
    }

    /// Returns a parent node, unless this node is the root of the tree.
    ///
    /// This method also returns `NodeType::Root`.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn parent(&self) -> Option<Node> {
        // TODO: we actually always have a parent - Root node
        Some(Node(try_opt!(try_opt!(self.0.borrow().parent.as_ref()).upgrade())))
    }

    /// Returns a parent element with selected tag name.
    ///
    /// Returns `None` if this node is the root of the tree or there is no parent
    /// nodes with such tag name.
    ///
    /// # Panics
    ///
    /// Panics if any of the parent nodes is currently mutability borrowed.
    pub fn parent_element<T>(&self, tag_name: T) -> Option<Node>
        where TagName: From<T>
    {
        let tg = TagName::from(tag_name);
        let mut parent = self.parent();
        while let Some(p) = parent {
            if p.is_tag_name(&tg) {
                return Some(p.clone());
            }
            parent = p.parent();
        }
        None
    }

    /// Returns `true` if node has parent node.
    ///
    /// This method ignores root node.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    ///
    /// # Examples
    /// ```
    /// use svgdom::Document;
    ///
    /// let doc = Document::from_data(
    /// b"<svg>
    ///     <rect/>
    /// </svg>").unwrap();
    ///
    /// let svg = doc.first_child().unwrap();
    /// let rect = svg.first_child().unwrap();
    /// assert_eq!(svg.has_parent(), false);
    /// assert_eq!(rect.has_parent(), true);
    /// ```
    pub fn has_parent(&self) -> bool {
        match self.parent() {
            Some(node) => {
                match node.node_type() {
                    NodeType::Root => false,
                    _ => true,
                }
            }
            None => false,
        }
    }

    /// Returns an iterator to this node’s children.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn children(&self) -> Children {
        Children(self.first_child())
    }

    /// Returns `true` is this node has children nodes.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn has_children(&self) -> bool {
        self.first_child().is_some()
    }

    /// Returns a reference to the first child of this node, unless it has no child.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn first_child(&self) -> Option<Node> {
        Some(Node(try_opt!(self.0.borrow().first_child.as_ref()).clone()))
    }

    /// Returns a reference to the last child of this node, unless it has no child.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn last_child(&self) -> Option<Node> {
        Some(Node(try_opt!(try_opt!(self.0.borrow().last_child.as_ref()).upgrade())))
    }

    /// Returns a reference to the previous sibling of this node, unless it is a first child.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn previous_sibling(&self) -> Option<Node> {
        Some(Node(try_opt!(try_opt!(self.0.borrow().previous_sibling.as_ref()).upgrade())))
    }

    /// Returns a reference to the previous sibling of this node, unless it is a first child.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn next_sibling(&self) -> Option<Node> {
        Some(Node(try_opt!(self.0.borrow().next_sibling.as_ref()).clone()))
    }

    /// Returns whether two references point to the same node.
    pub fn same_node(&self, other: &Node) -> bool {
        same_rc(&self.0, &other.0)
    }

    /// Detaches a node from its parent and siblings. Children are not affected.
    ///
    /// # Panics
    ///
    /// Panics if the node or one of its adjoining nodes is currently borrowed.
    pub fn detach(&self) {
        self.0.borrow_mut().detach();
    }

    /// Removes this node and all it children from the tree.
    ///
    /// Same as `detach()`, but also unlinks all linked nodes and attributes.
    ///
    /// # Panics
    ///
    /// Panics if the node or one of its adjoining nodes or any children node is currently borrowed.
    pub fn remove(&self) {
        Node::_remove(self);
        self.detach();
    }

    fn _remove(node: &Node) {
        // remove all attributes, which will trigger nodes unlink
        // if this node has referenced attributes
        let ids: Vec<AttributeId> = node.attributes().iter().map(|a| a.id).collect();
        for id in ids {
            node.remove_attribute(id);
        }

        // remove all attributes that linked to this node
        let mut link_ids = Vec::new();
        for linked in node.linked_nodes() {
            for attr in linked.attributes().iter() {
                match attr.value {
                    AttributeValue::Link(ref link) | AttributeValue::FuncLink(ref link) => {
                        if link == node {
                            link_ids.push(attr.id);
                        }
                    }
                    _ => {}
                }
            }

            while let Some(id) = link_ids.pop() {
                linked.remove_attribute(id);
            }
        }

        // repeat for children
        for child in node.children() {
            Node::_remove(&child);
        }
    }

    /// Appends a new child to this node, after existing children.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed.
    pub fn append(&self, new_child: &Node) {
        let mut self_borrow = self.0.borrow_mut();
        let mut last_child_opt = None;
        let nc = new_child.clone();
        {
            let mut new_child_borrow = nc.0.borrow_mut();
            new_child_borrow.detach();
            new_child_borrow.parent = Some(Rc::downgrade(&self.0));
            if let Some(last_child_weak) = self_borrow.last_child.take() {
                if let Some(last_child_strong) = last_child_weak.upgrade() {
                    new_child_borrow.previous_sibling = Some(last_child_weak);
                    last_child_opt = Some(last_child_strong);
                }
            }
            self_borrow.last_child = Some(Rc::downgrade(&nc.0));
        }

        if let Some(last_child_strong) = last_child_opt {
            let mut last_child_borrow = last_child_strong.borrow_mut();
            debug_assert!(last_child_borrow.next_sibling.is_none());
            last_child_borrow.next_sibling = Some(nc.0);
        } else {
            // No last child
            debug_assert!(self_borrow.first_child.is_none());
            self_borrow.first_child = Some(nc.0);
        }
    }

    /// Prepends a new child to this node, before existing children.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new child, or one of their adjoining nodes is currently borrowed.
    pub fn prepend(&self, new_child: Node) {
        let mut self_borrow = self.0.borrow_mut();
        {
            let mut new_child_borrow = new_child.0.borrow_mut();
            new_child_borrow.detach();
            new_child_borrow.parent = Some(Rc::downgrade(&self.0));
            match self_borrow.first_child.take() {
                Some(first_child_strong) => {
                    {
                        let mut first_child_borrow = first_child_strong.borrow_mut();
                        debug_assert!(first_child_borrow.previous_sibling.is_none());
                        first_child_borrow.previous_sibling = Some(Rc::downgrade(&new_child.0));
                    }
                    new_child_borrow.next_sibling = Some(first_child_strong);
                }
                None => {
                    debug_assert!(self_borrow.first_child.is_none());
                    self_borrow.last_child = Some(Rc::downgrade(&new_child.0));
                }
            }
        }
        self_borrow.first_child = Some(new_child.0);
    }

    /// Insert a new sibling after this node.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new sibling, or one of their adjoining nodes is currently borrowed.
    pub fn insert_after(&self, new_sibling: Node) {
        // TODO: add an example, since we need to detach 'new_sibling'
        //       before passing it to this method
        let mut self_borrow = self.0.borrow_mut();
        {
            let mut new_sibling_borrow = new_sibling.0.borrow_mut();
            new_sibling_borrow.detach();
            new_sibling_borrow.parent = self_borrow.parent.clone();
            new_sibling_borrow.previous_sibling = Some(Rc::downgrade(&self.0));
            match self_borrow.next_sibling.take() {
                Some(next_sibling_strong) => {
                    {
                        let mut next_sibling_borrow = next_sibling_strong.borrow_mut();
                        debug_assert!({
                            let weak = next_sibling_borrow.previous_sibling.as_ref().unwrap();
                            same_rc(&weak.upgrade().unwrap(), &self.0)
                        });
                        next_sibling_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
                    }
                    new_sibling_borrow.next_sibling = Some(next_sibling_strong);
                }
                None => {
                    if let Some(parent_ref) = self_borrow.parent.as_ref() {
                        if let Some(parent_strong) = parent_ref.upgrade() {
                            let mut parent_borrow = parent_strong.borrow_mut();
                            parent_borrow.last_child = Some(Rc::downgrade(&new_sibling.0));
                        }
                    }
                }
            }
        }
        self_borrow.next_sibling = Some(new_sibling.0);
    }

    /// Insert a new sibling before this node.
    ///
    /// # Panics
    ///
    /// Panics if the node, the new sibling, or one of their adjoining nodes is currently borrowed.
    pub fn insert_before(&self, new_sibling: Node) {
        let mut self_borrow = self.0.borrow_mut();
        let mut previous_sibling_opt = None;
        {
            let mut new_sibling_borrow = new_sibling.0.borrow_mut();
            new_sibling_borrow.detach();
            new_sibling_borrow.parent = self_borrow.parent.clone();
            new_sibling_borrow.next_sibling = Some(self.0.clone());
            if let Some(previous_sibling_weak) = self_borrow.previous_sibling.take() {
                if let Some(previous_sibling_strong) = previous_sibling_weak.upgrade() {
                    new_sibling_borrow.previous_sibling = Some(previous_sibling_weak);
                    previous_sibling_opt = Some(previous_sibling_strong);
                }
            }
            self_borrow.previous_sibling = Some(Rc::downgrade(&new_sibling.0));
        }

        if let Some(previous_sibling_strong) = previous_sibling_opt {
            let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
            debug_assert!({
                let rc = previous_sibling_borrow.next_sibling.as_ref().unwrap();
                same_rc(rc, &self.0)
            });
            previous_sibling_borrow.next_sibling = Some(new_sibling.0);
        } else {
            // No previous sibling.
            if let Some(parent_ref) = self_borrow.parent.as_ref() {
                if let Some(parent_strong) = parent_ref.upgrade() {
                    let mut parent_borrow = parent_strong.borrow_mut();
                    parent_borrow.first_child = Some(new_sibling.0);
                }
            }
        }
    }

    /// Returns node's type.
    ///
    /// You can't change type of the node. Only create new one.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn node_type(&self) -> NodeType {
        self.0.borrow().node_type
    }

    /// Returns a text data of the node, if there are any.
    ///
    /// Nodes with `Element` type can't contain text data.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn text(&self) -> Option<Ref<String>> {
        let b = self.0.borrow();
        match b.text {
            Some(_) => Some(Ref::map(self.0.borrow(), |n| n.text.as_ref().unwrap())),
            None => None,
        }
    }

    // TODO: set_text

    /// Returns `true` if there are any children text nodes.
    ///
    /// This method is recursive.
    ///
    /// # Panics
    ///
    /// Panics if the node or any descendants nodes are currently mutability borrowed.
    ///
    /// # Examples
    /// ```
    /// use svgdom::Document;
    ///
    /// let doc = Document::from_data(
    /// b"<svg>
    ///     <g>
    ///         <text>Some text</text>
    ///     </g>
    ///     <rect/>
    /// </svg>").unwrap();
    ///
    /// let svg = doc.first_child().unwrap();
    /// let g = svg.first_child().unwrap();
    /// assert_eq!(g.has_text_children(), true);
    ///
    /// let text = g.first_child().unwrap();
    /// assert_eq!(text.has_text_children(), true);
    ///
    /// let rect = g.next_sibling().unwrap();
    /// assert_eq!(rect.has_text_children(), false);
    /// ```
    pub fn has_text_children(&self) -> bool {
        // TODO: to has_text_child and check only first child

        for node in self.descendants_all() {
            if node.node_type() == NodeType::Text {
                return true;
            }
        }
        false
    }

    /// Sets an ID of the element.
    ///
    /// Only element nodes can contain ID.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently borrowed.
    pub fn set_id<S: Into<String>>(&self, id: S) {
        // TODO: check that it's unique.
        debug_assert!(self.node_type() == NodeType::Element);
        let mut self_borrow = self.0.borrow_mut();
        self_borrow.id = id.into();
    }

    /// Returns an ID of the element node.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn id(&self) -> Ref<String> {
        Ref::map(self.0.borrow(), |n| &n.id)
    }

    /// Returns `true` if node has a not empty ID.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn has_id(&self) -> bool {
        !self.0.borrow().id.is_empty()
    }

    /// Returns `true` if node has `Element` type.
    ///
    /// Shorthand for `node.node_type() == NodeType::Element`.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn is_element(&self) -> bool {
        match self.tag_name() {
            Some(tag) => {
                match *tag {
                    TagName::Id(_) => true,
                    TagName::Name(_) => false,
                }
            }
            None => false,
        }
    }

    /// Sets a tag name of the element node.
    ///
    /// Only element nodes can contain tag name.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently borrowed.
    pub fn set_tag_name<T>(&self, tag_name: T)
        where TagName: From<T>
    {
        debug_assert!(self.node_type() == NodeType::Element);

        let t = TagName::from(tag_name);

        // TODO: to error
        // tag_name can't be empty
        match &t {
            &TagName::Name(ref name) => debug_assert!(!name.is_empty()),
            _ => {},
        }

        let mut self_borrow = self.0.borrow_mut();
        self_borrow.tag_name = Some(t);
    }

    /// Returns a tag name of the element node.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn tag_name(&self) -> Option<Ref<TagName>> {
        let b = self.0.borrow();
        match b.tag_name {
            Some(_) => Some(Ref::map(self.0.borrow(), |n| n.tag_name.as_ref().unwrap())),
            None => None,
        }
    }

    /// Returns a tag name id of the SVG element node.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn tag_id(&self) -> Option<ElementId> {
        let b = self.0.borrow();
        match b.tag_name {
            Some(ref t) => {
                match *t {
                    TagName::Id(ref id) => Some(*id),
                    TagName::Name(_) => None,
                }
            }
            None => None,
        }
    }

    /// Returns `true` if node has the same tag name id as supplied.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn is_tag_id(&self, eid: ElementId) -> bool {
        let b = self.0.borrow();
        match &b.tag_name {
            &Some(ref v) => {
                match v {
                    &TagName::Id(ref id) => *id == eid,
                    &TagName::Name(_) => false,
                }
            }
            &None => false,
        }
    }

    /// Returns `true` if node has the same tag name as supplied.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn is_tag_name(&self, tag_name: &TagName) -> bool {
        let b = self.0.borrow();
        match &b.tag_name {
            &Some(ref v) => v == tag_name,
            &None => false,
        }
    }

    /// Returns `true` if node has a direct child with the same tag name as supplied.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn has_child_with_tag_name(&self, tag_name: &TagName) -> bool {
        self.children().any(|n| n.is_tag_name(tag_name))
    }

    /// Inserts new SVG attribute into attributes list.
    ///
    /// This method will overwrite an existing attribute with the same id.
    ///
    /// Use it to insert/create new attributes.
    /// For existing attributes use `Node::set_attribute_object()`.
    ///
    /// You can't use this method to set referenced attributes.
    /// Use `Node::set_link_attribute()` instead.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently borrowed.
    pub fn set_attribute<T>(&self, id: AttributeId, value: T)
        where AttributeValue: From<T>
    {
        // we must remove existing attribute to prevent dangling links
        self.remove_attribute(id);

        let a = Attribute::new(id, value);
        let mut attrs = self.attributes_mut();
        // TODO: very slow
        attrs.insert(a);
    }

    /// Inserts new SVG attribute into attributes list.
    ///
    /// This method will overwrite an existing attribute with the same id.
    ///
    /// # Panics
    ///
    /// - Panics if the node is currently borrowed.
    /// - Panics if attribute has a Link value.
    ///   Use `Node::set_link_attribute()` for such attributes.
    pub fn set_attribute_object(&self, attr: Attribute) {
        // TODO: fix stupid name
        // TODO: do not panic on invalid attribute type

        match attr.value {
            AttributeValue::Link(_) | AttributeValue::FuncLink(_) =>
                panic!("Link attributes must be set via set_link_attribute()"),
            _ => {}
        }

        // we must remove existing attribute to prevent dangling links
        self.remove_attribute(attr.id);

        let mut attrs = self.attributes_mut();
        attrs.insert(attr);
    }

    /// Inserts new referenced SVG attribute into attributes list.
    ///
    /// This method will overwrite an existing attribute with the same id.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently borrowed.
    ///
    /// # Examples
    /// ```
    /// use svgdom::{Document, ValueId};
    /// use svgdom::AttributeId as AId;
    /// use svgdom::ElementId as EId;
    ///
    /// // Create simple document.
    /// let doc = Document::new();
    /// let gradient = doc.create_element(EId::LinearGradient);
    /// let rect = doc.create_element(EId::Rect);
    ///
    /// doc.append(&gradient);
    /// doc.append(&rect);
    ///
    /// gradient.set_id("lg1");
    /// rect.set_id("rect1");
    ///
    /// // Set `fill` attribute value to `none`.
    /// // For now everything like in any other XML DOM library.
    /// rect.set_attribute(AId::Fill, ValueId::None);
    ///
    /// // Now we want to fill our rect with gradient.
    /// // To do this we need to set link attribute:
    /// rect.set_link_attribute(AId::Fill, gradient.clone()).unwrap();
    ///
    /// // Now our fill attribute has a link to `gradient` node.
    /// // Not as text, aka `url(#lg1)`, but actual reference.
    ///
    /// // This adds support for fast checking of elements usage. Which is very useful.
    ///
    /// // `gradient` is now used, since we link it.
    /// assert_eq!(gradient.is_used(), true);
    /// // Also, we can check how many elements are uses this `gradient`.
    /// assert_eq!(gradient.uses_count(), 1);
    /// // And even get this elements:
    /// assert_eq!(gradient.linked_nodes().next().unwrap(), rect);
    ///
    /// // `rect` is unused, because no one has referenced attribute that has link to it.
    /// assert_eq!(rect.is_used(), false);
    ///
    /// // Now, if we set other attribute value, `gradient` will be automatically unlinked.
    /// rect.set_attribute(AId::Fill, ValueId::None);
    /// // No one uses it anymore.
    /// assert_eq!(gradient.is_used(), false);
    /// ```
    pub fn set_link_attribute(&self, id: AttributeId, node: Node) -> Result<(), Error> {
        // TODO: rewrite to template specialization when it will be available
        // TODO" check that node is element

        if node.id().is_empty() {
            return Err(Error::ElementMustHaveAnId);
        }

        // we must remove existing attribute to prevent dangling links
        self.remove_attribute(id);

        // check for recursion
        {
            let self_borrow = self.0.borrow();
            let v = &self_borrow.linked_nodes;

            if v.iter().find(|n| Node(n.upgrade().unwrap()) == node).is_some() {
                return Err(Error::ElementCrosslink);
            }
        }

        {
            let a;
            if id == AttributeId::XlinkHref {
                a = Attribute::new(id, AttributeValue::Link(node.clone()));
            } else {
                a = Attribute::new(id, AttributeValue::FuncLink(node.clone()));
            }

            let mut attributes = self.attributes_mut();
            attributes.insert(a);
        }

        {
            let mut value_borrow = node.0.borrow_mut();
            value_borrow.linked_nodes.push(Rc::downgrade(&self.0));
        }

        Ok(())
    }

    /// Returns iterator over linked nodes.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn linked_nodes(&self) -> LinkAttributes {
        let self_borrow = self.0.borrow();

        LinkAttributes {
            data: self_borrow.linked_nodes.clone(),
            idx: 0,
        }
    }

    /// Returns `AttributeId` of the first available `node` in current node's attributes.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn find_reference_attribute(&self, node: &Node) -> Option<AttributeId> {
        // TODO: return iter, and not only first
        // let attrs = self.attributes();
        for a in self.0.borrow().attributes.iter() {
            match a.value {
                AttributeValue::Link(ref n) | AttributeValue::FuncLink(ref n) => {
                    if n == node {
                        return Some(a.id);
                    }
                }
                _ => {}
            }
        }

        None
    }

    /// Returns copy of attribute value by `id`.
    ///
    /// Use it only for simple `AttributeValue` types, and not for `String` and `Path`,
    /// since their copying will be very expensive.
    ///
    /// Prefer `Node::attributes()`.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn attribute_value(&self, id: AttributeId) -> Option<AttributeValue> {
        self.attributes().get_value(id).map(|x| x.clone())
    }

    /// Returns copy of attribute by `id`.
    ///
    /// Use it only for attributes with simple `AttributeValue` types,
    /// and not for `String` and `Path`, since their copying will be very expensive.
    ///
    /// Prefer `Node::attributes()`.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn attribute(&self, id: AttributeId) -> Option<Attribute> {
        self.attributes().get(id).map(|x| x.clone())
    }

    /// Returns a reference to `Attributes` of current the node.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn attributes(&self) -> Ref<Attributes> {
        Ref::map(self.0.borrow(), |n| &n.attributes)
    }

    /// Returns a mutable reference to `Attributes` of current the node.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently borrowed.
    pub fn attributes_mut(&self) -> RefMut<Attributes> {
        RefMut::map(self.0.borrow_mut(), |n| &mut n.attributes)
    }

    /// Returns first occurrence of the selected `AttributeId` from it's parents.
    ///
    /// This function will check all parent, not only direct parent.
    ///
    /// # Examples
    ///
    /// ```
    /// use svgdom::{Document, TagName, ElementId, AttributeId, Attribute};
    /// use svgdom::types::Color;
    ///
    /// let doc = Document::from_data(
    /// b"<svg stroke='blue'>
    ///     <g fill='red'>
    ///         <rect/>
    ///     </g>
    /// </svg>").unwrap();
    ///
    /// let rect = doc.first_child().unwrap().child_by_tag_name(&TagName::Id(ElementId::Rect)).unwrap();
    /// assert_eq!(rect.parent_attribute(AttributeId::Fill).unwrap(),
    ///            Attribute::new(AttributeId::Fill, Color::new(255, 0, 0)));
    /// assert_eq!(rect.parent_attribute(AttributeId::Stroke).unwrap(),
    ///            Attribute::new(AttributeId::Stroke, Color::new(0, 0, 255)));
    /// assert_eq!(rect.parent_attribute(AttributeId::Filter).is_some(), false);
    /// ```
    pub fn parent_attribute(&self, id: AttributeId) -> Option<Attribute> {
        let mut parent = self.parent();
        while let Some(p) = parent {
            if p.has_attribute(id) {
                return p.attribute(id);
            }
            parent = p.parent();
        }
        None
    }

    /// Returns `true` if node has attribute with such `id`.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn has_attribute(&self, id: AttributeId) -> bool {
        self.attributes().contains(id)
    }

    /// Returns `true` if node has attribute with such `id` and this attribute is visible.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn has_visible_attribute(&self, id: AttributeId) -> bool {
        self.has_attribute(id) && self.attributes().get(id).unwrap().visible
    }

    /// Returns `true` if node has any of the provided attributes.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn has_attributes(&self, ids: &[AttributeId]) -> bool {
        let attrs = self.attributes();
        for id in ids {
            if attrs.contains(*id) {
                return true;
            }
        }

        false
    }

    /// Returns `true` if node has attribute with such `id` and such `value`.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn has_attribute_with_value<T>(&self, id: AttributeId, value: T) -> bool
        where AttributeValue: From<T>
    {
        match self.attribute_value(id) {
            Some(a) => a == AttributeValue::from(value),
            None => false,
        }
    }

    /// Removes an attribute from the node.
    ///
    /// It will also unlink it, if it was an referenced attribute.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently borrowed.
    pub fn remove_attribute(&self, id: AttributeId) {
        if !self.has_attribute(id) {
            return;
        }

        let mut attrs = self.attributes_mut();

        // we must unlink referenced attributes
        match attrs.get_value(id) {
            Some(value) => {
                match *value {
                    AttributeValue::Link(ref node) | AttributeValue::FuncLink(ref node) => {
                        let mut self_borrow = node.0.borrow_mut();
                        let ln = &mut self_borrow.linked_nodes;
                        // this code can't panic, because we know that such node exist
                        let index = ln.iter().position(|x| {
                            same_rc(&x.upgrade().unwrap(), &self.0)
                        }).unwrap();
                        ln.remove(index);
                    }
                    _ => {}
                }
            }
            None => {}
        }

        attrs.remove(id);
    }

    /// Removes attributes from the node.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently borrowed.
    pub fn remove_attributes(&self, ids: &[AttributeId]) {
        for id in ids {
            self.remove_attribute(*id);
        }
    }

    /// Returns a reference to an unknown attributes object.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn unknown_attributes(&self) -> Ref<HashMap<String,String>> {
        Ref::map(self.0.borrow(), |n| &n.ext_attributes)
    }

    /// Returns a mutable reference to an unknown attributes object.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently borrowed.
    pub fn unknown_attributes_mut(&self) -> RefMut<HashMap<String,String>> {
        RefMut::map(self.0.borrow_mut(), |n| &mut n.ext_attributes)
    }

    /// Returns `true` if current node is linked to any of DOM nodes.
    ///
    /// See `Node::set_link_attribute()` for details.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn is_used(&self) -> bool {
        let self_borrow = self.0.borrow();
        !self_borrow.linked_nodes.is_empty()
    }

    /// Returns number of the nodes, which is linked to this node.
    ///
    /// See `Node::set_link_attribute()` for details.
    ///
    /// # Panics
    ///
    /// Panics if the node is currently mutability borrowed.
    pub fn uses_count(&self) -> usize {
        let self_borrow = self.0.borrow();
        self_borrow.linked_nodes.len()
    }

    /// Returns true if the current node is referenced.
    ///
    /// Referenced elements is elements that does not rendered by itself,
    /// rather defines rendering properties for other.
    ///
    /// List: `altGlyphDef`, `clipPath`, `cursor`, `filter`, `linearGradient`, `marker`,
    /// `mask`, `pattern`, `radialGradient` and `symbol`.
    ///
    /// Details: https://www.w3.org/TR/SVG/struct.html#Head
    ///
    /// # Examples
    ///
    /// ```
    /// use svgdom::Document;
    ///
    /// let doc = Document::from_data(b"<svg><linearGradient/></svg>").unwrap();
    /// let mut iter = doc.descendants();
    /// assert_eq!(iter.next().unwrap().is_referenced(), false); // svg
    /// assert_eq!(iter.next().unwrap().is_referenced(), true); // linearGradient
    /// ```
    pub fn is_referenced(&self) -> bool {
        match self.tag_name() {
            Some(v) => {
                match *v {
                    TagName::Id(ref id) => {
                        match *id {
                              ElementId::AltGlyphDef
                            | ElementId::ClipPath
                            | ElementId::Cursor
                            | ElementId::Filter
                            | ElementId::LinearGradient
                            | ElementId::Marker
                            | ElementId::Mask
                            | ElementId::Pattern
                            | ElementId::RadialGradient
                            | ElementId::Symbol => true,
                            _ => false,
                        }
                    }
                    _ => false,
                }
            }
            None => false,
        }
    }

    /// Returns true if the current node is a basic shape.
    ///
    /// List: `rect`, `circle`, `ellipse`, `line`, `polyline`, `polygon`.
    ///
    /// Details: https://www.w3.org/TR/SVG/shapes.html
    ///
    /// # Examples
    ///
    /// ```
    /// use svgdom::Document;
    ///
    /// let doc = Document::from_data(b"<svg><rect/></svg>").unwrap();
    /// let mut iter = doc.descendants();
    /// assert_eq!(iter.next().unwrap().is_basic_shape(), false); // svg
    /// assert_eq!(iter.next().unwrap().is_basic_shape(), true); // rect
    /// ```
    pub fn is_basic_shape(&self) -> bool {
        match self.tag_name() {
            Some(v) => {
                match *v {
                    TagName::Id(ref id) => {
                        match *id {
                              ElementId::Rect
                            | ElementId::Circle
                            | ElementId::Ellipse
                            | ElementId::Line
                            | ElementId::Polyline
                            | ElementId::Polygon => true,
                            _ => false,
                        }
                    }
                    _ => false,
                }
            }
            None => false,
        }
    }

    /// Returns `Node` if current node contains child with selected `TagName`.
    ///
    /// This function is recursive. Current node excluded.
    ///
    /// # Examples
    ///
    /// ```
    /// use svgdom::{Document, TagName, ElementId};
    ///
    /// let doc = Document::from_data(
    /// b"<svg>
    ///     <g>
    ///         <rect/>
    ///     </g>
    ///     <myelem/>
    /// </svg>").unwrap();
    ///
    /// let svg = doc.first_child().unwrap();
    /// // current node will be skipped
    /// assert_eq!(svg.child_by_tag_name(&TagName::Id(ElementId::Svg)).is_some(), false);
    /// // we'll get true since current method is recursive
    /// assert_eq!(svg.child_by_tag_name(&TagName::Id(ElementId::Rect)).is_some(), true);
    /// // check for not existing element
    /// assert_eq!(svg.child_by_tag_name(&TagName::Id(ElementId::Path)).is_some(), false);
    /// // check for non-svg element
    /// assert_eq!(svg.child_by_tag_name(&TagName::from("myelem")).is_some(), true);
    /// ```
    pub fn child_by_tag_name(&self, tag_name: &TagName) -> Option<Node> {
        let iter = self.descendants_all().skip(1);
        for node in iter {
            if node.is_tag_name(tag_name) {
                return Some(node.clone());
            }
        }
        None
    }

    /// Returns `Node` if current node contains child with selected `ElementId`.
    ///
    /// Shorthand for `Node::child_by_tag_name(&TagName::Id(id))`.
    pub fn child_by_tag_id(&self, id: ElementId) -> Option<Node> {
        self.child_by_tag_name(&TagName::Id(id))
    }

    /// Returns an iterator over descendant elements.
    ///
    /// # Examples
    ///
    /// ```
    /// use svgdom::{Document, ElementId};
    ///
    /// let doc = Document::from_data(
    /// b"<!--comment-->
    /// <svg>
    ///   <g>
    ///     <nonsvg/>
    ///     <rect/>
    ///   </g>
    ///   <text>Text</text>
    ///   <nonsvg/>
    /// </svg>").unwrap();
    ///
    /// let mut iter = doc.descendants();
    /// assert_eq!(iter.next().unwrap().is_tag_id(ElementId::Svg), true);
    /// assert_eq!(iter.next().unwrap().is_tag_id(ElementId::G), true);
    /// assert_eq!(iter.next().unwrap().is_tag_id(ElementId::Rect), true);
    /// assert_eq!(iter.next().unwrap().is_tag_id(ElementId::Text), true);
    /// assert_eq!(iter.next().is_none(), true);
    /// ```
    pub fn descendants(&self) -> Descendants {
        Descendants(self.traverse())
    }

    /// Returns an iterator over descendant nodes.
    pub fn descendants_all(&self) -> DescendantsAll {
        DescendantsAll(self.traverse())
    }

    /// Returns an iterator over descendant nodes.
    ///
    /// More complex alternative of the `Node::descendants_all()`.
    pub fn traverse(&self) -> Traverse {
        Traverse {
            root: self.clone(),
            next: Some(NodeEdge::Start(self.clone())),
        }
    }
}

fn same_rc<T>(a: &Rc<T>, b: &Rc<T>) -> bool {
    let a: *const T = &**a;
    let b: *const T = &**b;
    a == b
}

/// Cloning a `Node` only increments a reference count. It does not copy the data.
impl Clone for Node {
    fn clone(&self) -> Node {
        Node(self.0.clone())
    }
}

impl PartialEq for Node {
    fn eq(&self, other: &Node) -> bool {
        self.same_node(other)
    }
}

// TODO: write better messages
impl fmt::Debug for Node {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.node_type() {
            NodeType::Root => write!(f, "Root node"),
            NodeType::Element => write!(f, "<{:?} id={:?}>", self.tag_name().unwrap(), self.id()),
            NodeType::Declaration => write!(f, "Declaration node"),
            NodeType::Comment => write!(f, "Comment node"),
            NodeType::Cdata => write!(f, "CDATA node"),
            NodeType::Text => write!(f, "Text node"),
        }
    }
}

/// List of supported node types.
#[derive(Clone,Copy,PartialEq,Debug)]
pub enum NodeType {
    /// Root node of the `Document`.
    ///
    /// Constructed with `Document`. Unavailable to user.
    Root,
    /// Element node.
    ///
    /// Only an element can have attributes, ID and tag name.
    Element,
    /// Declaration node.
    Declaration,
    /// Comment node.
    Comment,
    /// CDATA node.
    Cdata,
    /// Text node.
    Text,
}

type Link = Rc<RefCell<NodeData>>;
type WeakLink = Weak<RefCell<NodeData>>;

#[allow(dead_code)]
struct NodeData {
    // TODO: check that doc is equal in append, insert, etc.
    doc: Option<Link>,

    parent: Option<WeakLink>,
    first_child: Option<Link>,
    last_child: Option<WeakLink>,
    previous_sibling: Option<WeakLink>,
    next_sibling: Option<Link>,

    node_type: NodeType, // TODO: should be immutable/const somehow
    tag_name: Option<TagName>,
    id: String,
    attributes: Attributes,
    ext_attributes: HashMap<String,String>,
    linked_nodes: Vec<WeakLink>,
    text: Option<String>,
}

impl NodeData {
    /// Detach a node from its parent and siblings. Children are not affected.
    fn detach(&mut self) {
        let parent_weak = self.parent.take();
        let previous_sibling_weak = self.previous_sibling.take();
        let next_sibling_strong = self.next_sibling.take();

        let previous_sibling_opt = previous_sibling_weak.as_ref().and_then(|weak| weak.upgrade());

        if let Some(next_sibling_ref) = next_sibling_strong.as_ref() {
            let mut next_sibling_borrow = next_sibling_ref.borrow_mut();
            next_sibling_borrow.previous_sibling = previous_sibling_weak;
        } else if let Some(parent_ref) = parent_weak.as_ref() {
            if let Some(parent_strong) = parent_ref.upgrade() {
                let mut parent_borrow = parent_strong.borrow_mut();
                parent_borrow.last_child = previous_sibling_weak;
            }
        }

        if let Some(previous_sibling_strong) = previous_sibling_opt {
            let mut previous_sibling_borrow = previous_sibling_strong.borrow_mut();
            previous_sibling_borrow.next_sibling = next_sibling_strong;
        } else if let Some(parent_ref) = parent_weak.as_ref() {
            if let Some(parent_strong) = parent_ref.upgrade() {
                let mut parent_borrow = parent_strong.borrow_mut();
                parent_borrow.first_child = next_sibling_strong;
            }
        }
    }
}

/// Wrapper arrow element tag name.
#[derive(Clone,PartialEq)]
pub enum TagName {
    /// For SVG elements.
    Id(ElementId),
    /// For unknown elements.
    Name(String),
}

impl From<ElementId> for TagName {
    fn from(value: ElementId) -> TagName {
        TagName::Id(value)
    }
}

impl From<String> for TagName {
    fn from(value: String) -> TagName {
        TagName::Name(value)
    }
}

impl<'a> From<&'a str> for TagName {
    fn from(value: &str) -> TagName {
        TagName::Name(String::from_str(value).unwrap())
    }
}

impl fmt::Debug for TagName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &TagName::Id(ref id) => write!(f, "{}", id.name()),
            &TagName::Name(ref name) => write!(f, "{}", name),
        }
    }
}

pub struct LinkAttributes {
    data: Vec<WeakLink>,
    idx: usize,
}

impl Iterator for LinkAttributes {
    type Item = Node;

    fn next(&mut self) -> Option<Node> {
        let i = self.idx;
        self.idx += 1;

        if i < self.data.len() {
            match self.data[i].upgrade() {
                Some(n) => Some(Node(n)),
                None => None,
            }
        } else {
            None
        }
    }
}

#[allow(missing_docs)]
#[derive(Clone)]
pub enum NodeEdge {
    /// Indicates that start of a node that has children.
    /// Yielded by `Traverse::next` before the node’s descendants.
    /// In HTML or XML, this corresponds to an opening tag like `<div>`
    Start(Node),

    /// Indicates that end of a node that has children.
    /// Yielded by `Traverse::next` after the node’s descendants.
    /// In HTML or XML, this corresponds to a closing tag like `</div>`
    End(Node),
}


/// An iterator of references to a given node and its descendants, in tree order.
#[derive(Clone)]
pub struct Traverse {
    root: Node,
    next: Option<NodeEdge>,
}

impl Iterator for Traverse {
    type Item = NodeEdge;

    /// # Panics
    ///
    /// Panics if the node about to be yielded is currently mutability borrowed.
    fn next(&mut self) -> Option<NodeEdge> {
        match self.next.take() {
            Some(item) => {
                self.next = match item {
                    NodeEdge::Start(ref node) => {
                        match node.first_child() {
                            Some(first_child) => Some(NodeEdge::Start(first_child)),
                            None => Some(NodeEdge::End(node.clone()))
                        }
                    }
                    NodeEdge::End(ref node) => {
                        if node.same_node(&self.root) {
                            None
                        } else {
                            match node.next_sibling() {
                                Some(next_sibling) => Some(NodeEdge::Start(next_sibling)),
                                None => match node.parent() {
                                    Some(parent) => Some(NodeEdge::End(parent)),

                                    // `node.parent()` here can only be `None`
                                    // if the tree has been modified during iteration,
                                    // but silently stopping iteration
                                    // seems a more sensible behavior than panicking.
                                    None => None
                                }
                            }
                        }
                    }
                };
                Some(item)
            }
            None => None
        }
    }
}

/// An iterator of references to a given node and its descendants, in tree order.
pub struct DescendantsAll(Traverse);

impl Iterator for DescendantsAll {
    type Item = Node;

    /// # Panics
    ///
    /// Panics if the node about to be yielded is currently mutability borrowed.
    fn next(&mut self) -> Option<Node> {
        loop {
            match self.0.next() {
                Some(NodeEdge::Start(node)) => return Some(node),
                Some(NodeEdge::End(_)) => {}
                None => return None
            }
        }
    }
}

#[derive(Clone)]
pub struct Descendants(Traverse);

impl Descendants {
    // TODO: find better way
    pub fn skip_children(&mut self) {
        // TODO: do nothing if current node did not have children
        let n = match self.next() {
            Some(n) => n.parent().unwrap(),
            None => return,
        };

        if !n.has_children() {
            return;
        }

        loop {
            match self.0.next() {
                Some(NodeEdge::Start(_)) => {}
                Some(NodeEdge::End(node)) => {
                    if n == node {
                        break;
                    }
                }
                None => break
            }
        }
    }
}

impl Iterator for Descendants {
    type Item = Node;

    /// # Panics
    ///
    /// Panics if the node about to be yielded is currently mutability borrowed.
    fn next(&mut self) -> Option<Node> {
        loop {
            match self.0.next() {
                Some(NodeEdge::Start(node)) => {
                    if node.is_element() {
                        return Some(node)
                    }
                }
                Some(NodeEdge::End(_)) => {}
                None => return None
            }
        }
    }
}

macro_rules! impl_node_iterator {
    ($name: ident, $next: expr) => {
        impl Iterator for $name {
            type Item = Node;

            /// # Panics
            ///
            /// Panics if the node about to be yielded is currently mutability borrowed.
            fn next(&mut self) -> Option<Node> {
                match self.0.take() {
                    Some(node) => {
                        self.0 = $next(&node);
                        Some(node)
                    }
                    None => None
                }
            }
        }
    }
}

/// An iterator of references to the children of a given node.
pub struct Children(Option<Node>);
impl_node_iterator!(Children, |node: &Node| node.next_sibling());