1use super::text_control::{TextControl, TextControlState};
4use crate::Brush;
5use std::{fmt, rc::Rc};
6use waft_embedder::{Color, Offset, Rect, TextAlign, TextSelection};
7use waft_foundation::{App, Handle};
8use waft_rendering::RenderBox;
9use waft_services::{SelectionChangedCause, TextInputFormatterRef};
10use waft_widgets::*;
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub enum TextWrapping {
15 #[default]
18 NoWrap,
19 Wrap,
21}
22
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
25pub enum ScrollBarVisibility {
26 Disabled,
28 Auto,
30 #[default]
32 Hidden,
33}
34
35pub type TextChangedCallback = Rc<dyn Fn(&mut App, String)>;
37
38pub type TextSelectionChangedCallback =
40 Rc<dyn Fn(&mut App, TextSelection, Option<SelectionChangedCause>)>;
41
42#[derive(Clone)]
44pub struct TextBox {
45 pub controller: TextEditingControllerRef,
47
48 pub focus_node: Option<FocusNodeRef>,
50
51 pub header: Option<WidgetRef>,
53
54 pub description: Option<WidgetRef>,
56
57 pub placeholder_text: String,
59
60 pub is_enabled: bool,
62
63 pub font_size: Option<f64>,
65
66 pub padding: Option<[f64; 4]>,
68
69 pub corner_radius: Option<f64>,
71
72 pub foreground: Option<Color>,
74
75 pub background: Option<Brush>,
77
78 pub border_brush: Option<Brush>,
80
81 pub selection_highlight_color: Option<Color>,
83
84 pub max_length: Option<i32>,
86
87 pub input_formatters: Vec<TextInputFormatterRef>,
89
90 pub autofocus: bool,
92
93 pub show_cursor: Option<bool>,
97
98 pub context_menu_builder: Option<EditableTextContextMenuBuilder>,
100
101 pub is_read_only: bool,
103
104 pub accepts_return: bool,
110
111 pub text_wrapping: TextWrapping,
113
114 pub horizontal_scroll_bar_visibility: ScrollBarVisibility,
116
117 pub max_lines: Option<i32>,
121
122 pub text_alignment: TextAlign,
124
125 pub placeholder_foreground: Option<Color>,
127
128 pub text_changed: Option<TextChangedCallback>,
130
131 pub selection_changed: Option<TextSelectionChangedCallback>,
133
134 pub key: Option<KeyRef>,
136}
137
138impl TextBox {
139 pub fn new(controller: TextEditingControllerRef) -> Self {
141 Self {
142 controller,
143 focus_node: None,
144 header: None,
145 description: None,
146 placeholder_text: String::new(),
147 is_enabled: true,
148 font_size: None,
149 padding: None,
150 corner_radius: None,
151 foreground: None,
152 background: None,
153 border_brush: None,
154 selection_highlight_color: None,
155 max_length: None,
156 input_formatters: Vec::new(),
157 autofocus: false,
158 show_cursor: None,
159 context_menu_builder: None,
160 is_read_only: false,
161 accepts_return: false,
162 text_wrapping: TextWrapping::NoWrap,
163 horizontal_scroll_bar_visibility: ScrollBarVisibility::Hidden,
164 max_lines: None,
165 text_alignment: TextAlign::Start,
166 placeholder_foreground: None,
167 text_changed: None,
168 selection_changed: None,
169 key: None,
170 }
171 }
172
173 pub fn focus_node(mut self, value: FocusNodeRef) -> Self {
175 self.focus_node = Some(value);
176 self
177 }
178
179 #[cfg_attr(debug_assertions, track_caller)]
181 pub fn header<K>(mut self, value: impl IntoWidget<K>) -> Self {
182 self.header = Some(value.into_widget());
183 self
184 }
185
186 #[cfg_attr(debug_assertions, track_caller)]
188 pub fn description<K>(mut self, value: impl IntoWidget<K>) -> Self {
189 self.description = Some(value.into_widget());
190 self
191 }
192
193 pub fn placeholder_text(mut self, value: impl Into<String>) -> Self {
195 self.placeholder_text = value.into();
196 self
197 }
198
199 pub fn is_enabled(mut self, value: bool) -> Self {
201 self.is_enabled = value;
202 self
203 }
204
205 pub fn font_size(mut self, value: f64) -> Self {
207 self.font_size = Some(value);
208 self
209 }
210
211 pub fn padding(mut self, value: [f64; 4]) -> Self {
213 self.padding = Some(value);
214 self
215 }
216
217 pub fn corner_radius(mut self, value: f64) -> Self {
219 self.corner_radius = Some(value);
220 self
221 }
222
223 pub fn foreground(mut self, value: Color) -> Self {
225 self.foreground = Some(value);
226 self
227 }
228
229 pub fn background(mut self, value: Brush) -> Self {
231 self.background = Some(value);
232 self
233 }
234
235 pub fn border_brush(mut self, value: Brush) -> Self {
237 self.border_brush = Some(value);
238 self
239 }
240
241 pub fn selection_highlight_color(mut self, value: Color) -> Self {
243 self.selection_highlight_color = Some(value);
244 self
245 }
246
247 pub fn max_length(mut self, value: i32) -> Self {
249 assert!(value >= 0, "MaxLength must be non-negative");
250 self.max_length = Some(value);
251 self
252 }
253
254 pub fn input_formatters(mut self, value: Vec<TextInputFormatterRef>) -> Self {
256 self.input_formatters = value;
257 self
258 }
259
260 pub fn autofocus(mut self, value: bool) -> Self {
262 self.autofocus = value;
263 self
264 }
265
266 pub fn context_menu_builder(
268 mut self,
269 value: impl Fn(&mut App, BuildContext, Handle<EditableTextState>) -> WidgetRef + 'static,
270 ) -> Self {
271 self.context_menu_builder = Some(Rc::new(value));
272 self
273 }
274
275 pub fn is_read_only(mut self, value: bool) -> Self {
277 self.is_read_only = value;
278 self
279 }
280
281 pub fn accepts_return(mut self, value: bool) -> Self {
283 self.accepts_return = value;
284 self
285 }
286
287 pub fn text_wrapping(mut self, value: TextWrapping) -> Self {
289 self.text_wrapping = value;
290 self
291 }
292
293 pub fn horizontal_scroll_bar_visibility(mut self, value: ScrollBarVisibility) -> Self {
295 self.horizontal_scroll_bar_visibility = value;
296 self
297 }
298
299 pub fn max_lines(mut self, value: i32) -> Self {
301 self.max_lines = Some(value);
302 self
303 }
304
305 pub fn text_alignment(mut self, value: TextAlign) -> Self {
307 self.text_alignment = value;
308 self
309 }
310
311 pub fn show_cursor(mut self, value: bool) -> Self {
313 self.show_cursor = Some(value);
314 self
315 }
316
317 pub fn placeholder_foreground(mut self, value: Color) -> Self {
319 self.placeholder_foreground = Some(value);
320 self
321 }
322
323 pub fn text_changed(mut self, value: impl Fn(&mut App, String) + 'static) -> Self {
325 self.text_changed = Some(Rc::new(value));
326 self
327 }
328
329 pub fn selection_changed(
331 mut self,
332 value: impl Fn(&mut App, TextSelection, Option<SelectionChangedCause>) + 'static,
333 ) -> Self {
334 self.selection_changed = Some(Rc::new(value));
335 self
336 }
337
338 pub fn key(mut self, key: KeyRef) -> Self {
340 self.key = Some(key);
341 self
342 }
343}
344
345impl fmt::Debug for TextBox {
346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347 f.debug_struct("TextBox")
348 .field("is_enabled", &self.is_enabled)
349 .finish_non_exhaustive()
350 }
351}
352
353impl StatefulWidget for TextBox {
354 type State = TextBoxState;
355
356 fn key(&self) -> Option<&KeyRef> {
357 self.key.as_ref()
358 }
359
360 fn create_state(&self) -> TextBoxState {
361 TextBoxState {
362 state: StateData::new(),
363 }
364 }
365}
366
367pub struct TextBoxState {
369 state: StateData<TextBox>,
370}
371
372impl TextBoxState {
373 pub fn get_rect_from_character_index(
380 self: Handle<Self>,
381 app: &mut App,
382 char_index: i32,
383 trailing_edge: bool,
384 ) -> Option<Rect> {
385 let length = self
386 .widget(app)
387 .controller
388 .text_value(app)
389 .encode_utf16()
390 .count();
391 if char_index < 0 || char_index as usize >= length {
392 return None;
393 }
394 let editable = self.text_control(app)?.render_editable(app)?;
395 let character = TextSelection::new(char_index, char_index + 1);
396 let boxes = editable.get_boxes_for_selection(app, character);
397 let glyph = boxes.first()?;
398 let x = if trailing_edge {
400 glyph.right
401 } else {
402 glyph.left
403 };
404 let top_left = editable
405 .as_box()
406 .local_to_global(app, Offset::new(x, glyph.top), None);
407 let own = self.context(app).find_render_object(app)?.as_box()?;
408 let local = own.global_to_local(app, top_left, None);
409 Some(Rect::from_ltwh(
410 local.dx(),
411 local.dy(),
412 0.0,
413 glyph.bottom - glyph.top,
414 ))
415 }
416
417 fn text_control(self: Handle<Self>, app: &App) -> Option<Handle<TextControlState>> {
419 let mut found = None;
420 self.context(app).visit_child_elements(app, &mut |child| {
421 found = child.state_handle::<TextControlState>(app);
422 });
423 found
424 }
425}
426
427impl State for TextBoxState {
428 type Widget = TextBox;
429 waft_widgets::state_accessors!();
430
431 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
432 TextControl::new(self.widget(app).clone(), None).into_widget()
433 }
434}