| 1 | use std::collections::BTreeMap;
|
| 2 |
|
| 3 | use crate::dsl::{Document, Inline};
|
| 4 |
|
| 5 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 6 | pub enum ParamKind {
|
| 7 | /// `${Name}` — free text
|
| 8 | Text,
|
| 9 | /// `$[Name]` — boolean checkbox
|
| 10 | Bool,
|
| 11 | }
|
| 12 |
|
| 13 | #[derive(Debug, Clone, PartialEq, Eq)]
|
| 14 | pub struct ParamSpec {
|
| 15 | pub name: String,
|
| 16 | pub kind: ParamKind,
|
| 17 | }
|
| 18 |
|
| 19 | pub fn collect_parameters(document: &Document) -> Vec<ParamSpec> {
|
| 20 | let mut kinds: BTreeMap<String, ParamKind> = BTreeMap::new();
|
| 21 | for block in &document.blocks {
|
| 22 | collect_kinds_from_block(block, &mut kinds);
|
| 23 | }
|
| 24 | kinds
|
| 25 | .into_iter()
|
| 26 | .map(|(name, kind)| ParamSpec { name, kind })
|
| 27 | .collect()
|
| 28 | }
|
| 29 |
|
| 30 | pub fn collect_parameter_names(document: &Document) -> Vec<String> {
|
| 31 | collect_parameters(document)
|
| 32 | .into_iter()
|
| 33 | .map(|p| p.name)
|
| 34 | .collect()
|
| 35 | }
|
| 36 |
|
| 37 | pub fn collect_parameter_names_from_source(
|
| 38 | source: &str,
|
| 39 | ) -> Result<Vec<String>, crate::dsl::ParseError> {
|
| 40 | let doc = crate::dsl::parse(source)?;
|
| 41 | Ok(collect_parameter_names(&doc))
|
| 42 | }
|
| 43 |
|
| 44 | /// Parse a checkbox-parameter value from CLI / dialog (`true`/`false`, `1`/`0`, …).
|
| 45 | pub fn parse_bool_value(raw: &str) -> Option<bool> {
|
| 46 | match raw.trim().to_ascii_lowercase().as_str() {
|
| 47 | "true" | "1" | "yes" | "y" | "on" => Some(true),
|
| 48 | "false" | "0" | "no" | "n" | "off" | "" => Some(false),
|
| 49 | _ => None,
|
| 50 | }
|
| 51 | }
|
| 52 |
|
| 53 | pub fn substitute_inlines(
|
| 54 | inlines: &[Inline],
|
| 55 | values: &std::collections::HashMap<String, String>,
|
| 56 | ) -> Vec<Inline> {
|
| 57 | inlines
|
| 58 | .iter()
|
| 59 | .map(|inline| match inline {
|
| 60 | Inline::Text(t) => Inline::Text(t.clone()),
|
| 61 | Inline::Param(name) => Inline::Text(values.get(name).cloned().unwrap_or_default()),
|
| 62 | Inline::CheckboxParam(name) => {
|
| 63 | let checked = values
|
| 64 | .get(name)
|
| 65 | .and_then(|v| parse_bool_value(v))
|
| 66 | .unwrap_or(false);
|
| 67 | Inline::Checkbox { checked }
|
| 68 | }
|
| 69 | Inline::Checkbox { checked } => Inline::Checkbox {
|
| 70 | checked: *checked,
|
| 71 | },
|
| 72 | })
|
| 73 | .collect()
|
| 74 | }
|
| 75 |
|
| 76 | pub fn substitute_string(input: &str, values: &std::collections::HashMap<String, String>) -> String {
|
| 77 | substitute_params(input, values, |_| String::new())
|
| 78 | }
|
| 79 |
|
| 80 | /// Substitute `${Name}` using provided values, with sample data for unresolved parameters.
|
| 81 | pub fn substitute_for_preview(
|
| 82 | input: &str,
|
| 83 | values: &std::collections::HashMap<String, String>,
|
| 84 | ) -> String {
|
| 85 | substitute_params(input, values, preview_placeholder)
|
| 86 | }
|
| 87 |
|
| 88 | fn substitute_params(
|
| 89 | input: &str,
|
| 90 | values: &std::collections::HashMap<String, String>,
|
| 91 | fallback: impl Fn(&str) -> String,
|
| 92 | ) -> String {
|
| 93 | let mut out = String::new();
|
| 94 | let chars: Vec<char> = input.chars().collect();
|
| 95 | let mut i = 0;
|
| 96 | while i < chars.len() {
|
| 97 | if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
|
| 98 | let start = i + 2;
|
| 99 | let mut j = start;
|
| 100 | while j < chars.len() && chars[j] != '}' {
|
| 101 | j += 1;
|
| 102 | }
|
| 103 | if j < chars.len() {
|
| 104 | let name: String = chars[start..j].iter().collect();
|
| 105 | let value = values
|
| 106 | .get(&name)
|
| 107 | .filter(|v| !v.trim().is_empty())
|
| 108 | .cloned()
|
| 109 | .unwrap_or_else(|| fallback(&name));
|
| 110 | out.push_str(&value);
|
| 111 | i = j + 1;
|
| 112 | continue;
|
| 113 | }
|
| 114 | }
|
| 115 | out.push(chars[i]);
|
| 116 | i += 1;
|
| 117 | }
|
| 118 | out
|
| 119 | }
|
| 120 |
|
| 121 | fn preview_placeholder(name: &str) -> String {
|
| 122 | let lower = name.to_ascii_lowercase();
|
| 123 | if lower.contains("date") {
|
| 124 | return "20260115".into();
|
| 125 | }
|
| 126 | if lower.contains("total") || lower.contains("amount") || lower.contains("price") {
|
| 127 | return "99.99".into();
|
| 128 | }
|
| 129 | if lower.contains("ean") || lower.contains("upc") || lower.contains("barcode") {
|
| 130 | return "4006381333931".into();
|
| 131 | }
|
| 132 | if lower.contains("url") || lower.contains("link") || lower.contains("qr") {
|
| 133 | return "https://example.com/sample".into();
|
| 134 | }
|
| 135 | if lower.contains("name") || lower.contains("store") {
|
| 136 | return "Sample Store".into();
|
| 137 | }
|
| 138 | "1234567890".into()
|
| 139 | }
|
| 140 |
|
| 141 | /// Sample payload that encodes successfully for preview when user data is not valid.
|
| 142 | pub fn preview_barcode_sample(symbology: crate::dsl::BarcodeSymbology) -> &'static str {
|
| 143 | use crate::dsl::BarcodeSymbology;
|
| 144 | match symbology {
|
| 145 | BarcodeSymbology::Ean13 => "4006381333931",
|
| 146 | BarcodeSymbology::Ean8 => "96385074",
|
| 147 | BarcodeSymbology::UpcA => "036000291452",
|
| 148 | BarcodeSymbology::Itf => "123456",
|
| 149 | BarcodeSymbology::Codabar => "A40156A",
|
| 150 | _ => "TEST12345",
|
| 151 | }
|
| 152 | }
|
| 153 |
|
| 154 | pub fn substitute_document(
|
| 155 | document: &Document,
|
| 156 | values: &std::collections::HashMap<String, String>,
|
| 157 | ) -> Document {
|
| 158 | use crate::dsl::Block;
|
| 159 |
|
| 160 | let blocks = document
|
| 161 | .blocks
|
| 162 | .iter()
|
| 163 | .map(|block| match block {
|
| 164 | Block::Paragraph { align, inlines } => Block::Paragraph {
|
| 165 | align: *align,
|
| 166 | inlines: substitute_inlines(inlines, values),
|
| 167 | },
|
| 168 | Block::Heading { level, align, inlines } => Block::Heading {
|
| 169 | level: *level,
|
| 170 | align: *align,
|
| 171 | inlines: substitute_inlines(inlines, values),
|
| 172 | },
|
| 173 | Block::List { align, items } => Block::List {
|
| 174 | align: *align,
|
| 175 | items: items
|
| 176 | .iter()
|
| 177 | .map(|item| crate::dsl::ListItem {
|
| 178 | depth: item.depth,
|
| 179 | inlines: substitute_inlines(&item.inlines, values),
|
| 180 | })
|
| 181 | .collect(),
|
| 182 | },
|
| 183 | Block::Rule => Block::Rule,
|
| 184 | Block::Feed(n) => Block::Feed(*n),
|
| 185 | Block::Cut => Block::Cut,
|
| 186 | Block::Image { path, width, align } => Block::Image {
|
| 187 | path: substitute_string(path, values),
|
| 188 | width: *width,
|
| 189 | align: *align,
|
| 190 | },
|
| 191 | Block::Barcode {
|
| 192 | mode,
|
| 193 | symbology,
|
| 194 | data,
|
| 195 | height,
|
| 196 | align,
|
| 197 | show_text,
|
| 198 | } => Block::Barcode {
|
| 199 | mode: *mode,
|
| 200 | symbology: *symbology,
|
| 201 | data: substitute_string(data, values),
|
| 202 | height: *height,
|
| 203 | align: *align,
|
| 204 | show_text: *show_text,
|
| 205 | },
|
| 206 | Block::Qr {
|
| 207 | mode,
|
| 208 | data,
|
| 209 | size,
|
| 210 | ecc,
|
| 211 | version,
|
| 212 | align,
|
| 213 | } => Block::Qr {
|
| 214 | mode: *mode,
|
| 215 | data: substitute_string(data, values),
|
| 216 | size: *size,
|
| 217 | ecc: *ecc,
|
| 218 | version: *version,
|
| 219 | align: *align,
|
| 220 | },
|
| 221 | Block::Date { format, align } => Block::Date {
|
| 222 | format: format.clone(),
|
| 223 | align: *align,
|
| 224 | },
|
| 225 | Block::Time { format, align } => Block::Time {
|
| 226 | format: *format,
|
| 227 | align: *align,
|
| 228 | },
|
| 229 | })
|
| 230 | .collect();
|
| 231 | Document { blocks }
|
| 232 | }
|
| 233 |
|
| 234 | fn collect_kinds_from_block(
|
| 235 | block: &crate::dsl::Block,
|
| 236 | kinds: &mut BTreeMap<String, ParamKind>,
|
| 237 | ) {
|
| 238 | use crate::dsl::Block;
|
| 239 |
|
| 240 | match block {
|
| 241 | Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
|
| 242 | collect_kinds_from_inlines(inlines, kinds);
|
| 243 | }
|
| 244 | Block::List { items, .. } => {
|
| 245 | for item in items {
|
| 246 | collect_kinds_from_inlines(&item.inlines, kinds);
|
| 247 | }
|
| 248 | }
|
| 249 | Block::Image { path, .. } => collect_text_from_raw(path, kinds),
|
| 250 | Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_text_from_raw(data, kinds),
|
| 251 | Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
|
| 252 | }
|
| 253 | }
|
| 254 |
|
| 255 | fn collect_kinds_from_inlines(inlines: &[Inline], kinds: &mut BTreeMap<String, ParamKind>) {
|
| 256 | for inline in inlines {
|
| 257 | match inline {
|
| 258 | Inline::Param(name) => {
|
| 259 | kinds.insert(name.clone(), ParamKind::Text);
|
| 260 | }
|
| 261 | Inline::CheckboxParam(name) => {
|
| 262 | kinds.insert(name.clone(), ParamKind::Bool);
|
| 263 | }
|
| 264 | Inline::Text(_) | Inline::Checkbox { .. } => {}
|
| 265 | }
|
| 266 | }
|
| 267 | }
|
| 268 |
|
| 269 | fn collect_text_from_raw(text: &str, kinds: &mut BTreeMap<String, ParamKind>) {
|
| 270 | let chars: Vec<char> = text.chars().collect();
|
| 271 | let mut i = 0;
|
| 272 | while i < chars.len() {
|
| 273 | if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
|
| 274 | let start = i + 2;
|
| 275 | let mut j = start;
|
| 276 | while j < chars.len() && chars[j] != '}' {
|
| 277 | j += 1;
|
| 278 | }
|
| 279 | if j < chars.len() {
|
| 280 | let name: String = chars[start..j].iter().collect();
|
| 281 | kinds.insert(name, ParamKind::Text);
|
| 282 | i = j + 1;
|
| 283 | continue;
|
| 284 | }
|
| 285 | }
|
| 286 | i += 1;
|
| 287 | }
|
| 288 | }
|
| 289 |
|
| 290 | pub fn substitute_inlines_for_preview(
|
| 291 | inlines: &[Inline],
|
| 292 | values: &std::collections::HashMap<String, String>,
|
| 293 | ) -> String {
|
| 294 | let mut out = String::new();
|
| 295 | for inline in inlines {
|
| 296 | match inline {
|
| 297 | Inline::Text(t) => out.push_str(t),
|
| 298 | Inline::Param(name) => {
|
| 299 | out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
|
| 300 | }
|
| 301 | Inline::CheckboxParam(name) => {
|
| 302 | let checked = values
|
| 303 | .get(name)
|
| 304 | .and_then(|v| parse_bool_value(v))
|
| 305 | .unwrap_or(false);
|
| 306 | out.push_str(crate::dsl::checkbox_glyph(checked));
|
| 307 | }
|
| 308 | Inline::Checkbox { checked } => {
|
| 309 | out.push_str(crate::dsl::checkbox_glyph(*checked));
|
| 310 | }
|
| 311 | }
|
| 312 | }
|
| 313 | out
|
| 314 | }
|
| 315 |
|
| 316 | /// Validate that bool parameters have parseable values when present.
|
| 317 | pub fn invalid_bool_parameters(
|
| 318 | document: &Document,
|
| 319 | values: &std::collections::HashMap<String, String>,
|
| 320 | ) -> Vec<String> {
|
| 321 | collect_parameters(document)
|
| 322 | .into_iter()
|
| 323 | .filter(|p| p.kind == ParamKind::Bool)
|
| 324 | .filter_map(|p| {
|
| 325 | let Some(raw) = values.get(&p.name) else {
|
| 326 | return None;
|
| 327 | };
|
| 328 | if parse_bool_value(raw).is_some() {
|
| 329 | None
|
| 330 | } else {
|
| 331 | Some(p.name)
|
| 332 | }
|
| 333 | })
|
| 334 | .collect()
|
| 335 | }
|
| 336 |
|
| 337 | #[cfg(test)]
|
| 338 | mod tests {
|
| 339 | use super::*;
|
| 340 | use std::collections::HashMap;
|
| 341 |
|
| 342 | #[test]
|
| 343 | fn collects_unique_sorted_names() {
|
| 344 | let doc = crate::dsl::parse("${B}\n${A}\n${B}").unwrap();
|
| 345 | assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
|
| 346 | }
|
| 347 |
|
| 348 | #[test]
|
| 349 | fn collects_checkbox_params_as_bool() {
|
| 350 | let doc = crate::dsl::parse("$[Paid]\n${Name}").unwrap();
|
| 351 | let params = collect_parameters(&doc);
|
| 352 | assert_eq!(
|
| 353 | params,
|
| 354 | vec![
|
| 355 | ParamSpec {
|
| 356 | name: "Name".into(),
|
| 357 | kind: ParamKind::Text,
|
| 358 | },
|
| 359 | ParamSpec {
|
| 360 | name: "Paid".into(),
|
| 361 | kind: ParamKind::Bool,
|
| 362 | },
|
| 363 | ]
|
| 364 | );
|
| 365 | }
|
| 366 |
|
| 367 | #[test]
|
| 368 | fn preview_substitutes_inlines() {
|
| 369 | let doc = crate::dsl::parse("Hello ${Name}").unwrap();
|
| 370 | let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
|
| 371 | panic!();
|
| 372 | };
|
| 373 | let mut values = HashMap::new();
|
| 374 | values.insert("Name".into(), "Ada".into());
|
| 375 | assert_eq!(
|
| 376 | substitute_inlines_for_preview(inlines, &values),
|
| 377 | "Hello Ada"
|
| 378 | );
|
| 379 | }
|
| 380 |
|
| 381 | #[test]
|
| 382 | fn substitutes_checkbox_param_to_glyph() {
|
| 383 | let doc = crate::dsl::parse("$[Paid] done").unwrap();
|
| 384 | let mut values = HashMap::new();
|
| 385 | values.insert("Paid".into(), "true".into());
|
| 386 | let sub = substitute_document(&doc, &values);
|
| 387 | let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
|
| 388 | panic!();
|
| 389 | };
|
| 390 | assert!(matches!(
|
| 391 | &inlines[0],
|
| 392 | Inline::Checkbox { checked: true }
|
| 393 | ));
|
| 394 | assert_eq!(
|
| 395 | substitute_inlines_for_preview(
|
| 396 | &[Inline::CheckboxParam("Paid".into())],
|
| 397 | &values
|
| 398 | ),
|
| 399 | "[x]"
|
| 400 | );
|
| 401 | }
|
| 402 |
|
| 403 | #[test]
|
| 404 | fn preview_substitutes_placeholders_for_barcodes() {
|
| 405 | let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
|
| 406 | assert_eq!(text, "1234567890");
|
| 407 | }
|
| 408 |
|
| 409 | #[test]
|
| 410 | fn substitutes_all_occurrences() {
|
| 411 | let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap();
|
| 412 | let mut values = HashMap::new();
|
| 413 | values.insert("Name".into(), "Ada".into());
|
| 414 | let sub = substitute_document(&doc, &values);
|
| 415 | let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
|
| 416 | panic!();
|
| 417 | };
|
| 418 | assert!(matches!(
|
| 419 | inlines.as_slice(),
|
| 420 | [
|
| 421 | Inline::Text(a),
|
| 422 | Inline::Text(b),
|
| 423 | Inline::Text(c),
|
| 424 | Inline::Text(d),
|
| 425 | ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada"
|
| 426 | ));
|
| 427 | }
|
| 428 |
|
| 429 | #[test]
|
| 430 | fn parse_bool_value_accepts_common_forms() {
|
| 431 | assert_eq!(parse_bool_value("true"), Some(true));
|
| 432 | assert_eq!(parse_bool_value("FALSE"), Some(false));
|
| 433 | assert_eq!(parse_bool_value("1"), Some(true));
|
| 434 | assert_eq!(parse_bool_value("0"), Some(false));
|
| 435 | assert_eq!(parse_bool_value("maybe"), None);
|
| 436 | }
|
| 437 | }
|