Skip to main content

lichtung_plot/recipe/
template.rs

1//! Commented templates of the actual declaration modes.
2
3use std::fmt::Write;
4
5use crate::{plots::PlotKind, Result};
6
7use super::{
8    codec::invalid,
9    figure::FAMILIES,
10    plot_input::modes::{modes, Mode},
11    schema::{Example, Field},
12    Recipe, RECIPE_VERSION,
13};
14
15const DOCUMENT_TASKS: &[&str] = &[
16    "theme",
17    "canvas",
18    "canvas_layout",
19    "canvas_style",
20    "composition",
21    "placement",
22];
23
24fn family(name: &str) -> Option<PlotKind> {
25    FAMILIES
26        .iter()
27        .find_map(|(kind, declared)| (*declared == name).then_some(*kind))
28}
29
30fn input_mode(kind: PlotKind, requested: Option<&str>) -> Result<Mode> {
31    let available = modes(kind);
32    if let Some(requested) = requested {
33        if let Some(mode) = available.iter().find(|mode| mode.name == requested) {
34            return Ok(*mode);
35        }
36    } else if let [mode] = available.as_slice() {
37        return Ok(*mode);
38    }
39    let choices = available
40        .iter()
41        .map(|mode| mode.name)
42        .collect::<Vec<_>>()
43        .join(", ");
44    Err(invalid(match requested {
45        Some(mode) => format!(
46            "{} has no input mode {mode:?}; choose from {choices}",
47            kind.name()
48        ),
49        None => format!(
50            "{} requires an input mode; choose from {choices}",
51            kind.name()
52        ),
53    }))
54}
55
56fn unknown_task(task: &str) -> crate::Error {
57    let tasks = FAMILIES
58        .iter()
59        .map(|(_, name)| *name)
60        .chain(DOCUMENT_TASKS.iter().copied())
61        .collect::<Vec<_>>()
62        .join(", ");
63    invalid(format!(
64        "unknown template task {task:?}; choose from {tasks}, or <plot kind>_style"
65    ))
66}
67
68fn binding(text: &mut String, name: &str, prefix: &str) {
69    writeln!(
70        text,
71        "\n{prefix}[bindings.{name}]\n{prefix}# Supply the local source, or replace the entire binding in memory.\n{prefix}# path = \"{name}.csv\""
72    ).expect("write to String");
73}
74
75fn bindings(text: &mut String, mode: Mode) {
76    if mode.grouped {
77        binding(text, "data", "");
78    } else {
79        for field in mode.fields {
80            if field.needed && matches!(field.example, Some(Example::Group(_))) {
81                binding(text, field.name, "");
82            }
83        }
84    }
85}
86
87fn scalar_fields(text: &mut String, fields: &[Field], prefix: &str) -> Result<()> {
88    for field in fields {
89        let name = field.name;
90        match field.example {
91            Some(Example::Column(description)) => {
92                writeln!(
93                    text,
94                    "{prefix}# {} {description}; example: {name} = {name:?}.",
95                    if field.needed { "Required" } else { "Optional" }
96                )
97                .expect("write to String");
98                if field.needed && prefix.is_empty() {
99                    writeln!(text, "{name} = {{ key = {{}} }}").expect("write to String");
100                } else {
101                    let optional = if field.needed { "" } else { "# " };
102                    writeln!(text, "{prefix}{optional}{name} = {name:?}").expect("write to String");
103                }
104            }
105            Some(Example::Variables) => {
106                writeln!(text,"{prefix}# Select ordered numeric columns: {{ keys = [\"a\", \"b\"] }}, {{ indices = [0, 1] }}\n{prefix}# or discover the current numeric columns with {{ numeric_only = true }}.\n{prefix}{name} = {{ keys = [{{}}] }}")
107                    .expect("write to String");
108            }
109            Some(Example::Grid) => {
110                writeln!(text,"{prefix}# Supply a rectangular numeric array or table (e.g. a local NPY file).\n{prefix}{name} = {{}}")
111                    .expect("write to String");
112            }
113            Some(Example::Literal(value)) => {
114                if field.needed {
115                    writeln!(text,"{prefix}# Required declaration; edit this example value.\n{prefix}{name} = {value}").expect("write to String");
116                } else {
117                    writeln!(text, "{prefix}# {name} = {value}").expect("write to String");
118                }
119            }
120            None if field.needed => {
121                return Err(invalid(format!(
122                    "required template field {name:?} has no example"
123                )));
124            }
125            Some(Example::Group(_)) | None => {}
126        }
127    }
128    Ok(())
129}
130
131fn plot(text: &mut String, owner: &str, kind: PlotKind, mode: Mode) -> Result<()> {
132    writeln!(
133        text,
134        "\n[{owner}]\nkind = {:?}\n# title = \"Title\"\n# theme = {{ preset = \"publication\" }}",
135        kind.name()
136    )
137    .expect("write to String");
138    let input = format!("{owner}.input.{}", mode.name);
139    writeln!(text, "\n[{input}]").expect("write to String");
140    if mode.grouped {
141        text.push_str("binding = \"data\"\n");
142    }
143    scalar_fields(text, mode.fields, "")?;
144    for field in mode.fields {
145        if let Some(Example::Group(fields)) = field.example {
146            let prefix = if field.needed { "" } else { "# " };
147            if !field.needed {
148                writeln!(text, "\n# Optional independently supplied {}:", field.name)
149                    .expect("write to String");
150                binding(text, field.name, prefix);
151            }
152            writeln!(
153                text,
154                "\n{prefix}[{input}.{}]\n{prefix}binding = {:?}",
155                field.name, field.name
156            )
157            .expect("write to String");
158            scalar_fields(text, fields, prefix)?;
159        }
160    }
161    Ok(())
162}
163
164fn output(text: &mut String) {
165    text.push_str("\n[output]\n# Select an action and its destination, or supply them at execution time.\n# action = \"image\"\n# image = \"figure.svg\"\n# layout = \"layout.json\"\n");
166}
167
168fn style(text: &mut String, kind: Option<PlotKind>) {
169    text.push_str("\n# Apply this style to a compatible existing native owner.\n# Omitted visual requests use the native default appearance.\n");
170    if let Some(kind) = kind {
171        writeln!(text, "[plot]\nscope = \"style\"\nkind = {:?}", kind.name())
172            .expect("write to String");
173    } else {
174        text.push_str("[canvas]\nscope = \"style\"\n");
175    }
176    text.push_str("theme = { preset = \"publication\" }\n");
177}
178
179fn document_task(text: &mut String, task: &str) -> Result<()> {
180    match task {
181        "theme" => text.push_str("\n[theme]\n# Select a preset and override its actual theme fields as needed.\npreset = \"publication\"\n"),
182        "canvas" => {
183            let mode = input_mode(PlotKind::Line,Some("xy"))?;
184            bindings(text,mode);
185            text.push_str("\n[canvas]\nrows = 1\ncolumns = 2\n\n[[canvas.panels]]\nname = \"overview\"\nrow = 0\ncolumn = 0\n");
186            plot(text,"canvas.panels.plot",PlotKind::Line,mode)?;
187            text.push_str("\n[[canvas.panels]]\nname = \"notes\"\nrow = 0\ncolumn = 1\ntext = { title = \"Notes\", body = \"Describe the figure here.\" }\n");
188            output(text);
189        }
190        "canvas_layout" => text.push_str("\n[canvas]\nscope = \"layout\"\nrows = 1\ncolumns = 2\n# Fill the declared footprints through the Canvas API by name or anchor.\n\n[[canvas.panels]]\nname = \"overview\"\nrow = 0\ncolumn = 0\n\n[[canvas.panels]]\nname = \"detail\"\nrow = 0\ncolumn = 1\n"),
191        "canvas_style" => style(text,None),
192        "composition" | "placement" => {
193            if task == "composition" {
194                text.push_str("\n[base]\n# Existing local SVG or PNG to use as the base.\nasset = \"base.svg\"\n");
195            }
196            text.push_str("\n[[placements]]\n# Supply the local overlay; the box is left, top, width, height in CSS pixels.\nasset = \"overlay.svg\"\nbox = [40, 20, 180, 120]\nfit = \"contain\"\n# position = \"center\"\n");
197            if task == "composition" {
198                text.push_str("\n[composition]\nexpand_canvas = false\n");
199                output(text);
200            }
201        }
202        _ => return Err(unknown_task(task)),
203    }
204    Ok(())
205}
206
207impl Recipe {
208    /// The current template tasks, including visual and document scopes.
209    pub fn template_tasks() -> Vec<String> {
210        FAMILIES
211            .iter()
212            .map(|(_, name)| (*name).to_owned())
213            .chain(DOCUMENT_TASKS.iter().map(|name| (*name).to_owned()))
214            .chain(FAMILIES.iter().map(|(_, name)| format!("{name}_style")))
215            .collect()
216    }
217
218    /// Input modes of this task. An empty list indicates a document or visual
219    /// task that does not take an input mode.
220    pub fn template_modes(task: &str) -> Result<Vec<&'static str>> {
221        if let Some(kind) = family(task) {
222            Ok(modes(kind).iter().map(|mode| mode.name).collect())
223        } else if DOCUMENT_TASKS.contains(&task)
224            || task.strip_suffix("_style").and_then(family).is_some()
225        {
226            Ok(Vec::new())
227        } else {
228            Err(unknown_task(task))
229        }
230    }
231
232    /// Generate commented TOML for a current native task. If the task has
233    /// distinct input modes, choose one with [`Self::template_for`].
234    pub fn template(task: &str) -> Result<String> {
235        Self::template_inner(task, None)
236    }
237
238    /// Generate a template for the explicitly selected native input mode.
239    pub fn template_for(task: &str, mode: &str) -> Result<String> {
240        Self::template_inner(task, Some(mode))
241    }
242
243    fn template_inner(task: &str, requested: Option<&str>) -> Result<String> {
244        let mut text = format!(
245            "# Lichtung Plot native Recipe\n# Schema: specs/recipe-{RECIPE_VERSION}.schema.json\n# Complete the marked inputs before checking or executing.\nrecipe_version = {RECIPE_VERSION:?}\n"
246        );
247        if let Some(kind) = family(task) {
248            let mode = input_mode(kind, requested)?;
249            bindings(&mut text, mode);
250            plot(&mut text, "plot", kind, mode)?;
251            output(&mut text);
252        } else {
253            let style_kind = task.strip_suffix("_style").and_then(family);
254            if style_kind.is_none() && !DOCUMENT_TASKS.contains(&task) {
255                return Err(unknown_task(task));
256            }
257            if requested.is_some() {
258                return Err(invalid(format!("template task {task:?} has no input mode")));
259            }
260            if let Some(kind) = style_kind {
261                style(&mut text, Some(kind));
262            } else {
263                document_task(&mut text, task)?;
264            }
265        }
266        // Templates are authored declarations too. Check their structure
267        // through the native reader; never open a suggested file or asset.
268        let document = text
269            .parse::<toml_edit::DocumentMut>()
270            .map_err(|error| invalid(format!("invalid template declaration: {error}")))?;
271        Self::inventory(&document)?;
272        Ok(text)
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279    use crate::recipe::RecipeFigure;
280
281    #[test]
282    fn every_actual_template_mode_is_readable_without_supplied_data() {
283        let directory = tempfile::tempdir().unwrap();
284        let path = directory.path().join("template.toml");
285        for &(kind, name) in FAMILIES {
286            let available = modes(kind);
287            assert_eq!(Recipe::template(name).is_ok(), available.len() == 1);
288            for mode in available {
289                let template = Recipe::template_for(name, mode.name).unwrap();
290                assert!(template.contains('#'));
291                std::fs::write(&path, template).unwrap();
292                let recipe = Recipe::read(&path).unwrap();
293                assert!(!recipe.bindings().is_empty(), "{name} {}", mode.name);
294                assert!(recipe.check().is_err(), "{name} {}", mode.name);
295            }
296            let style = Recipe::template(&format!("{name}_style")).unwrap();
297            std::fs::write(&path, style).unwrap();
298            Recipe::read(&path).unwrap().check().unwrap();
299        }
300        for &task in DOCUMENT_TASKS {
301            let template = Recipe::template(task).unwrap();
302            std::fs::write(&path, template).unwrap();
303            Recipe::read(&path).unwrap();
304            assert!(Recipe::template_for(task, "xy").is_err());
305        }
306        std::fs::write(&path, Recipe::template("canvas_layout").unwrap()).unwrap();
307        let RecipeFigure::Canvas(canvas) = Recipe::read(&path).unwrap().build().unwrap() else {
308            panic!("fillable Canvas");
309        };
310        assert_eq!(canvas.slots().len(), 2);
311        assert!(Recipe::template("future_family").is_err());
312        assert!(Recipe::template_for("line", "not_an_input").is_err());
313    }
314}