1use std::cell::Cell;
4
5use crate::layout::layout_ext::finish_view_sized;
6use crate::transactional_layout::TransactionalLayoutPending;
7use ailloli_ui_core::event::{Event, ImePreedit};
8#[cfg(test)]
9use ailloli_ui_core::geometry::Size;
10use ailloli_ui_core::geometry::{Constraints, Rect};
11use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
12use ailloli_ui_core::{Color, FontId, ScrollbarAxis, TextStyle, Theme};
13use ailloli_ui_runtime::component::reactive::with_untracked_reads;
14use ailloli_ui_runtime::component::{
15 Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
16};
17use ailloli_ui_runtime::input::{ActivationPolicy, EventCtx, FocusPolicy, InputRole, Selection};
18use ailloli_ui_runtime::layout::{LayoutArtifact, LayoutChild, LayoutCtx, LayoutResult};
19use ailloli_ui_runtime::scene::PaintCtx;
20use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawRRect, Invalidation};
21use ailloli_ui_text::{TextBuffer, TextEditState, TextInputMode, TextSystem};
22#[cfg(test)]
23use ailloli_ui_text::{TextEditAction, TextLayoutParams, WrapMode};
24
25use crate::text::editable_text::{draw_editable_mono_line, EditableTextStyle};
26
27#[cfg(test)]
28use super::text_field_core::apply_edit_action;
29use super::text_field_core::{
30 display_text_for_edit, handle_multi_line_text_event, handle_single_line_text_event,
31 ime_cursor_rect, ime_cursor_rect_multi_line, layout_multi_line_text, layout_single_line_text,
32 multi_line_scrollbar_geometry, paint_committed_single_line_text, paint_multi_line_text,
33 read_display_buffer, reveal_caret_multi_line_from_current_layout, TextFieldEventOptions,
34};
35use crate::scrollbar::{thumb_color_for_state, ScrollbarInteraction, ScrollbarVisualState};
36
37pub type TextInputChangeHandler<A> = std::rc::Rc<dyn Fn(&mut EventCtx<A>, String)>;
51
52#[derive(Debug, Clone, Copy)]
57pub struct TextInputStyle {
74 pub bg: Color,
76 pub border: Color,
78 pub border_focused: Color,
80 pub caret: Color,
82 pub placeholder: Color,
84 pub selection_bg: Color,
86 pub radius: f32,
88 pub pad_x: f32,
90 pub pad_y: f32,
92 pub text: TextStyle,
94 pub caret_w: f32,
96 pub caret_blink_ms: i64,
98}
99
100impl Default for TextInputStyle {
101 fn default() -> Self {
102 Self::from_theme(Theme::default())
103 }
104}
105
106impl TextInputStyle {
107 pub fn from_theme(theme: Theme) -> Self {
119 let palette = theme.palette();
120 let spacing = theme.spacing();
121 Self {
122 bg: palette.surface,
123 border: palette.border,
124 border_focused: palette.focus,
125 caret: palette.text,
126 placeholder: palette.text_muted,
127 selection_bg: palette.accent.with_alpha(0.34),
128 radius: theme.radius().input().tl,
129 pad_x: spacing.md,
130 pad_y: spacing.sm,
131 text: TextStyle::new(FontId::Mono, 14, palette.text),
132 caret_w: 1.0,
133 caret_blink_ms: 500,
134 }
135 }
136}
137
138#[allow(clippy::too_many_arguments)]
139pub fn draw_text_input(
168 rect: Rect,
169 text: &str,
170 caret_byte: usize,
171 selection: Option<Selection>,
172 preedit: Option<&ImePreedit>,
173 focused: bool,
174 now_ms: i64,
175 style: TextInputStyle,
176 text_system: &mut TextSystem,
177) -> Vec<DrawCmd> {
178 let mut out = Vec::new();
179
180 out.push(DrawCmd::RRect(DrawRRect {
181 rect,
182 radius: style.radius,
183 color: style.bg,
184 }));
185 out.push(DrawCmd::Border(DrawBorder {
186 rect,
187 radius: Radius::uniform(style.radius),
188 border: Border::new(
189 1.0,
190 if focused {
191 style.border_focused
192 } else {
193 style.border
194 },
195 ),
196 }));
197
198 let baseline_x = rect.x + style.pad_x;
199 let baseline_y = rect.y + style.pad_y + (style.text.px_size as f32);
200
201 let editable = EditableTextStyle {
202 text: style.text,
203 caret: style.caret,
204 caret_w: style.caret_w,
205 caret_blink_ms: style.caret_blink_ms,
206 selection_bg: Some(style.selection_bg),
207 };
208
209 out.extend(draw_editable_mono_line(
210 baseline_x,
211 baseline_y,
212 text,
213 caret_byte,
214 selection,
215 preedit,
216 focused,
217 now_ms,
218 editable,
219 text_system,
220 ));
221
222 out
223}
224
225pub struct TextInput<A = ()> {
256 pub(crate) layout: LayoutStyle,
258 pub(crate) flex_item: FlexItemStyle,
260 value: Option<Signal<String>>,
262 placeholder: Option<Binding<String>>,
264 style: TextInputStyle,
266 mode: TextInputMode,
268 on_change: Option<TextInputChangeHandler<A>>,
270}
271
272crate::impl_layout_builders!(TextInput);
273
274impl<A: 'static> Default for TextInput<A> {
275 fn default() -> Self {
276 Self::new()
277 }
278}
279
280impl<A: 'static> TextInput<A> {
281 pub fn new() -> Self {
293 Self {
294 layout: LayoutStyle::default(),
295 flex_item: FlexItemStyle::default(),
296 value: None,
297 placeholder: None,
298 style: TextInputStyle::default(),
299 mode: TextInputMode::SingleLine,
300 on_change: None,
301 }
302 }
303
304 pub fn bind(mut self, value: impl Into<Signal<String>>) -> Self {
320 self.value = Some(value.into());
321 self
322 }
323
324 pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
337 self.placeholder = Some(placeholder.into());
338 self
339 }
340
341 pub fn size(mut self, size: f32) -> Self {
355 self.style.text.px_size = size.round().max(1.0) as u16;
356 self
357 }
358
359 pub fn font_family(mut self, font: FontId) -> Self {
370 self.style.text.font = font;
371 self
372 }
373
374 pub fn text_style(mut self, style: TextStyle) -> Self {
388 self.style.text = style;
389 self
390 }
391
392 pub fn input_style(mut self, style: TextInputStyle) -> Self {
402 self.style = style;
403 self
404 }
405
406 pub fn multiline(mut self) -> Self {
419 self.mode = TextInputMode::MultiLine;
420 self
421 }
422
423 pub fn on_change(mut self, f: impl Fn(String) -> A + 'static) -> Self {
437 self.on_change = Some(std::rc::Rc::new(move |ctx, value| ctx.dispatch(f(value))));
438 self
439 }
440
441 pub fn on_change_ctx(mut self, f: impl Fn(&mut EventCtx<A>, String) + 'static) -> Self {
453 self.on_change = Some(std::rc::Rc::new(f));
454 self
455 }
456}
457
458pub struct TextInputWidget<A = ()> {
470 layout: LayoutStyle,
472 value: Signal<String>,
474 buffer: Signal<TextBuffer>,
476 edit: Signal<TextEditState>,
478 display_revision: Signal<u64>,
480 pending_reveal: Signal<bool>,
482 scrollbar_interaction: Signal<ScrollbarInteraction>,
484 pending_scrollbar_interaction:
486 Cell<Option<TransactionalLayoutPending<Option<ScrollbarInteraction>>>>,
487 placeholder: Option<Binding<String>>,
489 style: TextInputStyle,
491 mode: TextInputMode,
493 on_change: Option<TextInputChangeHandler<A>>,
495}
496
497impl<A: 'static> Widget<A> for TextInputWidget<A> {
498 fn debug_name(&self) -> &'static str {
499 "TextInput"
500 }
501
502 fn layout(
503 &self,
504 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
505 ctx: &mut LayoutCtx<'_>,
506 _children: &mut [LayoutChild],
507 constraints: Constraints,
508 ) -> LayoutResult {
509 let _ = self.value.revision();
510 let _ = self.buffer.revision();
511 let _ = self.display_revision.read();
512 let placeholder = self
513 .placeholder
514 .as_ref()
515 .map(|placeholder| placeholder.read());
516 let (size, text_layout) = with_untracked_reads(|| {
517 if self.mode == TextInputMode::MultiLine {
518 layout_multi_line_text(
519 ctx,
520 constraints,
521 self.layout,
522 &self.value,
523 &self.buffer,
524 &self.edit,
525 placeholder,
526 self.style,
527 )
528 } else {
529 layout_single_line_text(
530 ctx,
531 constraints,
532 self.layout,
533 &self.value,
534 &self.buffer,
535 &self.edit,
536 placeholder,
537 self.style,
538 )
539 }
540 });
541
542 let mut result = LayoutResult {
543 size,
544 children: Vec::new(),
545 paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
546 visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
547 overlay_hit_bounds: Vec::new(),
548 clip: None,
549 is_window_root_clip: false,
550 artifact: text_layout.map(LayoutArtifact::Text),
551 };
552 let geometries = with_untracked_reads(|| {
553 if self.mode == TextInputMode::MultiLine {
554 multi_line_scrollbar_geometry(
555 Rect::new(0.0, 0.0, size.w, size.h),
556 &result,
557 &self.value,
558 &self.buffer,
559 &self.edit,
560 self.style,
561 )
562 .into_iter()
563 .collect::<Vec<_>>()
564 } else {
565 Vec::new()
566 }
567 });
568 let mut interaction = with_untracked_reads(|| self.scrollbar_interaction.read());
569 let interaction = interaction
570 .reconcile(ctx.layout_pass(), &geometries)
571 .then_some(interaction);
572 if ctx.layout_pass().is_committed() {
573 self.pending_scrollbar_interaction
574 .set(TransactionalLayoutPending::new(ctx, interaction));
575 }
576 result.overlay_hit_bounds = geometries
577 .iter()
578 .map(|geometry| geometry.hit_track)
579 .collect();
580 result
581 }
582
583 fn layout_committed(&self, ctx: &mut LayoutCtx<'_>, bounds: Rect, layout: &LayoutResult) {
584 if let Some(interaction) = self
585 .pending_scrollbar_interaction
586 .take()
587 .and_then(|pending| pending.into_committed(ctx))
588 .flatten()
589 {
590 self.scrollbar_interaction.set(interaction);
591 }
592 if self.mode != TextInputMode::MultiLine
593 || !with_untracked_reads(|| self.pending_reveal.read())
594 {
595 return;
596 }
597 self.pending_reveal.set(false);
598 with_untracked_reads(|| {
599 let _ = reveal_caret_multi_line_from_current_layout(
600 bounds,
601 layout,
602 &self.value,
603 &self.buffer,
604 &self.edit,
605 self.style,
606 );
607 });
608 }
609
610 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
611 let style = self.style;
612 let focused = ctx.is_focused();
613
614 ctx.push(DrawCmd::RRect(DrawRRect {
615 rect: bounds,
616 radius: style.radius,
617 color: style.bg,
618 }));
619 ctx.push(DrawCmd::Border(DrawBorder {
620 rect: bounds,
621 radius: Radius::uniform(style.radius),
622 border: Border::new(
623 1.0,
624 if focused {
625 style.border_focused
626 } else {
627 style.border
628 },
629 ),
630 }));
631 if self.mode == TextInputMode::MultiLine {
632 let geometry = multi_line_scrollbar_geometry(
633 bounds,
634 layout,
635 &self.value,
636 &self.buffer,
637 &self.edit,
638 style,
639 );
640 let visual = geometry
641 .map(|geometry| {
642 self.scrollbar_interaction
643 .read()
644 .visual_state(geometry.axis, ctx.is_hovered())
645 })
646 .unwrap_or(ScrollbarVisualState::Normal);
647 paint_multi_line_text(
648 ctx,
649 bounds,
650 layout,
651 &self.value,
652 &self.buffer,
653 &self.edit,
654 self.placeholder.as_ref().map(|p| p.read()),
655 style,
656 focused,
657 thumb_color_for_state(style.border.with_alpha(0.62), visual),
658 );
659 } else {
660 paint_committed_single_line_text(
661 ctx,
662 bounds,
663 layout,
664 &self.value,
665 &self.buffer,
666 &self.edit,
667 self.placeholder.as_ref().map(|p| p.read()),
668 style,
669 focused,
670 );
671 }
672 }
673
674 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, layout: &LayoutResult) {
675 if self.mode == TextInputMode::MultiLine && matches!(event, Event::Pointer(_)) {
676 let geometry = multi_line_scrollbar_geometry(
677 bounds,
678 layout,
679 &self.value,
680 &self.buffer,
681 &self.edit,
682 self.style,
683 );
684 let geometries = geometry.into_iter().collect::<Vec<_>>();
685 let edit_state = self.edit.read();
686 let mut interaction = self.scrollbar_interaction.read();
687 let response = interaction.handle_event(ctx, event, &geometries);
688 if response.state_changed {
689 self.scrollbar_interaction.set(interaction);
690 }
691 if let Some((axis, target)) = response.scroll_to {
692 if axis == ScrollbarAxis::Vertical && target != edit_state.scroll_y {
693 let mut next = edit_state;
694 next.scroll_y = target;
695 self.edit.set(next);
696 }
697 }
698 if response.repaint {
699 ctx.request_repaint();
700 }
701 if response.consumed {
702 ctx.stop_propagation();
703 return;
704 }
705 }
706 let before_display = self.composed_display_text();
707 let before = self.value.read();
708 if self.mode == TextInputMode::MultiLine {
709 handle_multi_line_text_event(
710 ctx,
711 event,
712 bounds,
713 layout,
714 &self.value,
715 &self.buffer,
716 &self.edit,
717 &self.pending_reveal,
718 self.style,
719 TextFieldEventOptions::default(),
720 );
721 } else {
722 handle_single_line_text_event(
723 ctx,
724 event,
725 bounds,
726 layout,
727 &self.value,
728 &self.buffer,
729 &self.edit,
730 self.style,
731 TextFieldEventOptions::default(),
732 );
733 }
734 let after = self.value.read();
735 if self.composed_display_text() != before_display {
736 self.display_revision
737 .update(|revision| *revision = revision.wrapping_add(1).max(1));
738 }
739 if after != before {
740 if let Some(on_change) = &self.on_change {
741 on_change(ctx, after);
742 }
743 }
744 }
745
746 fn focus_policy(&self) -> FocusPolicy {
747 FocusPolicy::Focusable
748 }
749
750 fn activation_policy(&self) -> ActivationPolicy {
751 ActivationPolicy::AllowOnFocusOnly
752 }
753
754 fn input_role(&self) -> InputRole {
755 if self.mode == TextInputMode::MultiLine {
756 InputRole::TextMultiLine
757 } else {
758 InputRole::TextSingleLine
759 }
760 }
761
762 fn ime_cursor_rect(&self, bounds: Rect, layout: &LayoutResult) -> Option<Rect> {
763 if self.mode == TextInputMode::MultiLine {
764 ime_cursor_rect_multi_line(
765 bounds,
766 layout,
767 &self.value,
768 &self.buffer,
769 &self.edit,
770 self.style,
771 )
772 } else {
773 ime_cursor_rect(
774 bounds,
775 layout,
776 &self.value,
777 &self.buffer,
778 &self.edit,
779 self.style,
780 )
781 }
782 }
783}
784
785impl<A> TextInputWidget<A> {
786 fn composed_display_text(&self) -> String {
788 with_untracked_reads(|| {
789 let buffer = read_display_buffer(&self.value, &self.buffer);
790 let value = buffer.as_str();
791 let edit = self.edit.read();
792 display_text_for_edit(
793 &value,
794 edit.caret_byte.min(value.len()),
795 edit.preedit.as_ref(),
796 )
797 .0
798 })
799 }
800}
801
802struct TextInputComponent<A> {
804 layout: LayoutStyle,
806 value: Signal<String>,
808 placeholder: Option<Binding<String>>,
810 style: TextInputStyle,
812 mode: TextInputMode,
814 on_change: Option<TextInputChangeHandler<A>>,
816}
817
818impl<A: 'static> ComponentNode<A> for TextInputComponent<A> {
819 fn build(&self, context: &mut Context<A>) -> View<A> {
820 let edit = context.signal_with_invalidation(TextEditState::new(), Invalidation::Paint);
821 let buffer = context.signal_with_invalidation_factory(
822 || with_untracked_reads(|| TextBuffer::from_string(self.value.read())),
823 Invalidation::Paint,
824 );
825 let pending_reveal = context.signal_with_invalidation(false, Invalidation::Paint);
830 let scrollbar_interaction =
831 context.signal_with_invalidation(ScrollbarInteraction::default(), Invalidation::Paint);
832 let display_revision = context.signal_with_invalidation(0_u64, Invalidation::Layout);
833
834 View::leaf(TextInputWidget {
835 layout: self.layout,
836 value: self.value.clone(),
837 buffer,
838 edit,
839 display_revision,
840 pending_reveal,
841 scrollbar_interaction,
842 pending_scrollbar_interaction: Cell::new(None),
843 placeholder: self.placeholder.clone(),
844 style: self.style,
845 mode: self.mode,
846 on_change: self.on_change.clone(),
847 })
848 }
849}
850
851impl<A: 'static> IntoView<A> for TextInput<A> {
852 fn into_view(self) -> View<A> {
853 let value = self
854 .value
855 .expect("TextInput::bind(...) is required for now");
856
857 finish_view_sized(
858 View::component(TextInputComponent {
859 layout: self.layout,
860 value,
861 placeholder: self.placeholder,
862 style: self.style,
863 mode: self.mode,
864 on_change: self.on_change,
865 }),
866 self.flex_item,
867 LayoutSizeHint::from_layout(self.layout),
868 )
869 }
870}
871
872#[cfg(test)]
873mod tests {
874 use super::*;
878 use ailloli_ui_core::ElementId;
879 use ailloli_ui_runtime::app::RuntimeHandle;
880 use std::cell::RefCell;
881 use std::rc::Rc;
882
883 fn signal<T: 'static>(value: T) -> Signal<T> {
885 Signal::new(Rc::new(RefCell::new(value)), Rc::new(|| {}))
886 }
887
888 fn widget_with_value(value: &str) -> TextInputWidget {
890 TextInputWidget {
891 layout: LayoutStyle::default(),
892 value: signal(value.to_string()),
893 buffer: signal(TextBuffer::from_string(value.to_string())),
894 edit: signal(TextEditState::new()),
895 display_revision: signal(0),
896 pending_reveal: signal(false),
897 scrollbar_interaction: signal(ScrollbarInteraction::default()),
898 pending_scrollbar_interaction: Cell::new(None),
899 placeholder: None,
900 style: TextInputStyle {
901 text: TextStyle::new(FontId::Mono, 14, Color::new(1.0, 1.0, 1.0, 1.0)),
902 ..TextInputStyle::default()
903 },
904 mode: TextInputMode::SingleLine,
905 on_change: None,
906 }
907 }
908
909 #[test]
910 fn display_text_for_edit_inserts_preedit_without_mutating_text() {
911 let preedit = ImePreedit::new("é");
912 let (display, caret) = display_text_for_edit("caf", 3, Some(&preedit));
913
914 assert_eq!(display, "café");
915 assert_eq!(caret, "café".len());
916 }
917
918 #[test]
919 fn text_input_ime_cursor_uses_layout_artifact() {
920 let widget = widget_with_value("hello");
921 let mut ts = TextSystem::new();
922 let handle = ts.layout_cached(TextLayoutParams {
923 text: "hello",
924 style: widget.style.text,
925 max_width: Some(200.0),
926 wrap_mode: WrapMode::NoWrap,
927 });
928 let layout = LayoutResult {
929 size: Size::new(200.0, 40.0),
930 children: Vec::new(),
931 paint_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
932 visual_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
933 overlay_hit_bounds: Vec::new(),
934 clip: None,
935 is_window_root_clip: false,
936 artifact: Some(LayoutArtifact::Text(handle)),
937 };
938
939 let rect = <TextInputWidget as Widget<()>>::ime_cursor_rect(
940 &widget,
941 Rect::new(0.0, 0.0, 200.0, 40.0),
942 &layout,
943 )
944 .expect("ime cursor rect");
945
946 assert!(rect.h > 0.0);
947 }
948
949 #[test]
950 fn text_input_paint_skips_a_mismatched_committed_artifact() {
951 let widget = widget_with_value("fresh");
952 let mut text_system = TextSystem::new();
953 let stale = text_system.layout_cached(TextLayoutParams {
954 text: "stale",
955 style: widget.style.text,
956 max_width: Some(200.0),
957 wrap_mode: WrapMode::NoWrap,
958 });
959 let layout = LayoutResult {
960 size: Size::new(200.0, 40.0),
961 children: Vec::new(),
962 paint_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
963 visual_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
964 overlay_hit_bounds: Vec::new(),
965 clip: None,
966 is_window_root_clip: false,
967 artifact: Some(LayoutArtifact::Text(stale)),
968 };
969 let mut paint = PaintCtx::with_text_system(&mut text_system);
970
971 <TextInputWidget as Widget<()>>::paint(
972 &widget,
973 &mut paint,
974 Rect::new(0.0, 0.0, 200.0, 40.0),
975 &layout,
976 );
977
978 assert!(paint.layers.iter().all(|layer| {
979 layer
980 .cmds
981 .iter()
982 .all(|cmd| !matches!(cmd, DrawCmd::Text(_)))
983 }));
984 }
985
986 #[test]
987 fn text_input_edit_updates_persistent_buffer_and_public_string() {
988 let widget = widget_with_value("a");
989 let runtime = RuntimeHandle::<()>::new();
990 let mut ctx = EventCtx::new(runtime, ElementId(1));
991 let layout = LayoutResult {
992 size: Size::new(200.0, 40.0),
993 children: Vec::new(),
994 paint_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
995 visual_bounds: Rect::new(0.0, 0.0, 200.0, 40.0),
996 overlay_hit_bounds: Vec::new(),
997 clip: None,
998 is_window_root_clip: false,
999 artifact: None,
1000 };
1001
1002 apply_edit_action(
1003 &mut ctx,
1004 &widget.value,
1005 &widget.buffer,
1006 &widget.edit,
1007 TextEditAction::InsertText {
1008 text: "!".to_string(),
1009 },
1010 Rect::new(0.0, 0.0, 200.0, 40.0),
1011 &layout,
1012 widget.style,
1013 );
1014
1015 assert_eq!(widget.buffer.read().as_str(), "!a");
1016 assert_eq!(widget.value.read(), "!a");
1017 }
1018}