markdown_composer/types/
link.rs

1use crate::traits::{AsFooter, MarkdownElement};
2#[cfg(feature = "serde")]
3use serde::{Deserialize, Serialize};
4use std::fmt;
5
6/// A markdown link.
7#[derive(Clone, Debug, Default)]
8#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
9pub struct Link {
10    /// The text of the link.
11    pub text: String,
12    /// The url of the link.
13    pub url: String,
14    /// Whether the `Link`'s url should be rendered as a footer.
15    pub footer: bool,
16    /// Whether the link should be inlined (no new line).
17    pub inlined: bool,
18}
19
20impl Link {
21    /// Creates a new default `Link`.
22    pub fn new() -> Self {
23        Self::default()
24    }
25
26    /// Creates a new `Link` with the given values.
27    pub fn from(
28        text: impl Into<String>,
29        url: impl Into<String>,
30        footer: bool,
31        inlined: bool,
32    ) -> Self {
33        Self {
34            text: text.into(),
35            url: url.into(),
36            footer,
37            inlined,
38        }
39    }
40}
41
42impl AsFooter for Link {
43    fn as_footer(&self) -> Box<dyn MarkdownElement> {
44        Box::new(format!("[{}]: {}", self.text, self.url))
45    }
46}
47
48impl fmt::Display for Link {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        let text = if self.footer {
51            format!("[{}][{}]", self.text, self.text)
52        } else {
53            format!("[{}]({})", self.text, self.url)
54        };
55
56        if self.inlined {
57            write!(f, "{}", text)
58        } else {
59            writeln!(f, "{}", text)
60        }
61    }
62}