edamame 0.1.2

A fast TUI Markdown editor and viewer
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
//! Transient hint-line message system.  Owns [`MessageKind`],
//! the [`TransientMessage`] payload, and the App-level hooks for
//! emitting / expiring / dismissing flash notifications.
//!
//! Pulled out of `app.rs` in Step 2 of `refactor-app.md`.

use std::time::{Duration, Instant};

use crate::config;
use crate::config::KeyBindingOverrides;
use crate::config::KeyMap;
use crate::ui::{hint_line_for, HintContent, HintCtx, HintSet, ModalKind};

use super::modal::{Modal, NoticeModal};
use super::App;

/// Severity of a [`TransientMessage`].  Drives style selection.
/// All transient kinds auto-expire after `config.editor.transient_ms`;
/// situations that need the user to actually acknowledge a message
/// (errors, rejections, stubs) use [`App::notify`] to push a sticky
/// [`NoticeModal`] instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageKind {
    Info,
    Success,
}

/// A single transient status message shown in the hint line.
#[derive(Debug, Clone)]
pub(super) struct TransientMessage {
    pub(super) text: String,
    pub(super) kind: MessageKind,
    /// Wall-clock deadline after which non-error messages auto-expire.
    /// `None` for sticky errors.
    pub(super) until: Option<Instant>,
}

impl App {
    /// Emit a transient message on the hint line.  Auto-expires after
    /// `config.editor.transient_ms`.  Use for passive confirmations
    /// (saved, copied, file reloaded, etc.) — anything the user can
    /// safely miss.  For errors and rejections that need
    /// acknowledgement, use [`Self::notify`] instead.
    pub fn flash(&mut self, text: impl Into<String>, kind: MessageKind) {
        let text = text.into();
        let until = Some(Instant::now() + Duration::from_millis(self.config.editor.transient_ms));
        self.transient = Some(TransientMessage { text, kind, until });
        self.needs_draw = true;
    }

    /// Surface a sticky notification as a [`NoticeModal`].  Used for
    /// errors, rejections, and stub messages — anything the user needs
    /// to actually see and acknowledge rather than risk missing on the
    /// hint line.  Pushes onto [`Self::modal_stack`] so the notice
    /// stacks on top of any modal that triggered it; `Esc` dismisses.
    pub fn notify(&mut self, text: impl Into<String>, kind: ModalKind) {
        let text = text.into();
        // Coalesce: if the topmost modal is already a NoticeModal with
        // identical text+kind, skip the push so a retry loop (e.g.
        // repeated save failures) doesn't pile duplicates on the stack
        // for the user to dismiss one by one.
        if let Some(top) = self.modal_stack.top_mut() {
            if let Some(existing) = top.as_any().downcast_ref::<NoticeModal>() {
                if Modal::kind(existing) == kind && existing.text() == text {
                    return;
                }
            }
        }
        self.modal_stack
            .push(Box::new(NoticeModal::new(text, kind)));
        self.needs_draw = true;
    }

    /// Clear the current transient message if it has auto-expired.
    /// Called from the main loop before the draw gate so the hint line
    /// reverts to chords without the user having to press a key.
    /// Returns true when a redraw is needed.
    pub(super) fn expire_transient_if_due(&mut self) -> bool {
        let Some(msg) = self.transient.as_ref() else {
            return false;
        };
        let Some(deadline) = msg.until else {
            return false;
        };
        if Instant::now() >= deadline {
            self.transient = None;
            return true;
        }
        false
    }

    /// The deadline when the current transient expires, if any.
    /// Contributes to [`App::next_deadline`] so the main loop wakes in
    /// time to revert the hint line even with no input arriving.
    pub(super) fn transient_deadline(&self) -> Option<Instant> {
        self.transient.as_ref().and_then(|m| m.until)
    }

    /// Build the hint content for this frame.  Prompt > CommandLine >
    /// Transient > hovered-link > Chords, matching the plan's priority.
    pub(super) fn hint_content(&self) -> HintContent {
        if let Some(prompt) = self.hint_prompt.as_ref() {
            return HintContent::Prompt {
                prompt: prompt.prompt.clone(),
                chords: prompt.chords.clone(),
            };
        }
        // A vim command line (`/` `?`) replaces the chord row while the user
        // is typing it, sitting just below a modal prompt.
        if let Some(cl) = self.vim.as_ref().and_then(|v| v.cmdline.as_ref()) {
            return HintContent::CommandLine {
                prefix: cl.kind.prefix(),
                text: cl.input.clone(),
                cursor: cl.cursor,
                cursor_visible: self.editor.cursor_blink.is_visible(),
            };
        }
        if let Some(msg) = self.transient.as_ref() {
            let style = match msg.kind {
                MessageKind::Info => self.theme.transient_info,
                MessageKind::Success => self.theme.transient_success,
            };
            return HintContent::Transient {
                text: msg.text.clone(),
                style,
            };
        }
        // Hovered-link tooltip: while the mouse pointer rests on a link
        // the hint row shows its raw URL (browser-status-bar style),
        // replacing the chord row.  A prelude with no chords reuses the
        // Chords rendering path — plain `hint_label` text on the bar.
        // Sits below Prompt and Transient so a `Saved` flash or a
        // file-changed prompt is never masked by an idle hover.
        if let Some(url) = self.hovered_link.as_ref() {
            return HintContent::Chords(HintSet {
                prelude: Some(url.clone()),
                chords: Vec::new(),
                search_match: None,
            });
        }
        // Look up chord glyphs against the live KeyMap so any rebind
        // applied via the keybinds overlay shows up in the hint line
        // on the very next frame.  Falls back to the compiled-in
        // defaults during the brief window between `App::new` and the
        // first `KeyMap::build` in `run` — that path runs only when
        // building the override-aware keymap fails for unrelated
        // reasons, and the default keymap always builds.
        let fallback;
        let keymap = match self.keymap.as_ref() {
            Some(km) => km,
            None => {
                fallback = KeyMap::build(&KeyBindingOverrides::default())
                    .expect("default keymap always builds");
                &fallback
            }
        };
        // Vim reuses the same contextual + baseline hint row as the default
        // handler — the modal keys are vim-internal and the status bar badge
        // already advertises the active sub-mode.
        // The history-navigation hint surfaces whenever there's somewhere
        // to go in either direction — the single ⌥←→ chord covers both
        // NavigateBack and NavigateForward.
        // A vim VisualLine selection on a single line is charwise-empty, so the
        // hint line can't infer it from `selection_size` alone — pass the flag
        // through so the selection row shows under a V-LINE highlight.
        let ctx = HintCtx {
            nav_available: !self.nav_back.is_empty() || !self.nav_forward.is_empty(),
            visual_line: self.vim.as_ref().is_some_and(|v| v.is_visual_line()),
        };
        HintContent::Chords(hint_line_for(&self.editor, keymap, ctx))
    }

    /// Inspect `action` after dispatch and emit the matching flash
    /// notification.  Centralising this here means every code path
    /// that calls `Action::Save` / `Copy` / `Cut` gets consistent
    /// messaging without polluting `edit_ops::apply` with UI concerns.
    pub(super) fn flash_for_action(
        &mut self,
        action: &crate::config::Action,
        dirty_before_save: bool,
    ) {
        use crate::config::Action;
        match action {
            Action::Save => {
                if dirty_before_save && !self.editor.dirty {
                    self.flash("Saved", MessageKind::Success);
                } else if dirty_before_save && self.editor.dirty {
                    self.notify("Save failed", ModalKind::Error);
                }
            }
            Action::Copy | Action::Cut => {
                self.flash("Copied", MessageKind::Info);
            }
            _ => {}
        }
    }

    /// Flash shown when a modal flow's default-deny gate drops an
    /// action — shared by diff review and the search flow so a denied
    /// keypress gets the same "why did nothing happen" feedback in
    /// both.  `flow` names the flow ("search", "diff review").
    pub(super) fn flash_action_unavailable(&mut self, flow: &str) {
        self.flash(format!("Not available during {flow}"), MessageKind::Info);
        self.needs_draw = true;
    }

    /// Persist `config.toml` and flash a `Configuration updated`
    /// notification on success.  Centralises the save-and-notify
    /// pattern so every caller (capability suppression, remote-image
    /// policy, future settings overlay) gets the same UX without
    /// sprinkling `flash()` calls through the dispatch paths.
    pub(super) fn save_config_with_flash(&mut self, err_context: &'static str) {
        match self.config.save() {
            Ok(()) => {
                let msg = format!("Configuration updated{}", config::unpersisted_suffix());
                self.flash(msg, MessageKind::Success);
            }
            Err(e) => {
                tracing::warn!(error = %e, "{}", err_context);
                self.notify(format!("Config save failed: {e}"), ModalKind::Error);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    //! Exercise the transient-message mechanics directly
    //! against an `App` instance, bypassing the event loop.  Builds use
    //! [`Capabilities::default`] and the default config; no terminal is
    //! ever acquired.

    use std::time::Duration;

    use super::*;
    use crate::app::test_utils::make_app;
    use crate::config::Action;
    use crate::ui::HintContent;

    #[test]
    fn flash_records_transient_info() {
        let mut app = make_app();
        assert!(app.transient.is_none());
        app.flash("Copied", MessageKind::Info);
        let msg = app.transient.as_ref().unwrap();
        assert_eq!(msg.text, "Copied");
        assert!(matches!(msg.kind, MessageKind::Info));
        assert!(msg.until.is_some(), "all flashes auto-expire");
    }

    #[test]
    fn expire_transient_clears_only_after_deadline() {
        let mut app = make_app();
        app.flash("Saved", MessageKind::Success);
        // Force the deadline into the past.
        if let Some(msg) = app.transient.as_mut() {
            msg.until = Some(Instant::now() - Duration::from_millis(1));
        }
        assert!(app.expire_transient_if_due());
        assert!(app.transient.is_none());
    }

    #[test]
    fn notify_pushes_notice_modal() {
        use crate::app::modal::NoticeModal;
        let mut app = make_app();
        app.notify("Boom", ModalKind::Error);
        assert!(app.modal_stack.contains::<NoticeModal>());
    }

    #[test]
    fn notify_coalesces_duplicate_top_notice() {
        let mut app = make_app();
        let base = app.modal_stack.len();
        app.notify("Save failed", ModalKind::Error);
        app.notify("Save failed", ModalKind::Error);
        app.notify("Save failed", ModalKind::Error);
        assert_eq!(
            app.modal_stack.len() - base,
            1,
            "identical consecutive notices must collapse to one modal"
        );
    }

    #[test]
    fn notify_does_not_coalesce_distinct_text_or_kind() {
        let mut app = make_app();
        let base = app.modal_stack.len();
        app.notify("Save failed", ModalKind::Error);
        app.notify("Reload failed", ModalKind::Error);
        app.notify("Save failed", ModalKind::Warning);
        assert_eq!(
            app.modal_stack.len() - base,
            3,
            "different text or kind must each push a fresh modal"
        );
    }

    #[test]
    fn flash_for_action_save_success_emits_saved_flash() {
        let mut app = make_app();
        // Simulate a successful save: dirty was true before and the
        // editor-state dirty flag has just flipped to false.
        app.editor.dirty = false;
        app.flash_for_action(&Action::Save, /*dirty_before=*/ true);
        let msg = app.transient.as_ref().expect("flash recorded");
        assert_eq!(msg.text, "Saved");
        assert!(matches!(msg.kind, MessageKind::Success));
    }

    #[test]
    fn flash_for_action_save_failure_pushes_error_modal() {
        use crate::app::modal::NoticeModal;
        let mut app = make_app();
        // Failure: dirty was true and remains true after "save".
        app.editor.dirty = true;
        app.flash_for_action(&Action::Save, /*dirty_before=*/ true);
        assert!(
            app.modal_stack.contains::<NoticeModal>(),
            "save failure must surface a sticky NoticeModal"
        );
        assert!(
            app.transient.is_none(),
            "save failure no longer leaves a transient flash"
        );
    }

    #[test]
    fn flash_for_action_copy_emits_copied() {
        let mut app = make_app();
        app.flash_for_action(&Action::Copy, /*dirty_before=*/ false);
        let msg = app.transient.as_ref().expect("flash recorded");
        assert_eq!(msg.text, "Copied");
    }

    #[test]
    fn flash_for_action_cut_emits_copied() {
        let mut app = make_app();
        app.flash_for_action(&Action::Cut, /*dirty_before=*/ false);
        let msg = app.transient.as_ref().expect("flash recorded");
        assert_eq!(msg.text, "Copied");
    }

    #[test]
    fn flash_for_action_paste_is_silent() {
        let mut app = make_app();
        app.flash_for_action(&Action::Paste, /*dirty_before=*/ false);
        assert!(app.transient.is_none());
    }

    #[test]
    fn hint_content_defaults_to_chords() {
        let app = make_app();
        match app.hint_content() {
            HintContent::Chords(_) => {}
            other => panic!("expected Chords, got {other:?}"),
        }
    }

    /// The V-LINE row is only correct if `hint_content` actually derives
    /// `HintCtx::visual_line` from the live vim state — hard-coding it
    /// `false` would restore the original bug while every `hint_line_for`
    /// unit test still passed, so assert the wiring end-to-end.
    #[test]
    fn hint_content_derives_visual_line_from_vim_state() {
        use crate::document::Selection;
        use crate::input::vim::state::{VimState, VimSubMode};
        let mut app = make_app();
        app.editor.buffer.insert(0, "alpha\nbeta\n");
        app.editor.mode = crate::editor::Mode::Rendered;
        app.editor.refresh_parsed();
        // V-LINE on the first line: charwise-empty, so only the vim state
        // can tell the hint line a whole line is highlighted.
        app.editor.selection = Some(Selection {
            anchor: 0,
            active: 0,
        });
        app.vim = Some(VimState {
            sub_mode: VimSubMode::VisualLine,
            visual_anchor: Some(0),
            ..Default::default()
        });
        match app.hint_content() {
            HintContent::Chords(set) => {
                let labels: Vec<_> = set.chords.iter().map(|c| c.label.as_str()).collect();
                assert_eq!(
                    labels,
                    vec!["Cut", "Copy", "Paste"],
                    "hint_content must pass the live V-LINE sub-mode through to hint_line_for"
                );
            }
            other => panic!("expected Chords, got {other:?}"),
        }
        // Leaving V-LINE drops the row back to the baseline, proving the
        // flag is read per frame rather than latched.
        app.vim = Some(VimState::default());
        app.editor.selection = None;
        match app.hint_content() {
            HintContent::Chords(set) => {
                assert_eq!(set.chords[0].label, "Menu");
            }
            other => panic!("expected Chords, got {other:?}"),
        }
    }

    #[test]
    fn hint_content_prefers_transient_over_chords() {
        let mut app = make_app();
        app.flash("Copied", MessageKind::Info);
        match app.hint_content() {
            HintContent::Transient { text, .. } => assert_eq!(text, "Copied"),
            other => panic!("expected Transient, got {other:?}"),
        }
    }

    #[test]
    fn hovered_link_replaces_chord_row_with_url() {
        let mut app = make_app();
        app.hovered_link = Some("https://example.com".to_owned());
        match app.hint_content() {
            HintContent::Chords(set) => {
                assert_eq!(set.prelude.as_deref(), Some("https://example.com"));
                assert!(
                    set.chords.is_empty(),
                    "hover tooltip must replace the chord row, not prefix it"
                );
            }
            other => panic!("expected Chords with URL prelude, got {other:?}"),
        }
    }

    #[test]
    fn transient_outranks_hovered_link() {
        let mut app = make_app();
        app.hovered_link = Some("https://example.com".to_owned());
        app.flash("Saved", MessageKind::Success);
        match app.hint_content() {
            HintContent::Transient { text, .. } => assert_eq!(text, "Saved"),
            other => panic!("transient must mask the hover tooltip, got {other:?}"),
        }
    }

    #[test]
    fn clearing_hover_restores_chords() {
        let mut app = make_app();
        app.hovered_link = Some("./notes.md".to_owned());
        app.hovered_link = None;
        match app.hint_content() {
            HintContent::Chords(set) => assert!(!set.chords.is_empty()),
            other => panic!("expected default chord row, got {other:?}"),
        }
    }

    #[test]
    fn save_config_with_flash_emits_feedback() {
        // `Config::save` *might* fail when no config dir is available
        // in the test environment.  The success branch records a
        // transient; the failure branch pushes a NoticeModal — we
        // accept either so the test is robust to the environment.
        // Isolated because this drives a real `Config::save`, which
        // would otherwise rewrite the developer's own config file.
        use crate::app::modal::NoticeModal;
        let _iso = crate::test_env::config_isolation();
        let mut app = make_app();
        app.save_config_with_flash("test");
        assert!(app.transient.is_some() || app.modal_stack.contains::<NoticeModal>());
    }
}