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
/*
Copyright (C) 2020-2021 Kunal Mehta <legoktm@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//! Wikinodes represent various MediaWiki syntax constructs

use crate::gallery::Gallery;
use crate::image::Image;
use crate::inclusion::IncludeOnlyDataMw;
use crate::indicator::{IndicatorAttrs, IndicatorBody, IndicatorDataMw};
use crate::private::Sealed;
use crate::{
    assert_element, attribute_contains_word, clean_link, full_link, inner_data,
    parse_target, set_inner_data, Error, Result, Wikicode, WikinodeIterator,
};
use kuchikiki::{Attribute, ExpandedName, NodeRef};
use std::ops::Deref;
use urlencoding::{decode, encode};

mod behavior_switch;
pub use behavior_switch::BehaviorSwitch;

/// Enum that represents all the different types of nodes
#[derive(Debug, Clone)]
pub enum Wikinode {
    BehaviorSwitch(BehaviorSwitch),
    Category(Category),
    /// HTML comment
    Comment(Comment),
    DisplaySpace(DisplaySpace),
    /// External link
    ExtLink(ExtLink),
    Gallery(Gallery),
    Heading(Heading),
    HtmlEntity(HtmlEntity),
    Image(Image),
    IncludeOnly(IncludeOnly),
    Indicator(Indicator),
    InterwikiLink(InterwikiLink),
    LanguageLink(LanguageLink),
    Nowiki(Nowiki),
    Placeholder(Placeholder),
    Redirect(Redirect),
    Section(Section),
    /// Wiki (internal) link
    WikiLink(WikiLink),
    /// A generic HTML node that we haven't implemented a specific type for yet
    /// or doesn't need one.
    Generic(Wikicode),
}

impl Deref for Wikinode {
    type Target = NodeRef;

    fn deref(&self) -> &Self::Target {
        self.as_node()
    }
}

impl Wikinode {
    pub(crate) fn new_from_node(node: &NodeRef) -> Self {
        if node.as_comment().is_some() {
            return Comment::new_from_node(node).into();
        }
        if let Some(element) = node.as_element() {
            let tag_name = element.name.local.clone();
            let attributes = element.attributes.borrow();
            if let Some(typeof_) = attributes.get("typeof") {
                if typeof_.split(' ').any(|val| {
                    val == "mw:Placeholder"
                        || val.starts_with("mw:Placeholder/")
                }) {
                    return Placeholder::new_from_node(node).into();
                }
            }
            match tag_name {
                local_name!("a") => {
                    if let Some(rel) = attributes.get("rel") {
                        if attribute_contains_word(rel, InterwikiLink::REL) {
                            return InterwikiLink::new_from_node(node).into();
                        } else if attribute_contains_word(rel, WikiLink::REL) {
                            return WikiLink::new_from_node(node).into();
                        } else if attribute_contains_word(rel, ExtLink::REL) {
                            return ExtLink::new_from_node(node).into();
                        }
                        // fall through to generic
                    }
                }
                local_name!("h1")
                | local_name!("h2")
                | local_name!("h3")
                | local_name!("h4")
                | local_name!("h5")
                | local_name!("h6") => {
                    return Heading::new_from_node(node).into();
                }
                local_name!("link") => {
                    if let Some(rel) = attributes.get("rel") {
                        if attribute_contains_word(rel, Category::REL) {
                            return Category::new_from_node(node).into();
                        } else if attribute_contains_word(
                            rel,
                            LanguageLink::REL,
                        ) {
                            return LanguageLink::new_from_node(node).into();
                        } else if attribute_contains_word(rel, Redirect::REL) {
                            return Redirect::new_from_node(node).into();
                        }
                    }
                }
                local_name!("meta") => {
                    if let Some(property) = attributes.get("property") {
                        if property.starts_with("mw:PageProp/") {
                            return BehaviorSwitch::new_from_node(node).into();
                        }
                    } else if let Some(typeof_) = attributes.get("typeof") {
                        if attribute_contains_word(typeof_, IncludeOnly::TYPEOF)
                        {
                            return IncludeOnly::new_from_node(node).into();
                        } else if attribute_contains_word(
                            typeof_,
                            Indicator::TYPEOF,
                        ) {
                            return Indicator::new_from_node(node).into();
                        }
                    }
                }
                local_name!("section") => {
                    if attributes.contains("data-mw-section-id") {
                        return Section::new_from_node(node).into();
                    }
                }
                local_name!("span") => {
                    if let Some(typeof_) = attributes.get("typeof") {
                        if attribute_contains_word(typeof_, Nowiki::TYPEOF) {
                            return Nowiki::new_from_node(node).into();
                        } else if attribute_contains_word(
                            typeof_,
                            HtmlEntity::TYPEOF,
                        ) {
                            return HtmlEntity::new_from_node(node).into();
                        } else if attribute_contains_word(
                            typeof_,
                            DisplaySpace::TYPEOF,
                        ) {
                            return DisplaySpace::new_from_node(node).into();
                        } else if typeof_
                            .split(' ')
                            .any(|val| val.starts_with(Image::TYPEOF_PREFIX))
                        {
                            return Image::new_from_node(node).into();
                        }
                    }
                }
                local_name!("ul") => {
                    if let Some(typeof_) = attributes.get("typeof") {
                        if attribute_contains_word(typeof_, Gallery::TYPEOF) {
                            return Gallery::new_from_node(node).into();
                        }
                    }
                }
                // fall through to generic
                _ => {}
            }
        }

        Self::Generic(Wikicode::new_from_node(node))
    }

    pub fn as_behavior_switch(&self) -> Option<BehaviorSwitch> {
        match self {
            Self::BehaviorSwitch(switch) => Some(switch.clone()),
            _ => None,
        }
    }

    pub fn as_category(&self) -> Option<Category> {
        match self {
            Self::Category(category) => Some(category.clone()),
            _ => None,
        }
    }

    /// If this node is a comment, get a clone of it
    pub fn as_comment(&self) -> Option<Comment> {
        match self {
            Self::Comment(comment) => Some(comment.clone()),
            _ => None,
        }
    }

    pub fn as_displayspace(&self) -> Option<DisplaySpace> {
        match self {
            Self::DisplaySpace(displayspace) => Some(displayspace.clone()),
            _ => None,
        }
    }

    /// If this node is an external link, get a clone of it
    pub fn as_extlink(&self) -> Option<ExtLink> {
        match self {
            Self::ExtLink(extlink) => Some(extlink.clone()),
            _ => None,
        }
    }

    /// If this node is a gallery, get a clone of it
    pub fn as_gallery(&self) -> Option<Gallery> {
        match self {
            Self::Gallery(gallery) => Some(gallery.clone()),
            _ => None,
        }
    }

    /// If this node is generic, get a clone of it
    pub fn as_generic(&self) -> Option<Wikicode> {
        match self {
            Self::Generic(node) => Some(node.clone()),
            _ => None,
        }
    }

    pub fn as_heading(&self) -> Option<Heading> {
        match self {
            Self::Heading(heading) => Some(heading.clone()),
            _ => None,
        }
    }

    pub fn as_html_entity(&self) -> Option<HtmlEntity> {
        match self {
            Self::HtmlEntity(entity) => Some(entity.clone()),
            _ => None,
        }
    }

    pub fn as_image(&self) -> Option<Image> {
        match self {
            Self::Image(image) => Some(image.clone()),
            _ => None,
        }
    }

    pub fn as_includeonly(&self) -> Option<IncludeOnly> {
        match self {
            Self::IncludeOnly(includeonly) => Some(includeonly.clone()),
            _ => None,
        }
    }

    pub fn as_indicator(&self) -> Option<Indicator> {
        match self {
            Self::Indicator(indicator) => Some(indicator.clone()),
            _ => None,
        }
    }

    pub fn as_interwiki_link(&self) -> Option<InterwikiLink> {
        match self {
            Self::InterwikiLink(link) => Some(link.clone()),
            _ => None,
        }
    }

    pub fn as_language_link(&self) -> Option<LanguageLink> {
        match self {
            Self::LanguageLink(link) => Some(link.clone()),
            _ => None,
        }
    }

    pub fn as_nowiki(&self) -> Option<Nowiki> {
        match self {
            Self::Nowiki(nowiki) => Some(nowiki.clone()),
            _ => None,
        }
    }

    pub fn as_placeholder(&self) -> Option<Placeholder> {
        match self {
            Self::Placeholder(placeholder) => Some(placeholder.clone()),
            _ => None,
        }
    }

    pub fn as_redirect(&self) -> Option<Redirect> {
        match self {
            Self::Redirect(redirect) => Some(redirect.clone()),
            _ => None,
        }
    }

    pub fn as_section(&self) -> Option<Section> {
        match self {
            Self::Section(section) => Some(section.clone()),
            _ => None,
        }
    }

    /// If this node is a wiki link, get a clone of it
    pub fn as_wikilink(&self) -> Option<WikiLink> {
        match self {
            Self::WikiLink(wikilink) => Some(wikilink.clone()),
            _ => None,
        }
    }
}

impl Sealed for Wikinode {}

impl WikinodeIterator for Wikinode {
    fn as_node(&self) -> &NodeRef {
        // This relies on all the types deref to NodeRef
        match self {
            Self::BehaviorSwitch(switch) => switch,
            Self::Category(category) => category,
            Self::Comment(comment) => comment,
            Self::DisplaySpace(displayspace) => displayspace,
            Self::ExtLink(extlink) => extlink,
            Self::Gallery(gallery) => gallery,
            Self::Heading(heading) => heading,
            Self::HtmlEntity(entity) => entity,
            Self::Image(image) => image,
            Self::IncludeOnly(includeonly) => includeonly,
            Self::Indicator(indicator) => indicator,
            Self::InterwikiLink(link) => link,
            Self::LanguageLink(link) => link,
            Self::Nowiki(nowiki) => nowiki,
            Self::Placeholder(placeholder) => placeholder,
            Self::Redirect(redirect) => redirect,
            Self::Section(section) => section,
            Self::WikiLink(wikilink) => wikilink,
            Self::Generic(code) => code,
        }
    }
}

macro_rules! impl_traits {
    ( $name:ident ) => {
        impl From<$name> for Wikinode {
            fn from(node: $name) -> Self {
                Self::$name(node)
            }
        }

        impl Deref for $name {
            type Target = NodeRef;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl WikinodeIterator for $name {
            fn as_node(&self) -> &NodeRef {
                &self.0
            }
        }

        impl Sealed for $name {}
    };
}

impl_traits!(BehaviorSwitch);
impl_traits!(Category);
impl_traits!(Comment);
impl_traits!(DisplaySpace);
impl_traits!(ExtLink);
impl_traits!(Gallery);
impl_traits!(Heading);
impl_traits!(HtmlEntity);
impl_traits!(Image);
impl_traits!(IncludeOnly);
impl_traits!(Indicator);
impl_traits!(InterwikiLink);
impl_traits!(LanguageLink);
impl_traits!(Nowiki);
impl_traits!(Placeholder);
impl_traits!(Redirect);
impl_traits!(Section);
impl_traits!(WikiLink);

/// Represents a wikitext/HTML comment.
/// ```
/// # use parsoid::prelude::*;
/// let comment = Comment::new("foo");
/// assert_eq!(comment.text(), "foo".to_string());
/// assert_eq!(comment.to_string(), "<!--foo-->".to_string());
/// comment.set_text("bar");
/// assert_eq!(comment.to_string(), "<!--bar-->".to_string());
/// ```
#[derive(Debug, Clone)]
pub struct Comment(NodeRef);

impl Comment {
    /// Create a new `Comment`, with the given text
    pub fn new(text: &str) -> Self {
        Self(NodeRef::new_comment(text))
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        if element.as_comment().is_none() {
            unreachable!("Non-comment node passed");
        }
        Self(element.clone())
    }

    /// Get the text in the comment
    pub fn text(&self) -> String {
        self.as_comment().unwrap().borrow().to_string()
    }

    /// Set different text in the comment
    pub fn set_text(&self, text: &str) {
        self.as_comment().unwrap().replace(text.into());
    }
}

/// Represents an internal link (`[[Foo|bar]]`)
/// ```
/// # use parsoid::prelude::*;
/// let text = Wikicode::new_text("baz");
/// let link = WikiLink::new("Foo bar", &text);
/// assert_eq!(
///     link.raw_target(),
///     "./Foo_bar".to_string()
/// );
/// assert_eq!(
///     link.target(),
///     "Foo bar".to_string()
/// );
/// assert_eq!(
///     link.text_contents(), "baz".to_string()
/// );
/// assert_eq!(
///     link.to_string(),
///     "<a href=\"./Foo_bar\" rel=\"mw:WikiLink\">baz</a>".to_string()
/// );
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Wiki_links) for more details.
#[derive(Debug, Clone)]
pub struct WikiLink(NodeRef);

impl WikiLink {
    const REL: &'static str = "mw:WikiLink";
    pub(crate) const SELECTOR: &'static str = "[rel=\"mw:WikiLink\"]";

    /// Create a new wiki link
    pub fn new(target: &str, text: &NodeRef) -> Self {
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("a")),
            vec![
                (
                    ExpandedName::new(ns!(), local_name!("href")),
                    Attribute {
                        prefix: None,
                        value: full_link(target),
                    },
                ),
                (
                    ExpandedName::new(ns!(), local_name!("rel")),
                    Attribute {
                        prefix: None,
                        value: Self::REL.to_string(),
                    },
                ),
            ],
        );
        element.append(text.clone());
        Self(element)
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    /// Get the raw link target, usually prefixed with `./`
    pub fn raw_target(&self) -> String {
        self.as_element()
            .unwrap()
            .attributes
            .borrow()
            .get("href")
            .unwrap()
            .to_string()
    }

    /// Get the link target (basically the page title)
    pub fn target(&self) -> String {
        parse_target(&self.raw_target())
    }

    /// Set the link target.
    pub fn set_target(&self, target: &str) {
        self.as_element()
            .unwrap()
            .attributes
            .borrow_mut()
            .insert("href", full_link(target));
    }

    /// Is this an ISBN magic link?
    /// See [Help:Magic links](https://www.mediawiki.org/wiki/Help:Magic_links).
    pub fn is_isbn_magic_link(&self) -> bool {
        // T329347: Parsoid doesn't currently mark up ISBN magic links with a
        // class, but we can detect it by looking for the lack of a title=
        // attribute and that the text contents start with "ISBN ", which is
        // always hardcoded English.
        !self
            .as_element()
            .unwrap()
            .attributes
            .borrow()
            .contains("title")
            && self.text_contents().starts_with("ISBN ")
    }
}

/// Represents an external link (`[https://example.org/ Text]`)
/// ```
/// # use parsoid::prelude::*;
/// let text = Wikicode::new_text("Text");
/// let link = ExtLink::new("https://example.org/", &text);
/// assert_eq!(
///     link.target(),
///     "https://example.org/".to_string()
/// );
/// assert_eq!(
///     link.text_contents(), "Text".to_string()
/// );
/// assert_eq!(
///     link.to_string(),
///     "<a href=\"https://example.org/\" rel=\"mw:ExtLink\">Text</a>".to_string()
/// );
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#External_links) for more details.
#[derive(Debug, Clone)]
pub struct ExtLink(NodeRef);

impl ExtLink {
    const REL: &'static str = "mw:ExtLink";
    pub(crate) const SELECTOR: &'static str = "[rel~=\"mw:ExtLink\"]";

    /// Create a new external link
    pub fn new(target: &str, text: &NodeRef) -> Self {
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("a")),
            vec![
                (
                    ExpandedName::new(ns!(), local_name!("href")),
                    Attribute {
                        prefix: None,
                        value: target.to_string(),
                    },
                ),
                (
                    ExpandedName::new(ns!(), local_name!("rel")),
                    Attribute {
                        prefix: None,
                        value: Self::REL.to_string(),
                    },
                ),
            ],
        );
        element.append(text.clone());
        Self(element)
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    /// Get the link target
    pub fn target(&self) -> String {
        self.as_element()
            .unwrap()
            .attributes
            .borrow()
            .get("href")
            .unwrap()
            .to_string()
    }

    /// Set a new link target
    pub fn set_target(&self, target: &str) {
        self.as_element()
            .unwrap()
            .attributes
            .borrow_mut()
            .insert("href", target.to_string());
    }

    /// Is this a PMID or RFC magic link?
    /// See [Help:Magic links](https://www.mediawiki.org/wiki/Help:Magic_links).
    pub fn is_magic_link(&self) -> bool {
        // T329347: Look if it contains the "mw-magiclink" class
        if let Some(classes) =
            self.as_element().unwrap().attributes.borrow().get("class")
        {
            classes.split(' ').any(|class| class == "mw-magiclink")
        } else {
            false
        }
    }
}

/// Represents an interwiki (non-language) link (`[[:en:Foo]]`)
/// ```
/// # use parsoid::prelude::*;
/// let text = Wikicode::new_text("en:Foo");
/// let link = InterwikiLink::new("https://en.wikipedia.org/wiki/Foo", &text);
/// assert_eq!(
///     link.target(),
///     "https://en.wikipedia.org/wiki/Foo".to_string()
/// );
/// assert_eq!(
///     link.text_contents(), "en:Foo".to_string()
/// );
/// assert_eq!(
///     &link.to_string(),
///     "<a href=\"https://en.wikipedia.org/wiki/Foo\" rel=\"mw:WikiLink/Interwiki\">en:Foo</a>"
/// );
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Interwiki_non-language_links) for more details.
#[derive(Debug, Clone)]
pub struct InterwikiLink(NodeRef);

impl InterwikiLink {
    const REL: &'static str = "mw:WikiLink/Interwiki";
    // pub(crate) const SELECTOR: &'static str = "[rel=\"mw:WikiLink/Interwiki\"]";

    /// Create a new interwiki link
    pub fn new(target: &str, text: &NodeRef) -> Self {
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("a")),
            vec![
                (
                    ExpandedName::new(ns!(), local_name!("href")),
                    Attribute {
                        prefix: None,
                        value: target.to_string(),
                    },
                ),
                (
                    ExpandedName::new(ns!(), local_name!("rel")),
                    Attribute {
                        prefix: None,
                        value: Self::REL.to_string(),
                    },
                ),
            ],
        );
        element.append(text.clone());
        Self(element)
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    /// Get the link target
    pub fn target(&self) -> String {
        self.as_element()
            .unwrap()
            .attributes
            .borrow()
            .get("href")
            .unwrap()
            .to_string()
    }

    /// Set a new link target
    pub fn set_target(&self, target: &str) {
        self.as_element()
            .unwrap()
            .attributes
            .borrow_mut()
            .insert("href", target.to_string());
    }
}

/// A `<nowiki>` tag
///
/// ```
/// # use parsoid::prelude::*;
/// let nowiki = Nowiki::new("plain [[wikitext]]");
/// assert_eq!(
///     &nowiki.to_string(),
///     "<span typeof=\"mw:Nowiki\">plain [[wikitext]]</span>"
/// );
/// assert_eq!(
///     &nowiki.text_contents(),
///     "plain [[wikitext]]"
/// );
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Nowiki_blocks) for more details.
#[derive(Debug, Clone)]
pub struct Nowiki(NodeRef);

impl Nowiki {
    const TYPEOF: &'static str = "mw:Nowiki";
    // pub(crate) const SELECTOR: &'static str = "[typeof=\"mw:Nowiki\"]";

    /// Create a `<nowiki>` tag
    pub fn new(text: &str) -> Self {
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("span")),
            vec![(
                ExpandedName::new(ns!(), "typeof"),
                Attribute {
                    prefix: None,
                    value: Self::TYPEOF.to_string(),
                },
            )],
        );
        element.append(NodeRef::new_text(text));
        Self(element)
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }
}

/// An HTML entity that shouldn't be decoded during transformation
///
/// ```
/// # use parsoid::prelude::*;
/// // This is equal to &nbsp;
/// let entity = HtmlEntity::new("\u{a0}");
/// assert_eq!(
///     &entity.to_string(),
///     "<span typeof=\"mw:Entity\">&nbsp;</span>"
/// );
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#HTML_entities) for more details.
#[derive(Debug, Clone)]
pub struct HtmlEntity(NodeRef);

impl HtmlEntity {
    const TYPEOF: &'static str = "mw:Entity";
    // pub(crate) const SELECTOR: &'static str = "[typeof=\"mw:Entity\"]";

    pub fn new(text: &str) -> Self {
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("span")),
            vec![(
                ExpandedName::new(ns!(), "typeof"),
                Attribute {
                    prefix: None,
                    value: Self::TYPEOF.to_string(),
                },
            )],
        );
        element.append(NodeRef::new_text(text));
        Self(element)
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }
}

/// Section contains a `Heading` and its contents. This only covers sections
/// generated by `== headings ==`, and not any `<section>` tag that might be
/// present in the output (e.g. generated by an extension).
///
/// It is not expected that this node will be created manually.
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Headings_and_Sections) for more details.
#[derive(Debug, Clone)]
pub struct Section(NodeRef);

impl Section {
    pub(crate) const SELECTOR: &'static str = "section[data-mw-section-id]";

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    /// Get the section id (used by `action=edit` in section edits).
    ///
    /// This could be `0` (lead) or a greater integer.
    /// `-1` indicates an uneditable non-pseudo section, `-2` is an
    /// uneditable pseudo section
    pub fn section_id(&self) -> i32 {
        self.as_element()
            .unwrap()
            .attributes
            .borrow()
            .get("data-mw-section-id")
            // expect: Unreachable because this attribute is checked everywhere
            // this node type is created
            .expect("No data-mw-section-id attribute on section")
            .parse()
            // expect: This should be safe assuming we were provided
            // well-formed HTML.
            .expect("Invalid data-mw-section-id attribute")
    }

    pub fn is_editable(&self) -> bool {
        self.section_id() >= 0
    }

    pub fn is_pseudo_section(&self) -> bool {
        let id = self.section_id();
        id == -2 || id == 0
    }

    pub fn heading(&self) -> Option<Heading> {
        if !self.is_pseudo_section() {
            self.select_first(Heading::SELECTOR)
                .map(|node| Heading::new_from_node(&node))
        } else {
            None
        }
    }
}

/// A section heading (`== Some text ==`)
///
/// ```
/// # use parsoid::Result;
/// # use parsoid::prelude::*;
/// # fn main() -> Result<()> {
/// let heading = Heading::new(2, &Wikicode::new_text("Some text"))?;
/// assert_eq!(
///     &heading.to_string(),
///     "<h2>Some text</h2>"
/// );
/// assert_eq!(heading.level(), 2);
/// # Ok(())
/// # }
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Headings_and_Sections) for more details.
#[derive(Debug, Clone)]
pub struct Heading(NodeRef);

impl Heading {
    pub(crate) const SELECTOR: &'static str = "h1, h2, h3, h4, h5, h6";

    pub fn new(level: u32, contents: &NodeRef) -> Result<Self> {
        if !(1..=6).contains(&level) {
            return Err(Error::InvalidHeadingLevel(level));
        }
        let element = NodeRef::new_element(
            crate::build_qual_name(format!("h{level}").into()),
            vec![],
        );
        element.append(contents.clone());
        Ok(Self(element))
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    /// Get the numerical level of the heading, 1-6
    pub fn level(&self) -> u32 {
        match self.as_element().unwrap().name.local {
            local_name!("h1") => 1,
            local_name!("h2") => 2,
            local_name!("h3") => 3,
            local_name!("h4") => 4,
            local_name!("h5") => 5,
            local_name!("h6") => 6,
            _ => unreachable!("Non h[1-6] used in Heading"),
        }
    }
}

/// Represents a category link (`[[Category:Foo]]`)
/// ```
/// # use parsoid::prelude::*;
/// let cat = Category::new("Category:Foo bar", None);
/// assert_eq!(
///     &cat.category(),
///     "Category:Foo bar"
/// );
/// assert_eq!(
///     &cat.to_string(),
///     "<link href=\"./Category:Foo_bar\" rel=\"mw:PageProp/Category\">"
/// );
/// // Set a sort key
/// cat.set_sort_key(Some("Bar baz #quux"));
/// assert_eq!(
///     &cat.to_string(),
///     "<link href=\"./Category:Foo_bar#Bar%20baz%20%23quux\" rel=\"mw:PageProp/Category\">"
/// );
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Category_links) for more details.
#[derive(Debug, Clone)]
pub struct Category(NodeRef);

impl Category {
    const REL: &'static str = "mw:PageProp/Category";
    pub(crate) const SELECTOR: &'static str = "[rel=\"mw:PageProp/Category\"]";

    /// Create a new category link
    pub fn new(category: &str, sortkey: Option<&str>) -> Self {
        let href = Self::build_href(
            &full_link(category),
            sortkey.map(encode).as_deref(),
        );
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("link")),
            vec![
                (
                    ExpandedName::new(ns!(), local_name!("href")),
                    Attribute {
                        prefix: None,
                        value: href,
                    },
                ),
                (
                    ExpandedName::new(ns!(), local_name!("rel")),
                    Attribute {
                        prefix: None,
                        value: Self::REL.to_string(),
                    },
                ),
            ],
        );
        Self(element)
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    fn split_href(&self) -> (String, Option<String>) {
        let href = self
            .as_element()
            .unwrap()
            .attributes
            .borrow()
            .get("href")
            .unwrap()
            .to_string();
        let sp: Vec<_> = href.splitn(2, '#').collect();
        if sp.len() == 2 {
            (sp[0].to_string(), Some(sp[1].to_string()))
        } else {
            (sp[0].to_string(), None)
        }
    }

    fn build_href(category: &str, sortkey: Option<&str>) -> String {
        match sortkey {
            Some(sortkey) => {
                format!("{category}#{sortkey}")
            }
            None => category.to_string(),
        }
    }

    /// Get the category name
    pub fn category(&self) -> String {
        let (category, _) = self.split_href();
        clean_link(&category)
    }

    /// Get the sort key, if one is set
    pub fn sort_key(&self) -> Option<String> {
        let (_, sort_key) = self.split_href();
        // TODO: should we propagate this error instead of panic-ing?
        sort_key.map(|key| {
            decode(&key).expect("Unable to decode sort key").to_string()
        })
    }

    /// Set a different category name
    pub fn set_category(&self, category: &str) {
        let (_, sort_key) = self.split_href();
        self.set_href(&Self::build_href(
            &full_link(category),
            sort_key.as_deref(),
        ));
    }

    /// Set a different sort key
    pub fn set_sort_key(&self, sort_key: Option<&str>) {
        let (category, _) = self.split_href();
        self.set_href(&Self::build_href(
            &category,
            sort_key.map(encode).as_deref(),
        ));
    }

    fn set_href(&self, href: &str) {
        self.as_element()
            .unwrap()
            .attributes
            .borrow_mut()
            .insert("href", href.to_string());
    }
}

/// Represents a language link (`[[en:Foo]]`)
/// ```
/// # use parsoid::prelude::*;
/// let link = LanguageLink::new("https://en.wikipedia.org/wiki/Foo");
/// assert_eq!(
///     &link.target(),
///     "https://en.wikipedia.org/wiki/Foo"
/// );
/// assert_eq!(
///     &link.to_string(),
///     "<link href=\"https://en.wikipedia.org/wiki/Foo\" rel=\"mw:PageProp/Language\">"
/// );
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Language_links) for more details.
#[derive(Debug, Clone)]
pub struct LanguageLink(NodeRef);

impl LanguageLink {
    const REL: &'static str = "mw:PageProp/Language";
    // pub(crate) const SELECTOR: &'static str = "[rel=\"mw:PageProp/Language\"]";

    /// Create a new external link
    pub fn new(target: &str) -> Self {
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("link")),
            vec![
                (
                    ExpandedName::new(ns!(), local_name!("href")),
                    Attribute {
                        prefix: None,
                        value: target.to_string(),
                    },
                ),
                (
                    ExpandedName::new(ns!(), local_name!("rel")),
                    Attribute {
                        prefix: None,
                        value: Self::REL.to_string(),
                    },
                ),
            ],
        );
        Self(element)
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    /// Get the link target
    pub fn target(&self) -> String {
        self.as_element()
            .unwrap()
            .attributes
            .borrow()
            .get("href")
            .unwrap()
            .to_string()
    }

    /// Set a new link target
    pub fn set_target(&self, target: &str) {
        self.as_element()
            .unwrap()
            .attributes
            .borrow_mut()
            .insert("href", target.to_string());
    }
}

/// Represents a redirect (`#REDIRECT [[Foo]]`)
/// ```
/// # use parsoid::prelude::*;
/// let link = Redirect::new("Foo bar");
/// assert_eq!(
///     &link.target(),
///     "Foo bar"
/// );
/// assert_eq!(
///     &link.raw_target(),
///     "./Foo_bar"
/// );
/// assert_eq!(
///     &link.to_string(),
///     "<link href=\"./Foo_bar\" rel=\"mw:PageProp/redirect\">"
/// );
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Redirects) for more details.
#[derive(Debug, Clone)]
pub struct Redirect(NodeRef);

impl Redirect {
    const REL: &'static str = "mw:PageProp/redirect";
    pub(crate) const SELECTOR: &'static str = "[rel=\"mw:PageProp/redirect\"]";

    /// Create a new external link
    pub fn new(target: &str) -> Self {
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("link")),
            vec![
                (
                    ExpandedName::new(ns!(), local_name!("href")),
                    Attribute {
                        prefix: None,
                        value: "".to_string(),
                    },
                ),
                (
                    ExpandedName::new(ns!(), local_name!("rel")),
                    Attribute {
                        prefix: None,
                        value: Self::REL.to_string(),
                    },
                ),
            ],
        );
        let redirect = Self(element);
        redirect.set_target(target);
        redirect
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    pub fn is_external(&self) -> bool {
        !self.raw_target().starts_with("./")
    }

    /// Get the raw link target, usually beginning with `./`
    pub fn raw_target(&self) -> String {
        self.as_element()
            .unwrap()
            .attributes
            .borrow()
            .get("href")
            .unwrap()
            .to_string()
    }

    /// Get the link target, usually a page title but might also
    /// be an external URL
    pub fn target(&self) -> String {
        let raw = self.raw_target();
        if raw.starts_with("./") {
            clean_link(&raw)
        } else {
            raw
        }
    }

    /// Set a new link target
    pub fn set_target(&self, target: &str) {
        let new = if target.starts_with("http://")
            || target.starts_with("https://")
        {
            target.to_string()
        } else {
            full_link(target)
        };
        self.as_element()
            .unwrap()
            .attributes
            .borrow_mut()
            .insert("href", new);
    }
}

/// Represents a includeonly tag (`<includeonly>`)
///
/// ```
/// # use parsoid::Result;
/// # use parsoid::prelude::*;
/// # fn main() -> Result<()> {
/// let includeonly = IncludeOnly::new("foo bar")?;
/// assert_eq!(
///     &includeonly.wikitext()?,
///     "foo bar"
/// );
/// assert_eq!(
///     &includeonly.to_string(),
///     "<meta typeof=\"mw:Includes/IncludeOnly\" data-mw=\"{&quot;src&quot;:&quot;<includeonly>foo bar</includeonly>&quot;}\">"
/// );
/// includeonly.set_wikitext("bar foo")?;
/// assert_eq!(
///     &includeonly.to_string(),
///     "<meta typeof=\"mw:Includes/IncludeOnly\" data-mw=\"{&quot;src&quot;:&quot;<includeonly>bar foo</includeonly>&quot;}\">"
/// );
/// # Ok(())
/// # }
/// ```
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#noinclude_/_includeonly_/_onlyinclude) for more details.
///
/// Note that while the spec has two nodes, one opening and one closing
/// (`typeof="mw:Includes/IncludeOnly/End"`), we only represent the opening
/// one since Parsoid automatically handles the lack of one or any extra one.
#[derive(Debug, Clone)]
pub struct IncludeOnly(NodeRef);

impl IncludeOnly {
    const TYPEOF: &'static str = "mw:Includes/IncludeOnly";
    // pub(crate) const SELECTOR: &'static str = "[typeof=\"mw:Includes/IncludeOnly\"]";

    pub fn new(wikitext: &str) -> Result<Self> {
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("meta")),
            vec![(
                ExpandedName::new(ns!(), "typeof"),
                Attribute {
                    prefix: None,
                    value: Self::TYPEOF.to_string(),
                },
            )],
        );
        let includeonly = Self(element);
        includeonly.set_wikitext(wikitext)?;
        Ok(includeonly)
    }

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    /// Get the wikitext contained inside the `<includeonly>` tag
    pub fn wikitext(&self) -> Result<String> {
        let data: IncludeOnlyDataMw = inner_data(self)?;
        Ok(data
            .src
            .strip_prefix("<includeonly>")
            .unwrap()
            .strip_suffix("</includeonly>")
            .unwrap()
            .to_string())
    }

    /// Set new wikitext to be inside the `<includeonly>` tag
    pub fn set_wikitext(&self, wikitext: &str) -> Result<()> {
        set_inner_data(
            self,
            crate::inclusion::IncludeOnlyDataMw {
                src: format!("<includeonly>{wikitext}</includeonly>"),
            },
        )
    }
}

/// A placeholder marks DOM content that may not be edited by clients.
/// This library does not take any steps to prevent mutation of these nodes,
/// it is expected that users will skip any Placeholder nodes encountered.
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Expectations_of_editing_clients) for more details.
#[derive(Debug, Clone)]
pub struct Placeholder(NodeRef);

impl Placeholder {
    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }
}

/// DisplaySpace is a non-breaking space that is added by Parsoid in
/// post-processing and is not present in wikitext.
///
/// See the [spec](https://www.mediawiki.org/wiki/Specs/HTML/2.8.0#Display_space) for more details.
#[derive(Debug, Clone)]
pub struct DisplaySpace(NodeRef);

impl DisplaySpace {
    const TYPEOF: &'static str = "mw:DisplaySpace";

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }
}

/// Represents an indicator tag (`<indicator>`)
///
/// ```
/// # use parsoid::Result;
/// # use parsoid::prelude::*;
/// # fn main() -> Result<()> {
///
/// let indicator = Indicator::new("test", "[[Some wikitext]]")?;
/// assert_eq!(&indicator.name()?, "test");
/// assert_eq!(&indicator.wikitext()?, "[[Some wikitext]]");
/// indicator.set_wikitext("[[Some other wikitext!]]")?;
/// assert_eq!(&indicator.wikitext()?, "[[Some other wikitext!]]");
/// # Ok(())
/// # }
/// ```
///
/// There is currently no published specification for this node.
#[derive(Debug, Clone)]
pub struct Indicator(NodeRef);

impl Indicator {
    const TYPEOF: &'static str = "mw:Extension/indicator";

    pub(crate) fn new_from_node(element: &NodeRef) -> Self {
        assert_element(element);
        Self(element.clone())
    }

    pub fn new(name: &str, wikitext: &str) -> Result<Self> {
        let data = IndicatorDataMw {
            name: "indicator".to_string(),
            attrs: IndicatorAttrs {
                name: name.to_string(),
            },
            body: IndicatorBody {
                extsrc: wikitext.to_string(),
            },
        };
        let element = NodeRef::new_element(
            crate::build_qual_name(local_name!("meta")),
            vec![
                (
                    ExpandedName::new(ns!(), "typeof"),
                    Attribute {
                        prefix: None,
                        value: Self::TYPEOF.to_string(),
                    },
                ),
                (
                    ExpandedName::new(ns!(), "data-mw"),
                    Attribute {
                        prefix: None,
                        value: serde_json::to_string(&data)?,
                    },
                ),
            ],
        );
        Ok(Self(element))
    }

    pub fn name(&self) -> Result<String> {
        Ok(self.inner()?.attrs.name)
    }

    pub fn set_name(&self, name: &str) -> Result<()> {
        let mut data = self.inner()?;
        data.attrs.name = name.to_string();
        self.set_inner(data)?;
        Ok(())
    }

    pub fn wikitext(&self) -> Result<String> {
        Ok(self.inner()?.body.extsrc)
    }

    pub fn set_wikitext(&self, wikitext: &str) -> Result<()> {
        let mut data = self.inner()?;
        data.body.extsrc = wikitext.to_string();
        self.set_inner(data)?;
        Ok(())
    }

    fn inner(&self) -> Result<IndicatorDataMw> {
        inner_data(self)
    }

    fn set_inner(&self, data: IndicatorDataMw) -> Result<()> {
        set_inner_data(self, data)
    }
}