1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use super::*;
impl Context {
/// Render a single-line text input. Auto-handles cursor, typing, and backspace.
///
/// The widget claims focus via [`Context::register_focusable`]. When focused,
/// it consumes character, backspace, arrow, Home, and End key events.
///
/// # Example
///
/// ```no_run
/// # use slt::widgets::TextInputState;
/// # slt::run(|ui: &mut slt::Context| {
/// let mut input = TextInputState::with_placeholder("Search...");
/// ui.text_input(&mut input);
/// // input.value holds the current text
/// # });
/// ```
pub fn text_input(&mut self, state: &mut TextInputState) -> Response {
let colors = self.widget_theme.text_input;
self.text_input_colored(state, &colors)
}
/// Render a text input with custom widget colors.
pub fn text_input_colored(
&mut self,
state: &mut TextInputState,
colors: &WidgetColors,
) -> Response {
slt_assert(
!state.value.contains('\n'),
"text_input got a newline — use textarea instead",
);
let focused = self.register_focusable();
let old_value = state.value.clone();
state.cursor = state.cursor.min(state.value.chars().count());
if focused {
let mut consumed_indices = Vec::new();
// Hoist matched_suggestions out of the loop and recompute only
// after a mutation key (Char/Backspace/Delete) sets the dirty flag.
// A 10-key burst with one mutation: 10 calls -> 2 calls.
let compute_matched = |state: &TextInputState| -> Vec<String> {
if state.show_suggestions {
state
.matched_suggestions()
.into_iter()
.map(str::to_string)
.collect()
} else {
Vec::new()
}
};
let mut matched_suggestions = compute_matched(state);
let mut suggestions_dirty = false;
for (i, key) in self.available_key_presses() {
if suggestions_dirty {
matched_suggestions = compute_matched(state);
suggestions_dirty = false;
}
let suggestions_visible = !matched_suggestions.is_empty();
if suggestions_visible {
state.suggestion_index = state
.suggestion_index
.min(matched_suggestions.len().saturating_sub(1));
}
match key.code {
KeyCode::Up if suggestions_visible => {
state.suggestion_index = state.suggestion_index.saturating_sub(1);
consumed_indices.push(i);
}
KeyCode::Down if suggestions_visible => {
state.suggestion_index = (state.suggestion_index + 1)
.min(matched_suggestions.len().saturating_sub(1));
consumed_indices.push(i);
}
KeyCode::Esc if state.show_suggestions => {
state.show_suggestions = false;
state.suggestion_index = 0;
consumed_indices.push(i);
}
KeyCode::Tab if suggestions_visible => {
if let Some(selected) = matched_suggestions
.get(state.suggestion_index)
.or_else(|| matched_suggestions.first())
{
state.value = selected.clone();
state.cursor = state.value.chars().count();
state.show_suggestions = false;
state.suggestion_index = 0;
}
consumed_indices.push(i);
}
KeyCode::Char(ch) => {
if let Some(max) = state.max_length {
if state.value.chars().count() >= max {
continue;
}
}
let index = byte_index_for_char(&state.value, state.cursor);
state.value.insert(index, ch);
state.cursor += 1;
if !state.suggestions.is_empty() {
state.show_suggestions = true;
state.suggestion_index = 0;
}
suggestions_dirty = true;
consumed_indices.push(i);
}
KeyCode::Backspace => {
if state.cursor > 0 {
let start = byte_index_for_char(&state.value, state.cursor - 1);
let end = byte_index_for_char(&state.value, state.cursor);
state.value.replace_range(start..end, "");
state.cursor -= 1;
}
if !state.suggestions.is_empty() {
state.show_suggestions = true;
state.suggestion_index = 0;
}
suggestions_dirty = true;
consumed_indices.push(i);
}
KeyCode::Left => {
state.cursor = state.cursor.saturating_sub(1);
consumed_indices.push(i);
}
KeyCode::Right => {
state.cursor = (state.cursor + 1).min(state.value.chars().count());
consumed_indices.push(i);
}
KeyCode::Home => {
state.cursor = 0;
consumed_indices.push(i);
}
KeyCode::Delete => {
let len = state.value.chars().count();
if state.cursor < len {
let start = byte_index_for_char(&state.value, state.cursor);
let end = byte_index_for_char(&state.value, state.cursor + 1);
state.value.replace_range(start..end, "");
}
if !state.suggestions.is_empty() {
state.show_suggestions = true;
state.suggestion_index = 0;
}
suggestions_dirty = true;
consumed_indices.push(i);
}
KeyCode::End => {
state.cursor = state.value.chars().count();
consumed_indices.push(i);
}
_ => {}
}
}
for (i, text) in self.available_pastes() {
// Cache char count once and update incrementally — insert is
// O(1) amortized per char, so recomputing via `chars().count()`
// inside the loop would be O(n²) on large pastes.
let mut char_count = state.value.chars().count();
for ch in text.chars() {
// text_input is single-line; drop newlines, tabs, control
// chars, and other bytes that would corrupt rendering or
// trip the no-newline invariant upstream.
if (ch as u32) < 0x20 || ch == '\u{7f}' {
continue;
}
if let Some(max) = state.max_length {
if char_count >= max {
break;
}
}
let index = byte_index_for_char(&state.value, state.cursor);
state.value.insert(index, ch);
state.cursor += 1;
char_count += 1;
}
if !state.suggestions.is_empty() {
state.show_suggestions = true;
state.suggestion_index = 0;
}
suggestions_dirty = true;
consumed_indices.push(i);
}
// Suppress unused-assignment warning when no key after last paste.
let _ = suggestions_dirty;
self.consume_indices(consumed_indices);
}
if state.value.is_empty() {
state.show_suggestions = false;
state.suggestion_index = 0;
}
let matched_suggestions = if state.show_suggestions {
state
.matched_suggestions()
.into_iter()
.map(str::to_string)
.collect::<Vec<String>>()
} else {
Vec::new()
};
if !matched_suggestions.is_empty() {
state.suggestion_index = state
.suggestion_index
.min(matched_suggestions.len().saturating_sub(1));
}
let visible_width = self.area_width.saturating_sub(4) as usize;
let (input_text, cursor_offset) = if state.value.is_empty() {
if state.placeholder.len() > 100 {
slt_warn(
"text_input placeholder is very long (>100 chars) — consider shortening it",
);
}
let mut ph = state.placeholder.clone();
if focused {
ph.insert(0, '▎');
(ph, Some(0))
} else {
(ph, None)
}
} else {
let chars: Vec<char> = state.value.chars().collect();
let display_chars: Vec<char> = if state.masked {
vec!['•'; chars.len()]
} else {
chars.clone()
};
let cursor_display_pos: usize = display_chars[..state.cursor.min(display_chars.len())]
.iter()
.map(|c| UnicodeWidthChar::width(*c).unwrap_or(1))
.sum();
let scroll_offset = if cursor_display_pos >= visible_width {
cursor_display_pos - visible_width + 1
} else {
0
};
let mut rendered = String::new();
let mut cursor_offset = None;
let mut current_width: usize = 0;
for (idx, &ch) in display_chars.iter().enumerate() {
let cw = UnicodeWidthChar::width(ch).unwrap_or(1);
if current_width + cw <= scroll_offset {
current_width += cw;
continue;
}
if current_width - scroll_offset >= visible_width {
break;
}
if focused && idx == state.cursor {
cursor_offset = Some(rendered.chars().count());
rendered.push('▎');
}
rendered.push(ch);
current_width += cw;
}
if focused && state.cursor >= display_chars.len() {
cursor_offset = Some(rendered.chars().count());
rendered.push('▎');
}
(rendered, cursor_offset)
};
let input_style = if state.value.is_empty() && !focused {
Style::new()
.dim()
.fg(colors.fg.unwrap_or(self.theme.text_dim))
} else {
Style::new().fg(colors.fg.unwrap_or(self.theme.text))
};
let border_color = if focused {
colors.accent.unwrap_or(self.theme.primary)
} else if state.validation_error.is_some() {
colors.accent.unwrap_or(self.theme.error)
} else {
colors.border.unwrap_or(self.theme.border)
};
let mut response = self
.bordered(Border::Rounded)
.border_style(Style::new().fg(border_color))
.px(1)
.col(|ui| {
ui.styled_with_cursor(input_text, input_style, cursor_offset);
});
response.focused = focused;
response.changed = state.value != old_value;
let errors = state.errors();
if !errors.is_empty() {
for error in errors {
let mut warning = String::with_capacity(2 + error.len());
warning.push_str("⚠ ");
warning.push_str(error);
self.styled(
warning,
Style::new()
.dim()
.fg(colors.accent.unwrap_or(self.theme.error)),
);
}
} else if let Some(error) = state.validation_error.clone() {
let mut warning = String::with_capacity(2 + error.len());
warning.push_str("⚠ ");
warning.push_str(&error);
self.styled(
warning,
Style::new()
.dim()
.fg(colors.accent.unwrap_or(self.theme.error)),
);
}
if state.show_suggestions && !matched_suggestions.is_empty() {
let start = state.suggestion_index.saturating_sub(4);
let end = (start + 5).min(matched_suggestions.len());
let suggestion_border = colors.border.unwrap_or(self.theme.border);
let _ = self
.bordered(Border::Rounded)
.border_style(Style::new().fg(suggestion_border))
.px(1)
.col(|ui| {
for (idx, suggestion) in matched_suggestions[start..end].iter().enumerate() {
let actual_idx = start + idx;
if actual_idx == state.suggestion_index {
ui.styled(
suggestion.clone(),
Style::new()
.bg(colors.accent.unwrap_or(ui.theme().selected_bg))
.fg(colors.fg.unwrap_or(ui.theme().selected_fg)),
);
} else {
ui.styled(
suggestion.clone(),
Style::new().fg(colors.fg.unwrap_or(ui.theme().text)),
);
}
}
});
}
response
}
}