From 57450bee3268426d0a450726ca0c033ca99c5ff4 Mon Sep 17 00:00:00 2001 From: Federico Terzi Date: Sun, 7 Nov 2021 16:46:12 +0100 Subject: [PATCH] feat(core): refactor form's choice and list values to accept multiline strings. Fix #855 --- .../middleware/render/extension/form.rs | 53 +++++++++++++------ 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/espanso/src/cli/worker/engine/process/middleware/render/extension/form.rs b/espanso/src/cli/worker/engine/process/middleware/render/extension/form.rs index fb0510b..16da24f 100644 --- a/espanso/src/cli/worker/engine/process/middleware/render/extension/form.rs +++ b/espanso/src/cli/worker/engine/process/middleware/render/extension/form.rs @@ -63,14 +63,7 @@ fn convert_fields(fields: &Params) -> HashMap { .cloned(), values: params .get("values") - .and_then(|val| val.as_array()) - .map(|arr| { - arr - .iter() - .flat_map(|choice| choice.as_string()) - .cloned() - .collect() - }) + .and_then(|v| extract_values(v, params.get("trim_string_values"))) .unwrap_or_default(), }), Some(Value::String(field_type)) if field_type == "list" => Some(FormField::List { @@ -80,14 +73,7 @@ fn convert_fields(fields: &Params) -> HashMap { .cloned(), values: params .get("values") - .and_then(|val| val.as_array()) - .map(|arr| { - arr - .iter() - .flat_map(|choice| choice.as_string()) - .cloned() - .collect() - }) + .and_then(|v| extract_values(v, params.get("trim_string_values"))) .unwrap_or_default(), }), // By default, it's considered type 'text' @@ -113,3 +99,38 @@ fn convert_fields(fields: &Params) -> HashMap { } out } + +fn extract_values(value: &Value, trim_string_values: Option<&Value>) -> Option> { + let trim_string_values = *trim_string_values + .and_then(|v| v.as_bool()) + .unwrap_or(&true); + + match value { + Value::Array(values) => Some( + values + .iter() + .flat_map(|choice| choice.as_string()) + .cloned() + .collect(), + ), + Value::String(values) => Some( + values + .lines() + .filter_map(|line| { + if trim_string_values { + let trimmed_line = line.trim(); + if !trimmed_line.is_empty() { + Some(trimmed_line) + } else { + None + } + } else { + Some(line) + } + }) + .map(String::from) + .collect(), + ), + _ => None, + } +}