1use std::cell::Cell;
26use std::fmt;
27use std::rc::Rc;
28
29use iced::widget::text::LineHeight;
30use iced::widget::text_input::{Status, Style};
31use iced::widget::{self, Id, container, stack, text_input};
32use iced::{Alignment, Background, Border, Color, Element, Length, Padding};
33
34pub use crate::editing::{Shortcut, Shortcuts, default_keymap};
35
36use crate::editing::{self, Editing, Limit};
37use crate::icon::{Glyph, opacity, themed};
38use crate::keys::Keymap;
39use crate::theme::{Tokens, fade, mix, radius, space, text_size};
40
41const LINE_HEIGHT: f32 = 1.3;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
45pub enum Size {
46 Sm,
47 #[default]
48 Md,
49 Lg,
50}
51
52impl Size {
53 pub const ALL: [Size; 3] = [Size::Sm, Size::Md, Size::Lg];
54
55 pub const fn metrics(self) -> Metrics {
57 match self {
58 Size::Sm => Metrics {
59 height: 32.0,
60 padding_x: 10.0,
61 text: text_size::SM,
62 icon: 14.0,
63 },
64 Size::Md => Metrics {
65 height: 36.0,
66 padding_x: 12.0,
67 text: text_size::SM,
68 icon: 16.0,
69 },
70 Size::Lg => Metrics {
71 height: 40.0,
72 padding_x: 14.0,
73 text: text_size::MD,
74 icon: 18.0,
75 },
76 }
77 }
78}
79
80#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct Metrics {
83 pub height: f32,
84 pub padding_x: f32,
85 pub text: f32,
86 pub icon: f32,
87}
88
89impl Metrics {
90 pub fn padding(self, with_icon: bool) -> Padding {
93 let vertical = ((self.height - self.text * LINE_HEIGHT) / 2.0).max(0.0);
94 let left = if with_icon {
95 self.padding_x + self.icon + space::SM
96 } else {
97 self.padding_x
98 };
99 Padding {
100 top: vertical,
101 bottom: vertical,
102 left,
103 right: self.padding_x,
104 }
105 }
106}
107
108pub struct Input<'a, Message> {
112 placeholder: String,
113 value: String,
114 id: Option<Id>,
115 on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
116 on_submit: Option<Message>,
117 icon: Option<Glyph>,
118 secure: bool,
119 invalid: bool,
120 size: Size,
121 width: Length,
122 shortcuts: Shortcuts,
123 keymap: Keymap<Shortcut>,
124 on_clear: Option<Message>,
125 max_length: Option<usize>,
126}
127
128pub fn input<'a, Message>(placeholder: &str, value: &str) -> Input<'a, Message> {
130 Input {
131 placeholder: placeholder.to_owned(),
132 value: value.to_owned(),
133 id: None,
134 on_input: None,
135 on_submit: None,
136 icon: None,
137 secure: false,
138 invalid: false,
139 size: Size::default(),
140 width: Length::Fill,
141 shortcuts: Shortcuts::all(),
142 keymap: default_keymap(),
143 on_clear: None,
144 max_length: None,
145 }
146}
147
148pub fn clear_id() -> Id {
151 Id::new("iced-cube-input-clear")
152}
153
154impl<'a, Message> Input<'a, Message> {
155 pub fn id(mut self, id: impl Into<Id>) -> Self {
157 self.id = Some(id.into());
158 self
159 }
160
161 pub fn on_input(mut self, on_input: impl Fn(String) -> Message + 'a) -> Self {
163 self.on_input = Some(Box::new(on_input));
164 self
165 }
166
167 pub fn on_input_maybe(mut self, on_input: Option<impl Fn(String) -> Message + 'a>) -> Self {
168 self.on_input = on_input.map(|f| Box::new(f) as Box<dyn Fn(String) -> Message + 'a>);
169 self
170 }
171
172 pub fn on_submit(mut self, message: Message) -> Self {
174 self.on_submit = Some(message);
175 self
176 }
177
178 pub fn on_submit_maybe(mut self, message: Option<Message>) -> Self {
179 self.on_submit = message;
180 self
181 }
182
183 pub fn icon(mut self, glyph: Glyph) -> Self {
185 self.icon = Some(glyph);
186 self
187 }
188
189 pub fn secure(mut self, secure: bool) -> Self {
191 self.secure = secure;
192 self
193 }
194
195 pub fn invalid(mut self, invalid: bool) -> Self {
197 self.invalid = invalid;
198 self
199 }
200
201 pub fn size(mut self, size: Size) -> Self {
202 self.size = size;
203 self
204 }
205
206 pub fn width(mut self, width: impl Into<Length>) -> Self {
208 self.width = width.into();
209 self
210 }
211
212 pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
216 self.shortcuts = shortcuts;
217 self
218 }
219
220 pub fn keymap(mut self, keymap: Keymap<Shortcut>) -> Self {
222 self.keymap = keymap;
223 self
224 }
225
226 pub fn clearable(mut self, message: Message) -> Self {
229 self.on_clear = Some(message);
230 self
231 }
232
233 pub fn max_length(mut self, max_length: usize) -> Self {
237 self.max_length = Some(max_length);
238 self
239 }
240
241 pub fn is_enabled(&self) -> bool {
242 self.on_input.is_some()
243 }
244
245 pub fn shows_clear(&self) -> bool {
248 self.on_clear.is_some() && self.is_enabled() && !self.value.is_empty()
249 }
250}
251
252#[cfg(any(feature = "combobox", feature = "command", feature = "select"))]
255pub(crate) fn with_shortcuts<'a, Message: Clone + 'a>(
256 field: text_input::TextInput<'a, Message>,
257 value: &str,
258 secure: bool,
259 on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
260 keymap: Keymap<Shortcut>,
261 shortcuts: Shortcuts,
262) -> Element<'a, Message> {
263 limited(field, value, secure, on_input, keymap, shortcuts, None)
264}
265
266fn limited<'a, Message: Clone + 'a>(
269 field: text_input::TextInput<'a, Message>,
270 value: &str,
271 secure: bool,
272 on_input: Option<Box<dyn Fn(String) -> Message + 'a>>,
273 keymap: Keymap<Shortcut>,
274 shortcuts: Shortcuts,
275 max_length: Option<usize>,
276) -> Element<'a, Message> {
277 let Some(on_input) = on_input else {
278 return field.into();
279 };
280 let on_input: Rc<dyn Fn(String) -> Message + 'a> = Rc::from(on_input);
281 let edited = Rc::new(Cell::new(false));
282 let limit = max_length.map(|max| Rc::new(Limit::new(max, value)));
283 let field = field.on_input({
284 let (on_input, edited, limit) = (Rc::clone(&on_input), Rc::clone(&edited), limit.clone());
285 move |value| {
286 edited.set(true);
287 match &limit {
288 Some(limit) => on_input(limit.apply(value)),
289 None => on_input(value),
290 }
291 }
292 });
293 Editing::new(
294 field,
295 editing::Input::new(value, secure, on_input).limit(limit),
296 keymap,
297 shortcuts,
298 edited,
299 )
300 .into()
301}
302
303impl<Message: fmt::Debug> fmt::Debug for Input<'_, Message> {
304 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
305 f.debug_struct("Input")
306 .field("placeholder", &self.placeholder)
307 .field("value", &self.value)
308 .field("id", &self.id)
309 .field("enabled", &self.is_enabled())
310 .field("on_submit", &self.on_submit)
311 .field("icon", &self.icon)
312 .field("secure", &self.secure)
313 .field("invalid", &self.invalid)
314 .field("size", &self.size)
315 .field("width", &self.width)
316 .field("shortcuts", &self.shortcuts)
317 .field("keymap", &self.keymap)
318 .field("on_clear", &self.on_clear)
319 .field("max_length", &self.max_length)
320 .finish()
321 }
322}
323
324impl<'a, Message: Clone + 'a> From<Input<'a, Message>> for Element<'a, Message> {
325 fn from(input: Input<'a, Message>) -> Self {
326 let metrics = input.size.metrics();
327 let invalid = input.invalid;
328 let enabled = input.is_enabled();
329 let clearable = input.on_clear.is_some() && enabled;
330 let clear = input
331 .shows_clear()
332 .then_some(input.on_clear.clone())
333 .flatten();
334
335 let mut padding = metrics.padding(input.icon.is_some());
336 if clearable {
339 padding.right = metrics.padding_x + metrics.icon + space::SM;
340 }
341 let mut field = text_input(&input.placeholder, &input.value)
342 .secure(input.secure)
343 .size(metrics.text)
344 .line_height(LineHeight::Relative(LINE_HEIGHT))
345 .padding(padding)
346 .width(Length::Fill)
347 .on_submit_maybe(input.on_submit.filter(|_| enabled))
348 .style(move |theme, status| style(&Tokens::of(theme), status, invalid));
349 if let Some(id) = input.id {
350 field = field.id(id);
351 }
352 let field = limited(
353 field,
354 &input.value,
355 input.secure,
356 input.on_input,
357 input.keymap,
358 input.shortcuts,
359 input.max_length,
360 );
361 #[cfg(feature = "icedwright")]
362 let field = annotate(
363 field,
364 Field {
365 placeholder: input.placeholder.clone(),
366 value: input.value.clone(),
367 secure: input.secure,
368 enabled,
369 invalid,
370 },
371 "iced_cube::input",
372 );
373
374 if input.icon.is_none() && !clearable {
377 return container(field).width(input.width).into();
378 }
379
380 let status = if enabled {
381 Status::Active
382 } else {
383 Status::Disabled
384 };
385 let icon = input.icon.map(|glyph| {
386 let icon = themed(glyph, metrics.icon, opacity(enabled), move |theme| {
387 style(&Tokens::of(theme), status, invalid).icon
388 });
389 container(icon)
390 .padding(Padding::ZERO.left(metrics.padding_x))
391 .height(Length::Fill)
392 .align_y(Alignment::Center)
393 });
394 let clear = clear.map(|message| clear_button(metrics, message));
395
396 stack![field]
397 .push(icon)
398 .push(clear)
399 .width(input.width)
400 .into()
401 }
402}
403
404#[cfg(feature = "icedwright")]
406#[derive(Debug, Clone, Default)]
407pub(crate) struct Field {
408 pub(crate) placeholder: String,
409 pub(crate) value: String,
410 pub(crate) secure: bool,
411 pub(crate) enabled: bool,
412 pub(crate) invalid: bool,
413}
414
415#[cfg(feature = "icedwright")]
418pub(crate) fn annotate<'a, Message: 'a>(
419 element: Element<'a, Message>,
420 field: Field,
421 kind: &'static str,
422) -> Element<'a, Message> {
423 use icedwright_probe::role::{Editable, RoleKind};
424 use icedwright_probe::{Semantic, role, semantic};
425
426 fn states<'a, Message: 'a, R: RoleKind + Editable>(
427 mut annotated: Semantic<'a, Message, iced::Theme, iced::Renderer, R>,
428 field: &Field,
429 kind: &'static str,
430 ) -> Semantic<'a, Message, iced::Theme, iced::Renderer, R> {
431 annotated = annotated
433 .component(kind)
434 .caret_clock(icedwright_probe::CaretClock::Iced);
435 if !field.placeholder.is_empty() {
436 annotated = annotated.placeholder(field.placeholder.clone());
437 }
438 if !field.enabled {
439 annotated = annotated.disabled(true);
440 }
441 if field.invalid {
442 annotated = annotated.invalid(true);
443 }
444 annotated
445 }
446
447 if field.secure {
448 return states(semantic(element).role(role::PasswordInput), &field, kind).into();
449 }
450 let value = field.value.clone();
451 states(semantic(element).role(role::TextBox), &field, kind)
452 .value(value)
453 .into()
454}
455
456const CLEAR_PADDING: f32 = 2.0;
458
459fn clear_button<'a, Message: Clone + 'a>(
462 metrics: Metrics,
463 message: Message,
464) -> Element<'a, Message> {
465 let icon = themed(crate::lucide!(X), metrics.icon, 1.0, |theme| {
466 Tokens::of(theme).muted_foreground
467 });
468 let button = widget::button(icon)
469 .padding(CLEAR_PADDING)
470 .on_press(message)
471 .style(|theme, status| clear_style(&Tokens::of(theme), status));
472 let button: Element<'a, Message> = container(button).id(clear_id()).into();
473 #[cfg(feature = "icedwright")]
474 let button: Element<'a, Message> = icedwright_probe::semantic(button)
475 .role(icedwright_probe::role::Button)
476 .name("Clear")
477 .component("iced_cube::input")
478 .into();
479 container(button)
480 .padding(Padding::ZERO.right(metrics.padding_x - CLEAR_PADDING))
481 .width(Length::Fill)
482 .height(Length::Fill)
483 .align_x(Alignment::End)
484 .align_y(Alignment::Center)
485 .into()
486}
487
488pub fn clear_style(tokens: &Tokens, status: widget::button::Status) -> widget::button::Style {
490 use widget::button::Status as Button;
491 let background = matches!(status, Button::Hovered | Button::Pressed)
492 .then_some(Background::Color(tokens.accent));
493 widget::button::Style {
494 background,
495 text_color: tokens.muted_foreground,
496 border: Border {
497 radius: radius::SM.into(),
498 ..Border::default()
499 },
500 ..widget::button::Style::default()
501 }
502}
503
504pub fn style(tokens: &Tokens, status: Status, invalid: bool) -> Style {
506 let border = match (invalid, status) {
507 (true, _) => tokens.destructive,
508 (false, Status::Focused { .. }) => mix(tokens.border, tokens.foreground, 0.6),
509 (false, Status::Hovered) => mix(tokens.border, tokens.foreground, 0.25),
510 (false, Status::Active | Status::Disabled) => tokens.border,
511 };
512
513 let active = Style {
516 background: Background::Color(Color::TRANSPARENT),
517 border: Border {
518 color: border,
519 width: 1.0,
520 radius: radius::MD.into(),
521 },
522 icon: tokens.muted_foreground,
523 placeholder: tokens.muted_foreground,
524 value: tokens.foreground,
525 selection: fade(tokens.primary, 0.25),
526 };
527
528 if status != Status::Disabled {
529 return active;
530 }
531 Style {
532 background: Background::Color(tokens.disabled_field()),
533 border: Border {
534 color: fade(border, 0.5),
535 ..active.border
536 },
537 icon: fade(active.icon, 0.5),
538 placeholder: fade(active.placeholder, 0.5),
539 value: fade(active.value, 0.5),
540 selection: Color::TRANSPARENT,
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547 use crate::theme::{dark, light};
548
549 const STATES: [Status; 5] = [
550 Status::Active,
551 Status::Hovered,
552 Status::Focused { is_hovered: false },
553 Status::Focused { is_hovered: true },
554 Status::Disabled,
555 ];
556
557 fn border(style: Style) -> Color {
558 style.border.color
559 }
560
561 #[test]
562 fn default_builder_is_medium_fill_and_disabled() {
563 let i: Input<'_, ()> = input("Email", "");
564 assert_eq!(i.size, Size::Md);
565 assert_eq!(i.width, Length::Fill);
566 assert!(!i.secure && !i.invalid);
567 assert!(i.icon.is_none() && i.id.is_none());
568 assert!(!i.is_enabled());
569 assert_eq!(i.shortcuts, Shortcuts::all());
570 assert_eq!(i.keymap, default_keymap());
571 assert!(i.on_clear.is_none() && i.max_length.is_none());
572 assert!(!i.shows_clear());
573 }
574
575 #[test]
576 fn the_clear_button_shows_only_for_an_enabled_field_with_text() {
577 let shows = |value: &str, enabled: bool| {
578 input::<String>("", value)
579 .clearable(String::new())
580 .on_input_maybe(enabled.then_some(|s| s))
581 .shows_clear()
582 };
583 assert!(shows("text", true));
584 assert!(!shows("", true));
585 assert!(!shows("text", false));
586 assert!(!input::<String>("", "text").on_input(|s| s).shows_clear());
587 }
588
589 #[test]
590 fn max_length_is_kept() {
591 let i: Input<'_, ()> = input("", "").max_length(8);
592 assert_eq!(i.max_length, Some(8));
593 }
594
595 #[test]
596 fn the_clear_button_highlights_under_the_pointer() {
597 use widget::button::Status as Button;
598 for theme in [light(), dark()] {
599 let tokens = Tokens::of(&theme);
600 assert_eq!(clear_style(&tokens, Button::Active).background, None);
601 for status in [Button::Hovered, Button::Pressed] {
602 assert_eq!(
603 clear_style(&tokens, status).background,
604 Some(Background::Color(tokens.accent))
605 );
606 }
607 assert_eq!(
608 clear_style(&tokens, Button::Active).text_color,
609 tokens.muted_foreground
610 );
611 }
612 }
613
614 #[test]
615 fn shortcuts_and_keymap_can_be_changed() {
616 let i: Input<'_, ()> = input("", "")
617 .shortcuts(Shortcuts::none())
618 .keymap(Keymap::new());
619 assert_eq!(i.shortcuts, Shortcuts::none());
620 assert!(i.keymap.is_empty());
621 }
622
623 #[test]
624 fn on_input_enables_and_on_input_maybe_none_disables() {
625 assert!(input::<String>("", "").on_input(|s| s).is_enabled());
626 let none: Option<fn(String) -> String> = None;
627 assert!(
628 !input::<String>("", "")
629 .on_input(|s| s)
630 .on_input_maybe(none)
631 .is_enabled()
632 );
633 }
634
635 #[test]
636 fn builder_keeps_placeholder_and_value() {
637 let i: Input<'_, ()> = input("Search", "iced").secure(true).invalid(true);
638 assert_eq!(i.placeholder, "Search");
639 assert_eq!(i.value, "iced");
640 assert!(i.secure && i.invalid);
641 }
642
643 #[test]
644 fn sizes_grow_monotonically() {
645 let heights = Size::ALL.map(|s| s.metrics().height);
646 assert!(heights.windows(2).all(|w| w[0] < w[1]));
647 }
648
649 #[test]
650 fn padding_produces_the_target_height() {
651 for size in Size::ALL {
652 let m = size.metrics();
653 let p = m.padding(false);
654 let height = m.text * LINE_HEIGHT + p.top + p.bottom;
655 assert!((height - m.height).abs() < 1e-3, "{size:?}");
656 }
657 }
658
659 #[test]
660 fn icon_reserves_space_on_the_left_only() {
661 let m = Size::Md.metrics();
662 let plain = m.padding(false);
663 let with_icon = m.padding(true);
664 assert!(with_icon.left > plain.left + m.icon);
665 assert_eq!(with_icon.right, plain.right);
666 assert_eq!(with_icon.top, plain.top);
667 }
668
669 #[test]
670 fn hover_and_focus_strengthen_the_border() {
671 for theme in [light(), dark()] {
672 let tokens = Tokens::of(&theme);
673 let active = border(style(&tokens, Status::Active, false));
674 let hovered = border(style(&tokens, Status::Hovered, false));
675 let focused = border(style(&tokens, Status::Focused { is_hovered: false }, false));
676 assert_ne!(active, hovered);
677 assert_ne!(hovered, focused);
678 assert_eq!(
679 focused,
680 border(style(&tokens, Status::Focused { is_hovered: true }, false))
681 );
682 }
683 }
684
685 #[test]
686 fn invalid_uses_destructive_border_in_every_enabled_status() {
687 for theme in [light(), dark()] {
688 let tokens = Tokens::of(&theme);
689 for status in STATES {
690 let style = style(&tokens, status, true);
691 let expected = if status == Status::Disabled {
692 fade(tokens.destructive, 0.5)
693 } else {
694 tokens.destructive
695 };
696 assert_eq!(style.border.color, expected, "{status:?}");
697 }
698 }
699 }
700
701 #[test]
702 fn disabled_halves_text_alpha_and_mutes_background() {
703 for theme in [light(), dark()] {
704 let tokens = Tokens::of(&theme);
705 let active = style(&tokens, Status::Active, false);
706 let disabled = style(&tokens, Status::Disabled, false);
707 assert!((disabled.value.a - active.value.a * 0.5).abs() < 1e-6);
708 assert!((disabled.placeholder.a - active.placeholder.a * 0.5).abs() < 1e-6);
709 assert_ne!(disabled.background, active.background);
710 assert_eq!(
711 disabled.background,
712 Background::Color(tokens.disabled_field())
713 );
714 }
715 }
716
717 #[test]
718 fn enabled_fields_take_the_colour_of_their_surface() {
719 for theme in [light(), dark()] {
720 let tokens = Tokens::of(&theme);
721 for status in STATES.into_iter().filter(|s| *s != Status::Disabled) {
722 for invalid in [false, true] {
723 let style = style(&tokens, status, invalid);
724 assert_eq!(style.background, Background::Color(Color::TRANSPARENT));
725 }
726 }
727 }
728 }
729
730 #[test]
731 fn every_status_has_a_visible_border_and_readable_value() {
732 for theme in [light(), dark()] {
733 let tokens = Tokens::of(&theme);
734 for status in STATES {
735 for invalid in [false, true] {
736 let style = style(&tokens, status, invalid);
737 assert_eq!(style.border.width, 1.0);
738 assert!(style.border.color.a > 0.0);
739 assert_ne!(style.value, tokens.background);
740 }
741 }
742 }
743 }
744}