This repository has been archived on 2024-08-06. You can view files and clone it, but cannot push or open issues or pull requests.
leptos_form_tool/src/controls/select.rs

86 lines
2.5 KiB
Rust

use super::{BuilderFn, ControlBuilder, ControlData, ControlRenderData, ValidatedControlData};
use crate::{form::FormToolData, form_builder::FormBuilder, styles::FormStyle};
use leptos::{Signal, View};
use std::rc::Rc;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct SelectData {
pub name: String,
pub label: Option<String>,
/// The options for the select.
///
/// The first value is the string to display, the second is the value.
pub options: Vec<(String, String)>,
}
impl ControlData for SelectData {
type ReturnType = String;
fn build_control<FS: FormStyle>(
fs: &FS,
control: Rc<ControlRenderData<FS, Self>>,
value_getter: Signal<Self::ReturnType>,
value_setter: Rc<dyn Fn(Self::ReturnType)>,
validation_state: Signal<Result<(), String>>,
) -> View {
fs.select(control, value_getter, value_setter, validation_state)
}
}
impl ValidatedControlData for SelectData {}
impl<FD: FormToolData> FormBuilder<FD> {
pub fn select<FDT: Clone + PartialEq + 'static>(
self,
builder: impl BuilderFn<ControlBuilder<FD, SelectData, FDT>, FD::Context>,
) -> Self {
self.new_control(builder)
}
}
impl<FD: FormToolData, FDT> ControlBuilder<FD, SelectData, FDT> {
pub fn named(mut self, control_name: impl ToString) -> Self {
self.data.name = control_name.to_string();
self
}
pub fn labeled(mut self, label: impl ToString) -> Self {
self.data.label = Some(label.to_string());
self
}
pub fn with_option(mut self, option: impl ToString) -> Self {
self.data
.options
.push((option.to_string(), option.to_string()));
self
}
pub fn with_option_valued(mut self, display: impl ToString, value: impl ToString) -> Self {
self.data
.options
.push((display.to_string(), value.to_string()));
self
}
pub fn with_options(mut self, options: impl Iterator<Item = impl ToString>) -> Self {
for option in options {
self.data
.options
.push((option.to_string(), option.to_string()));
}
self
}
pub fn with_options_valued(
mut self,
options: impl Iterator<Item = (impl ToString, impl ToString)>,
) -> Self {
for option in options {
self.data
.options
.push((option.0.to_string(), option.1.to_string()));
}
self
}
}