BlueGit

timfa posprint

Files

posprint / src / params.rs

params.rs

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