ctb_formats_syndication/
hatom.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! hAtom microformat renderer for the syndication data model.
21//!
22//! Produces (X)HTML output with hAtom microformat markup, allowing feeds to
23//! be embedded in web pages and parsed by microformat-aware tools.
24//!
25//! The output follows the hAtom specification from microformats.org, using
26//! class names like `hfeed`, `hentry`, `entry-title`, `entry-content`,
27//! `author`, `updated`, `published`, and `rel-bookmark` for permalinks.
28//!
29//! Also includes microformats2 classes such as `h-feed`/`h-entry` and common
30//! properties like `p-name`, `u-url`, `p-author`, `dt-updated`, `e-content`.
31//!
32//! # Example Output
33//!
34//! ```html
35//! <div class="h-feed hfeed">
36//!   <h1 class="p-name">My Feed</h1>
37//!   <article class="h-entry hentry">
38//!     <h2 class="p-name entry-title">
39//!       <a href="https://example.org/post-1" rel="bookmark" class="u-url">My Post</a>
40//!     </h2>
41//!     <address class="p-author author h-card vcard">
42//!       <span class="p-name fn">Author Name</span>
43//!     </address>
44//!     <time class="dt-updated updated" datetime="2024-01-15T10:30:00Z">
45//!       2024-01-15T10:30:00Z
46//!     </time>
47//!     <div class="e-content entry-content">
48//!       <p>Post content here...</p>
49//!     </div>
50//!   </article>
51//! </div>
52//! ```
53//!
54//! Specifications:
55//!
56//! - hAtom: <https://microformats.org/wiki/hatom>
57//! - h-feed: <https://microformats.org/wiki/h-feed>
58//! - h-entry: <https://microformats.org/wiki/h-entry>
59
60use ctb_formats_html::entities::{escape_quoted_attr, escape_text};
61
62#[allow(
63    unused_imports,
64    clippy::wildcard_imports,
65    reason = "Standard workspace module prelude"
66)]
67use crate::utilities::*;
68
69use super::{Entry, Feed};
70use std::fmt::Write as _;
71
72/// Render a [`Feed`] into HTML with hAtom microformat markup.
73///
74/// Produces a complete HTML fragment with:
75/// - A container `<div class="h-feed hfeed">` wrapping all entries
76/// - Each entry as an `<article class="h-entry hentry">` with required fields
77/// - Proper semantic markup for authors, dates, and permalinks
78///
79/// The output is self-contained and can be embedded in a larger HTML page.
80pub(crate) fn render(feed: &Feed) -> Result<String> {
81    let mut output = String::new();
82
83    // Open container. Publish both mf2 + classic for backcompat.
84    writeln!(output, "<div class=\"h-feed hfeed\">")?;
85
86    // Feed name (mf2 p-name). hAtom doesn't standardize a feed-title property.
87    if !feed.title().is_empty() {
88        writeln!(
89            output,
90            "\t<h1 class=\"p-name\">{}</h1>",
91            escape_text(feed.title())
92        )?;
93    }
94
95    // Feed URLs (mf2 u-url). Use <a> (valid in fragments); avoid <link> which
96    // belongs in <head>.
97    if let Some(home_url) = feed.home_page_url() {
98        writeln!(
99            output,
100            "\t<a class=\"u-url\" rel=\"home\" href=\"{}\">{}</a>",
101            escape_quoted_attr(home_url),
102            escape_text(home_url)
103        )?;
104    }
105
106    if let Some(feed_url) = feed.feed_url() {
107        writeln!(
108            output,
109            "\t<a class=\"u-url\" rel=\"self\" href=\"{}\">{}</a>",
110            escape_quoted_attr(feed_url),
111            escape_text(feed_url)
112        )?;
113    }
114
115    for entry in feed.entries() {
116        write_entry(&mut output, entry)?;
117    }
118
119    writeln!(output, "</div>")?;
120    Ok(output)
121}
122
123/// Write an entry element with hAtom markup.
124fn write_entry(output: &mut String, entry: &Entry) -> Result<()> {
125    // Entry container (mf2 + classic).
126    writeln!(output, "\t<article class=\"h-entry hentry\">")?;
127
128    // Entry title (classic entry-title + mf2 p-name).
129    // If there's a URL, emit a permalink with rel-bookmark + mf2 u-url.
130    if let Some(url) = entry.url() {
131        writeln!(
132            output,
133            "\t\t<h2 class=\"p-name entry-title\"><a href=\"{}\" rel=\"bookmark\" class=\"u-url\">{}</a></h2>",
134            escape_quoted_attr(url),
135            escape_text(entry.title())
136        )?;
137    } else {
138        writeln!(
139            output,
140            "\t\t<h2 class=\"p-name entry-title\">{}</h2>",
141            escape_text(entry.title())
142        )?;
143    }
144
145    // Author (classic author + hCard; mf2 p-author h-card). hAtom requires this
146    // for validity; if missing we omit rather than inventing data.
147    if let Some(author_name) = entry.author() {
148        writeln!(
149            output,
150            "\t\t<address class=\"p-author author h-card vcard\"><span class=\"p-name fn\">{}</span></address>",
151            escape_text(author_name)
152        )?;
153    } else {
154        warn_fmt!("hAtom entry missing required author: id={}", entry.id());
155    }
156
157    // Updated is required for valid hAtom. If absent, hAtom says "use published"
158    // if present.
159    let date_updated = entry.updated();
160    let date_published = entry.date();
161    if !date_published.is_empty() {
162        writeln!(
163            output,
164            "\t\t<time class=\"published dt-published\" datetime=\"{}\">{}</time>",
165            escape_quoted_attr(date_published),
166            escape_text(date_published)
167        )?;
168    }
169    if let Some(updated) = date_updated {
170        if !updated.is_empty() {
171            writeln!(
172                output,
173                "\t\t<time class=\"updated dt-updated\" datetime=\"{}\">{}</time>",
174                escape_quoted_attr(updated),
175                escape_text(updated)
176            )?;
177        }
178    }
179    let has_date_updated = if let Some(updated) = date_updated {
180        !updated.is_empty()
181    } else {
182        false
183    };
184    if !has_date_updated && date_published.is_empty() {
185        warn!(
186            "No published or updated date was found. hAtom requires at least one."
187        );
188    }
189
190    // Entry content (classic entry-content + mf2 e-content). If missing, empty
191    // string is implied; we simply omit the element.
192    if !entry.body().is_empty() {
193        writeln!(output, "\t\t<div class=\"e-content entry-content\">")?;
194        writeln!(output, "\t\t\t{}", entry.body())?;
195        writeln!(output, "\t\t</div>")?;
196    }
197
198    writeln!(output, "\t</article>")?;
199    Ok(())
200}
201
202#[cfg(test)]
203#[allow(
204    clippy::panic,
205    clippy::expect_used,
206    clippy::unwrap_used,
207    clippy::unwrap_in_result,
208    clippy::panic_in_result_fn,
209    clippy::indexing_slicing,
210    clippy::arithmetic_side_effects,
211    reason = "Standard repository test boilerplate"
212)]
213mod tests {
214    use super::*;
215
216    #[crate::ctb_test]
217    fn test_render_empty_feed() -> Result<()> {
218        let feed = Feed::empty("Empty Test Feed");
219        let result = render(&feed)?;
220
221        assert!(result.contains("<div class=\"h-feed hfeed\">"));
222        assert!(result.contains("<h1 class=\"p-name\">Empty Test Feed</h1>"));
223        assert!(result.contains("</div>"));
224        Ok(())
225    }
226
227    #[crate::ctb_test]
228    fn test_render_feed_with_urls() -> Result<()> {
229        let feed = Feed::empty("Test Feed")
230            .with_home_page_url_opt(Some("https://example.org/".into()))
231            .with_feed_url_opt(Some("https://example.org/feed.html".into()));
232        let result = render(&feed)?;
233
234        assert!(
235            result.contains(
236                r#"<a class="u-url" rel="home" href="https://example.org/">"#
237            ),
238            "{result}"
239        );
240        assert!(
241            result.contains(r#"<a class="u-url" rel="self" href="https://example.org/feed.html">"#),
242            "{result}"
243        );
244        Ok(())
245    }
246
247    #[crate::ctb_test]
248    fn test_render_feed_with_entry() -> Result<()> {
249        let entry = Entry::new(
250            "entry-1",
251            "Test Entry",
252            "<p>Test content</p>",
253            "2024-01-15T10:30:00Z",
254        )
255        .with_author("Test Author")
256        .with_url_opt(Some("https://example.org/entry-1".into()));
257
258        let feed = Feed::new("Test Feed", vec![entry]);
259        let result = render(&feed)?;
260
261        assert!(result.contains("<article class=\"h-entry hentry\">"));
262        assert!(result.contains("<h2 class=\"p-name entry-title\">"));
263        assert!(
264            result.contains(
265                r#"<a href="https://example.org/entry-1" rel="bookmark" class="u-url">Test Entry</a>"#
266            ),
267            "{result}"
268        );
269        assert!(
270            result.contains("<address class=\"p-author author h-card vcard\">"),
271            "{result}"
272        );
273        assert!(
274            result.contains("<span class=\"p-name fn\">Test Author</span>")
275        );
276        assert!(
277            result.contains(r#"<time class="published dt-published" datetime="2024-01-15T10:30:00Z">"#),
278            "{result}"
279        );
280        assert!(result.contains("<div class=\"e-content entry-content\">"));
281        assert!(result.contains("<p>Test content</p>"));
282        assert!(result.contains("</article>"));
283        Ok(())
284    }
285
286    #[crate::ctb_test]
287    fn test_render_feed_with_updated_date() -> Result<()> {
288        let entry = Entry::new(
289            "entry-1",
290            "Test Entry",
291            "<p>Test content</p>",
292            "2024-01-15T10:30:00Z",
293        )
294        .with_author("Test Author")
295        .with_updated_opt(Some("2024-01-20T12:00:00Z".to_string()))
296        .with_url_opt(Some("https://example.org/entry-1".into()));
297
298        let feed = Feed::new("Test Feed", vec![entry]);
299        let result = render(&feed)?;
300
301        assert!(
302            result.contains(r#"<time class="published dt-published" datetime="2024-01-15T10:30:00Z">"#),
303            "{result}"
304        );
305        assert!(
306            result.contains(r#"<time class="updated dt-updated" datetime="2024-01-20T12:00:00Z">"#),
307            "{result}"
308        );
309        Ok(())
310    }
311
312    #[crate::ctb_test]
313    fn test_render_entry_minimal() -> Result<()> {
314        let entry = Entry::new("minimal-id", "Minimal Entry", "", "");
315        let feed = Feed::new("Minimal Feed", vec![entry]);
316        let result = render(&feed)?;
317
318        assert!(
319            result.contains(
320                "<h2 class=\"p-name entry-title\">Minimal Entry</h2>"
321            )
322        );
323        assert!(!result.contains("rel=\"bookmark\""));
324        assert!(!result.contains("<time"));
325        assert!(!result.contains("entry-content"));
326        assert!(!result.contains("author"));
327        Ok(())
328    }
329
330    #[crate::ctb_test]
331    fn test_render_entry_without_url() -> Result<()> {
332        let entry = Entry::new(
333            "no-url",
334            "Entry Without URL",
335            "<p>Content</p>",
336            "2024-01-10T00:00:00Z",
337        )
338        .with_author("Author");
339
340        let feed = Feed::new("Test", vec![entry]);
341        let result = render(&feed)?;
342
343        assert!(result.contains(
344            "<h2 class=\"p-name entry-title\">Entry Without URL</h2>"
345        ));
346        assert!(!result.contains("rel=\"bookmark\""));
347        Ok(())
348    }
349
350    #[crate::ctb_test]
351    fn test_render_multiple_entries() -> Result<()> {
352        let entry1 =
353            Entry::new("id-1", "First", "<p>First</p>", "2024-01-10T00:00:00Z");
354        let entry2 = Entry::new(
355            "id-2",
356            "Second",
357            "<p>Second</p>",
358            "2024-01-15T00:00:00Z",
359        );
360        let feed = Feed::new("Multi Entry Feed", vec![entry1, entry2]);
361        let result = render(&feed)?;
362
363        assert!(result.contains(">First</"));
364        assert!(result.contains(">Second</"));
365
366        let article_count =
367            result.matches("<article class=\"h-entry hentry\">").count();
368        assert_eq!(article_count, 2);
369        Ok(())
370    }
371
372    #[crate::ctb_test]
373    fn test_render_html_escaping_in_title() -> Result<()> {
374        let entry = Entry::new(
375            "escape-test",
376            "Title with <special> & \"chars\"",
377            "<p>Content</p>",
378            "2024-01-01T00:00:00Z",
379        );
380        let feed = Feed::new("Escape Test", vec![entry]);
381        let result = render(&feed)?;
382
383        assert!(result.contains("Title with &lt;special&gt; &amp; \"chars\""));
384        Ok(())
385    }
386
387    #[crate::ctb_test]
388    fn test_render_html_escaping_in_author() -> Result<()> {
389        let entry =
390            Entry::new("author-test", "Title", "", "2024-01-01T00:00:00Z")
391                .with_author("O'Brien & Sons <LLC>");
392
393        let feed = Feed::new("Author Escape Test", vec![entry]);
394        let result = render(&feed)?;
395
396        assert!(result.contains("O'Brien &amp; Sons &lt;LLC&gt;"));
397        Ok(())
398    }
399
400    #[crate::ctb_test]
401    fn test_render_url_escaping_in_permalink() -> Result<()> {
402        let entry = Entry::new("url-test", "Title", "", "2024-01-01T00:00:00Z")
403            .with_url_opt(Some(
404                "https://example.org/page?foo's=1&bar=2".into(),
405            ));
406
407        let feed = Feed::new("URL Escape Test", vec![entry]);
408        let result = render(&feed)?;
409
410        assert!(result.contains(
411            "href=\"https://example.org/page?foo&#x27;s=1&amp;bar=2\""
412        ));
413        Ok(())
414    }
415
416    #[crate::ctb_test]
417    fn test_hfeed_structure() -> Result<()> {
418        let feed = Feed::empty("Structure Test");
419        let result = render(&feed)?;
420
421        let Some(hfeed_start) = result.find("<div class=\"h-feed hfeed\">")
422        else {
423            bail!("missing h-feed container: {result}");
424        };
425        let Some(title_start) = result.find("<h1 class=\"p-name\">") else {
426            bail!("missing p-name title: {result}");
427        };
428        let Some(hfeed_end) = result.rfind("</div>") else {
429            bail!("missing closing div: {result}");
430        };
431
432        assert!(hfeed_start < title_start);
433        assert!(title_start < hfeed_end);
434        Ok(())
435    }
436
437    #[crate::ctb_test]
438    fn test_vcard_author_structure() -> Result<()> {
439        let entry =
440            Entry::new("vcard-test", "Title", "", "2024-01-01T00:00:00Z")
441                .with_author("Jane Doe");
442
443        let feed = Feed::new("vCard Test", vec![entry]);
444        let result = render(&feed)?;
445
446        assert!(result.contains("class=\"p-author author h-card vcard\""));
447        assert!(result.contains("class=\"p-name fn\""));
448        Ok(())
449    }
450}