mkui 0.1.0

A minimalist, typography-driven TUI library with Kitty graphics support
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Text input component with cursor and editing support
//!
//! Provides a reusable text input with:
//! - Cursor positioning and movement
//! - Basic editing (insert, delete, backspace)
//! - Navigation (home, end, left, right, word jumps)
//! - Submission handling (enter key)
//! - Optional prompt prefix

use crate::component::Component;
use crate::context::RenderContext;
use crate::event::{Event, EventHandler, Key};
use crate::layout::Rect;
use crate::render::Renderer;
use anyhow::Result;

/// Text input submission callback type
pub type OnSubmit = Box<dyn FnMut(&str)>;

/// Text input component
pub struct TextInput {
    /// Input buffer
    buffer: String,
    /// Cursor position (byte offset)
    cursor: usize,
    /// Prompt text displayed before input
    prompt: String,
    /// Style for the prompt (ANSI codes)
    prompt_style: String,
    /// Style for the input text (ANSI codes)
    input_style: String,
    /// Style for cursor (ANSI codes)
    cursor_style: String,
    /// Whether this input is focused
    focused: bool,
    /// Component dirty flag
    dirty: bool,
    /// Callback when Enter is pressed
    on_submit: Option<OnSubmit>,
}

impl TextInput {
    /// Create a new text input with the given prompt
    pub fn new(prompt: &str) -> Self {
        TextInput {
            buffer: String::new(),
            cursor: 0,
            prompt: prompt.to_string(),
            prompt_style: String::new(),
            input_style: String::new(),
            cursor_style: "\x1b[7m".to_string(), // Inverse video by default
            focused: false,
            dirty: true,
            on_submit: None,
        }
    }

    /// Set the prompt style
    pub fn with_prompt_style(mut self, style: impl Into<String>) -> Self {
        self.prompt_style = style.into();
        self
    }

    /// Set the input text style
    pub fn with_input_style(mut self, style: impl Into<String>) -> Self {
        self.input_style = style.into();
        self
    }

    /// Set the cursor style
    pub fn with_cursor_style(mut self, style: impl Into<String>) -> Self {
        self.cursor_style = style.into();
        self
    }

    /// Set submission callback
    pub fn on_submit<F>(mut self, callback: F) -> Self
    where
        F: FnMut(&str) + 'static,
    {
        self.on_submit = Some(Box::new(callback));
        self
    }

    /// Get current input value
    pub fn value(&self) -> &str {
        &self.buffer
    }

    /// Set the input value
    pub fn set_value(&mut self, value: &str) {
        self.buffer = value.to_string();
        self.cursor = self.buffer.len();
        self.dirty = true;
    }

    /// Clear the input
    pub fn clear(&mut self) {
        self.buffer.clear();
        self.cursor = 0;
        self.dirty = true;
    }

    /// Get cursor position
    pub fn cursor_position(&self) -> usize {
        self.cursor
    }

    /// Check if input is empty
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }

    /// Insert character at cursor
    fn insert_char(&mut self, c: char) {
        self.buffer.insert(self.cursor, c);
        self.cursor += c.len_utf8();
        self.dirty = true;
    }

    /// Delete character before cursor (backspace)
    fn delete_char_before(&mut self) {
        if self.cursor > 0 {
            // Find the previous character boundary
            let prev_boundary = self.buffer[..self.cursor]
                .char_indices()
                .next_back()
                .map(|(i, _)| i)
                .unwrap_or(0);

            self.buffer.remove(prev_boundary);
            self.cursor = prev_boundary;
            self.dirty = true;
        }
    }

    /// Delete character at cursor (delete key)
    fn delete_char_at(&mut self) {
        if self.cursor < self.buffer.len() {
            self.buffer.remove(self.cursor);
            self.dirty = true;
        }
    }

    /// Move cursor left
    fn move_left(&mut self) {
        if self.cursor > 0 {
            // Find previous character boundary
            self.cursor = self.buffer[..self.cursor]
                .char_indices()
                .next_back()
                .map(|(i, _)| i)
                .unwrap_or(0);
            self.dirty = true;
        }
    }

    /// Move cursor right
    fn move_right(&mut self) {
        if self.cursor < self.buffer.len() {
            // Find next character boundary
            self.cursor = self.buffer[self.cursor..]
                .char_indices()
                .nth(1)
                .map(|(i, _)| self.cursor + i)
                .unwrap_or(self.buffer.len());
            self.dirty = true;
        }
    }

    /// Move cursor to start
    fn move_to_start(&mut self) {
        if self.cursor != 0 {
            self.cursor = 0;
            self.dirty = true;
        }
    }

    /// Move cursor to end
    fn move_to_end(&mut self) {
        if self.cursor != self.buffer.len() {
            self.cursor = self.buffer.len();
            self.dirty = true;
        }
    }

    /// Move cursor to previous word boundary
    fn move_word_left(&mut self) {
        if self.cursor == 0 {
            return;
        }

        let chars: Vec<(usize, char)> = self.buffer[..self.cursor].char_indices().collect();
        if chars.is_empty() {
            return;
        }

        let mut i = chars.len() - 1;

        // Skip whitespace
        while i > 0 && chars[i].1.is_whitespace() {
            i -= 1;
        }

        // Skip word characters
        while i > 0 && !chars[i - 1].1.is_whitespace() {
            i -= 1;
        }

        self.cursor = chars.get(i).map(|(idx, _)| *idx).unwrap_or(0);
        self.dirty = true;
    }

    /// Move cursor to next word boundary
    fn move_word_right(&mut self) {
        if self.cursor >= self.buffer.len() {
            return;
        }

        let chars: Vec<(usize, char)> = self.buffer[self.cursor..].char_indices().collect();
        if chars.is_empty() {
            return;
        }

        let mut i = 0;

        // Skip current word characters
        while i < chars.len() && !chars[i].1.is_whitespace() {
            i += 1;
        }

        // Skip whitespace
        while i < chars.len() && chars[i].1.is_whitespace() {
            i += 1;
        }

        self.cursor = if i < chars.len() {
            self.cursor + chars[i].0
        } else {
            self.buffer.len()
        };
        self.dirty = true;
    }

    /// Delete word before cursor (Ctrl+W)
    fn delete_word_before(&mut self) {
        if self.cursor == 0 {
            return;
        }

        let original_cursor = self.cursor;
        self.move_word_left();
        let new_cursor = self.cursor;

        // Delete from new position to original position
        self.buffer.drain(new_cursor..original_cursor);
        self.dirty = true;
    }

    /// Delete from cursor to end of line (Ctrl+K)
    fn delete_to_end(&mut self) {
        if self.cursor < self.buffer.len() {
            self.buffer.truncate(self.cursor);
            self.dirty = true;
        }
    }

    /// Delete from cursor to start of line (Ctrl+U)
    fn delete_to_start(&mut self) {
        if self.cursor > 0 {
            self.buffer.drain(..self.cursor);
            self.cursor = 0;
            self.dirty = true;
        }
    }

    /// Handle paste event
    fn handle_paste(&mut self, text: &str) {
        // Only insert single-line content (strip newlines)
        let clean_text: String = text.chars().filter(|c| *c != '\n' && *c != '\r').collect();
        self.buffer.insert_str(self.cursor, &clean_text);
        self.cursor += clean_text.len();
        self.dirty = true;
    }

    fn write_input_text(&self, renderer: &mut Renderer, text: &str) -> Result<()> {
        if !self.input_style.is_empty() {
            renderer.write_styled(text, &self.input_style)
        } else {
            renderer.write_text(text)
        }
    }

    fn handle_key(&mut self, key: &Key) -> bool {
        match key {
            Key::Char(c) => {
                self.insert_char(*c);
                true
            }
            Key::Enter => {
                if let Some(callback) = &mut self.on_submit {
                    callback(&self.buffer);
                }
                true
            }
            Key::Esc => false,
            _ => self.handle_editing_key(key) || self.handle_navigation_key(key),
        }
    }

    fn handle_editing_key(&mut self, key: &Key) -> bool {
        match key {
            Key::Backspace => self.delete_char_before(),
            Key::Delete => self.delete_char_at(),
            Key::Ctrl('w') => self.delete_word_before(),
            Key::Ctrl('k') => self.delete_to_end(),
            Key::Ctrl('u') => self.delete_to_start(),
            _ => return false,
        }
        true
    }

    fn handle_navigation_key(&mut self, key: &Key) -> bool {
        match key {
            Key::Left => self.move_left(),
            Key::Right => self.move_right(),
            Key::Home | Key::Ctrl('a') => self.move_to_start(),
            Key::End | Key::Ctrl('e') => self.move_to_end(),
            Key::Alt('b') => self.move_word_left(),
            Key::Alt('f') => self.move_word_right(),
            _ => return false,
        }
        true
    }
}

impl EventHandler for TextInput {
    fn handle_event(&mut self, event: &Event) -> bool {
        if !self.focused {
            return false;
        }

        match event {
            Event::Key(key) => self.handle_key(key),
            Event::Paste(text) => {
                self.handle_paste(text);
                true
            }
            _ => false,
        }
    }

    fn on_focus(&mut self) {
        self.focused = true;
        self.dirty = true;
    }

    fn on_blur(&mut self) {
        self.focused = false;
        self.dirty = true;
    }
}

impl Component for TextInput {
    fn render(
        &mut self,
        renderer: &mut Renderer,
        bounds: Rect,
        _ctx: &RenderContext,
    ) -> Result<()> {
        renderer.move_cursor(bounds.x, bounds.y)?;

        // Render prompt
        if !self.prompt.is_empty() {
            if self.prompt_style.is_empty() {
                renderer.write_text(&self.prompt)?;
            } else {
                renderer.write_styled(&self.prompt, &self.prompt_style)?;
            }
        }

        // Calculate available width for input
        let prompt_len = self.prompt.chars().count() as u16;
        let available_width = bounds.width.saturating_sub(prompt_len);

        if available_width == 0 {
            self.dirty = false;
            return Ok(());
        }

        // Calculate visible portion of buffer (scroll if needed)
        let cursor_char_pos = self.buffer[..self.cursor].chars().count();
        let _buffer_char_len = self.buffer.chars().count();

        // Determine scroll offset to keep cursor visible
        let scroll_offset = if cursor_char_pos >= available_width as usize {
            cursor_char_pos - (available_width as usize - 1)
        } else {
            0
        };

        // Get visible text
        let visible_chars: String = self
            .buffer
            .chars()
            .skip(scroll_offset)
            .take(available_width as usize)
            .collect();

        let visible_cursor_pos = cursor_char_pos - scroll_offset;

        // Render text with cursor
        if self.focused && visible_cursor_pos < visible_chars.chars().count() {
            let before: String = visible_chars.chars().take(visible_cursor_pos).collect();
            let cursor_char: String = visible_chars
                .chars()
                .nth(visible_cursor_pos)
                .map(|c| c.to_string())
                .unwrap_or_else(|| " ".to_string());
            let after: String = visible_chars.chars().skip(visible_cursor_pos + 1).collect();

            self.write_input_text(renderer, &before)?;
            renderer.write_styled(&cursor_char, &self.cursor_style)?;
            self.write_input_text(renderer, &after)?;
        } else if self.focused {
            self.write_input_text(renderer, &visible_chars)?;
            renderer.write_styled(" ", &self.cursor_style)?;
        } else {
            self.write_input_text(renderer, &visible_chars)?;
        }

        self.dirty = false;
        Ok(())
    }

    fn min_size(&self) -> (u16, u16) {
        // Minimum: prompt + at least some space for input
        let prompt_len = self.prompt.chars().count() as u16;
        (prompt_len + 10, 1)
    }

    fn mark_dirty(&mut self) {
        self.dirty = true;
    }

    fn is_dirty(&self) -> bool {
        self.dirty
    }

    fn name(&self) -> &str {
        "TextInput"
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_text_input_creation() {
        let input = TextInput::new(": ");
        assert_eq!(input.value(), "");
        assert!(input.is_empty());
    }

    #[test]
    fn test_insert_and_cursor() {
        let mut input = TextInput::new("");
        input.focused = true;

        input.insert_char('h');
        input.insert_char('e');
        input.insert_char('l');
        input.insert_char('l');
        input.insert_char('o');

        assert_eq!(input.value(), "hello");
        assert_eq!(input.cursor_position(), 5);
    }

    #[test]
    fn test_navigation() {
        let mut input = TextInput::new("");
        input.set_value("hello world");

        input.move_to_start();
        assert_eq!(input.cursor_position(), 0);

        input.move_to_end();
        assert_eq!(input.cursor_position(), 11);

        input.move_left();
        assert_eq!(input.cursor_position(), 10);

        input.move_right();
        assert_eq!(input.cursor_position(), 11);
    }

    #[test]
    fn test_deletion() {
        let mut input = TextInput::new("");
        input.set_value("hello");

        input.delete_char_before();
        assert_eq!(input.value(), "hell");

        input.move_to_start();
        input.delete_char_at();
        assert_eq!(input.value(), "ell");
    }

    #[test]
    fn test_word_navigation() {
        let mut input = TextInput::new("");
        input.set_value("hello world test");

        input.move_to_start();
        input.move_word_right();
        // Should be at 'w' in 'world'
        assert_eq!(input.cursor_position(), 6);

        input.move_word_right();
        // Should be at 't' in 'test'
        assert_eq!(input.cursor_position(), 12);

        input.move_word_left();
        // Should be back at 'w' in 'world'
        assert_eq!(input.cursor_position(), 6);
    }

    #[test]
    fn test_clear() {
        let mut input = TextInput::new("");
        input.set_value("some text");

        input.clear();
        assert!(input.is_empty());
        assert_eq!(input.cursor_position(), 0);
    }
}