ailloli_ui_widgets/controls/
text_input.rs

1//! Single- and multi-line editable text widgets plus a legacy draw helper.
2
3use 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
37/// Shared callback receiving a complete owned value after an edit changes text.
38///
39/// It is not called for caret, selection, scroll, or preedit-only changes. The
40/// callback is synchronous and may dispatch zero or more application actions.
41///
42/// # Examples
43///
44/// ```
45/// use std::rc::Rc;
46/// use ailloli_ui_widgets::controls::text_input::TextInputChangeHandler;
47/// let handler: TextInputChangeHandler<()> = Rc::new(|ctx, _value| ctx.request_repaint());
48/// let _ = handler;
49/// ```
50pub type TextInputChangeHandler<A> = std::rc::Rc<dyn Fn(&mut EventCtx<A>, String)>;
51
52// -----------------------------------------------------------------------------
53// Legacy draw API (used by current app_ui). Kept for compatibility.
54// -----------------------------------------------------------------------------
55
56#[derive(Debug, Clone, Copy)]
57/// Colors, typography, logical-pixel metrics, and caret cadence for text input.
58///
59/// `caret_blink_ms` is one visible or hidden half-period in milliseconds; a
60/// non-positive value suppresses the caret. The legacy [`draw_text_input`]
61/// cannot display `placeholder` because it has no placeholder argument, while
62/// [`TextInput`] uses it when its bound value and IME preedit are empty.
63///
64/// # Examples
65///
66/// ```
67/// use ailloli_ui_core::Theme;
68/// use ailloli_ui_widgets::controls::TextInputStyle;
69/// let style = TextInputStyle::from_theme(Theme::dark());
70/// assert_eq!(style.text.px_size, 14);
71/// assert_eq!(style.caret_blink_ms, 500);
72/// ```
73pub struct TextInputStyle {
74    /// Input background fill.
75    pub bg: Color,
76    /// Unfocused one-pixel border color.
77    pub border: Color,
78    /// Focused one-pixel border color.
79    pub border_focused: Color,
80    /// Caret fill color.
81    pub caret: Color,
82    /// Placeholder glyph color used by the retained widget.
83    pub placeholder: Color,
84    /// Selection background color, hidden during IME preedit.
85    pub selection_bg: Color,
86    /// Uniform corner radius in logical pixels.
87    pub radius: f32,
88    /// Horizontal content inset in logical pixels.
89    pub pad_x: f32,
90    /// Vertical content inset in logical pixels.
91    pub pad_y: f32,
92    /// Editable text font, integer logical-pixel size, color, and decoration.
93    pub text: TextStyle,
94    /// Caret width in logical pixels.
95    pub caret_w: f32,
96    /// Blink half-period in milliseconds; non-positive disables the caret.
97    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    /// Resolves input colors, spacing, radius, and mono typography from `theme`.
108    ///
109    /// # Examples
110    ///
111    /// ```
112    /// use ailloli_ui_core::{FontId, Theme};
113    /// use ailloli_ui_widgets::controls::TextInputStyle;
114    /// let style = TextInputStyle::from_theme(Theme::dark());
115    /// assert_eq!(style.text.font, FontId::Mono);
116    /// assert_eq!(style.caret_w, 1.0);
117    /// ```
118    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)]
139/// Draws one legacy single-line text input into newly owned commands.
140///
141/// Paint order is background, border, optional selection, glyphs, then optional
142/// caret. `caret_byte` and [`Selection`] offsets use UTF-8 bytes and are
143/// length-clamped. Selection is omitted during IME preedit. A focused caret is
144/// visible on even `now_ms / caret_blink_ms` half-periods; non-positive cadence
145/// suppresses it. This helper does not clip horizontally or draw placeholder
146/// text and performs no event handling.
147///
148/// # Panics
149///
150/// Panics when a non-empty preedit is inserted at a clamped `caret_byte` that
151/// is not a UTF-8 character boundary.
152///
153/// # Examples
154///
155/// ```
156/// use ailloli_ui_core::Rect;
157/// use ailloli_ui_text::TextSystem;
158/// use ailloli_ui_widgets::controls::text_input::draw_text_input;
159/// use ailloli_ui_widgets::controls::TextInputStyle;
160/// let mut text = TextSystem::new();
161/// let commands = draw_text_input(
162///     Rect::new(0.0, 0.0, 200.0, 36.0), "hello", 5, None, None,
163///     false, 0, TextInputStyle::default(), &mut text,
164/// );
165/// assert_eq!(commands.len(), 3); // background, border, glyphs
166/// ```
167pub 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
225// -----------------------------------------------------------------------------
226// Widget API (ailloli_ui_runtime View/Widget)
227// -----------------------------------------------------------------------------
228
229/// Editable text field with focus, selection, IME, scrolling, and buffer backing.
230///
231/// The default mode is single-line; [`Self::multiline`] enables word-or-anywhere
232/// wrapping and two-axis caret reveal. The widget is always focusable and must
233/// be attached to a writable [`Signal<String>`] with [`Self::bind`]. External
234/// signal changes take precedence and are synchronized into the edit buffer on
235/// the next edit. Placeholder bindings never become the editable value.
236/// Single-line inputs accept native horizontal wheel deltas and `Shift` plus a
237/// vertical wheel delta. Multiline inputs expose an interactive overlay thumb
238/// that supports centered track clicks and captured dragging without moving the caret or
239/// invoking the change callback.
240///
241/// # Panics
242///
243/// Converting the builder into a view panics if [`Self::bind`] was not called.
244///
245/// # Examples
246///
247/// ```
248/// use std::{cell::RefCell, rc::Rc};
249/// use ailloli_ui_runtime::component::Signal;
250/// use ailloli_ui_widgets::controls::TextInput;
251/// let value = Signal::new(Rc::new(RefCell::new(String::new())), Rc::new(|| {}));
252/// let input: TextInput<()> = TextInput::new().bind(value).placeholder("Name");
253/// let _ = input;
254/// ```
255pub struct TextInput<A = ()> {
256    /// Layout configuration used to resolve intrinsic text geometry.
257    pub(crate) layout: LayoutStyle,
258    /// Flex-item behavior used by the parent layout.
259    pub(crate) flex_item: FlexItemStyle,
260    /// Required writable public string value.
261    value: Option<Signal<String>>,
262    /// Optional static or reactive placeholder.
263    placeholder: Option<Binding<String>>,
264    /// Resolved paint and text metrics.
265    style: TextInputStyle,
266    /// Single-line or multi-line editing/keymap mode.
267    mode: TextInputMode,
268    /// Optional callback receiving changed complete text.
269    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    /// Creates an unbound, single-line input with the default style.
282    ///
283    /// The builder cannot become a view until [`Self::bind`] supplies its value.
284    ///
285    /// # Examples
286    ///
287    /// ```
288    /// use ailloli_ui_widgets::controls::TextInput;
289    /// let input: TextInput<()> = TextInput::new();
290    /// let _ = input; // bind before converting into a view
291    /// ```
292    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    /// Sets the required writable string signal, replacing any previous one.
305    ///
306    /// User edits update both the persistent [`TextBuffer`] and this signal
307    /// before the optional change callback runs.
308    ///
309    /// # Examples
310    ///
311    /// ```
312    /// use std::{cell::RefCell, rc::Rc};
313    /// use ailloli_ui_runtime::component::Signal;
314    /// use ailloli_ui_widgets::controls::TextInput;
315    /// let value = Signal::new(Rc::new(RefCell::new("Ada".to_string())), Rc::new(|| {}));
316    /// let input: TextInput<()> = TextInput::new().bind(value);
317    /// let _ = input;
318    /// ```
319    pub fn bind(mut self, value: impl Into<Signal<String>>) -> Self {
320        self.value = Some(value.into());
321        self
322    }
323
324    /// Sets static or reactive placeholder text.
325    ///
326    /// It is displayed only when both the bound value and active IME preedit
327    /// are empty. An empty placeholder remains present but paints no glyphs.
328    ///
329    /// # Examples
330    ///
331    /// ```
332    /// use ailloli_ui_widgets::controls::TextInput;
333    /// let input: TextInput<()> = TextInput::new().placeholder("Search");
334    /// let _ = input;
335    /// ```
336    pub fn placeholder(mut self, placeholder: impl Into<Binding<String>>) -> Self {
337        self.placeholder = Some(placeholder.into());
338        self
339    }
340
341    /// Sets text size from a floating logical-pixel value.
342    ///
343    /// The value is rounded, clamped to at least `1`, then saturated to `u16`;
344    /// `NaN` and negative infinity therefore become `1`, while positive
345    /// infinity becomes `u16::MAX`.
346    ///
347    /// # Examples
348    ///
349    /// ```
350    /// use ailloli_ui_widgets::controls::TextInput;
351    /// let input: TextInput<()> = TextInput::new().size(15.6);
352    /// let _ = input; // resolved text size is 16 logical pixels
353    /// ```
354    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    /// Replaces only the editable text font identifier.
360    ///
361    /// # Examples
362    ///
363    /// ```
364    /// use ailloli_ui_core::FontId;
365    /// use ailloli_ui_widgets::controls::TextInput;
366    /// let input: TextInput<()> = TextInput::new().font_family(FontId::Ui);
367    /// let _ = input;
368    /// ```
369    pub fn font_family(mut self, font: FontId) -> Self {
370        self.style.text.font = font;
371        self
372    }
373
374    /// Replaces the complete editable text style.
375    ///
376    /// Placeholder and selection colors remain in [`TextInputStyle`].
377    ///
378    /// # Examples
379    ///
380    /// ```
381    /// use ailloli_ui_core::{Color, FontId, TextStyle};
382    /// use ailloli_ui_widgets::controls::TextInput;
383    /// let input: TextInput<()> =
384    ///     TextInput::new().text_style(TextStyle::new(FontId::Ui, 16, Color::WHITE));
385    /// let _ = input;
386    /// ```
387    pub fn text_style(mut self, style: TextStyle) -> Self {
388        self.style.text = style;
389        self
390    }
391
392    /// Replaces every paint, spacing, typography, and caret style value.
393    ///
394    /// # Examples
395    ///
396    /// ```
397    /// use ailloli_ui_widgets::controls::{TextInput, TextInputStyle};
398    /// let input: TextInput<()> = TextInput::new().input_style(TextInputStyle::default());
399    /// let _ = input;
400    /// ```
401    pub fn input_style(mut self, style: TextInputStyle) -> Self {
402        self.style = style;
403        self
404    }
405
406    /// Enables multi-line key handling, wrapping, scrolling, and IME geometry.
407    ///
408    /// The builder has no inverse; create a new input to return to single-line
409    /// mode. Height remains layout-driven and may grow from wrapped content.
410    ///
411    /// # Examples
412    ///
413    /// ```
414    /// use ailloli_ui_widgets::controls::TextInput;
415    /// let input: TextInput<()> = TextInput::new().multiline();
416    /// let _ = input;
417    /// ```
418    pub fn multiline(mut self) -> Self {
419        self.mode = TextInputMode::MultiLine;
420        self
421    }
422
423    /// Maps each changed complete value to an application action and dispatches it.
424    ///
425    /// The callback is not invoked for selection, caret, scrolling, or
426    /// preedit-only changes. A later change-handler builder replaces it.
427    ///
428    /// # Examples
429    ///
430    /// ```
431    /// use ailloli_ui_widgets::controls::TextInput;
432    /// enum Action { Changed(String) }
433    /// let input = TextInput::new().on_change(Action::Changed);
434    /// let _ = input;
435    /// ```
436    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    /// Installs a context-aware callback for changed complete values.
442    ///
443    /// A later change-handler builder replaces it.
444    ///
445    /// # Examples
446    ///
447    /// ```
448    /// use ailloli_ui_widgets::controls::TextInput;
449    /// let input = TextInput::<()>::new().on_change_ctx(|ctx, _value| ctx.request_repaint());
450    /// let _ = input;
451    /// ```
452    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
458/// Retained text-field leaf created internally by [`TextInput`].
459///
460/// Its stateful fields are intentionally private; public code should construct
461/// [`TextInput`] instead. The type remains nameable for widget diagnostics.
462///
463/// # Examples
464///
465/// ```
466/// use ailloli_ui_widgets::controls::text_input::TextInputWidget;
467/// assert!(std::any::type_name::<TextInputWidget<()>>().ends_with("TextInputWidget"));
468/// ```
469pub struct TextInputWidget<A = ()> {
470    /// Layout copied from the public builder.
471    layout: LayoutStyle,
472    /// Public string signal shared with the consumer.
473    value: Signal<String>,
474    /// Persistent editing buffer synchronized against `value`.
475    buffer: Signal<TextBuffer>,
476    /// Caret, selection, IME, drag, and scroll state.
477    edit: Signal<TextEditState>,
478    /// Revision of the composed value/preedit text that can change shaping.
479    display_revision: Signal<u64>,
480    /// Requests a post-layout multi-line caret reveal when no artifact existed.
481    pending_reveal: Signal<bool>,
482    /// Retained hover and captured multiline scrollbar gesture.
483    scrollbar_interaction: Signal<ScrollbarInteraction>,
484    /// Geometry-derived interaction cleanup staged for the active layout attempt.
485    pending_scrollbar_interaction:
486        Cell<Option<TransactionalLayoutPending<Option<ScrollbarInteraction>>>>,
487    /// Optional reactive placeholder.
488    placeholder: Option<Binding<String>>,
489    /// Paint, spacing, and text metrics.
490    style: TextInputStyle,
491    /// Keymap, wrapping, and scrolling mode.
492    mode: TextInputMode,
493    /// Optional changed-text callback.
494    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    /// Returns the exact value plus preedit string currently presented by paint.
787    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
802/// Component properties used to allocate persistent edit and buffer signals.
803struct TextInputComponent<A> {
804    /// Outer logical sizing policy.
805    layout: LayoutStyle,
806    /// Caller-owned UTF-8 text value.
807    value: Signal<String>,
808    /// Optional reactive placeholder for an empty value.
809    placeholder: Option<Binding<String>>,
810    /// Text, border, caret, and selection styling.
811    style: TextInputStyle,
812    /// Single-line or multiline input behavior.
813    mode: TextInputMode,
814    /// Optional callback receiving text after a committed change.
815    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        // This is administrative post-layout work, not a geometry input. Event
826        // paths explicitly request layout when they arm it; clearing it after a
827        // successful commit only needs the paint requested by the resulting
828        // scroll-state update.
829        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    //! Scenarios for IME display composition, layout-derived IME geometry, and
875    //! synchronization of persistent edit buffers with the public string signal.
876
877    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    /// Creates a deterministic signal whose invalidation callback is a no-op.
884    fn signal<T: 'static>(value: T) -> Signal<T> {
885        Signal::new(Rc::new(RefCell::new(value)), Rc::new(|| {}))
886    }
887
888    /// Builds a single-line retained widget with synchronized value and buffer.
889    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}