BlueGit

timfa posprint

Files

posprint / src / params.rs

params.rs

params.rs 9.8 KiB Download Raw
1use std::collections::BTreeSet;
2
3use crate::dsl::{Document, Inline};
4
5pub fn collect_parameter_names(document: &Document) -> Vec<String> {
6 let mut names = BTreeSet::new();
7 for block in &document.blocks {
8 collect_from_block(block, &mut names);
9 }
10 names.into_iter().collect()
11}
12
13pub fn collect_parameter_names_from_source(source: &str) -> Result<Vec<String>, crate::dsl::ParseError> {
14 let doc = crate::dsl::parse(source)?;
15 Ok(collect_parameter_names(&doc))
16}
17
18pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap<String, String>) -> Vec<Inline> {
19 inlines
20 .iter()
21 .map(|inline| match inline {
22 Inline::Text(t) => Inline::Text(t.clone()),
23 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
24 Inline::Checkbox { checked } => Inline::Checkbox {
25 checked: *checked,
26 },
27 })
28 .collect()
29}
30
31pub fn substitute_string(input: &str, values: &std::collections::HashMap<String, String>) -> String {
32 substitute_params(input, values, |_| String::new())
33}
34
35/// Substitute `${Name}` using provided values, with sample data for unresolved parameters.
36pub fn substitute_for_preview(
37 input: &str,
38 values: &std::collections::HashMap<String, String>,
39) -> String {
40 substitute_params(input, values, preview_placeholder)
41}
42
43fn substitute_params(
44 input: &str,
45 values: &std::collections::HashMap<String, String>,
46 fallback: impl Fn(&str) -> String,
47) -> String {
48 let mut out = String::new();
49 let chars: Vec<char> = input.chars().collect();
50 let mut i = 0;
51 while i < chars.len() {
52 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
53 let start = i + 2;
54 let mut j = start;
55 while j < chars.len() && chars[j] != '}' {
56 j += 1;
57 }
58 if j < chars.len() {
59 let name: String = chars[start..j].iter().collect();
60 let value = values
61 .get(&name)
62 .filter(|v| !v.trim().is_empty())
63 .cloned()
64 .unwrap_or_else(|| fallback(&name));
65 out.push_str(&value);
66 i = j + 1;
67 continue;
68 }
69 }
70 out.push(chars[i]);
71 i += 1;
72 }
73 out
74}
75
76fn preview_placeholder(name: &str) -> String {
77 let lower = name.to_ascii_lowercase();
78 if lower.contains("date") {
79 return "20260115".into();
80 }
81 if lower.contains("total") || lower.contains("amount") || lower.contains("price") {
82 return "99.99".into();
83 }
84 if lower.contains("ean") || lower.contains("upc") || lower.contains("barcode") {
85 return "4006381333931".into();
86 }
87 if lower.contains("url") || lower.contains("link") || lower.contains("qr") {
88 return "https://example.com/sample".into();
89 }
90 if lower.contains("name") || lower.contains("store") {
91 return "Sample Store".into();
92 }
93 "1234567890".into()
94}
95
96/// Sample payload that encodes successfully for preview when user data is not valid.
97pub fn preview_barcode_sample(symbology: crate::dsl::BarcodeSymbology) -> &'static str {
98 use crate::dsl::BarcodeSymbology;
99 match symbology {
100 BarcodeSymbology::Ean13 => "4006381333931",
101 BarcodeSymbology::Ean8 => "96385074",
102 BarcodeSymbology::UpcA => "036000291452",
103 BarcodeSymbology::Itf => "123456",
104 BarcodeSymbology::Codabar => "A40156A",
105 _ => "TEST12345",
106 }
107}
108
109pub fn substitute_document(
110 document: &Document,
111 values: &std::collections::HashMap<String, String>,
112) -> Document {
113 use crate::dsl::Block;
114
115 let blocks = document
116 .blocks
117 .iter()
118 .map(|block| match block {
119 Block::Paragraph { align, inlines } => Block::Paragraph {
120 align: *align,
121 inlines: substitute_inlines(inlines, values),
122 },
123 Block::Heading { level, align, inlines } => Block::Heading {
124 level: *level,
125 align: *align,
126 inlines: substitute_inlines(inlines, values),
127 },
128 Block::List { align, items } => Block::List {
129 align: *align,
130 items: items
131 .iter()
132 .map(|item| substitute_inlines(item, values))
133 .collect(),
134 },
135 Block::Rule => Block::Rule,
136 Block::Feed(n) => Block::Feed(*n),
137 Block::Cut => Block::Cut,
138 Block::Image { path, width, align } => Block::Image {
139 path: substitute_string(path, values),
140 width: *width,
141 align: *align,
142 },
143 Block::Barcode {
144 mode,
145 symbology,
146 data,
147 height,
148 align,
149 show_text,
150 } => Block::Barcode {
151 mode: *mode,
152 symbology: *symbology,
153 data: substitute_string(data, values),
154 height: *height,
155 align: *align,
156 show_text: *show_text,
157 },
158 Block::Qr {
159 mode,
160 data,
161 size,
162 ecc,
163 version,
164 align,
165 } => Block::Qr {
166 mode: *mode,
167 data: substitute_string(data, values),
168 size: *size,
169 ecc: *ecc,
170 version: *version,
171 align: *align,
172 },
173 Block::Date { format, align } => Block::Date {
174 format: format.clone(),
175 align: *align,
176 },
177 Block::Time { format, align } => Block::Time {
178 format: *format,
179 align: *align,
180 },
181 })
182 .collect();
183 Document { blocks }
184}
185
186fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {
187 use crate::dsl::Block;
188
189 match block {
190 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
191 collect_from_inlines(inlines, names);
192 }
193 Block::List { items, .. } => {
194 for item in items {
195 collect_from_inlines(item, names);
196 }
197 }
198 Block::Image { path, .. } => collect_from_raw(path, names),
199 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
200 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
201 }
202}
203
204fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
205 for inline in inlines {
206 match inline {
207 Inline::Param(name) => {
208 names.insert(name.clone());
209 }
210 Inline::Text(_) | Inline::Checkbox { .. } => {}
211 }
212 }
213}
214
215fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {
216 let chars: Vec<char> = text.chars().collect();
217 let mut i = 0;
218 while i < chars.len() {
219 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
220 let start = i + 2;
221 let mut j = start;
222 while j < chars.len() && chars[j] != '}' {
223 j += 1;
224 }
225 if j < chars.len() {
226 let name: String = chars[start..j].iter().collect();
227 names.insert(name);
228 i = j + 1;
229 continue;
230 }
231 }
232 i += 1;
233 }
234}
235
236pub fn substitute_inlines_for_preview(
237 inlines: &[Inline],
238 values: &std::collections::HashMap<String, String>,
239) -> String {
240 let mut out = String::new();
241 for inline in inlines {
242 match inline {
243 Inline::Text(t) => out.push_str(t),
244 Inline::Param(name) => {
245 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
246 }
247 Inline::Checkbox { checked } => {
248 out.push_str(crate::dsl::checkbox_glyph(*checked));
249 }
250 }
251 }
252 out
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258 use std::collections::HashMap;
259
260 #[test]
261 fn collects_unique_sorted_names() {
262 let doc = crate::dsl::parse("${B}\n${A}\n${B}").unwrap();
263 assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
264 }
265
266 #[test]
267 fn preview_substitutes_inlines() {
268 let doc = crate::dsl::parse("Hello ${Name}").unwrap();
269 let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
270 panic!();
271 };
272 let mut values = HashMap::new();
273 values.insert("Name".into(), "Ada".into());
274 assert_eq!(
275 substitute_inlines_for_preview(inlines, &values),
276 "Hello Ada"
277 );
278 }
279
280 #[test]
281 fn preview_substitutes_placeholders_for_barcodes() {
282 let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
283 assert_eq!(text, "1234567890");
284 }
285
286 #[test]
287 fn substitutes_all_occurrences() {
288 let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap();
289 let mut values = HashMap::new();
290 values.insert("Name".into(), "Ada".into());
291 let sub = substitute_document(&doc, &values);
292 let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
293 panic!();
294 };
295 assert!(matches!(
296 inlines.as_slice(),
297 [
298 Inline::Text(a),
299 Inline::Text(b),
300 Inline::Text(c),
301 Inline::Text(d),
302 ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada"
303 ));
304 }
305}