1use ansiq_core::{
2 ChangeHandler, Element, ElementKind, InputProps, Layout, Length, Style, SubmitHandler,
3};
4
5pub struct Input<Message = ()> {
6 value: String,
7 placeholder: String,
8 on_change: Option<ChangeHandler>,
9 on_submit: Option<SubmitHandler<Message>>,
10 layout: Layout,
11 style: Style,
12 focusable: bool,
13}
14
15impl Input<()> {
16 pub fn new() -> Self {
17 Self {
18 value: String::new(),
19 placeholder: String::new(),
20 on_change: None,
21 on_submit: None,
22 layout: Layout {
23 width: Length::Fill,
24 height: Length::Fixed(3),
25 },
26 style: Style::default(),
27 focusable: true,
28 }
29 }
30}
31
32impl<Message> Input<Message> {
33 pub fn value(mut self, value: impl Into<String>) -> Self {
34 self.value = value.into();
35 self
36 }
37
38 pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
39 self.placeholder = placeholder.into();
40 self
41 }
42
43 pub fn on_change<F>(mut self, handler: F) -> Self
44 where
45 F: FnMut(String) + 'static,
46 {
47 self.on_change = Some(std::boxed::Box::new(handler));
48 self
49 }
50
51 pub fn on_submit<NextMessage, F>(self, handler: F) -> Input<NextMessage>
52 where
53 F: FnMut(String) -> Option<NextMessage> + 'static,
54 {
55 Input {
56 value: self.value,
57 placeholder: self.placeholder,
58 on_change: self.on_change,
59 on_submit: Some(std::boxed::Box::new(handler)),
60 layout: self.layout,
61 style: self.style,
62 focusable: self.focusable,
63 }
64 }
65
66 pub fn layout(mut self, layout: Layout) -> Self {
67 self.layout = layout;
68 self
69 }
70
71 pub fn style(mut self, style: Style) -> Self {
72 self.style = style;
73 self
74 }
75
76 pub fn build(self) -> Element<Message> {
77 let Input {
78 value,
79 placeholder,
80 on_change,
81 on_submit,
82 layout,
83 style,
84 focusable,
85 } = self;
86 let cursor = value.chars().count();
87
88 Element::new(ElementKind::Input(InputProps {
89 value,
90 placeholder,
91 on_change,
92 on_submit,
93 cursor,
94 }))
95 .with_layout(layout)
96 .with_style(style)
97 .with_focusable(focusable)
98 }
99}