Merge pull request 'Scrolling: mouse wheel and keyboard, pinned view while streaming' (#115) from scrolling into main
This commit was merged in pull request #115.
This commit is contained in:
commit
56f23e798b
5 files changed
+344
-34
No files matched your search
@@ -14,7 +14,9 @@ hx -r # pick a session to resume
|
||||
hx -r parser # resume the session whose title best matches "parser"
|
||||
```
|
||||
|
||||
TUI: `enter` send, `alt-enter`/`ctrl-j` newline, `esc` abort, `ctrl-o` expand tool output, `pgup`/`pgdn` scroll.
|
||||
TUI: `enter` send, `alt-enter`/`ctrl-j` newline, `esc` abort, `ctrl-o` expand tool output.
|
||||
|
||||
Scrolling (chat, side panel, agent view): mouse wheel (3 lines, targets the region under the pointer), `pgup`/`pgdn` half a page, `alt-pgup`/`alt-pgdn` a full page, `alt-↑`/`alt-↓` 3 lines, `ctrl-home`/`ctrl-end` top / back to the live bottom. A scrolled-up view stays put while new text streams in (footer shows `↑N` lines below); reaching the bottom or sending a prompt follows again. The wheel needs mouse capture, which disables plain terminal text selection (use shift-drag): turn it off with `mouse = false` in config or `HX_MOUSE=0`.
|
||||
`/help` lists commands: builtins (`/model`, `/provider`, `/compact`, `/clear`, `/lsp`, `/mcp`, `/skills`, `/new`, `/sessions`, `/resume`, `/usage`, `/quit`), MCP
|
||||
prompts (`/server:prompt`) and skills. Typing `/` opens a completion popup for commands and their arguments
|
||||
(`up`/`down` select, `tab`/`enter` accept, `esc` close); `tab` completes `@file` (mentioned files are
|
||||
@@ -45,6 +47,7 @@ provider = "claude" # or "codex"
|
||||
# codex_model = "gpt-5.6-sol" # default: Codex's top-listed model
|
||||
# compact_at = 900000 # default: 90% of the model's context window
|
||||
max_tokens = 16384
|
||||
# mouse = true # wheel scrolling; false keeps terminal text selection
|
||||
# explore_model = "claude-haiku-4-5" # model for read-only `task` subagents; default: cheapest tier of the provider
|
||||
# system_prompt = "..." # replaces built-in prompt; AGENTS.md still appended
|
||||
|
||||
@@ -65,7 +68,9 @@ tests = "turn_end" # affected tests: turn_end | agent_end | off
|
||||
|
||||
## Subagents
|
||||
|
||||
The model can call `task(prompt, kind)` to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.\n\nA child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
|
||||
The model can call `task(prompt, kind)` to run a subagent with a fresh context and get back only its final answer (cut at 8 KB), so big searches don't fill the main context. `explore` (default) is read-only (`read`, `lsp`, `bash`) on the provider's cheapest model (`explore_model` in config); `general` has the parent's tools and model, and the lens runs on its edits. Up to 3 run in parallel, none can start another, a parent abort stops them. Their sessions are written to `<session>.sub/`; `hx stats` lists them and the footer token counts include them. **Overview:** while any subagent exists, a list sits above the footer (bottom right: spinner/✓, id, kind, task, time, calls, tokens). `ctrl-g` focuses it (`↑↓`, `enter` opens, `esc` closes); the detail view shows that agent's live transcript. Typing there messages the agent: while it runs the text is delivered at its next turn end (like steering the main agent), after it finished it continues that agent's conversation. `ctrl-c` aborts that agent only; `ctrl-s` sends its last answer to the main chat as `[subagent N] …`. NDJSON/RPC carry no per-agent events yet.
|
||||
|
||||
A child starts with a cold prompt cache and costs tokens of its own: it saves *main-context* size, not total tokens.
|
||||
|
||||
## Skills
|
||||
|
||||
|
||||
@@ -77,6 +77,8 @@ struct Config {
|
||||
max_tokens: Option<u32>,
|
||||
/// Model for read-only `task` subagents; default: the provider's cheapest tier (Haiku / Luna).
|
||||
explore_model: Option<String>,
|
||||
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
|
||||
mouse: Option<bool>,
|
||||
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended).
|
||||
system_prompt: Option<String>,
|
||||
lsp: Option<LspCfg>,
|
||||
@@ -121,6 +123,7 @@ impl Config {
|
||||
compact_at: o.compact_at.or(c.compact_at),
|
||||
max_tokens: o.max_tokens.or(c.max_tokens),
|
||||
explore_model: o.explore_model.or(c.explore_model),
|
||||
mouse: o.mouse.or(c.mouse),
|
||||
system_prompt: o.system_prompt.or(c.system_prompt),
|
||||
lsp: o.lsp.or(c.lsp),
|
||||
extensions: [c.extensions, o.extensions].concat(),
|
||||
@@ -613,6 +616,8 @@ async fn main() -> Result<()> {
|
||||
pricing,
|
||||
specs,
|
||||
open_sessions,
|
||||
mouse: cfg.mouse.unwrap_or(true)
|
||||
&& std::env::var_os("HX_MOUSE").is_none_or(|v| v != "0"),
|
||||
commands: {
|
||||
let mcp = mcp.clone();
|
||||
Box::new(move |name: &str, arg: &str| {
|
||||
|
||||
@@ -40,7 +40,7 @@ pub enum View {
|
||||
Detail {
|
||||
id: usize,
|
||||
ed: Editor,
|
||||
scroll: u16,
|
||||
scroll: crate::scroll::Scroll,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ pub struct Detail<'a> {
|
||||
pub frame: usize,
|
||||
}
|
||||
|
||||
pub fn draw_detail(f: &mut ratatui::Frame, d: &Detail, scroll: &mut u16) {
|
||||
pub fn draw_detail(f: &mut ratatui::Frame, d: &Detail, scroll: &mut crate::scroll::Scroll) {
|
||||
let Detail {
|
||||
row: r,
|
||||
model,
|
||||
@@ -176,9 +176,8 @@ pub fn draw_detail(f: &mut ratatui::Frame, d: &Detail, scroll: &mut u16) {
|
||||
);
|
||||
let para = Paragraph::new(t.lines(expanded, body.width)).wrap(Wrap { trim: false });
|
||||
let total = para.line_count(body.width) as u16;
|
||||
let max_up = total.saturating_sub(body.height);
|
||||
*scroll = (*scroll).min(max_up);
|
||||
f.render_widget(para.scroll((max_up - *scroll, 0)), body);
|
||||
let top = scroll.resolve(total, body.height);
|
||||
f.render_widget(para.scroll((top, 0)), body);
|
||||
let block = Block::default()
|
||||
.borders(Borders::TOP | Borders::BOTTOM)
|
||||
.border_style(th.dim());
|
||||
@@ -257,7 +256,7 @@ mod tests {
|
||||
t.push(Item::Assistant("found in src/a.rs".into()));
|
||||
let mut ed = Editor::default();
|
||||
ed.insert("and then?");
|
||||
let mut sc = 0;
|
||||
let mut sc = crate::scroll::Scroll::default();
|
||||
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 12)).unwrap();
|
||||
let row = r(3, Status::Running);
|
||||
let d = Detail {
|
||||
|
||||
+231
-26
@@ -5,6 +5,7 @@ pub mod choose;
|
||||
pub mod editor;
|
||||
pub mod picker;
|
||||
pub mod popup;
|
||||
pub mod scroll;
|
||||
pub mod sessions;
|
||||
pub mod status;
|
||||
pub mod theme;
|
||||
@@ -47,8 +48,21 @@ pub struct Setup {
|
||||
pub specs: Vec<CmdSpec>,
|
||||
/// Open the session picker at startup (`hx -r`).
|
||||
pub open_sessions: bool,
|
||||
/// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag.
|
||||
pub mouse: bool,
|
||||
}
|
||||
|
||||
/// Screen regions of the last draw, for routing the mouse wheel.
|
||||
#[derive(Default, Clone, Copy)]
|
||||
struct Areas {
|
||||
chat: Rect,
|
||||
panel: Rect,
|
||||
/// agent detail body (the whole view while it is open)
|
||||
detail: Rect,
|
||||
}
|
||||
|
||||
const WHEEL: u16 = 3;
|
||||
|
||||
pub enum CmdOut {
|
||||
Send(String),
|
||||
Show(String),
|
||||
@@ -93,8 +107,11 @@ struct App {
|
||||
t: Transcript,
|
||||
ed: Editor,
|
||||
files: Vec<String>,
|
||||
/// lines scrolled up from the bottom
|
||||
scroll: u16,
|
||||
scroll: scroll::Scroll,
|
||||
/// side panel scroll
|
||||
panel_scroll: scroll::Scroll,
|
||||
/// where the chat / side panel / agent detail were last drawn (mouse wheel targets)
|
||||
areas: Areas,
|
||||
expanded: bool,
|
||||
busy: bool,
|
||||
queue: VecDeque<String>,
|
||||
@@ -196,6 +213,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
commands,
|
||||
specs,
|
||||
open_sessions,
|
||||
mouse,
|
||||
} = setup;
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
agent.bus.add(Forward(tx.clone()));
|
||||
@@ -227,7 +245,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
t: Transcript::default(),
|
||||
ed: Editor::default(),
|
||||
files: project_files(&cwd),
|
||||
scroll: 0,
|
||||
scroll: Default::default(),
|
||||
panel_scroll: Default::default(),
|
||||
areas: Default::default(),
|
||||
expanded: false,
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
@@ -277,6 +297,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
commands: &commands,
|
||||
};
|
||||
let mut term = ratatui::init();
|
||||
if mouse {
|
||||
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableMouseCapture);
|
||||
}
|
||||
let mut keys = EventStream::new();
|
||||
let mut tick = tokio::time::interval(std::time::Duration::from_millis(50));
|
||||
let mut lens_tick = tokio::time::interval(std::time::Duration::from_secs(2));
|
||||
@@ -325,6 +348,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
submit(&mut app, line, &ctx).await;
|
||||
}
|
||||
}
|
||||
TEvent::Mouse(m) => on_mouse(&mut app, m),
|
||||
TEvent::Paste(s) => app.ed.insert(&s),
|
||||
_ => {}
|
||||
}
|
||||
@@ -391,6 +415,9 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
if mouse {
|
||||
let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableMouseCapture);
|
||||
}
|
||||
ratatui::restore();
|
||||
let a = agent.lock().await;
|
||||
let cost = pricing(a.model())
|
||||
@@ -472,7 +499,7 @@ fn agents_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||||
app.agents = Some(agents::View::Detail {
|
||||
id: s.sh.id,
|
||||
ed: Editor::default(),
|
||||
scroll: 0,
|
||||
scroll: Default::default(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -523,12 +550,17 @@ fn agents_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||||
KeyCode::Delete => ed.delete(),
|
||||
KeyCode::Left => ed.left(),
|
||||
KeyCode::Right => ed.right(),
|
||||
KeyCode::PageUp
|
||||
| KeyCode::PageDown
|
||||
| KeyCode::Home
|
||||
| KeyCode::End
|
||||
| KeyCode::Up
|
||||
| KeyCode::Down
|
||||
if scroll_key(&k, false, scroll, &mut Default::default()) => {}
|
||||
KeyCode::Home => ed.home(),
|
||||
KeyCode::End => ed.end(),
|
||||
KeyCode::Up => ed.up(),
|
||||
KeyCode::Down => ed.down(),
|
||||
KeyCode::PageUp => *scroll = scroll.saturating_add(10),
|
||||
KeyCode::PageDown => *scroll = scroll.saturating_sub(10),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -536,6 +568,66 @@ fn agents_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Scroll keys: PgUp/PgDn half a page, alt+PgUp/PgDn a full page, alt+Up/Down 3 lines,
|
||||
/// ctrl+Home/End first/last line. Plain Home/End/Up/Down stay with the editor (false).
|
||||
fn scroll_key(
|
||||
k: &KeyEvent,
|
||||
panel: bool,
|
||||
chat: &mut scroll::Scroll,
|
||||
side: &mut scroll::Scroll,
|
||||
) -> bool {
|
||||
let (ctrl, alt) = (
|
||||
k.modifiers.contains(KeyModifiers::CONTROL),
|
||||
k.modifiers.contains(KeyModifiers::ALT),
|
||||
);
|
||||
let s = if panel { side } else { chat };
|
||||
match k.code {
|
||||
KeyCode::PageUp => s.up(if alt { s.page() } else { s.half_page() }),
|
||||
KeyCode::PageDown => s.down(if alt { s.page() } else { s.half_page() }),
|
||||
KeyCode::Up if alt => s.up(WHEEL),
|
||||
KeyCode::Down if alt => s.down(WHEEL),
|
||||
KeyCode::Home if ctrl => s.start(),
|
||||
KeyCode::End if ctrl => s.end(),
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The side panel takes the scroll keys while it is open and the editor is empty.
|
||||
fn panel_focus(app: &App) -> bool {
|
||||
app.panel.is_some() && app.wide && app.ed.buf.is_empty()
|
||||
}
|
||||
|
||||
fn inside(r: Rect, x: u16, y: u16) -> bool {
|
||||
x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height
|
||||
}
|
||||
|
||||
/// Mouse wheel scrolls the region under the pointer: agent detail, side panel, or chat.
|
||||
fn on_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
|
||||
use crossterm::event::MouseEventKind::{ScrollDown, ScrollUp};
|
||||
let up = match m.kind {
|
||||
ScrollUp => true,
|
||||
ScrollDown => false,
|
||||
_ => return,
|
||||
};
|
||||
let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents {
|
||||
scroll
|
||||
} else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() {
|
||||
return;
|
||||
} else if app.panel.is_some() && inside(app.areas.panel, m.column, m.row) {
|
||||
&mut app.panel_scroll
|
||||
} else if inside(app.areas.chat, m.column, m.row) {
|
||||
&mut app.scroll
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
if up {
|
||||
s.up(WHEEL);
|
||||
} else {
|
||||
s.down(WHEEL);
|
||||
}
|
||||
}
|
||||
|
||||
fn picker_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||||
match app.picker.as_mut()?.key(k) {
|
||||
picker::Act::None => None,
|
||||
@@ -561,6 +653,7 @@ fn picker_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||||
fn show(app: &mut App, title: &str, text: String) {
|
||||
if app.wide {
|
||||
app.panel = Some((title.into(), text));
|
||||
app.panel_scroll.start();
|
||||
} else {
|
||||
app.t.push(Item::Info(text));
|
||||
}
|
||||
@@ -656,14 +749,19 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
live_popup(app);
|
||||
}
|
||||
KeyCode::Delete => app.ed.delete(),
|
||||
KeyCode::PageUp
|
||||
| KeyCode::PageDown
|
||||
| KeyCode::Home
|
||||
| KeyCode::End
|
||||
| KeyCode::Up
|
||||
| KeyCode::Down
|
||||
if scroll_key(&k, panel_focus(app), &mut app.scroll, &mut app.panel_scroll) => {}
|
||||
KeyCode::Left => app.ed.left(),
|
||||
KeyCode::Right => app.ed.right(),
|
||||
KeyCode::Home => app.ed.home(),
|
||||
KeyCode::End => app.ed.end(),
|
||||
KeyCode::Up => app.ed.up(),
|
||||
KeyCode::Down => app.ed.down(),
|
||||
KeyCode::PageUp => app.scroll = app.scroll.saturating_add(10),
|
||||
KeyCode::PageDown => app.scroll = app.scroll.saturating_sub(10),
|
||||
KeyCode::Tab => {
|
||||
let c = completion(app);
|
||||
let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect();
|
||||
@@ -736,7 +834,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
lsp_status,
|
||||
commands,
|
||||
} = *c;
|
||||
app.scroll = 0;
|
||||
app.scroll.end();
|
||||
let shown = line.clone();
|
||||
if let Some(cmd) = line.clone().strip_prefix('/') {
|
||||
let (c, arg) = cmd
|
||||
@@ -914,6 +1012,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
frame: (app.since.elapsed().as_millis() / 80) as usize,
|
||||
};
|
||||
agents::draw_detail(f, &d, scroll);
|
||||
app.areas.detail = f.area();
|
||||
return;
|
||||
}
|
||||
app.agents = None;
|
||||
@@ -939,26 +1038,30 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
Some((title, text)) if app.wide => {
|
||||
let [m, side] =
|
||||
Layout::horizontal([Constraint::Min(60), Constraint::Percentage(40)]).areas(main);
|
||||
f.render_widget(
|
||||
Paragraph::new(text.as_str())
|
||||
.wrap(Wrap { trim: false })
|
||||
.block(
|
||||
Block::new()
|
||||
.borders(Borders::LEFT)
|
||||
.border_style(th.dim())
|
||||
.title(Span::styled(format!(" {title} · esc "), th.dim())),
|
||||
),
|
||||
side,
|
||||
);
|
||||
let block = Block::new()
|
||||
.borders(Borders::LEFT)
|
||||
.border_style(th.dim())
|
||||
.title(Span::styled(format!(" {title} · esc "), th.dim()));
|
||||
let body = block.inner(side);
|
||||
let para = Paragraph::new(text.as_str()).wrap(Wrap { trim: false });
|
||||
let top = app
|
||||
.panel_scroll
|
||||
.resolve(para.line_count(body.width) as u16, body.height);
|
||||
f.render_widget(block, side);
|
||||
f.render_widget(para.scroll((top, 0)), body);
|
||||
app.areas.panel = side;
|
||||
m
|
||||
}
|
||||
_ => main,
|
||||
_ => {
|
||||
app.areas.panel = Rect::default();
|
||||
main
|
||||
}
|
||||
};
|
||||
app.areas.chat = main;
|
||||
let para = Paragraph::new(app.t.lines(app.expanded, main.width)).wrap(Wrap { trim: false });
|
||||
let total = para.line_count(main.width) as u16;
|
||||
let max_up = total.saturating_sub(main.height);
|
||||
app.scroll = app.scroll.min(max_up);
|
||||
f.render_widget(para.scroll((max_up - app.scroll, 0)), main);
|
||||
let top = app.scroll.resolve(total, main.height);
|
||||
f.render_widget(para.scroll((top, 0)), main);
|
||||
|
||||
if !sub_rows.is_empty() {
|
||||
let w = subs_area.width.min(56);
|
||||
@@ -1008,7 +1111,7 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
.as_ref()
|
||||
.map_or_else(|| agents_hint(app), |(c, _)| c.help()),
|
||||
queued: app.queue.len(),
|
||||
scroll: app.scroll,
|
||||
scroll: app.scroll.behind(),
|
||||
title: app.title.as_deref(),
|
||||
lens: &app.lens.0,
|
||||
lens_warn: app.lens.1,
|
||||
@@ -1227,6 +1330,106 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
fn long_chat(app: &mut App, n: usize) {
|
||||
for i in 0..n {
|
||||
app.t.push(Item::Info(format!("line {i}")));
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_at(app: &mut App, w: u16, h: u16) -> Vec<String> {
|
||||
let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).unwrap();
|
||||
term.draw(|f| draw(f, app)).unwrap();
|
||||
let b = term.backend().buffer().clone();
|
||||
(0..h)
|
||||
.map(|y| (0..w).map(|x| b[(x, y)].symbol().to_string()).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scroll_keys_page_pin_and_jump() {
|
||||
let mut app = test_app();
|
||||
long_chat(&mut app, 100);
|
||||
let ab = AbortHandle::detached();
|
||||
let press = |app: &mut App, code, m| {
|
||||
on_key(app, KeyEvent::new(code, m), &ab);
|
||||
};
|
||||
let rows = draw_at(&mut app, 60, 20);
|
||||
assert!(rows.iter().any(|r| r.contains("line 99")), "follows bottom");
|
||||
// main area is 20 - input(3) - footer(1) = 16 rows: half page = 8
|
||||
press(&mut app, KeyCode::PageUp, KeyModifiers::NONE);
|
||||
let rows = draw_at(&mut app, 60, 20);
|
||||
assert_eq!(app.scroll.behind(), 8);
|
||||
assert!(!rows.iter().any(|r| r.contains("line 99")), "{rows:#?}");
|
||||
assert!(
|
||||
rows[19].contains("↑8"),
|
||||
"footer shows lines behind: {}",
|
||||
rows[19]
|
||||
);
|
||||
let pinned: Vec<String> = rows[..16].to_vec();
|
||||
// new streamed text (20 more rows) doesn't move the pinned view, the gap grows
|
||||
long_chat(&mut app, 10);
|
||||
let rows = draw_at(&mut app, 60, 20);
|
||||
assert_eq!(rows[..16], pinned[..]);
|
||||
assert!(rows[19].contains("↑28"), "{}", rows[19]);
|
||||
// alt+up: 3 lines; ctrl+home: top; ctrl+end: back to following
|
||||
press(&mut app, KeyCode::Up, KeyModifiers::ALT);
|
||||
assert_eq!(app.scroll.behind(), 31);
|
||||
press(&mut app, KeyCode::Home, KeyModifiers::CONTROL);
|
||||
let rows = draw_at(&mut app, 60, 20);
|
||||
assert!(rows.iter().any(|r| r.contains("line 0")), "{rows:#?}");
|
||||
press(&mut app, KeyCode::End, KeyModifiers::CONTROL);
|
||||
let rows = draw_at(&mut app, 60, 20);
|
||||
assert!(rows[14].contains("line 9"), "bottom: {rows:#?}");
|
||||
assert!(rows[19].ends_with("Claude · m1"), "{}", rows[19]);
|
||||
// plain Home still edits text and doesn't scroll
|
||||
app.ed.insert("abc");
|
||||
press(&mut app, KeyCode::Home, KeyModifiers::NONE);
|
||||
assert_eq!((app.ed.cur, app.scroll.behind()), (0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mouse_wheel_goes_to_region_under_pointer() {
|
||||
use crossterm::event::{MouseEvent, MouseEventKind};
|
||||
let wheel = |kind, column, row| MouseEvent {
|
||||
kind,
|
||||
column,
|
||||
row,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
};
|
||||
let mut app = test_app();
|
||||
long_chat(&mut app, 100);
|
||||
app.panel = Some(("help".into(), (0..100).map(|i| format!("p{i}\n")).collect()));
|
||||
app.panel_scroll.start();
|
||||
let rows = draw_at(&mut app, 160, 20);
|
||||
assert!(app.wide && app.areas.panel.width > 0);
|
||||
let (chat, panel) = (app.areas.chat, app.areas.panel);
|
||||
assert!(chat.x + chat.width <= panel.x);
|
||||
on_mouse(&mut app, wheel(MouseEventKind::ScrollUp, chat.x + 1, 2));
|
||||
assert_eq!(
|
||||
(app.scroll.behind(), app.panel_scroll.behind() > 0),
|
||||
(3, true)
|
||||
);
|
||||
let before = app.panel_scroll.behind();
|
||||
on_mouse(&mut app, wheel(MouseEventKind::ScrollDown, panel.x + 3, 2));
|
||||
assert_eq!(
|
||||
(app.scroll.behind(), app.panel_scroll.behind()),
|
||||
(3, before - 3)
|
||||
);
|
||||
// outside both (input row) and non-wheel events do nothing
|
||||
on_mouse(&mut app, wheel(MouseEventKind::ScrollUp, 5, 18));
|
||||
on_mouse(&mut app, wheel(MouseEventKind::Moved, chat.x + 1, 2));
|
||||
assert_eq!(app.scroll.behind(), 3);
|
||||
// PgUp goes to the panel while it is open and the editor is empty
|
||||
let ab = AbortHandle::detached();
|
||||
on_key(
|
||||
&mut app,
|
||||
KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE),
|
||||
&ab,
|
||||
);
|
||||
assert_eq!(app.scroll.behind(), 3);
|
||||
assert!(rows.len() == 20);
|
||||
}
|
||||
|
||||
fn key(app: &mut App, code: KeyCode) -> Option<String> {
|
||||
on_key(
|
||||
app,
|
||||
@@ -1240,7 +1443,9 @@ mod tests {
|
||||
t: Transcript::default(),
|
||||
ed: Editor::default(),
|
||||
files: vec!["src/main.rs".into(), "src/lib.rs".into()],
|
||||
scroll: 0,
|
||||
scroll: Default::default(),
|
||||
panel_scroll: Default::default(),
|
||||
areas: Default::default(),
|
||||
expanded: false,
|
||||
busy: false,
|
||||
queue: VecDeque::new(),
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Scroll position of a text view. `top: None` follows the bottom (new text stays in view);
|
||||
//! `Some(n)` pins line `n` at the top, so streaming text below doesn't move what you are reading.
|
||||
|
||||
#[derive(Default, Debug, Clone, PartialEq)]
|
||||
pub struct Scroll {
|
||||
top: Option<u16>,
|
||||
/// last drawn size, so key/mouse handlers can page without knowing the layout
|
||||
total: u16,
|
||||
height: u16,
|
||||
}
|
||||
|
||||
impl Scroll {
|
||||
fn max(&self) -> u16 {
|
||||
self.total.saturating_sub(self.height)
|
||||
}
|
||||
fn cur(&self) -> u16 {
|
||||
self.top.unwrap_or(self.max()).min(self.max())
|
||||
}
|
||||
|
||||
/// Call while drawing with the content's line count and the view height; returns the first
|
||||
/// line to show. Reaching the bottom goes back to following.
|
||||
pub fn resolve(&mut self, total: u16, height: u16) -> u16 {
|
||||
self.total = total;
|
||||
self.height = height;
|
||||
if self.top.is_some_and(|t| t >= self.max()) {
|
||||
self.top = None;
|
||||
}
|
||||
self.cur()
|
||||
}
|
||||
|
||||
pub fn up(&mut self, n: u16) {
|
||||
self.top = Some(self.cur().saturating_sub(n));
|
||||
}
|
||||
pub fn down(&mut self, n: u16) {
|
||||
self.top = Some(self.cur().saturating_add(n));
|
||||
if self.top.is_some_and(|t| t >= self.max()) {
|
||||
self.top = None;
|
||||
}
|
||||
}
|
||||
pub fn half_page(&self) -> u16 {
|
||||
(self.height / 2).max(1)
|
||||
}
|
||||
pub fn page(&self) -> u16 {
|
||||
self.height.saturating_sub(1).max(1)
|
||||
}
|
||||
pub fn start(&mut self) {
|
||||
self.top = Some(0);
|
||||
}
|
||||
pub fn end(&mut self) {
|
||||
self.top = None;
|
||||
}
|
||||
/// Lines below the view (0 when following).
|
||||
pub fn behind(&self) -> u16 {
|
||||
self.max() - self.cur()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn follows_bottom_until_scrolled_and_pins_while_content_grows() {
|
||||
let mut s = Scroll::default();
|
||||
assert_eq!(s.resolve(100, 20), 80);
|
||||
s.up(10);
|
||||
assert_eq!((s.resolve(100, 20), s.behind()), (70, 10));
|
||||
// 30 more lines stream in: the pinned view stays, the gap grows
|
||||
assert_eq!((s.resolve(130, 20), s.behind()), (70, 40));
|
||||
// scrolling back down to the end resumes following
|
||||
s.down(1000);
|
||||
assert_eq!((s.resolve(130, 20), s.behind()), (110, 0));
|
||||
assert_eq!(s.resolve(140, 20), 120);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paging_clamping_start_end() {
|
||||
let mut s = Scroll::default();
|
||||
s.resolve(50, 10);
|
||||
assert_eq!((s.half_page(), s.page()), (5, 9));
|
||||
s.up(s.page());
|
||||
assert_eq!(s.resolve(50, 10), 31);
|
||||
s.start();
|
||||
assert_eq!(s.resolve(50, 10), 0);
|
||||
s.up(5);
|
||||
assert_eq!(s.resolve(50, 10), 0, "no underflow");
|
||||
s.end();
|
||||
assert_eq!(s.resolve(50, 10), 40);
|
||||
// content shorter than the view
|
||||
let mut t = Scroll::default();
|
||||
t.up(5);
|
||||
assert_eq!((t.resolve(3, 10), t.behind()), (0, 0));
|
||||
t.down(5);
|
||||
assert_eq!(t.resolve(3, 10), 0);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user