BlueGit

timfa posprint

Files

posprint / src / params.rs

params.rs

fixes
timfa Tim Falken · pushed by timfa · 4 months ago
4ab2186f History
params.rs 9.7 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::Code(t) => Inline::Code(t.clone()),
24 Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
25 Inline::Bold(inner) => Inline::Bold(substitute_inlines(inner, values)),
26 Inline::Italic(inner) => Inline::Italic(substitute_inlines(inner, values)),
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::Rule => Block::Rule,
129 Block::Feed(n) => Block::Feed(*n),
130 Block::Cut => Block::Cut,
131 Block::Image { path, width, align } => Block::Image {
132 path: substitute_string(path, values),
133 width: *width,
134 align: *align,
135 },
136 Block::Barcode {
137 mode,
138 symbology,
139 data,
140 height,
141 align,
142 show_text,
143 } => Block::Barcode {
144 mode: *mode,
145 symbology: *symbology,
146 data: substitute_string(data, values),
147 height: *height,
148 align: *align,
149 show_text: *show_text,
150 },
151 Block::Qr {
152 mode,
153 data,
154 size,
155 ecc,
156 version,
157 align,
158 } => Block::Qr {
159 mode: *mode,
160 data: substitute_string(data, values),
161 size: *size,
162 ecc: *ecc,
163 version: *version,
164 align: *align,
165 },
166 Block::Date { format, align } => Block::Date {
167 format: format.clone(),
168 align: *align,
169 },
170 Block::Time { format, align } => Block::Time {
171 format: *format,
172 align: *align,
173 },
174 })
175 .collect();
176 Document { blocks }
177}
178
179fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {
180 use crate::dsl::Block;
181
182 match block {
183 Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
184 collect_from_inlines(inlines, names);
185 }
186 Block::Image { path, .. } => collect_from_raw(path, names),
187 Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
188 Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
189 }
190}
191
192fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet<String>) {
193 for inline in inlines {
194 match inline {
195 Inline::Param(name) => {
196 names.insert(name.clone());
197 }
198 Inline::Bold(inner) | Inline::Italic(inner) => collect_from_inlines(inner, names),
199 Inline::Text(_) | Inline::Code(_) => {}
200 }
201 }
202}
203
204fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {
205 let chars: Vec<char> = text.chars().collect();
206 let mut i = 0;
207 while i < chars.len() {
208 if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
209 let start = i + 2;
210 let mut j = start;
211 while j < chars.len() && chars[j] != '}' {
212 j += 1;
213 }
214 if j < chars.len() {
215 let name: String = chars[start..j].iter().collect();
216 names.insert(name);
217 i = j + 1;
218 continue;
219 }
220 }
221 i += 1;
222 }
223}
224
225pub fn substitute_inlines_for_preview(
226 inlines: &[Inline],
227 values: &std::collections::HashMap<String, String>,
228) -> String {
229 let mut out = String::new();
230 for inline in inlines {
231 match inline {
232 Inline::Text(t) => out.push_str(t),
233 Inline::Code(t) => out.push_str(t),
234 Inline::Param(name) => {
235 out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
236 }
237 Inline::Bold(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
238 Inline::Italic(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
239 }
240 }
241 out
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247 use std::collections::HashMap;
248
249 #[test]
250 fn collects_unique_sorted_names() {
251 let doc = crate::dsl::parse("${B}\n${A}\n${B}").unwrap();
252 assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
253 }
254
255 #[test]
256 fn preview_substitutes_inlines() {
257 let doc = crate::dsl::parse("Hello ${Name}").unwrap();
258 let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
259 panic!();
260 };
261 let mut values = HashMap::new();
262 values.insert("Name".into(), "Ada".into());
263 assert_eq!(
264 substitute_inlines_for_preview(inlines, &values),
265 "Hello Ada"
266 );
267 }
268
269 #[test]
270 fn preview_substitutes_placeholders_for_barcodes() {
271 let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
272 assert_eq!(text, "1234567890");
273 }
274
275 #[test]
276 fn substitutes_all_occurrences() {
277 let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap();
278 let mut values = HashMap::new();
279 values.insert("Name".into(), "Ada".into());
280 let sub = substitute_document(&doc, &values);
281 let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
282 panic!();
283 };
284 assert!(matches!(
285 inlines.as_slice(),
286 [
287 Inline::Text(a),
288 Inline::Text(b),
289 Inline::Text(c),
290 Inline::Text(d),
291 ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada"
292 ));
293 }
294}