diff --git a/AGENTS-TASKS.md b/AGENTS-TASKS.md index f34d7e3..08d5ea1 100644 --- a/AGENTS-TASKS.md +++ b/AGENTS-TASKS.md @@ -282,3 +282,13 @@ These require user approval and are not part of the current implementation: TUI coverage includes nine state/render tests and three binary startup tests. - Release boundary: write workflows and history comparison stay in the CLI; cross-terminal visual review remains useful before publishing a final release. + +## TUI formatted details + +- [x] Default entity/event details to a readable, sectioned presentation. +- [x] Toggle formatted/raw JSON with `v`, preserving selection and resetting scroll. +- [x] Cover modal keys and both representations; update help and docs and run gates. +- Decision: format serialized fields in the TUI so nested/future metadata stays + visible without changing domain types or persistence. +- Validation: 112 all-feature tests and 108 portable tests, formatting, strict + Clippy, both release builds, and the PTY smoke check passed. diff --git a/README.md b/README.md index 61f96ed..c15b454 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,8 @@ Run `efo --help`, `efo --help`, or see the `efo chr show Aria` provide targeted or detailed inspection. Run `efo-tui` in a repository root (or use `--repository PATH`). Press `/` to -search and `1`/`2`/`3` to browse HEAD/index/worktree. Narrow terminals show one +search, `1`/`2`/`3` to browse HEAD/index/worktree, and `v` to toggle formatted +details and raw JSON. Narrow terminals show one focused panel; Tab cycles panels. Use `--no-color` for monochrome output and `?` for the scrollable keyboard reference. No Nerd Font is required. diff --git a/docs/tui-design.md b/docs/tui-design.md index 7eb44e6..b1ee755 100644 --- a/docs/tui-design.md +++ b/docs/tui-design.md @@ -27,7 +27,13 @@ The header reports HEAD, staged and unstaged changes, writer-lock state, the viewed layer, and its world summary. Start in the worktree. Press `1`, `2`, or `3` to browse HEAD, index, or worktree. Collection counts reflect the viewed layer. Entities sort by lowercase name, then stable UUID, and show a shortened -UUID beside their name; details include the full UUID and serialized fields. +UUID beside their name. Details default to a formatted view with the full UUID, +description, properties, metadata, and statistics. Bold headings, aligned +labels, and indented nested fields make events and other entities readable. +Press `v` to switch between formatted details and the complete, indented raw +JSON. The panel title identifies the mode. Switching resets detail scrolling to +the top, preserves the selected entity and layer, and keeps the chosen mode +while navigating or reloading during the session. Both modes wrap and scroll. Switch to an earlier layer to inspect an entity removed from the worktree. Use `efo diff` or `efo diff --staged` for a complete change comparison. @@ -47,6 +53,7 @@ While editing, ordinary character keys enter text instead of invoking commands. | `/` | Edit the search filter; Backspace removes a character | | `Enter`, `Esc` during search | Keep filter / restore previous filter | | `1`, `2`, `3` | View HEAD / index / worktree | +| `v` | Toggle formatted / raw JSON details | | `r` | Reload from disk, preserving selection by UUID when present | | `?`, `!` | Open help and the last reload diagnostic | | `?`, `!`, `q`, `Esc` in help | Close help | diff --git a/tui_efo/src/details.rs b/tui_efo/src/details.rs new file mode 100644 index 0000000..2070787 --- /dev/null +++ b/tui_efo/src/details.rs @@ -0,0 +1,216 @@ +//! Presentation-only entity views, derived from the same serialized fields. +use lib_efo::entity::Entity; +use ratatui::{ + style::Stylize, + text::{Line, Span, Text}, +}; +use serde_json::Value; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum DetailView { + #[default] + Formatted, + Json, +} + +impl DetailView { + pub fn toggle(&mut self) { + *self = match self { + Self::Formatted => Self::Json, + Self::Json => Self::Formatted, + }; + } + + pub fn name(self) -> &'static str { + match self { + Self::Formatted => "Formatted", + Self::Json => "JSON", + } + } + + pub fn text(self, entity: &Entity) -> Text<'static> { + match self { + Self::Json => match serde_json::to_string_pretty(entity) { + Ok(json) => Text::from(json), + Err(error) => Text::from(format!("Could not display details: {error}")), + }, + Self::Formatted => match serde_json::to_value(entity) { + Ok(value) => formatted(entity, &value), + Err(error) => Text::from(format!("Could not display details: {error}")), + }, + } + } +} + +fn formatted(entity: &Entity, value: &Value) -> Text<'static> { + let mut lines = vec![ + Line::from(entity.name.clone()).bold(), + Line::from(format!("@{}", entity.id)), + Line::from(""), + Line::from("Description").bold(), + ]; + if entity.description.is_empty() { + lines.push(Line::from("—")); + } else { + lines.extend( + entity + .description + .split('\n') + .map(|line| Line::from(line.to_owned())), + ); + } + if let Some(fields) = value.as_object() { + lines.push(Line::from("")); + lines.push(Line::from("Properties").bold()); + for key in ["entity_type", "duration", "effect_nature", "effect_bounds"] { + if let Some(value) = fields.get(key) { + field(&mut lines, key, value, 0); + } + } + for (key, value) in fields { + if matches!( + key.as_str(), + "name" + | "id" + | "description" + | "entity_type" + | "duration" + | "effect_nature" + | "effect_bounds" + ) { + continue; + } + lines.push(Line::from("")); + field(&mut lines, key, value, 0); + } + } + Text::from(lines) +} + +fn label(key: &str) -> String { + match key { + "entity_type" => "Type".into(), + "stats" => "Statistics".into(), + _ => { + let words = key.replace('_', " "); + let mut chars = words.chars(); + match chars.next() { + Some(first) => first.to_uppercase().collect::() + chars.as_str(), + None => String::new(), + } + } + } +} + +fn scalar(value: &Value) -> String { + match value { + Value::Null => "—".into(), + Value::String(text) if text.is_empty() => "(empty)".into(), + Value::String(text) => text.clone(), + _ => value.to_string(), + } +} + +fn field(lines: &mut Vec>, key: &str, value: &Value, depth: usize) { + let indent = " ".repeat(depth); + let label = label(key); + match value { + Value::Object(fields) if !fields.is_empty() => { + lines.push(Line::from(format!("{indent}{label}")).bold()); + for (key, value) in fields { + field(lines, key, value, depth + 1); + } + } + Value::Array(items) if items.iter().any(|item| item.is_object() || item.is_array()) => { + lines.push(Line::from(format!("{indent}{label}")).bold()); + for (index, value) in items.iter().enumerate() { + field(lines, &format!("Item {}", index + 1), value, depth + 1); + } + } + _ => { + let text = match value { + Value::Object(_) => "(empty)".into(), + Value::Array(items) if items.is_empty() => "None".into(), + Value::Array(items) => items.iter().map(scalar).collect::>().join(", "), + _ => scalar(value), + }; + for (index, part) in text.split('\n').enumerate() { + let prefix = if index == 0 { + format!("{label}:") + } else { + String::new() + }; + lines.push(Line::from(vec![ + Span::raw(format!("{indent}{prefix:<16} ")).bold(), + Span::raw(part.to_owned()), + ])); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use lib_efo::{entity::EntityDuration, stats::EntityType}; + + #[test] + fn event_has_readable_sections_and_exact_json_alternative() { + let mut event = Entity::default(); + event.name = "Éclipse".into(); + event.description = "First line\nSecond line".into(); + event.entity_type = EntityType::Event; + event.change_duration(EntityDuration::Duration(8)); + let text = DetailView::Formatted.text(&event).to_string(); + for expected in [ + "Éclipse", + "First line\nSecond line", + "Properties", + "Type:", + "Event", + "Statistics", + "Metadata", + "Duration:", + ] { + assert!(text.contains(expected), "missing {expected}: {text}"); + } + assert!(!text.contains("\"entity_type\"")); + let json = DetailView::Json.text(&event).to_string(); + assert_eq!( + serde_json::from_str::(&json).expect("JSON"), + serde_json::to_value(&event).expect("entity") + ); + } + + #[test] + fn nested_and_future_fields_remain_visible() { + let mut lines = Vec::new(); + field( + &mut lines, + "custom_fields", + &serde_json::json!({ + "notes": "α\nβ", "enabled": false, "missing": null, + "position": [74, 50], "links": [{"other_id": "@abc", "weight": -3}], + "empty_map": {}, "empty_list": [] + }), + 0, + ); + let text = Text::from(lines).to_string(); + for expected in [ + "Custom fields", + "Notes:", + "α", + "β", + "false", + "—", + "74, 50", + "Other id:", + "@abc", + "-3", + "(empty)", + "None", + ] { + assert!(text.contains(expected), "missing {expected}: {text}"); + } + } +} diff --git a/tui_efo/src/main.rs b/tui_efo/src/main.rs index a4359d0..18c1850 100644 --- a/tui_efo/src/main.rs +++ b/tui_efo/src/main.rs @@ -1,19 +1,22 @@ //! Interactive, read-only Epoch Forge repository browser. #![deny(clippy::unwrap_used)] +mod details; + use clap::Parser; use crossterm::{ event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}, execute, terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode}, }; +use details::DetailView; use lib_efo::{entity::Entity, epoch::EpochInfo, workspace::Workspace}; use ratatui::{ Frame, Terminal, backend::CrosstermBackend, layout::{Constraint, Direction, Layout, Rect}, - style::{Color, Modifier, Style, Stylize}, - text::{Line, Text}, + style::{Color, Modifier, Style}, + text::Text, widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}, }; use std::{ @@ -31,7 +34,7 @@ use std::{ about = "Browse an Epoch Forge repository interactively" )] #[command( - after_long_help = "KEYS:\n Tab / Shift-Tab Move focus\n Arrows or h/j/k/l Navigate\n ? Toggle help\n r Reload repository\n q or Esc Quit\n\nSearch with /; select HEAD/index/worktree with 1/2/3. Home/End and PageUp/PageDown navigate. Ctrl-C exits. This browser is read-only. Use `efo` for mutations and recovery." + after_long_help = "KEYS:\n Tab / Shift-Tab Move focus\n Arrows or h/j/k/l Navigate\n ? Toggle help\n v Toggle formatted / JSON details\n r Reload repository\n q or Esc Quit\n\nSearch with /; select HEAD/index/worktree with 1/2/3. Home/End and PageUp/PageDown navigate. Ctrl-C exits. This browser is read-only. Use `efo` for mutations and recovery." )] struct Args { /// Disable colours (also respects NO_COLOR). @@ -142,6 +145,7 @@ struct App { entity_list: ListState, collection_list: ListState, details_offset: u16, + detail_view: DetailView, help: bool, help_offset: u16, help_max: u16, @@ -171,6 +175,7 @@ impl App { entity_list: ListState::default(), collection_list: ListState::default(), details_offset: 0, + detail_view: DetailView::default(), help: false, help_offset: 0, help_max: 0, @@ -377,6 +382,11 @@ impl App { } } KeyCode::Char('r') => self.reload(), + KeyCode::Char('v') => { + self.detail_view.toggle(); + self.details_offset = 0; + self.details_max = 0; + } KeyCode::Tab if key.modifiers.contains(KeyModifiers::SHIFT) => { self.focus = self.focus.previous() } @@ -513,7 +523,7 @@ fn render(frame: &mut Frame<'_>, app: &mut App) { Paragraph::new(if app.search.is_some() { format!(" /{}▏ Enter apply · Esc cancel", app.query) } else { - format!(" {}\n Tab focus · / search · 1 HEAD 2 index 3 worktree · r reload · ? help · q quit", app.message) + format!(" {}\n Tab focus · / search · v view · 1 HEAD 2 index 3 worktree · r reload · ? help · q quit", app.message) }), rows[2], ); @@ -620,23 +630,7 @@ fn render_entities(frame: &mut Frame<'_>, app: &mut App, area: Rect) { fn render_details(frame: &mut Frame<'_>, app: &mut App, area: Rect) { let text = app.selected_entity().map_or_else( || Text::from("No entity selected."), - |entity| { - let json = serde_json::to_string_pretty(entity) - .unwrap_or_else(|error| format!("Could not display details: {error}")); - let mut lines = vec![ - Line::from(entity.name.clone()).bold(), - Line::from(format!("@{}", entity.id)), - ]; - lines.extend( - entity - .description - .lines() - .map(|line| Line::from(line.to_owned())), - ); - lines.push(Line::from("")); - lines.extend(json.lines().map(|line| Line::from(line.to_owned()))); - Text::from(lines) - }, + |entity| app.detail_view.text(entity), ); let paragraph = Paragraph::new(text).wrap(Wrap { trim: false }); app.details_max = paragraph @@ -645,7 +639,8 @@ fn render_details(frame: &mut Frame<'_>, app: &mut App, area: Rect) { .min(usize::from(u16::MAX)) as u16; app.details_offset = app.details_offset.min(app.details_max); let title = format!( - "Details · line {}/{}", + "{} · v toggle · {}/{}", + app.detail_view.name(), u32::from(app.details_offset) + 1, u32::from(app.details_max) + 1 ); @@ -660,7 +655,7 @@ fn render_help(frame: &mut Frame<'_>, app: &mut App, area: Rect) { let popup = centered_rect(88, area.height, area); frame.render_widget(Clear, popup); let text = format!( - "Tab / Shift-Tab, h/l Move focus\nUp/Down, j/k Navigate or scroll details\nHome/End, PgUp/PgDn Jump or page in focused panel\n/ Search name, description, UUID\nEnter / Esc Apply / cancel search (empty clears)\n1 / 2 / 3 Browse HEAD / index / worktree\nr Reload, preserving selected UUID\n? or ! Help and last reload diagnostic\nq, Esc Close help; then quit\nCtrl-C Quit from any view\n\nRead-only. Use efo diff / diff --staged to compare layers.\nUse efo for changes and recovery.\n\n{}", + "Tab / Shift-Tab, h/l Move focus\nUp/Down, j/k Navigate or scroll details\nHome/End, PgUp/PgDn Jump or page in focused panel\n/ Search name, description, UUID\nEnter / Esc Apply / cancel search (empty clears)\n1 / 2 / 3 Browse HEAD / index / worktree\nv Toggle formatted / raw JSON details\nr Reload, preserving selected UUID\n? or ! Help and last reload diagnostic\nq, Esc Close help; then quit\nCtrl-C Quit from any view\n\nRead-only. Use efo diff / diff --staged to compare layers.\nUse efo for changes and recovery.\n\n{}", app.diagnostic.as_deref().unwrap_or("No reload errors.") ); let paragraph = Paragraph::new(text).wrap(Wrap { trim: true }); @@ -855,6 +850,12 @@ mod tests { key(&mut app, KeyCode::Down); assert_eq!(app.details_offset, app.details_max); terminal.draw(|f| render(f, &mut app)).expect("draw"); + key(&mut app, KeyCode::Char('v')); + terminal.draw(|f| render(f, &mut app)).expect("draw JSON"); + key(&mut app, KeyCode::End); + terminal + .draw(|f| render(f, &mut app)) + .expect("draw JSON end"); assert!(terminal.backend().to_string().contains('}')); app.diagnostic = Some("Distinct final diagnostic".into()); key(&mut app, KeyCode::Char('!')); @@ -925,4 +926,33 @@ mod tests { terminal.draw(|f| render(f, &mut app)).expect("draw"); assert_eq!(app.entity_list.offset(), offset); } + #[test] + fn detail_toggle_is_modal_and_preserves_entity_and_layer() { + let (_temp, mut app) = app(); + app.workspace.worktree.world.characters = vec![entity("Aria", 1)]; + app.focus = Focus::Details; + let mut terminal = Terminal::new(TestBackend::new(60, 16)).expect("terminal"); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + assert!(terminal.backend().to_string().contains("Formatted")); + key(&mut app, KeyCode::End); + key(&mut app, KeyCode::Char('v')); + assert_eq!(app.details_offset, 0); + assert_eq!(app.detail_view, DetailView::Json); + assert_eq!(app.selected_entity().expect("entity").name, "Aria"); + assert_eq!(app.layer, Layer::Worktree); + terminal.draw(|f| render(f, &mut app)).expect("draw"); + assert!(terminal.backend().to_string().contains("JSON")); + assert!(terminal.backend().to_string().contains("\"description\"")); + key(&mut app, KeyCode::Char('?')); + key(&mut app, KeyCode::Char('v')); + assert_eq!(app.detail_view, DetailView::Json); + key(&mut app, KeyCode::Esc); + key(&mut app, KeyCode::Char('/')); + key(&mut app, KeyCode::Char('v')); + assert_eq!(app.query, "v"); + assert_eq!(app.detail_view, DetailView::Json); + key(&mut app, KeyCode::Esc); + key(&mut app, KeyCode::Char('v')); + assert_eq!(app.detail_view, DetailView::Formatted); + } } diff --git a/tui_efo/tests/terminal_smoke.py b/tui_efo/tests/terminal_smoke.py index abf8153..0c956e4 100644 --- a/tui_efo/tests/terminal_smoke.py +++ b/tui_efo/tests/terminal_smoke.py @@ -28,7 +28,7 @@ with tempfile.TemporaryDirectory() as directory: os.write(master, b'\x1b[1;1R') try: drain(0.3) - for keys in [b'\t', b'/dra', b'\r', b'2', b'3', b'\t', b'\x1b[F', b'?', b'\x1b[F', b'?', b'r']: + for keys in [b'\t', b'/dra', b'\r', b'2', b'3', b'\t', b'v', b'\x1b[F', b'v', b'?', b'\x1b[F', b'?', b'r']: os.write(master, keys) drain(0.06) fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 16, 60, 0, 0))