Skip to main content

typst_batch/process/
inputs.rs

1//! Shared `with_inputs` methods via trait.
2
3use typst::foundations::{Dict, IntoValue, Str};
4
5use crate::codegen::Inputs;
6
7/// Trait for types that accept `sys.inputs` configuration.
8///
9/// Provides `with_inputs`, `with_inputs_dict`, and `with_inputs_obj` methods.
10pub trait WithInputs: Sized {
11    /// Get mutable reference to the inputs field.
12    fn inputs_mut(&mut self) -> &mut Option<Dict>;
13
14    /// Set `sys.inputs` from key-value pairs.
15    ///
16    /// # Example
17    ///
18    /// ```ignore
19    /// let compiler = Compiler::new(root)
20    ///     .with_inputs([("key", "value"), ("draft", true)]);
21    /// ```
22    fn with_inputs<I, K, V>(mut self, inputs: I) -> Self
23    where
24        I: IntoIterator<Item = (K, V)>,
25        K: Into<Str>,
26        V: IntoValue,
27    {
28        let dict: Dict = inputs
29            .into_iter()
30            .map(|(k, v)| (k.into(), v.into_value()))
31            .collect();
32        *self.inputs_mut() = Some(dict);
33        self
34    }
35
36    /// Set `sys.inputs` from a pre-built Dict.
37    fn with_inputs_dict(mut self, inputs: Dict) -> Self {
38        *self.inputs_mut() = Some(inputs);
39        self
40    }
41
42    /// Set `sys.inputs` from an [`Inputs`] object.
43    ///
44    /// Use [`Inputs::from_json()`] or [`Inputs::from_json_with_content()`]
45    /// to create the inputs.
46    fn with_inputs_obj(mut self, inputs: Inputs) -> Self {
47        *self.inputs_mut() = Some(inputs.into_dict());
48        self
49    }
50}