hjkl-form 0.36.0

Vim-modal forms for hjkl-based apps.
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
//! Field types — the building blocks of a `Form`.

use crate::host::FormFieldHost;
use crate::validate::Validator;
use hjkl_buffer::View;
use hjkl_engine::{CoarseMode, Editor, Host, Input, Key, Options};
use hjkl_vim::VimEditorExt;

/// Metadata shared by every field variant. Holds the label,
/// required-marker, the most recent validator error, and an optional
/// placeholder shown when text fields are empty.
pub struct FieldMeta {
    pub label: String,
    pub required: bool,
    pub error: Option<String>,
    pub placeholder: Option<String>,
}

impl FieldMeta {
    /// Construct a field with just a label. Use the builder methods to
    /// layer on `required`, `placeholder`, etc.
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            required: false,
            error: None,
            placeholder: None,
        }
    }

    /// Mark the field as required (renderers prefix the label with `*`).
    pub fn required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    /// Set the placeholder text shown when the field is empty and not
    /// being edited.
    pub fn placeholder(mut self, text: impl Into<String>) -> Self {
        self.placeholder = Some(text.into());
        self
    }
}

/// A text input field — either single-line or multi-line. Owns its own
/// `Editor<View, FormFieldHost>` so the full vim grammar applies.
///
/// Two construction paths:
///
/// - [`TextFieldEditor::with_meta`] — used by [`crate::Form`] to wire a
///   field with label / validator / placeholder metadata.
/// - [`TextFieldEditor::new`] / [`TextFieldEditor::with_text`] — the
///   standalone primitive: a vim-grammar one-line (or N-line) prompt
///   without a surrounding form. Used by hosts that need just the
///   editing surface (`:` command palette, `/` `?` search prompt, etc.).
///
/// In standalone single-line mode, `Enter` is **swallowed** by
/// [`TextFieldEditor::handle_input`]: there is no "next field" to jump
/// to, and the surrounding host typically interprets `Enter` as
/// "submit / commit" via its own dispatcher before the keystroke ever
/// reaches the field. This keeps the buffer single-line by construction.
pub struct TextFieldEditor {
    pub meta: FieldMeta,
    pub editor: Editor<View, FormFieldHost>,
    pub validator: Option<Validator>,
    /// Visible body height for multi-line fields. Single-line is 1.
    pub rows: u16,
    /// True when the field is single-line — gates Enter swallowing in
    /// the standalone `handle_input` path and label rendering choices.
    pub(crate) single_line: bool,
    /// `dirty_gen` of the buffer at the moment the user entered Insert
    /// on this field. Used to decide whether a `Changed` event fires
    /// on Esc.
    pub(crate) enter_gen: u64,
}

impl TextFieldEditor {
    /// Build a standalone vim-grammar text field with empty buffer.
    /// `single_line=true` suppresses Enter from inserting newlines and
    /// sets `rows=1`; multi-line fields default to `rows=3`. Hosts that
    /// want a different multi-line height should bump `rows` afterwards
    /// or use [`TextFieldEditor::with_meta`].
    pub fn new(single_line: bool) -> Self {
        let buffer = View::new();
        let host = FormFieldHost::new();
        let editor = hjkl_vim::vim_editor(buffer, host, Options::default());
        Self {
            meta: FieldMeta::new(""),
            editor,
            validator: None,
            rows: if single_line { 1 } else { 3 },
            single_line,
            enter_gen: 0,
        }
    }

    /// Standalone variant pre-populated with `text`. Cursor lands at the
    /// end of the inserted content; mode is `Normal`.
    pub fn with_text(text: &str, single_line: bool) -> Self {
        let mut me = Self::new(single_line);
        me.set_text(text);
        me
    }

    /// Form-style constructor: full metadata + render-height. The label
    /// / placeholder / required marker render via
    /// [`crate::Form`]'s ratatui adapter.
    pub fn with_meta(meta: FieldMeta, rows: u16) -> Self {
        let buffer = View::new();
        let host = FormFieldHost::new();
        let editor = hjkl_vim::vim_editor(buffer, host, Options::default());
        Self {
            meta,
            editor,
            validator: None,
            single_line: rows <= 1,
            rows,
            enter_gen: 0,
        }
    }

    /// Attach a validator that runs on field-blur and on submit.
    pub fn with_validator(mut self, validator: Validator) -> Self {
        self.validator = Some(validator);
        self
    }

    /// Pre-fill the editor's buffer with `text`.
    pub fn with_initial(mut self, text: &str) -> Self {
        let buffer = View::from_str(text);
        let host = FormFieldHost::new();
        self.editor = hjkl_vim::vim_editor(buffer, host, Options::default());
        self
    }

    /// Borrow the underlying [`View`] for span rendering, snapshots,
    /// or other read-only consumers.
    pub fn buffer(&self) -> &View {
        self.editor.buffer()
    }

    /// Mutable buffer access. Rare — prefer [`TextFieldEditor::handle_input`]
    /// which routes through the vim FSM and keeps the cursor consistent.
    pub fn buffer_mut(&mut self) -> &mut View {
        self.editor.buffer_mut()
    }

    /// Snapshot the buffer's current text. Multi-line buffers join with
    /// `'\n'`. A single-line field returns only its first (visible) line, so a
    /// newline slipped in via `o`/`O`/paste can't submit hidden multi-line data
    /// that the renderer never showed.
    pub fn text(&self) -> String {
        let s = self.editor.buffer().as_string();
        if self.single_line {
            s.split('\n').next().unwrap_or("").to_string()
        } else {
            s
        }
    }

    /// Replace contents wholesale, e.g. when opening a prompt with a
    /// preset value. Drops the inner editor and rebuilds it; cursor
    /// lands at the end of the new content and mode is `Normal`.
    pub fn set_text(&mut self, text: &str) {
        let buffer = View::from_str(text);
        let host = FormFieldHost::new();
        self.editor = hjkl_vim::vim_editor(buffer, host, Options::default());
        // Land cursor at end-of-text so `enter_insert_at_end` puts the
        // caret right after the last character.
        let n = self.editor.buffer().row_count();
        if n > 0 {
            let row = n - 1;
            let rope = self.editor.buffer().rope();
            let col = hjkl_buffer::rope_line_str(&rope, row).chars().count();
            self.editor
                .buffer_mut()
                .set_cursor(hjkl_buffer::Position::new(row, col));
        }
    }

    /// Cursor position as `(row, col)` in chars. Use directly to place
    /// the terminal cursor in the prompt's render rect.
    pub fn cursor(&self) -> (usize, usize) {
        self.editor.cursor()
    }

    /// Discipline-agnostic coarse mode of the inner editor (Normal / Insert /
    /// Select / ...).
    ///
    /// A form field only ever needs "am I inserting text or not" — it has no
    /// business naming vim-specific states. Reading [`CoarseMode`] instead of
    /// `VimMode` keeps this widget usable under any keybinding discipline
    /// (#265 / #267).
    pub fn coarse_mode(&self) -> CoarseMode {
        self.editor.coarse_mode()
    }

    /// Force the inner editor into Insert mode at the end of the
    /// current line. Used by hosts that open a prompt and want the user
    /// typing immediately.
    pub fn enter_insert_at_end(&mut self) {
        // Move cursor to end of last line.
        let n = self.editor.buffer().row_count();
        let row = n.saturating_sub(1);
        let eol_rope = self.editor.buffer().rope();
        let col = hjkl_buffer::rope_line_str(&eol_rope, row).chars().count();
        self.editor
            .buffer_mut()
            .set_cursor(hjkl_buffer::Position::new(row, col));
        // Normalise FSM to Normal first so `enter_insert_shift_a` cleanly
        // transitions (it expects Normal mode as the entry point).
        self.editor.force_normal();
        // `A` (append at end of line) puts the editor in Insert at EOL —
        // exactly the entry point we want for prompts.
        self.editor.enter_insert_shift_a(1);
    }

    /// Force the inner editor back to Normal mode (Esc).
    pub fn enter_normal(&mut self) {
        self.editor.force_normal();
    }

    /// Forward a key event to the inner editor's vim FSM. Returns
    /// `true` when the buffer's `dirty_gen` advanced — useful for
    /// triggering incremental search on `/` `?` prompts.
    ///
    /// In single-line standalone mode, `Enter` while in Insert is
    /// swallowed: there is no next field to jump to. Hosts intercept
    /// `Enter` upstream as "submit", so the field never sees it in
    /// practice; this guard is the belt-and-suspenders.
    pub fn handle_input(&mut self, input: Input) -> bool {
        // Single-line: drop newline-producing Enter in Insert mode.
        if self.single_line
            && input.key == Key::Enter
            && self.editor.coarse_mode() == CoarseMode::Insert
        {
            return false;
        }
        let before = self.editor.buffer().dirty_gen();
        hjkl_vim::dispatch_input(&mut self.editor, input);
        self.editor.buffer().dirty_gen() != before
    }

    /// View dirty generation — bumps on every content edit.
    pub fn dirty_gen(&self) -> u64 {
        self.editor.buffer().dirty_gen()
    }

    /// Set the field's host viewport width. The renderer should call
    /// this every frame so motions / scroll stay in-bounds.
    pub fn set_viewport_width(&mut self, width: u16) {
        self.editor.host_mut().viewport_mut().width = width;
    }

    /// Set the field's host viewport height. Single-line fields pass 1.
    pub fn set_viewport_height(&mut self, height: u16) {
        self.editor.host_mut().viewport_mut().height = height;
    }
}

/// A checkbox field. `value` is the toggled state.
pub struct CheckboxField {
    pub meta: FieldMeta,
    pub value: bool,
}

impl CheckboxField {
    /// Construct an unchecked checkbox.
    pub fn new(meta: FieldMeta) -> Self {
        Self { meta, value: false }
    }

    /// Set the initial checked state.
    pub fn with_value(mut self, value: bool) -> Self {
        self.value = value;
        self
    }
}

/// A select field — the user cycles through `options` with `h` / `l`.
pub struct SelectField {
    pub meta: FieldMeta,
    pub options: Vec<String>,
    pub index: usize,
}

impl SelectField {
    /// Construct a select field with a list of options. The first
    /// option is selected by default.
    pub fn new(meta: FieldMeta, options: Vec<String>) -> Self {
        Self {
            meta,
            options,
            index: 0,
        }
    }

    /// Currently-selected option (`None` if `options` is empty).
    pub fn selected(&self) -> Option<&str> {
        self.options.get(self.index).map(String::as_str)
    }
}

/// A submit "button" — an `Enter` while focused fires the form's submit
/// handler.
pub struct SubmitField {
    pub meta: FieldMeta,
}

impl SubmitField {
    /// Construct a submit "button" field.
    pub fn new(meta: FieldMeta) -> Self {
        Self { meta }
    }
}

/// Sum-type for all field variants. The form holds a `Vec<Field>`.
pub enum Field {
    SingleLineText(TextFieldEditor),
    MultiLineText(TextFieldEditor),
    Select(SelectField),
    Checkbox(CheckboxField),
    Submit(SubmitField),
}

impl Field {
    /// Borrow the field's metadata.
    pub fn meta(&self) -> &FieldMeta {
        match self {
            Field::SingleLineText(f) | Field::MultiLineText(f) => &f.meta,
            Field::Select(f) => &f.meta,
            Field::Checkbox(f) => &f.meta,
            Field::Submit(f) => &f.meta,
        }
    }

    /// Mutably borrow the field's metadata.
    pub fn meta_mut(&mut self) -> &mut FieldMeta {
        match self {
            Field::SingleLineText(f) | Field::MultiLineText(f) => &mut f.meta,
            Field::Select(f) => &mut f.meta,
            Field::Checkbox(f) => &mut f.meta,
            Field::Submit(f) => &mut f.meta,
        }
    }

    /// True for text fields (single- or multi-line).
    pub fn is_text(&self) -> bool {
        matches!(self, Field::SingleLineText(_) | Field::MultiLineText(_))
    }

    /// True for single-line text fields specifically.
    pub fn is_single_line_text(&self) -> bool {
        matches!(self, Field::SingleLineText(_))
    }

    /// True if the field can take focus. All variants are focusable in
    /// v1; v2 may add static "presentational" rows.
    pub fn is_focusable(&self) -> bool {
        // TODO(v2): non-focusable presentational rows (headings, hints).
        let _ = self;
        true
    }
}

#[cfg(test)]
mod standalone_tests {
    //! Tests for the standalone `TextFieldEditor` API used by host
    //! prompts (`:` palette, `/` `?` search). The form-side path is
    //! covered by `crate::fsm::tests`.

    use super::*;

    fn ki(c: char) -> Input {
        Input {
            key: Key::Char(c),
            ..Input::default()
        }
    }

    #[test]
    fn text_round_trips_via_set_text() {
        let mut f = TextFieldEditor::new(true);
        f.set_text("hello");
        assert_eq!(f.text(), "hello");
    }

    #[test]
    fn with_text_constructor_pre_populates() {
        let f = TextFieldEditor::with_text("abc", true);
        assert_eq!(f.text(), "abc");
    }

    #[test]
    fn single_line_text_strips_injected_newline() {
        // set_text / o / O / paste can slip a newline into a single-line
        // buffer; text() must surface only the visible first line, never the
        // hidden remainder.
        let f = TextFieldEditor::with_text("visible\nhidden", true);
        assert_eq!(f.text(), "visible");
        // A multi-line field is unchanged.
        let g = TextFieldEditor::with_text("a\nb", false);
        assert_eq!(g.text(), "a\nb");
    }

    #[test]
    fn handle_input_i_enters_insert() {
        let mut f = TextFieldEditor::new(true);
        f.handle_input(ki('i'));
        assert_eq!(f.coarse_mode(), CoarseMode::Insert);
    }

    #[test]
    fn handle_input_types_and_esc_returns_to_normal() {
        let mut f = TextFieldEditor::new(true);
        f.handle_input(ki('i'));
        f.handle_input(ki('h'));
        f.handle_input(ki('i'));
        f.handle_input(Input {
            key: Key::Esc,
            ..Input::default()
        });
        assert_eq!(f.text(), "hi");
        assert_eq!(f.coarse_mode(), CoarseMode::Normal);
    }

    #[test]
    fn dirty_gen_advances_after_insert() {
        let mut f = TextFieldEditor::new(true);
        let before = f.dirty_gen();
        f.handle_input(ki('i'));
        f.handle_input(ki('x'));
        assert!(f.dirty_gen() > before);
    }

    #[test]
    fn enter_insert_at_end_lands_cursor_at_eol() {
        let mut f = TextFieldEditor::with_text("abc", true);
        f.enter_insert_at_end();
        let (row, col) = f.cursor();
        assert_eq!(row, 0);
        // After `A` + Insert mode, cursor is past the last char.
        assert_eq!(col, 3);
        assert_eq!(f.coarse_mode(), CoarseMode::Insert);
    }

    #[test]
    fn single_line_swallows_enter_in_insert() {
        let mut f = TextFieldEditor::new(true);
        f.enter_insert_at_end();
        let dirty = f.handle_input(Input {
            key: Key::Enter,
            ..Input::default()
        });
        assert!(!dirty, "Enter must not mutate buffer in single-line Insert");
        assert_eq!(f.text(), "");
    }

    #[test]
    fn multi_line_accepts_enter_in_insert() {
        let mut f = TextFieldEditor::new(false);
        f.enter_insert_at_end();
        f.handle_input(ki('a'));
        f.handle_input(Input {
            key: Key::Enter,
            ..Input::default()
        });
        f.handle_input(ki('b'));
        assert_eq!(f.text(), "a\nb");
    }
}