use std::collections::BTreeSet; use crate::dsl::{Document, Inline}; pub fn collect_parameter_names(document: &Document) -> Vec { let mut names = BTreeSet::new(); for block in &document.blocks { collect_from_block(block, &mut names); } names.into_iter().collect() } pub fn collect_parameter_names_from_source(source: &str) -> Result, crate::dsl::ParseError> { let doc = crate::dsl::parse(source)?; Ok(collect_parameter_names(&doc)) } pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap) -> Vec { inlines .iter() .map(|inline| match inline { Inline::Text(t) => Inline::Text(t.clone()), Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()), }) .collect() } pub fn substitute_string(input: &str, values: &std::collections::HashMap) -> String { substitute_params(input, values, |_| String::new()) } /// Substitute `${Name}` using provided values, with sample data for unresolved parameters. pub fn substitute_for_preview( input: &str, values: &std::collections::HashMap, ) -> String { substitute_params(input, values, preview_placeholder) } fn substitute_params( input: &str, values: &std::collections::HashMap, fallback: impl Fn(&str) -> String, ) -> String { let mut out = String::new(); let chars: Vec = input.chars().collect(); let mut i = 0; while i < chars.len() { if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' { let start = i + 2; let mut j = start; while j < chars.len() && chars[j] != '}' { j += 1; } if j < chars.len() { let name: String = chars[start..j].iter().collect(); let value = values .get(&name) .filter(|v| !v.trim().is_empty()) .cloned() .unwrap_or_else(|| fallback(&name)); out.push_str(&value); i = j + 1; continue; } } out.push(chars[i]); i += 1; } out } fn preview_placeholder(name: &str) -> String { let lower = name.to_ascii_lowercase(); if lower.contains("date") { return "20260115".into(); } if lower.contains("total") || lower.contains("amount") || lower.contains("price") { return "99.99".into(); } if lower.contains("ean") || lower.contains("upc") || lower.contains("barcode") { return "4006381333931".into(); } if lower.contains("url") || lower.contains("link") || lower.contains("qr") { return "https://example.com/sample".into(); } if lower.contains("name") || lower.contains("store") { return "Sample Store".into(); } "1234567890".into() } /// Sample payload that encodes successfully for preview when user data is not valid. pub fn preview_barcode_sample(symbology: crate::dsl::BarcodeSymbology) -> &'static str { use crate::dsl::BarcodeSymbology; match symbology { BarcodeSymbology::Ean13 => "4006381333931", BarcodeSymbology::Ean8 => "96385074", BarcodeSymbology::UpcA => "036000291452", BarcodeSymbology::Itf => "123456", BarcodeSymbology::Codabar => "A40156A", _ => "TEST12345", } } pub fn substitute_document( document: &Document, values: &std::collections::HashMap, ) -> Document { use crate::dsl::Block; let blocks = document .blocks .iter() .map(|block| match block { Block::Paragraph { align, inlines } => Block::Paragraph { align: *align, inlines: substitute_inlines(inlines, values), }, Block::Heading { level, align, inlines } => Block::Heading { level: *level, align: *align, inlines: substitute_inlines(inlines, values), }, Block::List { align, items } => Block::List { align: *align, items: items .iter() .map(|item| substitute_inlines(item, values)) .collect(), }, Block::Rule => Block::Rule, Block::Feed(n) => Block::Feed(*n), Block::Cut => Block::Cut, Block::Image { path, width, align } => Block::Image { path: substitute_string(path, values), width: *width, align: *align, }, Block::Barcode { mode, symbology, data, height, align, show_text, } => Block::Barcode { mode: *mode, symbology: *symbology, data: substitute_string(data, values), height: *height, align: *align, show_text: *show_text, }, Block::Qr { mode, data, size, ecc, version, align, } => Block::Qr { mode: *mode, data: substitute_string(data, values), size: *size, ecc: *ecc, version: *version, align: *align, }, Block::Date { format, align } => Block::Date { format: format.clone(), align: *align, }, Block::Time { format, align } => Block::Time { format: *format, align: *align, }, }) .collect(); Document { blocks } } fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet) { use crate::dsl::Block; match block { Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => { collect_from_inlines(inlines, names); } Block::List { items, .. } => { for item in items { collect_from_inlines(item, names); } } Block::Image { path, .. } => collect_from_raw(path, names), Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names), Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {} } } fn collect_from_inlines(inlines: &[Inline], names: &mut BTreeSet) { for inline in inlines { match inline { Inline::Param(name) => { names.insert(name.clone()); } Inline::Text(_) => {} } } } fn collect_from_raw(text: &str, names: &mut BTreeSet) { let chars: Vec = text.chars().collect(); let mut i = 0; while i < chars.len() { if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' { let start = i + 2; let mut j = start; while j < chars.len() && chars[j] != '}' { j += 1; } if j < chars.len() { let name: String = chars[start..j].iter().collect(); names.insert(name); i = j + 1; continue; } } i += 1; } } pub fn substitute_inlines_for_preview( inlines: &[Inline], values: &std::collections::HashMap, ) -> String { let mut out = String::new(); for inline in inlines { match inline { Inline::Text(t) => out.push_str(t), Inline::Param(name) => { out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values)); } } } out } #[cfg(test)] mod tests { use super::*; use std::collections::HashMap; #[test] fn collects_unique_sorted_names() { let doc = crate::dsl::parse("${B}\n${A}\n${B}").unwrap(); assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]); } #[test] fn preview_substitutes_inlines() { let doc = crate::dsl::parse("Hello ${Name}").unwrap(); let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else { panic!(); }; let mut values = HashMap::new(); values.insert("Name".into(), "Ada".into()); assert_eq!( substitute_inlines_for_preview(inlines, &values), "Hello Ada" ); } #[test] fn preview_substitutes_placeholders_for_barcodes() { let text = substitute_for_preview("${DocumentNumber}", &HashMap::new()); assert_eq!(text, "1234567890"); } #[test] fn substitutes_all_occurrences() { let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap(); let mut values = HashMap::new(); values.insert("Name".into(), "Ada".into()); let sub = substitute_document(&doc, &values); let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else { panic!(); }; assert!(matches!( inlines.as_slice(), [ Inline::Text(a), Inline::Text(b), Inline::Text(c), Inline::Text(d), ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada" )); } }