cuj-tui 0.1.0

cui — a read-only TUI browser for cuj vaults
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
//! Application state and the command reducer. The reducer is pure
//! state manipulation (it may read the vault and run index
//! queries) and never touches the terminal, so every transition is
//! testable headless.

use std::collections::HashMap;

use metatheca::Uuid;
use ratatui::widgets::ListState;

use crate::cmdline::{CmdLine, ExCommand};
use crate::highlight::{self, Rendered};
use crate::keymap::Command;
use crate::query::{self, FindSpec, SearchEngine};
use crate::snapshot::{JotRow, Snapshot};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mode {
    Normal,
    Command,
    Help,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Focus {
    List,
    View,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Level {
    Info,
    Warn,
    Error,
}

/// What the left list is currently showing.
pub enum ListSource {
    All,
    Find {
        spec: String,
        entries: Vec<Uuid>,
    },
    Search {
        query: String,
        hits: Vec<(Uuid, f64)>,
        engine: SearchEngine,
        /// The result cap this search ran with (`m` doubles it).
        k: usize,
    },
    Backlinks {
        of_ref: String,
        entries: Vec<Uuid>,
    },
}

impl ListSource {
    pub fn is_all(&self) -> bool {
        matches!(self, ListSource::All)
    }

    /// The list panel's block title.
    pub fn title(&self, count: usize, scope: Option<&str>) -> String {
        match self {
            ListSource::All => {
                format!(" jots — {} ({count}) ", scope.unwrap_or("all"))
            }
            ListSource::Find { spec, .. } => format!(" find: {spec} ({count}) "),
            ListSource::Search { query, engine, .. } => match engine {
                SearchEngine::Hybrid => format!(" search: {query} ({count}) "),
                SearchEngine::Bm25 => format!(" search (bm25): {query} ({count}) "),
            },
            ListSource::Backlinks { of_ref, .. } => {
                format!(" backlinks: {of_ref} ({count}) ")
            }
        }
    }

    /// Score column for search results.
    pub fn score_of(&self, entry: Uuid) -> Option<f64> {
        match self {
            ListSource::Search { hits, .. } => {
                hits.iter().find(|(e, _)| *e == entry).map(|(_, s)| *s)
            }
            _ => None,
        }
    }
}

pub struct AppState {
    pub app: cuj::App,
    pub snapshot: Snapshot,
    /// Profile scope; None = all profiles.
    pub profile: Option<String>,
    pub source: ListSource,
    /// Indices into snapshot.rows: current source ∩ profile scope.
    pub visible: Vec<usize>,
    pub list: ListState,
    pub focus: Focus,
    pub mode: Mode,
    pub view_scroll: u16,
    /// Pre-wrap line count of the selected jot's content.
    pub content_lines: usize,
    pub content_cache: HashMap<Uuid, Rendered>,
    pub cmdline: CmdLine,
    /// Transclusion in the content view (`x` toggles): expanded
    /// content comes from cuj's show --expand path.
    pub expand: bool,
    pub message: Option<(Level, String)>,
    /// The stale-index warning fires once per snapshot.
    pub stale_warned: bool,
    pub quit: bool,
    /// Viewport heights, updated by the draw pass.
    pub list_height: u16,
    pub view_height: u16,
}

impl AppState {
    pub fn new(app: cuj::App) -> crate::Result<AppState> {
        let snapshot = Snapshot::build(&app)?;
        let active = app.client.active_profile.clone();
        let profile = snapshot
            .profiles
            .iter()
            .any(|(name, _)| *name == active)
            .then_some(active);
        let mut state = AppState {
            app,
            snapshot,
            profile,
            source: ListSource::All,
            visible: Vec::new(),
            list: ListState::default(),
            focus: Focus::List,
            mode: Mode::Normal,
            view_scroll: 0,
            content_lines: 0,
            content_cache: HashMap::new(),
            cmdline: CmdLine::default(),
            expand: false,
            message: None,
            stale_warned: false,
            quit: false,
            list_height: 0,
            view_height: 0,
        };
        state.recompute_visible();
        Ok(state)
    }

    pub fn scope(&self) -> Option<&str> {
        self.profile.as_deref()
    }

    /// Rebuild `visible` from source ∩ scope and clamp selection.
    pub fn recompute_visible(&mut self) {
        let scope = self.profile.clone();
        let scope = scope.as_deref();
        let snap = &self.snapshot;
        let in_scope = |i: &usize| scope.is_none_or(|p| snap.rows[*i].profile == p);
        self.visible = match &self.source {
            ListSource::All => (0..snap.rows.len()).filter(in_scope).collect(),
            ListSource::Find { entries, .. } | ListSource::Backlinks { entries, .. } => entries
                .iter()
                .filter_map(|e| snap.by_entry.get(e).copied())
                .filter(in_scope)
                .collect(),
            ListSource::Search { hits, .. } => hits
                .iter()
                .filter_map(|(e, _)| snap.by_entry.get(e).copied())
                .filter(in_scope)
                .collect(),
        };
        match (self.list.selected(), self.visible.len()) {
            (_, 0) => self.list.select(None),
            (None, _) => self.select_index(0),
            (Some(s), n) if s >= n => self.select_index(n - 1),
            _ => {}
        }
    }

    pub fn selected_row(&self) -> Option<&JotRow> {
        let i = self.list.selected()?;
        self.visible.get(i).map(|&r| &self.snapshot.rows[r])
    }

    /// Select by position in `visible`, resetting the view scroll.
    pub fn select_index(&mut self, i: usize) {
        if self.visible.is_empty() {
            self.list.select(None);
            return;
        }
        let i = i.min(self.visible.len() - 1);
        if self.list.selected() != Some(i) {
            self.view_scroll = 0;
        }
        self.list.select(Some(i));
    }

    /// Select the row holding `entry`, if visible.
    pub fn select_entry(&mut self, entry: Uuid) -> bool {
        let pos = self
            .visible
            .iter()
            .position(|&r| self.snapshot.rows[r].entry == entry);
        match pos {
            Some(i) => {
                self.select_index(i);
                true
            }
            None => false,
        }
    }

    pub fn set_message(&mut self, level: Level, text: impl Into<String>) {
        self.message = Some((level, text.into()));
    }

    /// Load the selected jot's content into the cache (head-only,
    /// so `Vault::get_bytes` suffices — no transient Reads needed),
    /// highlighted under its profile's parser configuration, and
    /// clamp the view scroll. Called once per loop iteration,
    /// before drawing.
    pub fn ensure_content(&mut self) {
        let Some((entry, profile, id)) = self
            .selected_row()
            .map(|r| (r.entry, r.profile.clone(), r.id))
        else {
            self.content_lines = 0;
            self.view_scroll = 0;
            return;
        };
        if !self.content_cache.contains_key(&entry) {
            let raw = || match self.app.vault.get_bytes(&entry.hyphenated().to_string()) {
                Ok(b) => String::from_utf8_lossy(&b).into_owned(),
                Err(e) => format!("(content unavailable: {e})"),
            };
            // Transclusion goes through cuj's expanding show path;
            // plain view reads the blob directly.
            let text = if self.expand {
                let r = cuj::RefArg {
                    profile: Some(profile.clone()),
                    id,
                    suffix: None,
                };
                match cuj::queries::show(&self.app, &cuj::Opts::default(), &r, true) {
                    Ok(cuj::queries::ShowOutcome::Shown { content, .. }) => content,
                    _ => raw(),
                }
            } else {
                raw()
            };
            let config = self
                .snapshot
                .configs
                .get(&profile)
                .cloned()
                .unwrap_or_else(|| cuj::facts::ProfileConfig::new(&profile));
            self.content_cache
                .insert(entry, highlight::render(&text, &config));
        }
        self.content_lines = self.content_cache[&entry].lines.len();
        // Approximate clamp: scroll offsets are pre-wrap lines.
        let max = self
            .content_lines
            .saturating_sub(self.view_height.max(1) as usize)
            .min(u16::MAX as usize) as u16;
        if self.view_scroll > max {
            self.view_scroll = max;
        }
    }

    pub fn content_of(&self, entry: Uuid) -> Option<&Rendered> {
        self.content_cache.get(&entry)
    }
}

// ── the reducer ────────────────────────────────────────────────────

pub fn apply(state: &mut AppState, cmd: Command) {
    // Any new command clears the previous message.
    state.message = None;
    match cmd {
        Command::Quit => state.quit = true,
        Command::Help => state.mode = Mode::Help,
        Command::Reload => reload(state),
        Command::CycleFocus => {
            state.focus = match state.focus {
                Focus::List => Focus::View,
                Focus::View => Focus::List,
            };
        }
        Command::Open => {
            if state.list.selected().is_some() {
                state.focus = Focus::View;
            }
        }
        Command::Back => back(state),
        Command::MoveDown => move_by(state, 1),
        Command::MoveUp => move_by(state, -1),
        Command::MoveTop => move_top(state),
        Command::MoveBottom => move_bottom(state),
        Command::HalfPageDown => move_by(state, half_page(state)),
        Command::HalfPageUp => move_by(state, -half_page(state)),
        Command::NextProfile => next_profile(state),
        Command::StartCommand(prefill) => {
            state.mode = Mode::Command;
            state.cmdline.start(prefill);
        }
        Command::Backlinks => backlinks_selected(state),
        Command::MoreResults => more_results(state),
        Command::ToggleExpand => {
            state.expand = !state.expand;
            state.content_cache.clear();
            state.set_message(
                Level::Info,
                if state.expand {
                    "transclusion on"
                } else {
                    "transclusion off"
                },
            );
        }
        // Edit needs the terminal (suspend, $EDITOR, resume), so
        // the run loop intercepts it before the reducer; reaching
        // here means a context without a terminal.
        Command::Edit => state.set_message(Level::Error, "edit needs a terminal"),
        Command::Ex(ex) => apply_ex(state, ex),
    }
}

fn more_results(state: &mut AppState) {
    match &state.source {
        ListSource::Search { query, k, .. } => {
            let (query, k) = (query.clone(), k.saturating_mul(2));
            run_search_k(state, query, k);
        }
        _ => state.set_message(Level::Info, "more applies to search results"),
    }
}

/// The selected jot as an edit target: an explicit-profile RefArg
/// plus its display label.
pub fn edit_target(state: &AppState) -> Option<(cuj::RefArg, String)> {
    let row = state.selected_row()?;
    let r = cuj::RefArg {
        profile: Some(row.profile.clone()),
        id: row.id,
        suffix: None,
    };
    Some((r, format!("--{}--{}", row.profile, row.id)))
}

fn apply_ex(state: &mut AppState, ex: ExCommand) {
    match ex {
        ExCommand::Quit => state.quit = true,
        ExCommand::Help => state.mode = Mode::Help,
        ExCommand::Reload => reload(state),
        ExCommand::Profile(name) => set_profile(state, name),
        ExCommand::Find(spec) => run_find(state, spec),
        ExCommand::Search(query) => run_search(state, query),
        ExCommand::Goto(r) => goto(state, &r),
        ExCommand::Backlinks(Some(r)) => match resolve_ref(state, &r) {
            Ok(i) => {
                let row = &state.snapshot.rows[i];
                let (entry, label) = (row.entry, row.short_ref(state.scope()));
                run_backlinks(state, entry, label);
            }
            Err(msg) => state.set_message(Level::Error, msg),
        },
        ExCommand::Backlinks(None) => backlinks_selected(state),
    }
}

// ── movement ───────────────────────────────────────────────────────

fn half_page(state: &AppState) -> i64 {
    let h = match state.focus {
        Focus::List => state.list_height,
        Focus::View => state.view_height,
    };
    (h / 2).max(1) as i64
}

fn move_by(state: &mut AppState, delta: i64) {
    match state.focus {
        Focus::List => {
            let Some(sel) = state.list.selected() else {
                return;
            };
            let n = state.visible.len() as i64;
            let next = (sel as i64 + delta).clamp(0, (n - 1).max(0));
            state.select_index(next as usize);
        }
        Focus::View => {
            let next = (state.view_scroll as i64 + delta).max(0);
            // Upper clamp happens in ensure_content, which knows
            // the content length.
            state.view_scroll = next.min(u16::MAX as i64) as u16;
        }
    }
}

fn move_top(state: &mut AppState) {
    match state.focus {
        Focus::List => state.select_index(0),
        Focus::View => state.view_scroll = 0,
    }
}

fn move_bottom(state: &mut AppState) {
    match state.focus {
        Focus::List => {
            if !state.visible.is_empty() {
                state.select_index(state.visible.len() - 1);
            }
        }
        // Clamped down to the real maximum by ensure_content.
        Focus::View => state.view_scroll = u16::MAX,
    }
}

/// Staged retreat: View → List, then results → all jots.
fn back(state: &mut AppState) {
    if state.focus == Focus::View {
        state.focus = Focus::List;
        return;
    }
    if !state.source.is_all() {
        let keep = state.selected_row().map(|r| r.entry);
        state.source = ListSource::All;
        state.recompute_visible();
        if let Some(e) = keep {
            state.select_entry(e);
        }
    }
}

// ── profile scope ──────────────────────────────────────────────────

fn next_profile(state: &mut AppState) {
    let mut options: Vec<Option<String>> = state
        .snapshot
        .profiles
        .iter()
        .map(|(name, _)| Some(name.clone()))
        .collect();
    options.push(None);
    let cur = options
        .iter()
        .position(|o| *o == state.profile)
        .unwrap_or(options.len() - 1);
    let next = options[(cur + 1) % options.len()].clone();
    set_scope(state, next);
}

fn set_profile(state: &mut AppState, name: String) {
    if name == "all" {
        set_scope(state, None);
    } else if state.snapshot.profiles.iter().any(|(n, _)| *n == name) {
        set_scope(state, Some(name));
    } else {
        state.set_message(Level::Error, format!("not found: profile {name:?}"));
    }
}

fn set_scope(state: &mut AppState, scope: Option<String>) {
    state.profile = scope;
    state.recompute_visible();
    state.select_index(0);
    let label = match state.scope() {
        Some(p) => format!("profile: {p} ({} jots)", state.visible.len()),
        None => format!("profile: all ({} jots)", state.visible.len()),
    };
    state.set_message(Level::Info, label);
}

// ── snapshot reload ────────────────────────────────────────────────

fn reload(state: &mut AppState) {
    let keep = state.selected_row().map(|r| r.entry);
    match Snapshot::build(&state.app) {
        Ok(s) => {
            state.snapshot = s;
            state.content_cache.clear();
            state.stale_warned = false;
            if let Some(p) = state.profile.clone() {
                if !state.snapshot.profiles.iter().any(|(n, _)| *n == p) {
                    state.profile = None;
                }
            }
            state.recompute_visible();
            if let Some(e) = keep {
                state.select_entry(e);
            }
            state.set_message(Level::Info, "reloaded");
        }
        Err(e) => state.set_message(Level::Error, e.to_string()),
    }
}

// ── queries ────────────────────────────────────────────────────────

fn run_find(state: &mut AppState, spec: FindSpec) {
    match query::find(&state.app, &spec) {
        Ok((entries, stale)) => {
            state.source = ListSource::Find {
                spec: spec.raw.clone(),
                entries,
            };
            finish_query(state, stale, None);
        }
        Err(e) => state.set_message(Level::Error, e.to_string()),
    }
}

fn run_search(state: &mut AppState, query_text: String) {
    run_search_k(state, query_text, 50);
}

fn run_search_k(state: &mut AppState, query_text: String, k: usize) {
    match query::search(&state.app, &state.snapshot, &query_text, k) {
        Ok((hits, stale, engine)) => {
            state.source = ListSource::Search {
                query: query_text,
                hits,
                engine,
                k,
            };
            let note = match engine {
                SearchEngine::Hybrid => None,
                SearchEngine::Bm25 => Some(" — bm25 only (no zetetes chain; run 'zetetes init')"),
            };
            finish_query(state, stale, note);
        }
        Err(e) => state.set_message(Level::Error, e.to_string()),
    }
}

fn backlinks_selected(state: &mut AppState) {
    let Some(row) = state.selected_row() else {
        state.set_message(Level::Error, "no jot selected");
        return;
    };
    let (entry, label) = (row.entry, row.short_ref(state.scope()));
    run_backlinks(state, entry, label);
}

fn run_backlinks(state: &mut AppState, of: Uuid, label: String) {
    match query::backlinks(&state.app, of) {
        Ok((entries, stale)) => {
            state.source = ListSource::Backlinks {
                of_ref: label,
                entries,
            };
            finish_query(state, stale, None);
        }
        Err(e) => state.set_message(Level::Error, e.to_string()),
    }
}

fn finish_query(state: &mut AppState, stale: bool, note: Option<&str>) {
    state.recompute_visible();
    state.select_index(0);
    state.focus = Focus::List;
    if stale && !state.stale_warned {
        state.stale_warned = true;
        state.set_message(
            Level::Warn,
            "index stale — results may lag; run 'cuj reindex'",
        );
    } else {
        let n = state.visible.len();
        state.set_message(
            Level::Info,
            format!("{n} result{}{}", plural(n), note.unwrap_or("")),
        );
    }
}

fn plural(n: usize) -> &'static str {
    if n == 1 { "" } else { "s" }
}

// ── goto ───────────────────────────────────────────────────────────

/// Resolve a `--ref` against the snapshot: explicit profile, else
/// the scoped profile (bare `--N` is ambiguous under `all`, as in
/// the CLI).
fn resolve_ref(state: &AppState, r: &cuj::RefArg) -> Result<usize, String> {
    let profile = match r.profile.clone().or_else(|| state.profile.clone()) {
        Some(p) => p,
        None => {
            return Err("bare --N is ambiguous under profile all; use --profile--N".into());
        }
    };
    state
        .snapshot
        .by_ident
        .get(&(profile.clone(), r.id))
        .copied()
        .ok_or_else(|| format!("not found: --{profile}--{}", r.id))
}

fn goto(state: &mut AppState, r: &cuj::RefArg) {
    let row_idx = match resolve_ref(state, r) {
        Ok(i) => i,
        Err(msg) => {
            state.set_message(Level::Error, msg);
            return;
        }
    };
    let (entry, profile) = {
        let row = &state.snapshot.rows[row_idx];
        (row.entry, row.profile.clone())
    };
    // Widen scope if the target lives in another profile.
    if state.scope().is_some_and(|p| p != profile) {
        state.profile = Some(profile);
        state.recompute_visible();
    }
    if !state.select_entry(entry) {
        // Not in the current result list: fall back to all jots.
        state.source = ListSource::All;
        state.recompute_visible();
        state.select_entry(entry);
    }
    state.focus = Focus::View;
    // A fragment or bookmark suffix scrolls the view to its line.
    if let Some(suffix) = r.suffix.clone() {
        scroll_to_suffix(state, entry, &suffix);
    }
}

/// The pre-wrap line a reference suffix points at; ensure_content
/// clamps against the real content length afterwards.
fn scroll_to_suffix(state: &mut AppState, entry: Uuid, suffix: &cuj::app::Suffix) {
    let text = match state.app.vault.get_bytes(&entry.hyphenated().to_string()) {
        Ok(b) => String::from_utf8_lossy(&b).into_owned(),
        Err(_) => return,
    };
    let line = match suffix {
        cuj::app::Suffix::Lines(a, _) => a.saturating_sub(1),
        cuj::app::Suffix::Bookmark(name) => {
            let anchor = format!("!!{name}");
            match text
                .lines()
                .position(|l| l.split_whitespace().any(|w| w == anchor))
            {
                Some(i) => i,
                None => {
                    state.set_message(Level::Warn, format!("bookmark #{name} not found"));
                    return;
                }
            }
        }
    };
    state.view_scroll = line.min(u16::MAX as usize) as u16;
}