kimun-notes 0.12.0

A terminal-based notes application
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
//! `PanelOrder` — the pure focus/order/visibility state machine for the
//! editor screen's persistent **Panels**. Keyed only on `PanelKind`, so it
//! carries no vault or heavy component state and is testable in isolation.
//! `PanelSet` (below) composes it with the concrete panels.

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::widgets::{Block, Borders};

use crate::components::Component;
use crate::components::backlinks_panel::QueryPanel;
use crate::components::event_state::EventState;
use crate::components::events::{AppTx, InputEvent};
use crate::components::panel::PanelKind;
use crate::components::sidebar::SidebarComponent;
use crate::components::text_editor::TextEditorComponent;
use crate::settings::themes::Theme;

struct Slot {
    kind: PanelKind,
    visible: bool,
}

/// Ordered panels + which one is focused. Order is config-driven and may be
/// permuted at runtime; focus tracks a panel by kind, not by index, so it
/// survives reordering. The editor panel is always visible.
pub struct PanelOrder {
    slots: Vec<Slot>,
    focus: usize,
}

impl PanelOrder {
    /// Default layout: sidebar (visible) → editor (visible, focused) → Query
    /// panel (hidden).
    pub fn new() -> Self {
        let slots = vec![
            Slot {
                kind: PanelKind::Sidebar,
                visible: true,
            },
            Slot {
                kind: PanelKind::Editor,
                visible: true,
            },
            Slot {
                kind: PanelKind::Query,
                visible: false,
            },
        ];
        let focus = slots
            .iter()
            .position(|s| s.kind == PanelKind::Editor)
            .expect("editor slot present");
        Self { slots, focus }
    }

    /// The currently focused panel.
    pub fn focused(&self) -> PanelKind {
        self.slots[self.focus].kind
    }

    /// The panel one step left of focus in the current order, or `None` if
    /// focus is already at the left end.
    pub fn prev_kind(&self) -> Option<PanelKind> {
        self.focus.checked_sub(1).map(|i| self.slots[i].kind)
    }

    /// The panel one step right of focus in the current order, or `None` if
    /// focus is already at the right end.
    pub fn next_kind(&self) -> Option<PanelKind> {
        self.slots.get(self.focus + 1).map(|s| s.kind)
    }

    /// Move focus to `kind`. No-op if the kind is not present.
    pub fn focus(&mut self, kind: PanelKind) {
        if let Some(i) = self.slots.iter().position(|s| s.kind == kind) {
            self.focus = i;
        }
    }

    /// Whether `kind` is currently visible.
    pub fn is_visible(&self, kind: PanelKind) -> bool {
        self.slots
            .iter()
            .find(|s| s.kind == kind)
            .is_some_and(|s| s.visible)
    }

    /// Reveal `kind`.
    pub fn show(&mut self, kind: PanelKind) {
        if let Some(s) = self.slots.iter_mut().find(|s| s.kind == kind) {
            s.visible = true;
        }
    }

    /// Hide `kind`. The editor is always visible, so hiding it is a no-op.
    pub fn hide(&mut self, kind: PanelKind) {
        if kind == PanelKind::Editor {
            return;
        }
        if let Some(s) = self.slots.iter_mut().find(|s| s.kind == kind) {
            s.visible = false;
        }
        // If focus was on the panel we just hid, move it to the nearest
        // visible panel (the editor is always visible, so a target exists).
        if !self.slots[self.focus].visible {
            self.focus = self.nearest_visible(self.focus);
        }
    }

    /// The visible panels in their current left→right order. Drives the
    /// render layout: each panel contributes one column in this sequence.
    pub fn visible_in_order(&self) -> Vec<PanelKind> {
        self.slots
            .iter()
            .filter(|s| s.visible)
            .map(|s| s.kind)
            .collect()
    }

    /// Reorder the panels to match `order` (a permutation of the panel kinds).
    /// Each panel keeps its visibility, and focus stays on the same panel by
    /// kind — so a config reorder needs no other state changes. Kinds omitted
    /// from `order` keep their relative position at the end.
    pub fn set_order(&mut self, order: &[PanelKind]) {
        let focused_kind = self.focused();
        let mut new: Vec<Slot> = Vec::with_capacity(self.slots.len());
        for &k in order {
            if let Some(pos) = self.slots.iter().position(|s| s.kind == k) {
                new.push(self.slots.remove(pos));
            }
        }
        new.append(&mut self.slots);
        self.slots = new;
        self.focus = self
            .slots
            .iter()
            .position(|s| s.kind == focused_kind)
            .unwrap_or(0);
    }

    /// Index of the nearest visible slot, searching outward from `from`.
    /// Falls back to `from` if somehow nothing is visible (cannot happen —
    /// the editor is always visible).
    fn nearest_visible(&self, from: usize) -> usize {
        let n = self.slots.len();
        (1..n)
            .flat_map(|d| [from.checked_sub(d), Some(from + d).filter(|&i| i < n)])
            .flatten()
            .find(|&i| self.slots[i].visible)
            .unwrap_or(from)
    }
}

impl Default for PanelOrder {
    fn default() -> Self {
        Self::new()
    }
}

/// Column width a panel occupies when laid out. The editor fills; the sidebar
/// and Query panel are fixed-width. (A future config could override these.)
fn panel_column(kind: PanelKind) -> Constraint {
    match kind {
        PanelKind::Sidebar => Constraint::Length(30),
        PanelKind::Editor => Constraint::Min(0),
        PanelKind::Query => Constraint::Length(40),
    }
}

/// The editor screen's persistent **Panels** — the sidebar, the editor, and
/// the **Query panel** — plus the `PanelOrder` that decides their order,
/// visibility, and which one is focused. Routes input and render to the
/// focused / visible panels; the host (`EditorScreen`) reaches a specific
/// panel through the typed accessors for panel-specific calls.
pub struct PanelSet {
    order: PanelOrder,
    sidebar: SidebarComponent,
    editor: TextEditorComponent,
    query: QueryPanel,
}

impl PanelSet {
    pub fn from_panels(
        sidebar: SidebarComponent,
        editor: TextEditorComponent,
        query: QueryPanel,
    ) -> Self {
        Self {
            order: PanelOrder::new(),
            sidebar,
            editor,
            query,
        }
    }

    // ── Order / focus / visibility (delegate to PanelOrder) ─────────────────

    pub fn focused(&self) -> PanelKind {
        self.order.focused()
    }

    pub fn focused_label(&self) -> &'static str {
        self.order.focused().label()
    }

    pub fn prev_kind(&self) -> Option<PanelKind> {
        self.order.prev_kind()
    }

    pub fn next_kind(&self) -> Option<PanelKind> {
        self.order.next_kind()
    }

    pub fn is_visible(&self, kind: PanelKind) -> bool {
        self.order.is_visible(kind)
    }

    pub fn show(&mut self, kind: PanelKind) {
        self.order.show(kind);
    }

    pub fn hide(&mut self, kind: PanelKind) {
        self.order.hide(kind);
    }

    pub fn set_order(&mut self, order: &[PanelKind]) {
        self.order.set_order(order);
    }

    /// Move focus to `kind`. Any transition away from the editor closes its
    /// autocomplete popup so it doesn't linger while another panel owns input.
    pub fn focus(&mut self, kind: PanelKind) {
        if kind != PanelKind::Editor {
            self.editor.close_autocomplete();
        }
        self.order.focus(kind);
    }

    // ── Typed accessors for panel-specific calls ───────────────────────────

    pub fn sidebar(&self) -> &SidebarComponent {
        &self.sidebar
    }
    pub fn sidebar_mut(&mut self) -> &mut SidebarComponent {
        &mut self.sidebar
    }
    pub fn editor(&self) -> &TextEditorComponent {
        &self.editor
    }
    pub fn editor_mut(&mut self) -> &mut TextEditorComponent {
        &mut self.editor
    }
    pub fn query(&self) -> &QueryPanel {
        &self.query
    }
    pub fn query_mut(&mut self) -> &mut QueryPanel {
        &mut self.query
    }

    // ── Routing ────────────────────────────────────────────────────────────

    /// Footer hints for the focused panel.
    pub fn focused_hints(&self) -> Vec<(String, String)> {
        match self.order.focused() {
            PanelKind::Sidebar => self.sidebar.hint_shortcuts(),
            PanelKind::Editor => self.editor.hint_shortcuts(),
            PanelKind::Query => self.query.hint_shortcuts(),
        }
    }

    /// Route an input event to the focused panel. The Query panel speaks
    /// `handle_key`, so non-key events are not delivered to it.
    pub fn handle_input(&mut self, event: &InputEvent, tx: &AppTx) -> EventState {
        match self.order.focused() {
            PanelKind::Sidebar => self.sidebar.handle_input(event, tx),
            PanelKind::Editor => self.editor.handle_input(event, tx),
            PanelKind::Query => {
                if let InputEvent::Key(key) = event {
                    self.query.handle_key(key, tx)
                } else {
                    EventState::NotConsumed
                }
            }
        }
    }

    /// Lay the visible panels out left→right in their current order and render
    /// each. `show_focus` is false while an overlay is open, so no panel draws
    /// its focused highlight under the overlay.
    pub fn render(&mut self, f: &mut Frame, area: Rect, theme: &Theme, show_focus: bool) {
        let visible = self.order.visible_in_order();
        if visible.is_empty() {
            return;
        }
        let constraints: Vec<Constraint> = visible.iter().map(|k| panel_column(*k)).collect();
        let columns = Layout::default()
            .direction(Direction::Horizontal)
            .constraints(constraints)
            .split(area);

        let focused = self.order.focused();
        for (i, kind) in visible.iter().enumerate() {
            let is_focused = show_focus && *kind == focused;
            let rect = columns[i];
            match kind {
                PanelKind::Sidebar => self.sidebar.render(f, rect, theme, is_focused),
                PanelKind::Query => self.query.render(f, rect, theme, is_focused),
                PanelKind::Editor => {
                    // The editor's frame is drawn here (not by the component) so
                    // the dirty marker and focus border live with the layout.
                    let title = if self.editor.is_dirty() {
                        "Editor [+]"
                    } else {
                        "Editor"
                    };
                    let block = Block::default()
                        .title(title)
                        .borders(Borders::ALL)
                        .border_style(theme.border_style(is_focused))
                        .style(theme.base_style());
                    let inner = block.inner(rect);
                    f.render_widget(block, rect);
                    self.editor.render(f, inner, theme, is_focused);
                }
            }
        }
    }
}

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

    #[test]
    fn default_focus_is_editor() {
        let order = PanelOrder::new();
        assert_eq!(order.focused(), PanelKind::Editor);
    }

    #[test]
    fn adjacent_kinds_follow_order_and_clamp_at_ends() {
        let order = PanelOrder::new();
        // focus = editor (middle)
        assert_eq!(order.prev_kind(), Some(PanelKind::Sidebar));
        assert_eq!(order.next_kind(), Some(PanelKind::Query));
    }

    #[test]
    fn focus_moves_and_clamps_at_ends() {
        let mut order = PanelOrder::new();
        order.focus(PanelKind::Sidebar);
        assert_eq!(order.focused(), PanelKind::Sidebar);
        assert_eq!(order.prev_kind(), None);
        assert_eq!(order.next_kind(), Some(PanelKind::Editor));

        order.focus(PanelKind::Query);
        assert_eq!(order.prev_kind(), Some(PanelKind::Editor));
        assert_eq!(order.next_kind(), None);
    }

    #[test]
    fn show_hide_toggles_visibility_except_editor() {
        let mut order = PanelOrder::new();
        assert!(order.is_visible(PanelKind::Sidebar));
        assert!(!order.is_visible(PanelKind::Query));

        order.show(PanelKind::Query);
        assert!(order.is_visible(PanelKind::Query));
        order.hide(PanelKind::Sidebar);
        assert!(!order.is_visible(PanelKind::Sidebar));

        // Editor cannot be hidden.
        order.hide(PanelKind::Editor);
        assert!(order.is_visible(PanelKind::Editor));
    }

    #[test]
    fn hiding_focused_panel_moves_focus_to_visible() {
        let mut order = PanelOrder::new();
        order.focus(PanelKind::Sidebar);
        order.hide(PanelKind::Sidebar);
        // Focus cannot stay on a hidden panel.
        assert!(order.is_visible(order.focused()));
        assert_eq!(order.focused(), PanelKind::Editor);
    }

    #[test]
    fn set_order_permutes_keeping_focus_and_visibility() {
        let mut order = PanelOrder::new();
        // Sidebar visible, Query hidden, focus on Editor.
        order.set_order(&[PanelKind::Query, PanelKind::Editor, PanelKind::Sidebar]);

        // Focus tracks the same panel by kind.
        assert_eq!(order.focused(), PanelKind::Editor);
        // Adjacency now follows the new order.
        assert_eq!(order.prev_kind(), Some(PanelKind::Query));
        assert_eq!(order.next_kind(), Some(PanelKind::Sidebar));
        // Visibility is preserved per kind across the reorder.
        assert!(order.is_visible(PanelKind::Sidebar));
        assert!(!order.is_visible(PanelKind::Query));
    }

    #[test]
    fn visible_in_order_skips_hidden_and_follows_order() {
        let mut order = PanelOrder::new();
        assert_eq!(
            order.visible_in_order(),
            vec![PanelKind::Sidebar, PanelKind::Editor]
        );
        order.show(PanelKind::Query);
        order.set_order(&[PanelKind::Query, PanelKind::Editor, PanelKind::Sidebar]);
        assert_eq!(
            order.visible_in_order(),
            vec![PanelKind::Query, PanelKind::Editor, PanelKind::Sidebar]
        );
    }
}