Skip to main content

mneme/tui/
app.rs

1use std::sync::Arc;
2
3use chrono::{DateTime, Utc};
4
5use crate::config::settings::Settings;
6use crate::store::db::Database;
7use crate::store::entities::{EntitySearchResult, EntityType};
8use crate::store::memory::{GraphData, Memory, MemoryStats, ProjectSummary, SearchQuery, Session};
9
10/// Tabs del panel de detalle.
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub enum DetailTab {
13    Content,
14    Structured,
15    Entities,
16    Temporal,
17    Relations,
18}
19impl DetailTab {
20    pub fn label(&self) -> &'static str {
21        match self {
22            Self::Content => "Content",
23            Self::Structured => "Fields",
24            Self::Entities => "Entities",
25            Self::Temporal => "Temporal",
26            Self::Relations => "Graph",
27        }
28    }
29    pub fn next(&self) -> Self {
30        match self {
31            Self::Content => Self::Structured,
32            Self::Structured => Self::Entities,
33            Self::Entities => Self::Temporal,
34            Self::Temporal => Self::Relations,
35            Self::Relations => Self::Content,
36        }
37    }
38    pub fn prev(&self) -> Self {
39        match self {
40            Self::Content => Self::Relations,
41            Self::Structured => Self::Content,
42            Self::Entities => Self::Structured,
43            Self::Temporal => Self::Entities,
44            Self::Relations => Self::Temporal,
45        }
46    }
47}
48
49/// Estado global de la app — estilo lazygit/lazydocker.
50pub struct App {
51    pub project: String,
52    pub memories: Vec<Memory>,
53    pub sessions: Vec<Session>,
54    pub selected: usize,
55    pub scroll: usize,
56    pub search: String,
57    pub status_msg: Option<String>,
58    pub quit: bool,
59    pub show_help: bool,
60    pub detail_tab: DetailTab,
61    pub detail_scroll: usize,
62    pub stats: Option<MemoryStats>,
63    pub graph: Option<GraphData>,
64    pub graph_sel: usize,
65    pub entity_data: Option<Vec<(String, EntityType, u32)>>,
66    pub temporal_data: Option<(Vec<Memory>, u8)>,
67    pub active_panel: usize, // 0=lista, 1=detalle, 2=search
68    pub total_mems: u32,
69    pub db: Arc<Database>,
70}
71
72impl App {
73    pub fn new(db: Arc<Database>, _settings: Arc<Settings>) -> Self {
74        // Show all projects by default, or infer if none
75        let project = Settings::infer_project();
76        Self {
77            project,
78            memories: Vec::new(),
79            sessions: Vec::new(),
80            selected: 0,
81            scroll: 0,
82            search: String::new(),
83            status_msg: None,
84            quit: false,
85            show_help: false,
86            detail_tab: DetailTab::Content,
87            detail_scroll: 0,
88            stats: None,
89            graph: None,
90            graph_sel: 0,
91            entity_data: None,
92            temporal_data: None,
93            active_panel: 0,
94            total_mems: 0,
95            db,
96        }
97    }
98
99    // ── CARGA ──
100    pub fn load(&mut self) {
101        let s = self.db.memories();
102        if self.search.is_empty() {
103            // Show memories from all projects
104            let mut all = Vec::new();
105            if let Ok(projects) = s.list_projects() {
106                for p in &projects {
107                    if let Ok(pmems) = s.list(&p.name, None, None, None, 100, 0) {
108                        all.extend(pmems);
109                    }
110                }
111            }
112            all.sort_by(|a, b| b.created_at.cmp(&a.created_at));
113            all.truncate(500);
114            self.memories = all;
115        } else {
116            let q = SearchQuery {
117                text: self.search.clone(),
118                project: None,
119                scope: None,
120                memory_type: None,
121                importance: None,
122                tags: vec![],
123                limit: 200,
124                include_snippet: false,
125                all_projects: true,
126            };
127            self.memories = s
128                .search(&q, &crate::store::search::SearchWeights::default(), None)
129                .unwrap_or_default()
130                .into_iter()
131                .map(|r| r.memory)
132                .collect();
133        }
134        self.selected = self.selected.min(self.memories.len().saturating_sub(1));
135        self.scroll = 0;
136        self.detail_scroll = 0;
137        // Show total stats across all projects
138        let mut total_mems = self.memories.len() as u32;
139        if let Ok(projects) = s.list_projects() {
140            total_mems = projects.iter().map(|p| p.memory_count).sum();
141        }
142        self.total_mems = total_mems;
143        self.sessions = self
144            .db
145            .sessions()
146            .list(&self.project, 50)
147            .unwrap_or_default();
148    }
149
150    // ── NAV ──
151    pub fn down(&mut self) {
152        if !self.memories.is_empty() {
153            self.selected = (self.selected + 1).min(self.memories.len() - 1);
154            if self.selected >= self.scroll + 20 {
155                self.scroll += 1;
156            }
157        }
158    }
159    pub fn up(&mut self) {
160        self.selected = self.selected.saturating_sub(1);
161        if self.selected < self.scroll {
162            self.scroll = self.scroll.saturating_sub(1);
163        }
164    }
165    pub fn first(&mut self) {
166        self.selected = 0;
167        self.scroll = 0;
168    }
169    pub fn last(&mut self) {
170        if !self.memories.is_empty() {
171            self.selected = self.memories.len() - 1;
172            self.scroll = self.selected.saturating_sub(19);
173        }
174    }
175    pub fn pgdn(&mut self) {
176        if !self.memories.is_empty() {
177            self.selected = (self.selected + 20).min(self.memories.len() - 1);
178            if self.selected >= self.scroll + 20 {
179                self.scroll += 20;
180            }
181        }
182    }
183    pub fn pgup(&mut self) {
184        self.selected = self.selected.saturating_sub(20);
185        if self.selected < self.scroll {
186            self.scroll = self.scroll.saturating_sub(20);
187        }
188    }
189    pub fn sel(&self) -> Option<&Memory> {
190        self.memories.get(self.selected)
191    }
192
193    // ── DETAIL ──
194    pub fn tab_next(&mut self) {
195        self.detail_tab = self.detail_tab.next();
196        self.detail_scroll = 0;
197    }
198    pub fn tab_prev(&mut self) {
199        self.detail_tab = self.detail_tab.prev();
200        self.detail_scroll = 0;
201    }
202    pub fn dscroll_down(&mut self) {
203        self.detail_scroll += 3;
204    }
205    pub fn dscroll_up(&mut self) {
206        self.detail_scroll = self.detail_scroll.saturating_sub(3);
207    }
208
209    // ── ACTIONS ──
210    pub fn delete_sel(&mut self) {
211        if let Some(m) = self.sel() {
212            self.db.memories().delete(m.id, false).ok();
213            self.status_msg = Some("🗑 Deleted".into());
214            self.load();
215        }
216    }
217    pub fn load_graph(&mut self) {
218        self.graph = self.db.memories().get_graph(&self.project).ok();
219        self.graph_sel = 0;
220    }
221    pub fn graph_next(&mut self) {
222        if let Some(ref d) = self.graph {
223            if !d.nodes.is_empty() {
224                self.graph_sel = (self.graph_sel + 1) % d.nodes.len();
225            }
226        }
227    }
228    pub fn graph_prev(&mut self) {
229        if let Some(ref d) = self.graph {
230            if !d.nodes.is_empty() {
231                self.graph_sel = self.graph_sel.checked_sub(1).unwrap_or(d.nodes.len() - 1);
232            }
233        }
234    }
235    pub fn load_entity(&mut self) {
236        self.entity_data = self.db.entities().frequent_entities(&self.project, 30).ok();
237    }
238    pub fn load_temporal(&mut self) {
239        self.temporal_data = Some((
240            self.db
241                .memories()
242                .list(&self.project, None, None, None, 500, 0)
243                .unwrap_or_default(),
244            0,
245        ));
246    }
247    pub fn temporal_cycle(&mut self) {
248        if let Some(ref mut td) = self.temporal_data {
249            td.1 = (td.1 + 1) % 3;
250        }
251    }
252}