microformats 0.18.2

A union library of the Microformats types and associated parser.
Documentation
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
use super::{
    ElementPtr, ElementRef, Error, merge_hash_maps, non_empty_string,
    property::{DeclKind, adjust_timestamps, explicit, implied, item},
    remove_surrounding_whitespace,
};
use microformats_types::{Class, Document, Item, Properties};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use swc_html_ast::{Attribute, Child, Element, Text};
use swc_html_codegen::{
    CodeGenerator, CodegenConfig, Emit,
    writer::basic::{BasicHtmlWriter, BasicHtmlWriterConfig, IndentType, LineFeed},
};

#[cfg(feature = "debug_flow")]
use microformats_types::ElementSource;

#[derive(Clone, PartialEq, Eq)]
pub struct Node {
    pub elem: Element,
}

impl std::fmt::Debug for Node {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Node")
            .field("classes", &self.mf_classes())
            .field("id", &self.id())
            .field("tag", &self.tag())
            .finish()
    }
}

impl Node {
    fn class_str(&self) -> String {
        self.attr("class").unwrap_or_default()
    }

    fn id(&self) -> Option<String> {
        self.attr("id").filter(super::non_empty_string)
    }

    pub(crate) fn mf_classes(&self) -> Vec<DeclKind> {
        DeclKind::from_str(self.class_str())
    }

    pub(crate) fn property_classes(&self) -> Vec<DeclKind> {
        self.mf_classes()
            .into_iter()
            .filter(|c| !c.is_root())
            .collect::<Vec<_>>()
    }

    pub(crate) fn root_classes(&self) -> Vec<Class> {
        DeclKind::extract_root_classes(&self.mf_classes())
    }

    pub(crate) fn attr(&self, name: &str) -> Option<String> {
        self.elem
            .attributes
            .iter()
            .find(|attr| attr.name == name)
            .and_then(|attr| attr.value.as_ref().map(|v| v.to_string()))
    }

    pub(crate) fn attrs(&self, name: &str) -> Vec<String> {
        self.elem
            .attributes
            .iter()
            .filter(|attr| attr.name == name)
            .filter_map(|attr| attr.value.as_ref().map(|v| v.to_string()))
            .collect()
    }

    pub(crate) fn tag(&self) -> &str {
        &self.elem.tag_name
    }

    pub fn full_attribute_map(&self) -> BTreeMap<String, String> {
        self.elem
            .attributes
            .iter()
            .filter_map(|attr| {
                attr.value
                    .as_ref()
                    .map(|v| (attr.name.to_string(), v.to_string()))
            })
            .collect()
    }

    #[tracing::instrument(level = "trace", skip(self), ret, fields(base_url = base_url.as_str()))]
    pub(crate) fn text_content(
        &self,
        base_url: &url::Url,
    ) -> Result<Extraction, crate::parse::Error> {
        InnerTextExtractor::new(self.elem.to_owned(), false, base_url.to_owned()).extract()
    }

    #[tracing::instrument(level = "trace", skip(self), ret, fields(base_url = base_url.as_str()))]
    pub(crate) fn text_content_with_img_links(
        &self,
        base_url: &url::Url,
    ) -> Result<Extraction, crate::parse::Error> {
        InnerTextExtractor::new(self.elem.to_owned(), true, base_url.to_owned()).extract()
    }

    #[tracing::instrument(level = "trace", skip(self), ret)]
    pub(crate) fn html_content(&self) -> Result<String, crate::parse::Error> {
        InnerHtmlExtractor::new(self.elem.to_owned()).extract()
    }

    pub fn elements(&self) -> Vec<Node> {
        self.elem
            .children
            .iter()
            .filter_map(|child| {
                if let Child::Element(elem) = child {
                    Some(Self {
                        elem: elem.to_owned(),
                    })
                } else {
                    None
                }
            })
            .collect::<Vec<_>>()
    }

    #[cfg(feature = "debug_flow")]
    /// Capture comprehensive debug information about this HTML element.
    ///
    /// This method collects all relevant information about the element that could
    /// be useful for debugging the parsing process, including its identifier,
    /// tag name, classes, attributes, position, and parent context.
    ///
    /// # Returns
    ///
    /// An `ElementSource` struct containing detailed information about this element,
    /// including its unique identifier from the data-mf2-id attribute, tag name,
    /// all CSS classes, complete attribute map, and source position.
    pub fn capture_debug_info(&self) -> ElementSource {
        ElementSource {
            mf2_id: self.attr("data-mf2-id").filter(|s| !s.is_empty()),
            tag: self.tag().to_string(),
            classes: self
                .class_str()
                .split_ascii_whitespace()
                .map(|s| s.to_string())
                .collect(),
            attributes: self.full_attribute_map(),
            position: self.source_position(),
            parent_ids: vec![], // Will be filled during hierarchy tracking
        }
    }

    #[cfg(feature = "debug_flow")]
    /// Get the source code position of this element.
    ///
    /// Returns a SourcePosition struct containing the line number, column number,
    /// and byte offset of this element in the original HTML source.
    pub fn source_position(&self) -> microformats_types::SourcePosition {
        use microformats_types::SourcePosition;

        // SWC doesn't provide direct line/column info, so we'll use the byte offset
        // and estimate line/column based on the original HTML parsing
        let offset = self.elem.span.lo.0 as usize;

        SourcePosition {
            line: 1,            // Placeholder - would need proper line tracking
            column: offset + 1, // Simple column calculation
            offset,
        }
    }
}

struct InnerTextExtractor {
    lines: Vec<String>,
    root: Element,
    extract_src_of_img: bool,
    base_url: url::Url,
    link_nodes: Vec<Node>,
}

impl InnerTextExtractor {
    fn new(root: Element, extract_src_of_img: bool, base_url: url::Url) -> Self {
        Self {
            lines: Default::default(),
            root,
            extract_src_of_img,
            base_url,
            link_nodes: Default::default(),
        }
    }

    #[tracing::instrument(level = "trace", skip(self))]
    fn extract(mut self) -> Result<Extraction, crate::parse::Error> {
        let elem = self.root.to_owned();
        self.emit(&elem)?;
        let text = self
            .lines
            .into_iter()
            .filter(non_empty_string)
            .collect::<Vec<_>>()
            .join("")
            .to_string();

        let mut links = Vec::default();
        for link_node in self.link_nodes {
            if let Some(href) = link_node.attr("href") {
                links.push(if !href.starts_with("#") {
                    self.base_url.join(&href)?.to_string()
                } else {
                    href
                })
            }
        }

        Ok(Extraction { text, links })
    }
}

#[derive(Debug, PartialEq, Eq, Default)]
pub(crate) struct Extraction {
    pub text: String,
    pub links: Vec<String>,
}

impl From<Extraction> for String {
    fn from(extract: Extraction) -> Self {
        extract.text
    }
}

impl swc_html_codegen::Emit<Child> for InnerTextExtractor {
    #[tracing::instrument(level = "trace", skip(self, child), ret, name = "emit_child")]
    fn emit(&mut self, child: &Child) -> swc_html_codegen::Result {
        match child {
            Child::Text(text) => self.emit(text),
            Child::Element(elem) => self.emit(elem),
            Child::Comment(_) => Ok(()),
            _ => Ok(()),
        }
    }
}

impl swc_html_codegen::Emit<Element> for InnerTextExtractor {
    #[tracing::instrument(level = "trace", skip(self, element), ret, name = "emit_element")]
    fn emit(&mut self, element: &Element) -> swc_html_codegen::Result {
        let node = Node {
            elem: element.to_owned(),
        };

        if ["script", "style", "template"].contains(&node.tag()) {
            return Ok(());
        }

        if node.attr("href").filter(|_| node.tag() == "a").is_some() {
            self.link_nodes.push(node.clone());
        }

        if let Some(alt_text) = node.attr("alt").filter(|_| node.tag() == "img") {
            self.lines.push(alt_text);
        } else if let Some(src_url) = node
            .attr("src")
            .filter(|_| node.tag() == "img" && self.extract_src_of_img)
        {
            let full_url = self.base_url.join(&src_url).map_err(|_| std::fmt::Error)?;
            self.lines.push(format!(" {full_url} "));
        } else {
            for child in element.children.iter() {
                self.emit(&child)?;
            }
        }

        Ok(())
    }
}

impl swc_html_codegen::Emit<Text> for InnerTextExtractor {
    #[tracing::instrument(level = "trace", skip(self, text_node), ret, name = "emit_text")]
    fn emit(&mut self, text_node: &Text) -> swc_html_codegen::Result {
        self.lines.push(text_node.data.as_str().to_string());
        Ok(())
    }
}

struct InnerHtmlExtractor {
    root: Element,
}

impl InnerHtmlExtractor {
    fn extract(self) -> Result<String, crate::parse::Error> {
        let wtr_cfg = BasicHtmlWriterConfig {
            indent_type: IndentType::Tab,
            indent_width: 2,
            linefeed: LineFeed::LF,
        };
        let cg_cfg = CodegenConfig {
            minify: false,
            scripting_enabled: true,
            quotes: Some(true),
            ..Default::default()
        };
        let mut html = String::default();
        let html_writer = BasicHtmlWriter::new(&mut html, None, wtr_cfg);
        let mut generator = CodeGenerator::new(html_writer, cg_cfg);

        for child in self.root.children {
            generator.emit(&child)?;
        }

        Ok(remove_surrounding_whitespace(html))
    }

    fn new(root: Element) -> Self {
        Self { root }
    }
}

pub(crate) struct HtmlUrlExpander;

impl HtmlUrlExpander {
    #[allow(dead_code)]
    pub(crate) fn expand_urls_in_html(
        element: &Element,
        base_url: &url::Url,
    ) -> Result<String, crate::parse::Error> {
        // First generate the HTML
        let wtr_cfg = BasicHtmlWriterConfig {
            indent_type: IndentType::Tab,
            indent_width: 2,
            linefeed: LineFeed::LF,
        };
        let cg_cfg = CodegenConfig {
            minify: false,
            scripting_enabled: true,
            quotes: Some(true),
            ..Default::default()
        };
        let mut html = String::default();
        let html_writer = BasicHtmlWriter::new(&mut html, None, wtr_cfg);
        let mut generator = CodeGenerator::new(html_writer, cg_cfg);

        for child in &element.children {
            generator.emit(child)?;
        }

        let html = remove_surrounding_whitespace(html);

        // Post-process the HTML to expand URLs
        Self::expand_urls_in_html_string(&html, base_url)
    }

    pub(crate) fn expand_urls_in_html_string(
        html: &str,
        base_url: &url::Url,
    ) -> Result<String, crate::parse::Error> {
        use regex::Regex;

        // Regex to match href="..." and src="..." attributes
        let href_regex = Regex::new(r#"(?i)\bhref\s*=\s*"([^"]*)""#).unwrap();
        let src_regex = Regex::new(r#"(?i)\bsrc\s*=\s*"([^"]*)""#).unwrap();

        let mut result = html.to_string();

        // Expand href attributes
        result = href_regex
            .replace_all(&result, |caps: &regex::Captures| {
                let url_str = &caps[1];
                if !url_str.starts_with("http://")
                    && !url_str.starts_with("https://")
                    && !url_str.starts_with("#")
                {
                    if let Ok(expanded) = base_url.join(url_str) {
                        return format!(r#"href="{}""#, expanded);
                    }
                }
                caps[0].to_string()
            })
            .to_string();

        // Expand src attributes
        result = src_regex
            .replace_all(&result, |caps: &regex::Captures| {
                let url_str = &caps[1];
                if !url_str.starts_with("http://")
                    && !url_str.starts_with("https://")
                    && !url_str.starts_with("#")
                {
                    if let Ok(expanded) = base_url.join(url_str) {
                        return format!(r#"src="{}""#, expanded);
                    }
                }
                caps[0].to_string()
            })
            .to_string();

        // Remove self-closing slashes from void elements to match HTML5 style
        let void_elements = [
            "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
            "source", "track", "wbr",
        ];
        for element in &void_elements {
            let pattern = format!(r#"<{}[^>]*\s*/>"#, regex::escape(element));
            let regex = Regex::new(&pattern).unwrap();
            result = regex
                .replace_all(&result, |caps: &regex::Captures| {
                    caps[0].replace(r#" />"#, ">")
                })
                .to_string();
        }

        Ok(result)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Placement {
    Root,
    TopLevel {
        node: ElementPtr,
    },
    ChildOf {
        parent: ElementPtr,
        child: ElementPtr,
    },
    PropertyItemOf {
        property_elem: ElementPtr,
        parent: ElementPtr,
    },
    PropertyOf {
        parent: ElementPtr,
        kind: DeclKind,
        owner: ElementPtr,
    },
    BaseURL {
        node: Node,
    },
    Meta {
        node: Node,
    },
    Link {
        node: Node,
    },
    DocumentLanguage {
        language: String,
    },
}

impl Placement {
    fn property_parent_item(&self, item: ElementPtr) -> Result<Self, Error> {
        match self {
            Self::PropertyItemOf {
                property_elem: node,
                ..
            }
            | Self::ChildOf { child: node, .. }
            | Self::TopLevel { node } => Ok(Self::PropertyItemOf {
                property_elem: item,
                parent: Arc::clone(node),
            }),
            Self::Root => self.child_item(item),
            _ => Err(Error::MissingParentItemForProperty(self.to_owned())),
        }
    }

    #[tracing::instrument]
    fn child_item(&self, item: ElementPtr) -> Result<Self, Error> {
        match self {
            Self::PropertyItemOf {
                property_elem: node,
                ..
            }
            | Self::ChildOf { child: node, .. }
            | Self::TopLevel { node } => Ok(Self::ChildOf {
                child: item,
                parent: Arc::clone(node),
            }),
            Self::Root => Ok(Self::TopLevel { node: item }),
            _ => Err(Error::MissingParentItem(self.to_owned())),
        }
    }

    #[tracing::instrument]
    fn property_declarations(
        &self,
        item: ElementPtr,
        property_classes: &[DeclKind],
    ) -> Result<Vec<Self>, Error> {
        let parent = if let Ok(Self::PropertyItemOf { ref parent, .. }) =
            self.property_parent_item(Arc::clone(&item))
        {
            Arc::clone(parent)
        } else {
            return Err(Error::MissingParentItemForPropertyDeclaration(
                self.to_owned(),
            ));
        };

        property_classes
            .iter()
            .try_fold(Vec::default(), |mut placements, prop| {
                placements.push(Self::PropertyOf {
                    parent: Arc::clone(&parent),
                    kind: prop.to_owned(),
                    owner: Arc::clone(&item),
                });
                Ok(placements)
            })
    }
}

#[derive(Default)]
pub(crate) struct MatchedElements {
    pub places: Vec<Placement>,
    pub elements: Vec<ElementPtr>,
    pub hook: Option<Arc<dyn super::ParserHook>>,
    pub enable_id_generation: bool,
    pub id_counter: AtomicUsize,
}

impl std::fmt::Debug for MatchedElements {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("MatchedElements")
            .field(&self.places)
            .finish()
    }
}

impl MatchedElements {
    #[tracing::instrument(level = "trace", skip(self), fields(count = %self.places.len()))]
    fn remember_place(&mut self, place: Placement) {
        if !self.places.contains(&place) {
            self.places.push(place);
        }
    }

    #[tracing::instrument(level = "trace", skip(self, node), fields(count = %self.elements.len()))]
    fn remember_element(&mut self, node: Node) -> ElementPtr {
        let ptr = ElementPtr::new(ElementRef {
            node,
            index: self.elements.len(),
        });
        self.elements.push(Arc::clone(&ptr));
        ptr
    }

    fn explicit_properties(
        &self,
        item: ElementPtr,
        base_url: &url::Url,
    ) -> Result<Properties, crate::parse::Error> {
        self.places
            .iter()
            .filter_map(|loc| {
                if let Placement::PropertyOf {
                    parent,
                    kind,
                    owner,
                } = loc
                {
                    if parent.node.elem == item.node.elem {
                        Some(explicit::PropertyParser::new(
                            Arc::clone(owner),
                            kind.to_owned(),
                            base_url.to_owned(),
                            Some(Arc::clone(parent)),
                        ))
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .try_fold(Properties::default(), |mut properties, property_parser| {
                if let Some((property_name, property_value)) = property_parser.expand()? {
                    if let Some(values) = properties.get_mut(&property_name) {
                        values.push(property_value.clone());
                    } else {
                        properties.insert(property_name.clone(), vec![property_value.clone()]);
                    }
                    if let Some(ref hook) = self.hook {
                        hook.on_property_matched(
                            &property_parser.elem.node,
                            &property_name,
                            &property_value,
                        );
                    }
                }

                Result::<_, crate::parse::Error>::Ok(properties)
            })
    }

    fn item_properties(
        &self,
        item: ElementPtr,
        base_url: &url::Url,
    ) -> Result<Properties, crate::parse::Error> {
        self.places
            .iter()
            .filter_map(|loc| {
                if let Placement::PropertyItemOf {
                    parent,
                    property_elem,
                } = loc
                {
                    if parent.node.elem == item.node.elem {
                        Some(item::PropertyParser::new(
                            Arc::clone(property_elem),
                            base_url,
                        ))
                    } else {
                        None
                    }
                } else {
                    None
                }
            })
            .try_fold(Properties::default(), |mut properties, property_parser| {
                let elem_clone = property_parser.property_elem.clone();
                for (property_name, property_values) in property_parser.expand(self)? {
                    if let Some(values) = properties.get_mut(&property_name) {
                        values.extend(property_values.clone());
                    } else {
                        properties.insert(property_name.clone(), property_values.clone());
                    }
                    for value in &property_values {
                        if let Some(ref hook) = self.hook {
                            hook.on_property_matched(&elem_clone.node, &property_name, value);
                        }
                    }
                }

                Result::<_, crate::parse::Error>::Ok(properties)
            })
    }

    #[tracing::instrument(level = "trace", skip(self, item), err, fields(base_url = base_url.to_string()))]
    fn properties_for(
        &self,
        item: ElementPtr,
        base_url: &url::Url,
    ) -> Result<Properties, crate::parse::Error> {
        let mut properties = self.explicit_properties(Arc::clone(&item), base_url)?;
        merge_hash_maps(
            &mut properties,
            self.item_properties(Arc::clone(&item), base_url)?,
        );

        adjust_timestamps(&mut properties);
        Ok(properties)
    }

    #[tracing::instrument(level = "trace", skip(self, item), ret, err)]
    fn children_for(
        &self,
        item: ElementPtr,
        base_url: &url::Url,
    ) -> Result<Vec<Item>, crate::parse::Error> {
        let elements = self
            .places
            .iter()
            .filter_map(|loc| {
                if let Placement::ChildOf { parent, child } = loc {
                    if *parent == item { Some(child) } else { None }
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();

        let expected_count = elements.len();
        let resulting_items =
            elements
                .into_iter()
                .try_fold(Vec::default(), |mut items, item_elem| {
                    let child_item =
                        self.expand_item_from_element(Arc::clone(item_elem), base_url)?;

                    items.push(child_item);

                    Result::<_, crate::parse::Error>::Ok(items)
                })?;

        assert_eq!(expected_count, resulting_items.len());
        Ok(resulting_items)
    }

    #[tracing::instrument(level = "trace", skip(self), ret)]
    pub(crate) fn top_level_elements(&self) -> Vec<ElementPtr> {
        self.places
            .iter()
            .filter_map(|place| {
                if let Placement::TopLevel { node } = place {
                    Some(Arc::clone(node))
                } else {
                    None
                }
            })
            .collect()
    }

    pub fn link_relation_elements(&self) -> Vec<Node> {
        self.places
            .iter()
            .filter_map(|place| {
                if let Placement::Link { node } = place {
                    Some(node.to_owned())
                } else {
                    None
                }
            })
            .collect()
    }

    pub(crate) fn discern_base_url(&self) -> Option<url::Url> {
        self.places.iter().find_map(|place| {
            if let Placement::BaseURL { node } = place {
                let url_base = node.attr("href").filter(non_empty_string)?;
                if let Ok(mut base_url) = url_base.parse::<url::Url>() {
                    if base_url.path().is_empty() {
                        base_url.set_path("/");
                    }
                    Some(base_url)
                } else {
                    None
                }
            } else {
                None
            }
        })
    }

    #[tracing::instrument(level = "trace", skip(self, item_elem), ret, err, fields(base_url = base_url.to_string()))]
    pub(crate) fn expand_item_from_element(
        &self,
        item_elem: ElementPtr,
        base_url: &url::Url,
    ) -> Result<Item, crate::parse::Error> {
        let document_language = if let Some(Placement::DocumentLanguage { language }) = self
            .places
            .iter()
            .find(|pos| matches!(pos, Placement::DocumentLanguage { .. }))
        {
            Some(language.to_owned())
        } else {
            None
        };
        let mut item = Item::new(item_elem.node.root_classes());
        item.id = item_elem.node.id();
        item.lang = item_elem
            .node
            .attr("lang")
            .filter(non_empty_string)
            .or(document_language);
        item.children
            .extend(self.children_for(Arc::clone(&item_elem), base_url)?);

        let mut properties = self.properties_for(Arc::clone(&item_elem), base_url)?;
        if item.children.is_empty() {
            let props = properties.to_owned();
            merge_hash_maps(
                &mut properties,
                implied::PropertiesParser::new(Arc::clone(&item_elem), props, base_url)
                    .extract_implied()?,
            )
        }

        // Call hooks for all properties
        for (name, values) in &properties {
            for value in values {
                if let Some(ref hook) = self.hook {
                    hook.on_property_matched(&item_elem.node, name, value);
                }
            }
        }

        item.properties.extend(properties);

        Ok(item)
    }

    // With a parent location and an item to test, return the location to use for children.
    fn translate_location(
        &mut self,
        parent_location: &Placement,
        element: &mut Element,
    ) -> Result<Placement, Error> {
        let node = Node {
            elem: element.clone(),
        };
        // Add a[rel] to link relation lookup.
        if node.tag() == "a"
            && node.attr("rel").filter(non_empty_string).is_some()
            && node.attr("href").is_some()
        {
            self.remember_place(Placement::Link { node: node.clone() });
        }

        // Pull out html[lang] and mark it as the root.
        if let Some(language) = node
            .attr("lang")
            .filter(non_empty_string)
            .filter(|_| node.tag() == "html")
        {
            self.remember_place(Placement::DocumentLanguage { language })
        }

        // Grab some elements for checks.
        if node.mf_classes().is_empty() {
            if node.tag() == "base" {
                self.remember_place(Placement::BaseURL { node });
            } else if node.tag() == "meta" {
                self.remember_place(Placement::Meta { node });
            } else if node.tag() == "link" && node.attr("href").is_some() {
                self.remember_place(Placement::Link { node });
            }

            return Ok(parent_location.to_owned());
        }

        let is_item_elem = !node.root_classes().is_empty();
        let explicit_property_classes = node.property_classes();
        let is_property = !explicit_property_classes.is_empty();

        // Insert self into shared list of elements.
        let elem_ref = self.remember_element(node);

        // Add data-mf2-id if enabled
        if self.enable_id_generation {
            let id = self.id_counter.fetch_add(1, Ordering::Relaxed);
            element.attributes.push(Attribute {
                span: Default::default(),
                namespace: None,
                prefix: None,
                name: "data-mf2-id".into(),
                raw_name: None,
                value: Some(format!("mf2-{}", id).into()),
                raw_value: None,
            });
        }

        let child_location = if is_item_elem && !is_property {
            Some(parent_location.child_item(Arc::clone(&elem_ref))?)
        } else if is_property {
            if is_item_elem {
                Some(parent_location.property_parent_item(Arc::clone(&elem_ref))?)
            } else if let Ok(property_decls) = parent_location
                .property_declarations(Arc::clone(&elem_ref), &explicit_property_classes)
            {
                for property_decl in property_decls {
                    self.remember_place(property_decl);
                }

                Some(parent_location.to_owned())
            } else {
                None
            }
        } else {
            None
        };

        if let Some(child_location) = child_location {
            // Persist the resolved location and provide the next (child) element a place to go.
            self.remember_place(child_location.to_owned());
            Ok(child_location)
        } else {
            // Push it to the top of the document if we can't resolve it.
            // NOTE: We should flag this node somehow in the parser.
            Ok(Placement::Root)
        }
    }

    /// Does the work of iterating through the child nodes, selecting children and attempting to
    /// flag it for later processing.
    ///
    /// # Errors
    ///
    /// This function will return an error if transveral through the DOM failed.
    #[tracing::instrument(level = "trace", ret, err, skip(self, children))]
    pub(crate) fn walk_over_children(
        &mut self,
        children: &mut [Child],
        location: &Placement,
    ) -> Result<(), crate::parse::Error> {
        for child in children.iter_mut() {
            if let Child::Element(element) = child {
                let local_location = self.translate_location(location, element)?;
                self.walk_over_children(&mut element.children, &local_location)?;
            }
        }

        Ok(())
    }

    pub(crate) fn for_document(
        dom: &mut swc_html_ast::Document,
        hook: Option<Arc<dyn super::ParserHook>>,
        enable_id_generation: bool,
    ) -> Result<Self, crate::parse::Error> {
        let mut elements = Self {
            places: Vec::new(),
            elements: Vec::new(),
            hook,
            enable_id_generation,
            id_counter: AtomicUsize::new(0),
        };
        elements.walk_over_children(&mut dom.children, &Placement::Root)?;

        Ok(elements)
    }

    /// For tests: for_document with default parameters (no hook, no ID generation)
    #[allow(dead_code)]
    pub(crate) fn for_document_default(
        dom: &mut swc_html_ast::Document,
    ) -> Result<Self, crate::parse::Error> {
        Self::for_document(dom, None, false)
    }
}

pub struct LinkRelationExpander {
    pub base_url: url::Url,
    pub elements: Vec<Node>,
}

impl LinkRelationExpander {
    pub fn expand(self, document: &mut Document) -> Result<(), crate::parse::Error> {
        for node in self.elements {
            // Collect ALL rel attributes from each node
            let rel_strs = node
                .attrs("rel")
                .into_iter()
                .filter(non_empty_string)
                .map(remove_surrounding_whitespace)
                .filter(|s| !s.is_empty());

            if rel_strs.clone().count() == 0 {
                continue;
            }

            let url = self
                .base_url
                .join(
                    &node
                        .attr("href")
                        .filter(non_empty_string)
                        .map(remove_surrounding_whitespace)
                        .unwrap_or_default(),
                )
                .map_err(crate::parse::Error::from)?;

            // Concatenate all rel values and split on whitespace
            let concatenated_rel_str = rel_strs.collect::<Vec<_>>().join(" ");
            let rels = concatenated_rel_str
                .split_ascii_whitespace()
                .map(ToString::to_string)
                .collect::<Vec<_>>();

            let hreflang = node.attr("hreflang").filter(non_empty_string);
            let title = node.attr("title").filter(non_empty_string);
            let media = node.attr("media").filter(non_empty_string);
            let r#type = node.attr("type").filter(non_empty_string);
            let Extraction { text, .. } = node.text_content(&self.base_url)?;

            let relation = microformats_types::Relation {
                rels,
                hreflang,
                media,
                title,
                r#type,
                text: Some(text),
            };

            document.add_relation(url.clone(), relation);
        }
        Ok(())
    }
}

#[cfg(test)]
pub(crate) mod test;