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
//! Experimental extensions for microformats parsing.
//!
//! This module provides optional features that extend the core microformats functionality.
//! These features are opt-in via Cargo feature flags and allow users to enable
//! experimental capabilities while maintaining backward compatibility.
//!
//! # Available Features
//!
//! ## `cleaner` Feature
//! The `cleaner` feature provides the [`CleanedDocument`] trait for filtering
//! documents to contain only recognized microformat classes.
//!
//! # Example - Document Cleaning
//!
//! ```ignore
//! use microformats::extensions::CleanedDocument;
//!
//! let doc = microformats::from_html(html, &url)?;
//! let cleaned = doc.with_only_known_classes();
//! // Or using the shorter alias:
//! let cleaned = doc.as_cleaned();
//! ```
//!
//! ## `picture` Feature (Experimental)
//!
//! The `picture` feature enables enhanced parsing of HTML `<picture>` elements,
//! providing support for responsive images with multiple sources, srcset attributes,
//! and media queries.
//!
//! ### Enabling the Feature
//!
//! Add to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! microformats = { version = "0.18", features = ["picture"] }
//! ```
//!
//! ### Picture Element Processing
//!
//! When enabled, the parser can handle complex picture elements:
//!
//! ```html
//! <picture class="u-photo">
//!     <source srcset="/images/hero-800w.jpg 800w, /images/hero-400w.jpg 400w"
//!             media="(min-width: 800px)" type="image/jpeg">
//!     <source srcset="/images/hero-600h.jpg 600h"
//!             media="(min-width: 600px)" type="image/webp">
//!     <img src="/images/fallback.jpg" alt="Hero image">
//! </picture>
//! ```
//!
//! ### Output Format
//!
//! Picture elements are parsed into structured data containing:
//! - Multiple `<source>` elements with their srcset, media, and type attributes
//! - Fallback `<img>` element information
//! - All URL resolution relative to the document base URL
//!
//! ### Supported Properties
//!
//! The picture feature works with standard microformats properties:
//! - `u-photo` - Photo images
//! - `u-logo` - Logo images
//! - `u-avatar` - Avatar images
//! - `p-name` - Name extraction from picture alt text
//!
//! ### Experimental Status
//!
//! ⚠️ **Note**: The picture parsing feature is experimental and subject to change.
//! The API and output format may evolve as the feature matures. Consider this
//! when building long-term dependencies on the picture parsing capabilities.
//!
//! This allows users to opt-in to experimental features while maintaining
//! backward compatibility for standard parsing.

use microformats_types::{Document, Item, Properties, PropertyValue};

/// Trait for cleaning documents of unrecognized microformat classes.
#[cfg(feature = "cleaner")]
pub trait CleanedDocument {
    /// Returns a new document containing only items with recognized microformat classes.
    ///
    /// This filters both top-level items and nested items (children and property values).
    fn with_only_known_classes(&self) -> Self;

    /// Returns a new document containing only items with recognized microformat classes.
    ///
    /// This is an alias for `with_only_known_classes()` and provides a more concise syntax.
    /// This filters both top-level items and nested items (children and property values).
    fn as_cleaned(&self) -> Self
    where
        Self: Sized,
    {
        self.with_only_known_classes()
    }

    /// Returns a list of items with unrecognized (custom) classes.
    fn unrecognized_items(&self) -> Vec<&Item>;
}

#[cfg(feature = "cleaner")]
impl CleanedDocument for Document {
    fn with_only_known_classes(&self) -> Self {
        let filtered_items = self.items.iter().filter_map(filter_item).collect();

        Self {
            items: filtered_items,
            url: self.url.clone(),
            rels: self.rels.clone(),
            lang: self.lang.clone(),
            #[cfg(feature = "metaformats")]
            meta_item: self.meta_item.as_ref().and_then(filter_item),
            #[cfg(feature = "debug_flow")]
            _debug_context: self._debug_context.clone(),
        }
    }

    fn unrecognized_items(&self) -> Vec<&Item> {
        let mut result = Vec::new();

        for item in &self.items {
            result.extend(collect_unrecognized_items(item));
        }

        result
    }
}

/// Returns `Some(item)` if all its classes are recognized, with nested items filtered.
/// Returns `None` if any class is unrecognized.
fn filter_item(item: &Item) -> Option<Item> {
    if item.r#type.iter().any(|c| !c.is_recognized()) {
        return None;
    }

    Some(Item {
        r#type: item.r#type.clone(),
        properties: filter_properties(&item.properties),
        children: item.children.iter().filter_map(filter_item).collect(),
        id: item.id.clone(),
        lang: item.lang.clone(),
        value: item.value.clone(),
    })
}

/// Filters property values, cleaning any nested items.
fn filter_properties(props: &Properties) -> Properties {
    props
        .iter()
        .map(|(key, values)| {
            let filtered_values = values
                .iter()
                .filter_map(|pv| match pv {
                    PropertyValue::Item(nested) => filter_item(nested).map(PropertyValue::Item),
                    _other => Some(pv.clone()),
                })
                .collect();
            (key.clone(), filtered_values)
        })
        .collect()
}

/// Collects all unrecognized items from an item tree.
fn collect_unrecognized_items<'a>(item: &'a Item) -> Vec<&'a Item> {
    let mut result = Vec::new();

    if item.r#type.iter().any(|c| !c.is_recognized()) {
        result.push(item);
    }

    // Check children
    for child in item.children.iter() {
        result.extend(collect_unrecognized_items(child));
    }

    // Check property values for nested items
    for values in item.properties.values() {
        for pv in values {
            if let PropertyValue::Item(nested) = pv {
                result.extend(collect_unrecognized_items(nested));
            }
        }
    }

    result
}

#[cfg(feature = "cleaner")]
mod test {
    use super::*;
    use microformats_types::{Class, Item, Items, KnownClass, PropertyValue};

    fn make_document_with_known_class() -> Document {
        Document {
            items: vec![Item {
                r#type: vec![Class::Known(KnownClass::Card)],
                properties: Default::default(),
                children: Items::from(vec![]),
                id: None,
                lang: None,
                value: None,
            }],
            url: None,
            rels: Default::default(),
            lang: None,
            #[cfg(feature = "metaformats")]
            meta_item: None,
            #[cfg(feature = "debug_flow")]
            _debug_context: Default::default(),
        }
    }

    fn make_document_with_custom_class() -> Document {
        Document {
            items: vec![Item {
                r#type: vec![Class::Custom("h-custom".to_string())],
                properties: Default::default(),
                children: Items::from(vec![]),
                id: None,
                lang: None,
                value: None,
            }],
            url: None,
            rels: Default::default(),
            lang: None,
            #[cfg(feature = "metaformats")]
            meta_item: None,
            #[cfg(feature = "debug_flow")]
            _debug_context: Default::default(),
        }
    }

    fn make_document_with_mixed_classes() -> Document {
        Document {
            items: vec![
                Item {
                    r#type: vec![Class::Known(KnownClass::Card)],
                    properties: Default::default(),
                    children: Items::from(vec![]),
                    id: None,
                    lang: None,
                    value: None,
                },
                Item {
                    r#type: vec![Class::Custom("h-custom".to_string())],
                    properties: Default::default(),
                    children: Items::from(vec![]),
                    id: None,
                    lang: None,
                    value: None,
                },
            ],
            url: None,
            rels: Default::default(),
            lang: None,
            #[cfg(feature = "metaformats")]
            meta_item: None,
            #[cfg(feature = "debug_flow")]
            _debug_context: Default::default(),
        }
    }

    fn make_document_with_nested_custom() -> Document {
        Document {
            items: vec![Item {
                r#type: vec![Class::Known(KnownClass::Entry)],
                properties: [(
                    "author".to_string(),
                    vec![PropertyValue::Item(Item {
                        r#type: vec![Class::Custom("h-custom".to_string())],
                        properties: Default::default(),
                        children: Items::from(vec![]),
                        id: None,
                        lang: None,
                        value: None,
                    })],
                )]
                .into_iter()
                .collect(),
                children: Items::from(vec![]),
                id: None,
                lang: None,
                value: None,
            }],
            url: None,
            rels: Default::default(),
            lang: None,
            #[cfg(feature = "metaformats")]
            meta_item: None,
            #[cfg(feature = "debug_flow")]
            _debug_context: Default::default(),
        }
    }

    fn make_document_with_children_custom() -> Document {
        Document {
            items: vec![Item {
                r#type: vec![Class::Known(KnownClass::Card)],
                properties: Default::default(),
                children: Items::from(vec![Item {
                    r#type: vec![Class::Custom("h-custom".to_string())],
                    properties: Default::default(),
                    children: Items::from(vec![]),
                    id: None,
                    lang: None,
                    value: None,
                }]),
                id: None,
                lang: None,
                value: None,
            }],
            url: None,
            rels: Default::default(),
            lang: None,
            #[cfg(feature = "metaformats")]
            meta_item: None,
            #[cfg(feature = "debug_flow")]
            _debug_context: Default::default(),
        }
    }

    #[test]
    fn with_only_known_classes_keeps_recognized_classes() {
        let doc = make_document_with_known_class();
        let cleaned = doc.with_only_known_classes();

        assert_eq!(cleaned.items.len(), 1);
        assert!(matches!(
            cleaned.items[0].r#type[0],
            Class::Known(KnownClass::Card)
        ));
    }

    #[test]
    fn with_only_known_classes_removes_custom_classes() {
        let doc = make_document_with_custom_class();
        let cleaned = doc.with_only_known_classes();

        assert!(cleaned.items.is_empty());
    }

    #[test]
    fn with_only_known_classes_filters_mixed() {
        let doc = make_document_with_mixed_classes();
        let cleaned = doc.with_only_known_classes();

        assert_eq!(cleaned.items.len(), 1);
        assert!(matches!(
            cleaned.items[0].r#type[0],
            Class::Known(KnownClass::Card)
        ));
    }

    #[test]
    fn with_only_known_classes_removes_nested_custom_in_properties() {
        let doc = make_document_with_nested_custom();
        let cleaned = doc.with_only_known_classes();

        assert_eq!(cleaned.items.len(), 1);
        let author_values = &cleaned.items[0].properties["author"];
        assert!(author_values.is_empty());
    }

    #[test]
    fn with_only_known_classes_removes_custom_children() {
        let doc = make_document_with_children_custom();
        let cleaned = doc.with_only_known_classes();

        assert_eq!(cleaned.items.len(), 1);
        assert!(cleaned.items[0].children.is_empty());
    }

    #[test]
    fn with_only_known_classes_preserves_url() {
        let url = url::Url::parse("https://example.com").unwrap();
        let mut doc = make_document_with_known_class();
        doc.url = Some(url.clone());

        let cleaned = doc.with_only_known_classes();

        assert_eq!(cleaned.url, Some(url));
    }

    #[test]
    fn with_only_known_classes_preserves_rels() {
        let url = url::Url::parse("https://example.com").unwrap();
        let mut doc = make_document_with_known_class();
        doc.rels.items.insert(
            url.clone(),
            microformats_types::Relation {
                rels: vec!["me".to_string()],
                ..Default::default()
            },
        );

        let cleaned = doc.with_only_known_classes();

        assert!(cleaned.rels.items.get(&url).is_some());
    }

    #[test]
    fn with_only_known_classes_preserves_lang() {
        let mut doc = make_document_with_known_class();
        doc.lang = Some("en".to_string());

        let cleaned = doc.with_only_known_classes();

        assert_eq!(cleaned.lang, Some("en".to_string()));
    }

    #[test]
    fn with_only_known_classes_empty_document() {
        let doc = Document {
            items: vec![],
            url: None,
            rels: Default::default(),
            lang: None,
            #[cfg(feature = "metaformats")]
            meta_item: None,
            #[cfg(feature = "debug_flow")]
            _debug_context: Default::default(),
        };

        let cleaned = doc.with_only_known_classes();

        assert!(cleaned.items.is_empty());
    }

    #[test]
    fn with_only_known_classes_all_custom() {
        let doc = make_document_with_custom_class();
        let cleaned = doc.with_only_known_classes();

        assert!(cleaned.items.is_empty());
    }

    #[test]
    fn as_cleaned_same_as_with_only_known_classes() {
        let doc = make_document_with_mixed_classes();
        let cleaned_with_method = doc.with_only_known_classes();
        let cleaned_with_alias = doc.as_cleaned();

        assert_eq!(
            cleaned_with_method.items.len(),
            cleaned_with_alias.items.len()
        );
        assert!(matches!(
            cleaned_with_alias.items[0].r#type[0],
            Class::Known(KnownClass::Card)
        ));
    }

    #[test]
    fn as_cleaned_with_known_classes() {
        let doc = make_document_with_known_class();
        let cleaned = doc.as_cleaned();

        assert_eq!(cleaned.items.len(), 1);
        assert!(matches!(
            cleaned.items[0].r#type[0],
            Class::Known(KnownClass::Card)
        ));
    }

    #[test]
    fn as_cleaned_removes_custom_classes() {
        let doc = make_document_with_custom_class();
        let cleaned = doc.as_cleaned();

        assert!(cleaned.items.is_empty());
    }

    #[test]
    fn unrecognized_items_returns_custom() {
        let doc = make_document_with_custom_class();
        let unrecognized = doc.unrecognized_items();

        assert_eq!(unrecognized.len(), 1);
    }

    #[test]
    fn unrecognized_items_empty_for_known() {
        let doc = make_document_with_known_class();
        let unrecognized = doc.unrecognized_items();

        assert!(unrecognized.is_empty());
    }

    #[test]
    fn unrecognized_items_finds_all_custom() {
        let doc = make_document_with_mixed_classes();
        let unrecognized = doc.unrecognized_items();

        assert_eq!(unrecognized.len(), 1);
    }

    #[test]
    fn unrecognized_items_finds_nested_custom() {
        let doc = make_document_with_nested_custom();
        let unrecognized = doc.unrecognized_items();

        assert_eq!(unrecognized.len(), 1);
    }

    #[test]
    fn unrecognized_items_finds_custom_children() {
        let doc = make_document_with_children_custom();
        let unrecognized = doc.unrecognized_items();

        assert_eq!(unrecognized.len(), 1);
    }

    #[test]
    fn unrecognized_items_empty_document() {
        let doc = Document {
            items: vec![],
            url: None,
            rels: Default::default(),
            lang: None,
            #[cfg(feature = "metaformats")]
            meta_item: None,
            #[cfg(feature = "debug_flow")]
            _debug_context: Default::default(),
        };

        let unrecognized = doc.unrecognized_items();

        assert!(unrecognized.is_empty());
    }
}