tinted_builder/template.rs
1mod base16;
2
3use crate::{error::TintedBuilderError, scheme::Scheme};
4
5/// A struct representing a template that can be rendered with the provided color scheme.
6///
7/// The `Template` struct holds the content of the template and the scheme used to render it. It
8/// provides methods to create a new template and render it into a `String` using the specified
9/// color scheme.
10pub struct Template {
11 content: String,
12 scheme: Scheme,
13}
14
15impl Template {
16 /// Creates a new `Template` instance.
17 ///
18 /// # Arguments
19 ///
20 /// * `content` - A `String` representing the content of the template.
21 /// * `scheme` - A `Scheme` enum that determines which color scheme to use when rendering the template.
22 ///
23 /// # Returns
24 ///
25 /// A new `Template` instance with the provided content and scheme.
26 pub fn new(content: String, scheme: Scheme) -> Template {
27 Template { content, scheme }
28 }
29
30 /// Renders the template into a `String` using the provided color scheme.
31 ///
32 /// This method applies the specified `Scheme` to the template content, converting placeholders
33 /// in the content to their corresponding values from the scheme context.
34 ///
35 /// # Errors
36 ///
37 /// Returns a `TintedBuilderError` if the rendering process fails. This could happen if the
38 /// content contains placeholders that cannot be resolved using the scheme context.
39 ///
40 /// # Examples
41 ///
42 /// ```
43 /// use tinted_builder::{Template, Scheme};
44 ///
45 /// let scheme_yaml = r#"
46 /// system: "base16"
47 /// name: "Some name"
48 /// author: "Some author"
49 /// variant: "dark"
50 /// palette:
51 /// base00: "241b26"
52 /// base01: "2f2a3f"
53 /// base02: "46354a"
54 /// base03: "6c3cb2"
55 /// base04: "7e5f83"
56 /// base05: "eed5d9"
57 /// base06: "d9c2c6"
58 /// base07: "e4ccd0"
59 /// base08: "877bb6"
60 /// base09: "de5b44"
61 /// base0A: "a84a73"
62 /// base0B: "c965bf"
63 /// base0C: "9c5fce"
64 /// base0D: "6a9eb5"
65 /// base0E: "78a38f"
66 /// base0F: "a3a079"
67 /// "#;
68 /// let template = Template::new(
69 /// r#"{{scheme-system}} scheme name is "{{scheme-name}}" and first color is #{{base00-hex}}"#.to_string(),
70 /// Scheme::Base16(serde_yaml::from_str(scheme_yaml).unwrap())
71 /// );
72 /// let rendered = template.render().unwrap();
73 ///
74 /// assert_eq!(
75 /// rendered,
76 /// r#"base16 scheme name is "Some name" and first color is #241b26"#
77 /// );
78 /// ```
79 pub fn render(&self) -> Result<String, TintedBuilderError> {
80 match self.scheme {
81 Scheme::Base16(ref scheme) | Scheme::Base24(ref scheme) => {
82 let ctx = base16::to_template_context(&scheme.clone());
83 let rendered = base16::render(&self.content, &ctx)?;
84
85 Ok(rendered)
86 }
87 }
88 }
89}