markdown_composer/types/
image.rs

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