Skip to main content

tablo_core/schema/fields/builders/
into.rs

1//! What a builder's `default` and `options` take.
2
3use crate::{
4    Text,
5    values::{FormScalar, FormValue},
6};
7
8/// A value a field's `default` takes: any [`FormScalar`] or a `&str` or `&String` in the form
9/// spelling, or an array or `Vec` of them for a multiple choice.
10pub trait IntoFormValue {
11    /// The value as its control posts it.
12    fn into_form_value(self) -> FormValue;
13}
14
15impl<T: FormScalar> IntoFormValue for T {
16    fn into_form_value(self) -> FormValue {
17        FormValue::Text(self.to_form())
18    }
19}
20
21impl IntoFormValue for &str {
22    fn into_form_value(self) -> FormValue {
23        FormValue::Text(self.to_string())
24    }
25}
26
27impl IntoFormValue for &String {
28    fn into_form_value(self) -> FormValue {
29        FormValue::Text(self.clone())
30    }
31}
32
33impl<T: FormScalar> IntoFormValue for Vec<T> {
34    fn into_form_value(self) -> FormValue {
35        FormValue::List(self.iter().map(FormScalar::to_form).collect())
36    }
37}
38
39impl IntoFormValue for Vec<&str> {
40    fn into_form_value(self) -> FormValue {
41        FormValue::List(self.into_iter().map(str::to_string).collect())
42    }
43}
44
45impl<T: FormScalar, const N: usize> IntoFormValue for [T; N] {
46    fn into_form_value(self) -> FormValue {
47        Vec::from(self).into_form_value()
48    }
49}
50
51impl<const N: usize> IntoFormValue for [&str; N] {
52    fn into_form_value(self) -> FormValue {
53        Vec::from(self).into_form_value()
54    }
55}
56
57/// A choice's static options as `(value, label)` pairs, in display order. A value listed alone
58/// is its own label; a label is a [`Text`], so a message translates it.
59pub trait IntoOptions {
60    fn into_options(self) -> Vec<(String, Text)>;
61}
62
63impl IntoOptions for Vec<String> {
64    fn into_options(self) -> Vec<(String, Text)> {
65        self.into_iter()
66            .map(|value| (value.clone(), Text::from(value)))
67            .collect()
68    }
69}
70
71impl<const N: usize> IntoOptions for [&str; N] {
72    fn into_options(self) -> Vec<(String, Text)> {
73        self.into_iter()
74            .map(|value| (value.to_string(), Text::from(value)))
75            .collect()
76    }
77}
78
79impl<L: Into<Text>> IntoOptions for Vec<(String, L)> {
80    fn into_options(self) -> Vec<(String, Text)> {
81        self.into_iter()
82            .map(|(value, label)| (value, label.into()))
83            .collect()
84    }
85}
86
87impl<L: Into<Text>, const N: usize> IntoOptions for [(&str, L); N] {
88    fn into_options(self) -> Vec<(String, Text)> {
89        self.into_iter()
90            .map(|(value, label)| (value.to_string(), label.into()))
91            .collect()
92    }
93}