tui-canvas 0.8.10

Form/textarea/input for TUI
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
// src/editor/mode.rs

#[cfg(feature = "cursor-style")]
use crate::cursor::CursorManager;

use crate::DataProvider;
use crate::canvas::modes::AppMode;
use crate::canvas::state::SelectionState;
use crate::editor::EditorCore;
#[cfg(feature = "keybindings")]
use crate::editor::behavior::KeybindingParadigm;

impl<D: DataProvider> EditorCore<D> {
    pub(crate) fn set_highlight_mode_selection(&mut self, selection: SelectionState) {
        self.ui_state.current_mode = AppMode::Sel;
        self.ui_state.selection = selection;

        #[cfg(feature = "cursor-style")]
        {
            let _ = CursorManager::update_for_mode(AppMode::Sel);
        }
    }

    /// Change mode
    pub fn set_mode(&mut self, mode: AppMode) {
        // A genuine mode change ends any in-progress undo-coalescing run. In
        // normal mode the mode never actually changes (always Ins), and the
        // wrappers call `enter_edit_mode` on every keystroke, so we must only
        // break on a real transition to keep typing coalesced.
        #[cfg(not(feature = "textmode-normal"))]
        if self.ui_state.current_mode != mode {
            self.break_undo_coalescing();
        }

        // Avoid unused param warning in normalmode
        #[cfg(feature = "textmode-normal")]
        let _ = mode;

        // NORMALMODE: force Ins, ignore requested mode
        #[cfg(feature = "textmode-normal")]
        {
            self.ui_state.current_mode = AppMode::Ins;
            self.ui_state.selection = SelectionState::None;

            #[cfg(feature = "cursor-style")]
            {
                let _ = CursorManager::update_for_mode(AppMode::Ins);
            }
        }

        // Default (not normal): paradigm-specific modal behavior
        #[cfg(not(feature = "textmode-normal"))]
        {
            #[cfg(feature = "keybindings")]
            {
                match self.keybinding_paradigm() {
                    KeybindingParadigm::Helix => self.set_mode_helix(mode),
                    KeybindingParadigm::Emacs | KeybindingParadigm::Vscode => {
                        self.set_mode_emacs(mode)
                    }
                    KeybindingParadigm::Vim => self.set_mode_vim(mode),
                }
            }
            #[cfg(not(feature = "keybindings"))]
            self.set_mode_vim(mode);
        }
    }

    /// Exit insert mode to normal mode
    pub fn exit_edit_mode(&mut self) -> anyhow::Result<()> {
        #[cfg(feature = "validation")]
        {
            let current_text = self.current_text();
            if !self
                .ui_state
                .validation
                .allows_field_switch(self.ui_state.current_field, current_text)
            {
                if let Some(reason) = self
                    .ui_state
                    .validation
                    .field_switch_block_reason(self.ui_state.current_field, current_text)
                {
                    self.ui_state
                        .validation
                        .set_last_switch_block(reason.clone());
                    return Err(anyhow::anyhow!("Cannot exit edit mode: {}", reason));
                }
            }
        }

        let current_text = self.current_text();
        if !current_text.is_empty() {
            let max_normal_pos = current_text.chars().count().saturating_sub(1);
            if self.ui_state.cursor_pos > max_normal_pos {
                self.set_cursor_raw(max_normal_pos);
            }
        }

        #[cfg(feature = "validation")]
        {
            let field_index = self.ui_state.current_field;
            if let Some(cfg) = self.ui_state.validation.get_field_config(field_index) {
                if cfg.external_validation_enabled {
                    let text = self.current_text().to_string();
                    if !text.is_empty() {
                        self.set_external_validation(
                            field_index,
                            crate::validation::ExternalValidationState::Validating,
                        );
                        if let Some(cb) = self.external_validation_callback.as_mut() {
                            let final_state = cb(field_index, &text);
                            self.set_external_validation(field_index, final_state);
                        }
                    }
                }
            }
        }

        // NORMALMODE: stay in Ins (do not switch to Nor)
        #[cfg(feature = "textmode-normal")]
        {
            #[cfg(feature = "suggestions")]
            {
                self.dismiss_suggestions();
            }
            Ok(())
        }

        // Default (not normal): original vim behavior
        #[cfg(not(feature = "textmode-normal"))]
        {
            self.set_mode(AppMode::Nor);
            #[cfg(feature = "suggestions")]
            {
                self.dismiss_suggestions();
            }
            Ok(())
        }
    }

    /// Enter insert mode
    pub fn enter_edit_mode(&mut self) {
        #[cfg(feature = "computed")]
        {
            if let Some(computed_state) = &self.ui_state.computed {
                if computed_state.is_computed_field(self.ui_state.current_field) {
                    return;
                }
            }
        }

        // NORMALMODE: already in Ins, but enforce it
        #[cfg(feature = "textmode-normal")]
        {
            self.ui_state.current_mode = AppMode::Ins;
            self.ui_state.selection = SelectionState::None;
            #[cfg(feature = "cursor-style")]
            {
                let _ = CursorManager::update_for_mode(AppMode::Ins);
            }
        }

        // Default (not normal): paradigm-specific insert entry
        #[cfg(not(feature = "textmode-normal"))]
        {
            #[cfg(feature = "keybindings")]
            match self.keybinding_paradigm() {
                KeybindingParadigm::Helix => self.enter_edit_mode_helix(),
                KeybindingParadigm::Emacs | KeybindingParadigm::Vscode => {
                    self.enter_edit_mode_emacs()
                }
                KeybindingParadigm::Vim => self.enter_edit_mode_vim(),
            }
            #[cfg(not(feature = "keybindings"))]
            self.enter_edit_mode_vim();
        }

        // Check if suggestions should be shown based on trigger
        #[cfg(feature = "suggestions")]
        self.check_suggestion_trigger();
    }

    // Selection/visual mode

    pub fn enter_highlight_mode(&mut self) {
        #[cfg(feature = "textmode-normal")]
        {}

        #[cfg(not(feature = "textmode-normal"))]
        {
            #[cfg(feature = "keybindings")]
            match self.keybinding_paradigm() {
                KeybindingParadigm::Helix => self.enter_highlight_mode_helix(),
                KeybindingParadigm::Emacs | KeybindingParadigm::Vscode => {
                    self.enter_highlight_mode_emacs()
                }
                KeybindingParadigm::Vim => self.enter_highlight_mode_vim(),
            }
            #[cfg(not(feature = "keybindings"))]
            self.enter_highlight_mode_vim();
        }
    }

    pub fn enter_highlight_line_mode(&mut self) {
        #[cfg(feature = "textmode-normal")]
        {}

        #[cfg(not(feature = "textmode-normal"))]
        {
            #[cfg(feature = "keybindings")]
            match self.keybinding_paradigm() {
                KeybindingParadigm::Helix => self.enter_highlight_line_mode_helix(),
                KeybindingParadigm::Emacs | KeybindingParadigm::Vscode => {
                    self.enter_highlight_line_mode_emacs()
                }
                KeybindingParadigm::Vim => self.enter_highlight_line_mode_vim(),
            }
            #[cfg(not(feature = "keybindings"))]
            self.enter_highlight_line_mode_vim();
        }
    }

    pub fn exit_highlight_mode(&mut self) {
        #[cfg(feature = "textmode-normal")]
        {}

        #[cfg(not(feature = "textmode-normal"))]
        {
            #[cfg(feature = "keybindings")]
            match self.keybinding_paradigm() {
                KeybindingParadigm::Helix => self.exit_highlight_mode_helix(),
                KeybindingParadigm::Emacs | KeybindingParadigm::Vscode => {
                    self.exit_highlight_mode_emacs()
                }
                KeybindingParadigm::Vim => self.exit_highlight_mode_vim(),
            }
            #[cfg(not(feature = "keybindings"))]
            self.exit_highlight_mode_vim();
        }
    }

    pub fn is_highlight_mode(&self) -> bool {
        #[cfg(feature = "textmode-normal")]
        {
            false
        }
        #[cfg(not(feature = "textmode-normal"))]
        {
            return self.ui_state.current_mode == AppMode::Sel;
        }
    }

    pub fn selection_state(&self) -> &SelectionState {
        &self.ui_state.selection
    }

    // Visual-mode movements reuse existing movement methods
    // These keep calling the movement methods; in normalmode selection is never enabled,
    // so these just move without creating a selection.
    pub fn move_left_with_selection(&mut self) {
        let _ = self.move_left();
    }

    pub fn move_right_with_selection(&mut self) {
        let _ = self.move_right();
    }

    pub fn move_up_with_selection(&mut self) {
        let _ = self.move_up();
    }

    pub fn move_down_with_selection(&mut self) {
        let _ = self.move_down();
    }

    pub fn move_word_next_with_selection(&mut self) {
        self.move_word_next();
    }

    pub fn move_word_end_with_selection(&mut self) {
        self.move_word_end();
    }

    pub fn move_word_prev_with_selection(&mut self) {
        self.move_word_prev();
    }

    pub fn move_word_end_prev_with_selection(&mut self) {
        self.move_word_end_prev();
    }

    pub fn move_big_word_next_with_selection(&mut self) {
        self.move_big_word_next();
    }

    pub fn move_big_word_end_with_selection(&mut self) {
        self.move_big_word_end();
    }

    pub fn move_big_word_prev_with_selection(&mut self) {
        self.move_big_word_prev();
    }

    pub fn move_big_word_end_prev_with_selection(&mut self) {
        self.move_big_word_end_prev();
    }

    pub fn move_line_start_with_selection(&mut self) {
        self.move_line_start();
    }

    pub fn move_line_end_with_selection(&mut self) {
        self.move_line_end();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::canvas::modes::AppMode;

    #[derive(Clone)]
    struct TestProvider {
        fields: Vec<(&'static str, String)>,
    }

    impl TestProvider {
        fn new(values: &[&'static str]) -> Self {
            Self {
                fields: values
                    .iter()
                    .enumerate()
                    .map(|(i, value)| {
                        let name = match i {
                            0 => "a",
                            1 => "b",
                            _ => "c",
                        };
                        (name, (*value).to_string())
                    })
                    .collect(),
            }
        }
    }

    impl DataProvider for TestProvider {
        fn field_count(&self) -> usize {
            self.fields.len()
        }

        fn field_name(&self, index: usize) -> &str {
            self.fields[index].0
        }

        fn field_value(&self, index: usize) -> &str {
            &self.fields[index].1
        }

        fn set_field_value(&mut self, index: usize, value: String) {
            self.fields[index].1 = value;
        }
    }

    #[test]
    fn visual_characterwise_toggles_and_switches_from_linewise() {
        let mut editor = EditorCore::new(TestProvider::new(&["alpha", "beta"]));

        editor.enter_highlight_mode();
        assert_eq!(editor.mode(), AppMode::Sel);
        assert!(matches!(
            editor.selection_state(),
            SelectionState::Characterwise { anchor: (0, 0) }
        ));

        editor.enter_highlight_mode();
        assert_eq!(editor.mode(), AppMode::Nor);
        assert!(matches!(editor.selection_state(), SelectionState::None));

        editor.enter_highlight_line_mode();
        assert!(matches!(
            editor.selection_state(),
            SelectionState::Linewise { anchor_field: 0 }
        ));

        editor.move_down();
        editor.enter_highlight_mode();
        assert!(matches!(
            editor.selection_state(),
            SelectionState::Characterwise { anchor: (1, 0) }
        ));
    }

    #[test]
    fn visual_linewise_toggles_and_switches_from_characterwise() {
        let mut editor = EditorCore::new(TestProvider::new(&["alpha", "beta"]));

        editor.enter_highlight_line_mode();
        assert_eq!(editor.mode(), AppMode::Sel);
        assert!(matches!(
            editor.selection_state(),
            SelectionState::Linewise { anchor_field: 0 }
        ));

        editor.enter_highlight_line_mode();
        assert_eq!(editor.mode(), AppMode::Nor);
        assert!(matches!(editor.selection_state(), SelectionState::None));

        editor.enter_highlight_mode();
        editor.move_down();
        editor.enter_highlight_line_mode();
        assert!(matches!(
            editor.selection_state(),
            SelectionState::Linewise { anchor_field: 0 }
        ));
    }

    #[test]
    fn visual_linewise_switch_preserves_selected_line_range() {
        let mut editor = EditorCore::new(TestProvider::new(&["alpha", "beta", "gamma"]));

        editor.enter_highlight_mode();
        editor.move_down();
        editor.enter_highlight_line_mode();

        assert_eq!(editor.current_field(), 1);
        assert!(matches!(
            editor.selection_state(),
            SelectionState::Linewise { anchor_field: 0 }
        ));
    }
}