feat(core): refactor form's choice and list values to accept multiline strings. Fix #855

This commit is contained in:
Federico Terzi 2021-11-07 16:46:12 +01:00
parent d02c63dccf
commit 57450bee32

View File

@ -63,14 +63,7 @@ fn convert_fields(fields: &Params) -> HashMap<String, FormField> {
.cloned(), .cloned(),
values: params values: params
.get("values") .get("values")
.and_then(|val| val.as_array()) .and_then(|v| extract_values(v, params.get("trim_string_values")))
.map(|arr| {
arr
.iter()
.flat_map(|choice| choice.as_string())
.cloned()
.collect()
})
.unwrap_or_default(), .unwrap_or_default(),
}), }),
Some(Value::String(field_type)) if field_type == "list" => Some(FormField::List { Some(Value::String(field_type)) if field_type == "list" => Some(FormField::List {
@ -80,14 +73,7 @@ fn convert_fields(fields: &Params) -> HashMap<String, FormField> {
.cloned(), .cloned(),
values: params values: params
.get("values") .get("values")
.and_then(|val| val.as_array()) .and_then(|v| extract_values(v, params.get("trim_string_values")))
.map(|arr| {
arr
.iter()
.flat_map(|choice| choice.as_string())
.cloned()
.collect()
})
.unwrap_or_default(), .unwrap_or_default(),
}), }),
// By default, it's considered type 'text' // By default, it's considered type 'text'
@ -113,3 +99,38 @@ fn convert_fields(fields: &Params) -> HashMap<String, FormField> {
} }
out out
} }
fn extract_values(value: &Value, trim_string_values: Option<&Value>) -> Option<Vec<String>> {
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,
}
}