ailloli_ui_widgets/text/
editable_text.rs

1//! Immediate-mode shaping and painting for one editable monospace line.
2
3use ailloli_ui_core::event::ImePreedit;
4use ailloli_ui_core::{Color, Rect, TextStyle};
5use ailloli_ui_runtime::input::Selection;
6use ailloli_ui_runtime::{DrawCmd, DrawRect, DrawText};
7use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
8
9#[derive(Debug, Clone, Copy)]
10/// Colors, metrics, and blink cadence for [`draw_editable_mono_line`].
11///
12/// Widths are logical pixels and `caret_blink_ms` is milliseconds per visible
13/// or hidden half-period. A non-positive blink value suppresses the caret.
14///
15/// # Examples
16///
17/// ```
18/// use ailloli_ui_widgets::text::EditableTextStyle;
19/// let style = EditableTextStyle::default();
20/// assert_eq!(style.caret_w, 1.0);
21/// assert_eq!(style.caret_blink_ms, 500);
22/// assert!(style.selection_bg.is_some());
23/// ```
24pub struct EditableTextStyle {
25    /// Glyph font, size in integer logical pixels, color, and decoration.
26    pub text: TextStyle,
27    /// Caret fill color.
28    pub caret: Color,
29    /// Caret width in logical pixels; not clamped by the draw helper.
30    pub caret_w: f32,
31    /// Milliseconds per blink half-period; non-positive disables the caret.
32    pub caret_blink_ms: i64,
33    /// Optional selection fill; `None` suppresses selection painting.
34    pub selection_bg: Option<Color>,
35}
36
37/// Supplies a 15-pixel mono style, one-pixel caret, and 500 ms blink cadence.
38impl Default for EditableTextStyle {
39    fn default() -> Self {
40        Self {
41            text: TextStyle::new(
42                ailloli_ui_core::FontId::Mono,
43                15,
44                Color::rgba(243, 246, 251, 1.0),
45            ),
46            caret: Color::rgba(243, 246, 251, 1.0),
47            caret_w: 1.0,
48            caret_blink_ms: 500,
49            selection_bg: Some(Color::rgba(37, 99, 235, 0.35)),
50        }
51    }
52}
53
54/// Inserts optional preedit text into an owned display string and maps its caret.
55///
56/// Byte offsets are length-clamped but must already be UTF-8 character
57/// boundaries; `String::insert_str` panics otherwise.
58fn layout_string_for_edit(
59    text: &str,
60    caret_byte: usize,
61    preedit: Option<&ImePreedit>,
62) -> (String, usize) {
63    match preedit {
64        None => (text.to_string(), caret_byte.min(text.len())),
65        Some(p) => {
66            let mut s = text.to_string();
67            let at = caret_byte.min(s.len());
68            if !p.text.is_empty() {
69                s.insert_str(at, &p.text);
70            }
71            let caret_in_display = if let Some((a, b)) = p.selection {
72                at + a.max(b).min(p.text.len())
73            } else {
74                at + p.text.len()
75            };
76            let len = s.len();
77            (s, caret_in_display.min(len))
78        }
79    }
80}
81
82/// Single-line editable text; baseline Y = `baseline_y` (see `DrawText.pos[1]`).
83///
84/// Paint order: selection background (optional) → glyphs → caret.
85/// Byte offsets use UTF-8 bytes and must be character boundaries when preedit
86/// insertion occurs. Selection is intentionally hidden during preedit. The
87/// function allocates a display string and returns newly owned draw commands.
88///
89/// # Panics
90///
91/// Panics when a non-empty preedit is inserted at a clamped `caret_byte` that
92/// is not a UTF-8 character boundary.
93///
94/// # Examples
95///
96/// ```
97/// use ailloli_ui_widgets::text::{draw_editable_mono_line, EditableTextStyle};
98/// use ailloli_ui_text::TextSystem;
99/// let mut text_system = TextSystem::new();
100/// let commands = draw_editable_mono_line(
101///     4.0, 18.0, "hello", 5, None, None, false, 0,
102///     EditableTextStyle::default(), &mut text_system,
103/// );
104/// assert_eq!(commands.len(), 1); // glyph command; unfocused means no caret
105/// ```
106#[allow(clippy::too_many_arguments)]
107pub fn draw_editable_mono_line(
108    baseline_x: f32,
109    baseline_y: f32,
110    text: &str,
111    caret_byte: usize,
112    selection: Option<Selection>,
113    preedit: Option<&ImePreedit>,
114    focused: bool,
115    now_ms: i64,
116    style: EditableTextStyle,
117    text_system: &mut TextSystem,
118) -> Vec<DrawCmd> {
119    let mut out = Vec::new();
120    let (display, caret_in_display) = layout_string_for_edit(text, caret_byte, preedit);
121
122    let laid = text_system.layout_cached(TextLayoutParams {
123        text: display.as_str(),
124        style: style.text,
125        max_width: None,
126        wrap_mode: WrapMode::NoWrap,
127    });
128
129    let px = style.text.px_size as f32;
130    let y_top = (baseline_y - px).round();
131
132    let caret_x = (baseline_x + laid.caret_x_at(caret_in_display)).round();
133
134    if preedit.is_none() {
135        if let Some(sel) = selection {
136            if !sel.is_collapsed() {
137                if let Some(bg) = style.selection_bg {
138                    let (lo, hi) = sel.normalized();
139                    let lo = lo.min(display.len());
140                    let hi = hi.min(display.len());
141                    let x0 = (baseline_x + laid.caret_x_at(lo)).round();
142                    let x1 = (baseline_x + laid.caret_x_at(hi)).round();
143                    let w = (x1 - x0).max(1.0);
144                    out.push(DrawCmd::Rect(DrawRect {
145                        rect: Rect::new(x0, y_top, w, px + 2.0),
146                        color: bg,
147                    }));
148                }
149            }
150        }
151    }
152
153    out.push(DrawCmd::Text(DrawText {
154        pos: [baseline_x, baseline_y],
155        color: style.text.color,
156        decoration: ailloli_ui_core::TextDecoration::None,
157        layout: laid,
158    }));
159
160    if focused && style.caret_blink_ms > 0 {
161        let on = ((now_ms / style.caret_blink_ms) % 2) == 0;
162        if on {
163            out.push(DrawCmd::Rect(DrawRect {
164                rect: Rect::new(caret_x, y_top, style.caret_w, px + 2.0),
165                color: style.caret,
166            }));
167        }
168    }
169
170    out
171}