| 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::AlignedRow { parts } => Block::AlignedRow {
|
| 169 | parts: parts
|
| 170 | .iter()
|
| 171 | .map(|(align, inlines)| (*align, substitute_inlines(inlines, values)))
|
| 172 | .collect(),
|
| 173 | },
|
| 174 | Block::Heading { level, align, inlines } => Block::Heading {
|
| 175 | level: *level,
|
| 176 | align: *align,
|
| 177 | inlines: substitute_inlines(inlines, values),
|
| 178 | },
|
| 179 | Block::List { align, items } => Block::List {
|
| 180 | align: *align,
|
| 181 | items: items
|
| 182 | .iter()
|
| 183 | .map(|item| crate::dsl::ListItem {
|
| 184 | depth: item.depth,
|
| 185 | inlines: substitute_inlines(&item.inlines, values),
|
| 186 | })
|
| 187 | .collect(),
|
| 188 | },
|
| 189 | Block::Rule => Block::Rule,
|
| 190 | Block::Feed(n) => Block::Feed(*n),
|
| 191 | Block::Cut => Block::Cut,
|
| 192 | Block::Image { path, width, align } => Block::Image {
|
| 193 | path: substitute_string(path, values),
|
| 194 | width: *width,
|
| 195 | align: *align,
|
| 196 | },
|
| 197 | Block::Barcode {
|
| 198 | mode,
|
| 199 | symbology,
|
| 200 | data,
|
| 201 | height,
|
| 202 | align,
|
| 203 | show_text,
|
| 204 | } => Block::Barcode {
|
| 205 | mode: *mode,
|
| 206 | symbology: *symbology,
|
| 207 | data: substitute_string(data, values),
|
| 208 | height: *height,
|
| 209 | align: *align,
|
| 210 | show_text: *show_text,
|
| 211 | },
|
| 212 | Block::Qr {
|
| 213 | mode,
|
| 214 | data,
|
| 215 | size,
|
| 216 | ecc,
|
| 217 | version,
|
| 218 | align,
|
| 219 | } => Block::Qr {
|
| 220 | mode: *mode,
|
| 221 | data: substitute_string(data, values),
|
| 222 | size: *size,
|
| 223 | ecc: *ecc,
|
| 224 | version: *version,
|
| 225 | align: *align,
|
| 226 | },
|
| 227 | Block::Date { format, align } => Block::Date {
|
| 228 | format: format.clone(),
|
| 229 | align: *align,
|
| 230 | },
|
| 231 | Block::Time { format, align } => Block::Time {
|
| 232 | format: *format,
|
| 233 | align: *align,
|
| 234 | },
|
| 235 | })
|
| 236 | .collect();
|
| 237 | Document { blocks }
|
| 238 | }
|
| 239 |
|
| 240 | fn collect_kinds_from_block(
|
| 241 | block: &crate::dsl::Block,
|
| 242 | kinds: &mut BTreeMap<String, ParamKind>,
|
| 243 | ) {
|
| 244 | use crate::dsl::Block;
|
| 245 |
|
| 246 | match block {
|
| 247 | Block::Paragraph { inlines, .. } | Block::Heading { inlines, .. } => {
|
| 248 | collect_kinds_from_inlines(inlines, kinds);
|
| 249 | }
|
| 250 | Block::AlignedRow { parts } => {
|
| 251 | for (_, inlines) in parts {
|
| 252 | collect_kinds_from_inlines(inlines, kinds);
|
| 253 | }
|
| 254 | }
|
| 255 | Block::List { items, .. } => {
|
| 256 | for item in items {
|
| 257 | collect_kinds_from_inlines(&item.inlines, kinds);
|
| 258 | }
|
| 259 | }
|
| 260 | Block::Image { path, .. } => collect_text_from_raw(path, kinds),
|
| 261 | Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_text_from_raw(data, kinds),
|
| 262 | Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
|
| 263 | }
|
| 264 | }
|
| 265 |
|
| 266 | fn collect_kinds_from_inlines(inlines: &[Inline], kinds: &mut BTreeMap<String, ParamKind>) {
|
| 267 | for inline in inlines {
|
| 268 | match inline {
|
| 269 | Inline::Param(name) => {
|
| 270 | kinds.insert(name.clone(), ParamKind::Text);
|
| 271 | }
|
| 272 | Inline::CheckboxParam(name) => {
|
| 273 | kinds.insert(name.clone(), ParamKind::Bool);
|
| 274 | }
|
| 275 | Inline::Text(_) | Inline::Checkbox { .. } => {}
|
| 276 | }
|
| 277 | }
|
| 278 | }
|
| 279 |
|
| 280 | fn collect_text_from_raw(text: &str, kinds: &mut BTreeMap<String, ParamKind>) {
|
| 281 | let chars: Vec<char> = text.chars().collect();
|
| 282 | let mut i = 0;
|
| 283 | while i < chars.len() {
|
| 284 | if chars[i] == '$' && i + 1 < chars.len() && chars[i + 1] == '{' {
|
| 285 | let start = i + 2;
|
| 286 | let mut j = start;
|
| 287 | while j < chars.len() && chars[j] != '}' {
|
| 288 | j += 1;
|
| 289 | }
|
| 290 | if j < chars.len() {
|
| 291 | let name: String = chars[start..j].iter().collect();
|
| 292 | kinds.insert(name, ParamKind::Text);
|
| 293 | i = j + 1;
|
| 294 | continue;
|
| 295 | }
|
| 296 | }
|
| 297 | i += 1;
|
| 298 | }
|
| 299 | }
|
| 300 |
|
| 301 | pub fn substitute_inlines_for_preview(
|
| 302 | inlines: &[Inline],
|
| 303 | values: &std::collections::HashMap<String, String>,
|
| 304 | ) -> String {
|
| 305 | let mut out = String::new();
|
| 306 | for inline in inlines {
|
| 307 | match inline {
|
| 308 | Inline::Text(t) => out.push_str(t),
|
| 309 | Inline::Param(name) => {
|
| 310 | out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
|
| 311 | }
|
| 312 | Inline::CheckboxParam(name) => {
|
| 313 | let checked = values
|
| 314 | .get(name)
|
| 315 | .and_then(|v| parse_bool_value(v))
|
| 316 | .unwrap_or(false);
|
| 317 | out.push_str(crate::dsl::checkbox_glyph(checked));
|
| 318 | }
|
| 319 | Inline::Checkbox { checked } => {
|
| 320 | out.push_str(crate::dsl::checkbox_glyph(*checked));
|
| 321 | }
|
| 322 | }
|
| 323 | }
|
| 324 | out
|
| 325 | }
|
| 326 |
|
| 327 | /// Validate that bool parameters have parseable values when present.
|
| 328 | pub fn invalid_bool_parameters(
|
| 329 | document: &Document,
|
| 330 | values: &std::collections::HashMap<String, String>,
|
| 331 | ) -> Vec<String> {
|
| 332 | collect_parameters(document)
|
| 333 | .into_iter()
|
| 334 | .filter(|p| p.kind == ParamKind::Bool)
|
| 335 | .filter_map(|p| {
|
| 336 | let Some(raw) = values.get(&p.name) else {
|
| 337 | return None;
|
| 338 | };
|
| 339 | if parse_bool_value(raw).is_some() {
|
| 340 | None
|
| 341 | } else {
|
| 342 | Some(p.name)
|
| 343 | }
|
| 344 | })
|
| 345 | .collect()
|
| 346 | }
|
| 347 |
|
| 348 | #[cfg(test)]
|
| 349 | mod tests {
|
| 350 | use super::*;
|
| 351 | use std::collections::HashMap;
|
| 352 |
|
| 353 | #[test]
|
| 354 | fn collects_unique_sorted_names() {
|
| 355 | let doc = crate::dsl::parse("${B}\n${A}\n${B}").unwrap();
|
| 356 | assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
|
| 357 | }
|
| 358 |
|
| 359 | #[test]
|
| 360 | fn collects_checkbox_params_as_bool() {
|
| 361 | let doc = crate::dsl::parse("$[Paid]\n${Name}").unwrap();
|
| 362 | let params = collect_parameters(&doc);
|
| 363 | assert_eq!(
|
| 364 | params,
|
| 365 | vec![
|
| 366 | ParamSpec {
|
| 367 | name: "Name".into(),
|
| 368 | kind: ParamKind::Text,
|
| 369 | },
|
| 370 | ParamSpec {
|
| 371 | name: "Paid".into(),
|
| 372 | kind: ParamKind::Bool,
|
| 373 | },
|
| 374 | ]
|
| 375 | );
|
| 376 | }
|
| 377 |
|
| 378 | #[test]
|
| 379 | fn preview_substitutes_inlines() {
|
| 380 | let doc = crate::dsl::parse("Hello ${Name}").unwrap();
|
| 381 | let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
|
| 382 | panic!();
|
| 383 | };
|
| 384 | let mut values = HashMap::new();
|
| 385 | values.insert("Name".into(), "Ada".into());
|
| 386 | assert_eq!(
|
| 387 | substitute_inlines_for_preview(inlines, &values),
|
| 388 | "Hello Ada"
|
| 389 | );
|
| 390 | }
|
| 391 |
|
| 392 | #[test]
|
| 393 | fn substitutes_checkbox_param_to_glyph() {
|
| 394 | let doc = crate::dsl::parse("$[Paid] done").unwrap();
|
| 395 | let mut values = HashMap::new();
|
| 396 | values.insert("Paid".into(), "true".into());
|
| 397 | let sub = substitute_document(&doc, &values);
|
| 398 | let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
|
| 399 | panic!();
|
| 400 | };
|
| 401 | assert!(matches!(
|
| 402 | &inlines[0],
|
| 403 | Inline::Checkbox { checked: true }
|
| 404 | ));
|
| 405 | assert_eq!(
|
| 406 | substitute_inlines_for_preview(
|
| 407 | &[Inline::CheckboxParam("Paid".into())],
|
| 408 | &values
|
| 409 | ),
|
| 410 | "[x]"
|
| 411 | );
|
| 412 | }
|
| 413 |
|
| 414 | #[test]
|
| 415 | fn preview_substitutes_placeholders_for_barcodes() {
|
| 416 | let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
|
| 417 | assert_eq!(text, "1234567890");
|
| 418 | }
|
| 419 |
|
| 420 | #[test]
|
| 421 | fn substitutes_all_occurrences() {
|
| 422 | let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap();
|
| 423 | let mut values = HashMap::new();
|
| 424 | values.insert("Name".into(), "Ada".into());
|
| 425 | let sub = substitute_document(&doc, &values);
|
| 426 | let crate::dsl::Block::Paragraph { inlines, .. } = &sub.blocks[0] else {
|
| 427 | panic!();
|
| 428 | };
|
| 429 | assert!(matches!(
|
| 430 | inlines.as_slice(),
|
| 431 | [
|
| 432 | Inline::Text(a),
|
| 433 | Inline::Text(b),
|
| 434 | Inline::Text(c),
|
| 435 | Inline::Text(d),
|
| 436 | ] if a == "Hi " && b == "Ada" && c == " and " && d == "Ada"
|
| 437 | ));
|
| 438 | }
|
| 439 |
|
| 440 | #[test]
|
| 441 | fn parse_bool_value_accepts_common_forms() {
|
| 442 | assert_eq!(parse_bool_value("true"), Some(true));
|
| 443 | assert_eq!(parse_bool_value("FALSE"), Some(false));
|
| 444 | assert_eq!(parse_bool_value("1"), Some(true));
|
| 445 | assert_eq!(parse_bool_value("0"), Some(false));
|
| 446 | assert_eq!(parse_bool_value("maybe"), None);
|
| 447 | }
|
| 448 | }
|