Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b2cbb23fe2 | ||
|
|
9fe9fe4628 | ||
|
|
e6a254b734 | ||
|
|
dc783778c8 |
@@ -202,6 +202,41 @@ pub fn command_program(command: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Program name (already basenamed and lowercased) -> the tool id its mark
|
||||
/// stands for. Mirrors the web's `BY_PROGRAM` in `web/src/toolIcon.ts`;
|
||||
/// recognition is deliberately narrow, so an unrecognised program has no tool.
|
||||
const BY_PROGRAM: [(&str, &str); 17] = [
|
||||
("claude", "claude"),
|
||||
("claude-code", "claude"),
|
||||
("codex", "codex"),
|
||||
("opencode", "opencode"),
|
||||
("gemini", "gemini"),
|
||||
("aider", "aider"),
|
||||
("cursor", "cursor"),
|
||||
("cursor-agent", "cursor"),
|
||||
("pi", "pi"),
|
||||
("bash", "shell"),
|
||||
("zsh", "shell"),
|
||||
("sh", "shell"),
|
||||
("fish", "shell"),
|
||||
("dash", "shell"),
|
||||
("ksh", "shell"),
|
||||
("nu", "shell"),
|
||||
("xonsh", "shell"),
|
||||
];
|
||||
|
||||
/// The tool id a command line's icon stands for (`claude`, `codex`,
|
||||
/// `opencode`, ...), or `None` when the program is not one we have a mark for.
|
||||
/// The command bar matches this field (`docs/COMMAND-BAR.md`), so it must name
|
||||
/// the same tools the web's `splitCommand().tool` does.
|
||||
pub fn command_tool(command: &str) -> Option<&'static str> {
|
||||
let program = command_program(command).to_lowercase();
|
||||
BY_PROGRAM
|
||||
.iter()
|
||||
.find(|(name, _)| *name == program)
|
||||
.map(|(_, tool)| *tool)
|
||||
}
|
||||
|
||||
/// `FOO=bar`, the shell's own prefix for one command's environment.
|
||||
fn is_env_assignment(word: &str) -> bool {
|
||||
let mut chars = word.chars();
|
||||
@@ -476,4 +511,22 @@ mod tests {
|
||||
assert_eq!(command_program("sudo"), "sudo");
|
||||
assert_eq!(command_program(""), "");
|
||||
}
|
||||
|
||||
/// The command bar's `tool` field (docs/COMMAND-BAR.md) names the same
|
||||
/// tools the web's `splitCommand().tool` does.
|
||||
#[test]
|
||||
fn command_tool_names_the_mark_the_card_shows() {
|
||||
assert_eq!(command_tool("claude --resume"), Some("claude"));
|
||||
assert_eq!(command_tool("npx opencode"), Some("opencode"));
|
||||
assert_eq!(command_tool("/bin/zsh -l"), Some("shell"));
|
||||
assert_eq!(command_tool("CLAUDE"), Some("claude"));
|
||||
}
|
||||
|
||||
/// Narrow on purpose: an unrecognised program has no mark, so the
|
||||
/// candidate has no `tool` field to match rather than a wrong one.
|
||||
#[test]
|
||||
fn command_tool_is_absent_for_an_unrecognised_program() {
|
||||
assert_eq!(command_tool("hx src/main.rs"), None);
|
||||
assert_eq!(command_tool(""), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,9 @@ pub enum Action {
|
||||
RenameHighlighted,
|
||||
|
||||
// Chrome
|
||||
/// Open the `ctrl-k` command bar (`docs/COMMAND-BAR.md`) — a query line
|
||||
/// over the sessions, ranked by the shared matcher.
|
||||
OpenCommandBar,
|
||||
ToggleSidebar,
|
||||
ShowHelp,
|
||||
Quit,
|
||||
@@ -94,6 +97,7 @@ impl Action {
|
||||
Action::FastForwardSpawn => "Create session with defaults".into(),
|
||||
Action::KillHighlighted => "Kill selected session".into(),
|
||||
Action::RenameHighlighted => "Rename selected session".into(),
|
||||
Action::OpenCommandBar => "Go to a session".into(),
|
||||
Action::ToggleSidebar => "Show or hide sidebar".into(),
|
||||
Action::ShowHelp => "Show help".into(),
|
||||
Action::Quit => "Quit Maestro".into(),
|
||||
@@ -120,6 +124,7 @@ impl Action {
|
||||
"FastForwardSpawn" => return Ok(Action::FastForwardSpawn),
|
||||
"KillHighlighted" => return Ok(Action::KillHighlighted),
|
||||
"RenameHighlighted" => return Ok(Action::RenameHighlighted),
|
||||
"OpenCommandBar" => return Ok(Action::OpenCommandBar),
|
||||
"ToggleSidebar" => return Ok(Action::ToggleSidebar),
|
||||
"ShowHelp" => return Ok(Action::ShowHelp),
|
||||
"Quit" => return Ok(Action::Quit),
|
||||
@@ -239,10 +244,23 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// The command bar is an ordinary keymap entry, so it must round-trip
|
||||
/// like every other action (#153).
|
||||
#[test]
|
||||
fn open_command_bar_round_trips() {
|
||||
assert_eq!(
|
||||
Action::parse("OpenCommandBar").unwrap(),
|
||||
Action::OpenCommandBar
|
||||
);
|
||||
assert_eq!(Action::OpenCommandBar.to_string(), "OpenCommandBar");
|
||||
assert_eq!(Action::OpenCommandBar.help_label(), "Go to a session");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_round_trips() {
|
||||
for a in [
|
||||
Action::EnterInsert,
|
||||
Action::OpenCommandBar,
|
||||
Action::RenameHighlighted,
|
||||
Action::Quit,
|
||||
Action::OpenSpawnModal,
|
||||
|
||||
@@ -23,6 +23,7 @@ use uuid::Uuid;
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::catalog::CatalogStore;
|
||||
use crate::command_bar::{BarOutcome, BarTarget, CommandBar};
|
||||
use crate::config::TuiConfig;
|
||||
use crate::daemon_link::DaemonLink;
|
||||
use crate::draft::{DraftInputResult, DraftPane};
|
||||
@@ -78,6 +79,9 @@ pub struct App {
|
||||
/// Edit buffer behind [`OverlayKind::Rename`] (#125), kept here for the
|
||||
/// same reason the worktree entries are.
|
||||
rename_input: TextInput,
|
||||
/// Query buffer and result list behind [`OverlayKind::CommandBar`] (#153),
|
||||
/// kept here for the same reason the rename buffer is.
|
||||
command_bar: Option<CommandBar>,
|
||||
region: RegionMap,
|
||||
last_sent_size: HashMap<Uuid, (u16, u16)>,
|
||||
clicks: ClickTracker,
|
||||
@@ -210,6 +214,7 @@ impl App {
|
||||
link,
|
||||
http,
|
||||
rename_input: TextInput::default(),
|
||||
command_bar: None,
|
||||
draft_tx,
|
||||
draft_rx,
|
||||
region: RegionMap::default(),
|
||||
@@ -430,6 +435,32 @@ impl App {
|
||||
(OverlayDecision::Consumed, Vec::new())
|
||||
}
|
||||
},
|
||||
// The bar owns every key while it is up: the keymap must not see
|
||||
// `j`, `x` or `q` as commands mid-query.
|
||||
Some(OverlayKind::CommandBar) => {
|
||||
let outcome = match self.command_bar.as_mut() {
|
||||
Some(bar) => bar.handle_key(key),
|
||||
None => BarOutcome::Close,
|
||||
};
|
||||
match outcome {
|
||||
BarOutcome::Stay => (OverlayDecision::Consumed, Vec::new()),
|
||||
BarOutcome::Close => {
|
||||
self.close_command_bar();
|
||||
(OverlayDecision::Consumed, Vec::new())
|
||||
}
|
||||
BarOutcome::Open(BarTarget::Session(sid)) => {
|
||||
self.close_command_bar();
|
||||
// The same open path the sidebar's own attach uses, so
|
||||
// a bar attach can never leave the layout in a state a
|
||||
// highlight-and-enter could not produce.
|
||||
self.state.sidebar_highlight = Some(SidebarItem::Session(sid));
|
||||
(
|
||||
OverlayDecision::Consumed,
|
||||
self.dispatch(Action::AttachHighlighted),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(OverlayKind::Help) => {
|
||||
self.state.dismiss_overlay();
|
||||
(OverlayDecision::Consumed, Vec::new())
|
||||
@@ -475,6 +506,7 @@ impl App {
|
||||
};
|
||||
self.state.show_overlay(OverlayKind::Help);
|
||||
}
|
||||
Action::OpenCommandBar => self.open_command_bar(),
|
||||
Action::OpenSpawnModal => {
|
||||
self.open_spawn_modal();
|
||||
effects.push(Effect::LoadDraft);
|
||||
@@ -537,6 +569,10 @@ impl App {
|
||||
/// highlight already sitting on the attached session — clears at once.
|
||||
fn refresh_preview(&mut self) {
|
||||
let wanted = match (self.state.focus, &self.state.sidebar_highlight) {
|
||||
// The bar is a view over the app, not a place in it: while it is
|
||||
// up the sidebar highlight behind it previews nothing
|
||||
// (`docs/COMMAND-BAR.md`, "Focus round-trip").
|
||||
_ if self.state.overlay() == Some(&OverlayKind::CommandBar) => None,
|
||||
(Focus::Sidebar, Some(SidebarItem::Session(sid))) => Some(*sid),
|
||||
_ => None,
|
||||
};
|
||||
@@ -588,6 +624,25 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the command bar up over whatever is behind it (#153). Opening
|
||||
/// while a session is previewed discards the preview first, like any
|
||||
/// other real change (`docs/PREVIEW.md`); focus and mode are left alone,
|
||||
/// so closing gives the keyboard back to whatever held it.
|
||||
fn open_command_bar(&mut self) {
|
||||
let snapshot = self.catalog.snapshot();
|
||||
self.command_bar = Some(CommandBar::new(&snapshot.sessions, &self.home_dir));
|
||||
self.pending_preview = None;
|
||||
self.clear_preview();
|
||||
self.state.show_overlay(OverlayKind::CommandBar);
|
||||
}
|
||||
|
||||
/// Take the bar down, dropping its query. Every exit goes through here so
|
||||
/// a stale buffer can never outlive the overlay.
|
||||
fn close_command_bar(&mut self) {
|
||||
self.command_bar = None;
|
||||
self.state.dismiss_overlay();
|
||||
}
|
||||
|
||||
fn clear_preview(&mut self) {
|
||||
if self.state.preview.take().is_some() {
|
||||
self.epoch = self.epoch.wrapping_add(1);
|
||||
@@ -1222,6 +1277,7 @@ impl App {
|
||||
draft: self.draft.as_ref(),
|
||||
help: &self.help,
|
||||
rename_input: &self.rename_input,
|
||||
command_bar: self.command_bar.as_ref(),
|
||||
link: &link_status,
|
||||
};
|
||||
|
||||
@@ -2716,6 +2772,181 @@ mod tests {
|
||||
.is_none());
|
||||
}
|
||||
|
||||
// -- command bar (#153) -------------------------------------------------
|
||||
|
||||
fn seed_two_sessions(app: &mut App) -> (Uuid, Uuid) {
|
||||
use chrono::Utc;
|
||||
use maestro_protocol::{CatalogEvent, Session, SessionStatus};
|
||||
let make = |n: u128, name: &str, focused: Option<chrono::DateTime<Utc>>| Session {
|
||||
id: Uuid::from_u128(n),
|
||||
command: "bash".into(),
|
||||
cwd: std::path::PathBuf::from("/"),
|
||||
env: Default::default(),
|
||||
metadata: HashMap::from([(
|
||||
"name".to_string(),
|
||||
serde_json::Value::String(name.to_string()),
|
||||
)]),
|
||||
worktree: None,
|
||||
status: SessionStatus::Running,
|
||||
created_at: Utc::now(),
|
||||
foreground: None,
|
||||
activity: Default::default(),
|
||||
activity_detail: None,
|
||||
last_activity_at: Utc::now(),
|
||||
activity_since: Utc::now(),
|
||||
current_cwd: None,
|
||||
blocked_work: None,
|
||||
last_focused_at: focused,
|
||||
};
|
||||
let older = Utc::now() - chrono::Duration::seconds(60);
|
||||
app.catalog.apply_event(CatalogEvent::Snapshot {
|
||||
sessions: vec![
|
||||
make(1, "alpha", Some(older)),
|
||||
make(2, "bravo", Some(Utc::now())),
|
||||
],
|
||||
});
|
||||
(Uuid::from_u128(1), Uuid::from_u128(2))
|
||||
}
|
||||
|
||||
/// `ctrl-k` is an ordinary keymap entry, bound in both modes so the bar
|
||||
/// opens from the sidebar and from inside a pane (`docs/COMMAND-BAR.md`).
|
||||
#[test]
|
||||
fn ctrl_k_is_bound_to_the_command_bar_in_both_modes() {
|
||||
let app = make_app();
|
||||
assert_eq!(
|
||||
app.cfg.keymap.resolve(Mode::Normal, "ctrl-k"),
|
||||
Some(Action::OpenCommandBar)
|
||||
);
|
||||
assert_eq!(
|
||||
app.cfg.keymap.resolve(Mode::Insert, "ctrl-k"),
|
||||
Some(Action::OpenCommandBar)
|
||||
);
|
||||
}
|
||||
|
||||
/// The help overlay builds its lines from the live keymap, so the bar
|
||||
/// appears there with no second list to maintain.
|
||||
#[test]
|
||||
fn the_help_overlay_lists_the_command_bar() {
|
||||
let app = make_app();
|
||||
let lines = render_help_lines(&app.cfg);
|
||||
assert!(
|
||||
lines
|
||||
.iter()
|
||||
.any(|l| l.contains("ctrl-k") && l.contains("Go to a session")),
|
||||
"{lines:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_the_bar_lists_sessions_most_recently_focused_first() {
|
||||
let mut app = make_app();
|
||||
let (alpha, bravo) = seed_two_sessions(&mut app);
|
||||
app.dispatch(Action::OpenCommandBar);
|
||||
assert_eq!(app.state.overlay(), Some(&OverlayKind::CommandBar));
|
||||
let bar = app.command_bar.as_ref().unwrap();
|
||||
assert_eq!(bar.query(), "");
|
||||
assert_eq!(
|
||||
bar.rows()
|
||||
.iter()
|
||||
.map(|r| match r.target {
|
||||
BarTarget::Session(id) => id,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
vec![bravo, alpha]
|
||||
);
|
||||
}
|
||||
|
||||
/// Opening from Insert mode leaves the keyboard where it was, so closing
|
||||
/// gives it back — the bar is a view over the app, not a place in it.
|
||||
#[test]
|
||||
fn opening_from_insert_mode_leaves_focus_and_mode_alone() {
|
||||
let mut app = make_app();
|
||||
seed_two_sessions(&mut app);
|
||||
app.state.attach_to_focused(Uuid::from_u128(1));
|
||||
assert_eq!(
|
||||
(app.state.focus, app.state.mode),
|
||||
(Focus::Pane, Mode::Insert)
|
||||
);
|
||||
|
||||
app.dispatch(Action::OpenCommandBar);
|
||||
assert_eq!(app.state.overlay(), Some(&OverlayKind::CommandBar));
|
||||
assert_eq!(
|
||||
(app.state.focus, app.state.mode),
|
||||
(Focus::Pane, Mode::Insert)
|
||||
);
|
||||
|
||||
let (decision, effects) = app.handle_overlay_input(&InputKey::Esc);
|
||||
assert_eq!(decision, OverlayDecision::Consumed);
|
||||
assert!(effects.is_empty());
|
||||
assert!(app.state.overlay().is_none());
|
||||
assert!(app.command_bar.is_none());
|
||||
assert_eq!(
|
||||
(app.state.focus, app.state.mode),
|
||||
(Focus::Pane, Mode::Insert)
|
||||
);
|
||||
}
|
||||
|
||||
/// Enter goes through the same open path the sidebar's attach uses.
|
||||
#[test]
|
||||
fn enter_attaches_the_highlighted_session() {
|
||||
let mut app = make_app();
|
||||
let (_alpha, bravo) = seed_two_sessions(&mut app);
|
||||
app.dispatch(Action::OpenCommandBar);
|
||||
let (decision, effects) = app.handle_overlay_input(&InputKey::Enter);
|
||||
assert_eq!(decision, OverlayDecision::Consumed);
|
||||
assert_eq!(effects, vec![Effect::Attach(bravo)]);
|
||||
assert!(app.state.overlay().is_none());
|
||||
assert!(app.command_bar.is_none());
|
||||
assert_eq!(app.state.active_session(), Some(bravo));
|
||||
}
|
||||
|
||||
/// Down moves the highlight, so Enter opens the second row instead.
|
||||
#[test]
|
||||
fn the_highlight_moves_before_enter_attaches() {
|
||||
let mut app = make_app();
|
||||
let (alpha, _bravo) = seed_two_sessions(&mut app);
|
||||
app.dispatch(Action::OpenCommandBar);
|
||||
app.handle_overlay_input(&InputKey::Down);
|
||||
let (_, effects) = app.handle_overlay_input(&InputKey::Enter);
|
||||
assert_eq!(effects, vec![Effect::Attach(alpha)]);
|
||||
assert_eq!(app.state.active_session(), Some(alpha));
|
||||
}
|
||||
|
||||
/// Typing goes to the query, not to the keymap: `q` must not quit and `x`
|
||||
/// must not raise a kill confirm while the bar is up.
|
||||
#[test]
|
||||
fn typing_reaches_the_query_rather_than_the_keymap() {
|
||||
let mut app = make_app();
|
||||
seed_two_sessions(&mut app);
|
||||
app.dispatch(Action::OpenCommandBar);
|
||||
for c in "bra".chars() {
|
||||
let (decision, _) = app.handle_overlay_input(&InputKey::Char {
|
||||
c,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
});
|
||||
assert_eq!(decision, OverlayDecision::Consumed);
|
||||
}
|
||||
let bar = app.command_bar.as_ref().unwrap();
|
||||
assert_eq!(bar.query(), "bra");
|
||||
assert_eq!(bar.rows().len(), 1);
|
||||
}
|
||||
|
||||
/// The bar is not previewed into (`docs/PREVIEW.md`): opening discards a
|
||||
/// preview and the highlight behind it raises no new one.
|
||||
#[test]
|
||||
fn opening_the_bar_discards_a_preview() {
|
||||
let mut app = make_app();
|
||||
let (alpha, _bravo) = seed_two_sessions(&mut app);
|
||||
app.state.sidebar_highlight = Some(SidebarItem::Session(alpha));
|
||||
app.state.preview = Some(alpha);
|
||||
|
||||
app.dispatch(Action::OpenCommandBar);
|
||||
assert_eq!(app.state.preview, None);
|
||||
assert_eq!(app.pending_preview, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kill_highlighted_opens_confirm() {
|
||||
use chrono::Utc;
|
||||
|
||||
@@ -0,0 +1,758 @@
|
||||
//! The `ctrl-k` command bar (`docs/COMMAND-BAR.md`): a query line over a
|
||||
//! result list, opened from Normal or Insert mode, closed with Escape.
|
||||
//!
|
||||
//! Sessions are the only kind here (#153); the sigils (#154), the session
|
||||
//! action page (#155) and the leader's literal Ctrl-K (#156) land later. The
|
||||
//! grouping below is already kind-generic so those slot in without a rewrite.
|
||||
//!
|
||||
//! Ranking is [`crate::matcher`]'s job and nothing here reorders it — the
|
||||
//! groups are a rendering of the ranked list, in the order their best-scoring
|
||||
//! member appears. The web bar (`web/src/commandBar.ts`) implements the same
|
||||
//! contract; the two must agree.
|
||||
|
||||
use maestro_protocol::display::{abbreviate_dir, command_tool, session_tree_path};
|
||||
use maestro_protocol::{Session, SessionStatus};
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::{Modifier, Style};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
|
||||
use ratatui::Frame;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::input::InputKey;
|
||||
use crate::matcher::{
|
||||
match_and_rank, CandidateKind, MatchCandidate, MatchFieldName, MatchRange, SessionCandidate,
|
||||
};
|
||||
use crate::overlays::centered;
|
||||
use crate::palette;
|
||||
use crate::text_input::TextInput;
|
||||
|
||||
/// What Enter on a row does. Only sessions exist today; `>` commands and `~`
|
||||
/// directories (#154) become further variants.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BarTarget {
|
||||
Session(Uuid),
|
||||
}
|
||||
|
||||
/// One row of the result list, already resolved to what it renders and what it
|
||||
/// opens. Headers are labels, not rows, so they are never in this list.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BarRow {
|
||||
pub kind: CandidateKind,
|
||||
pub target: BarTarget,
|
||||
/// Primary text — the name as the sidebar shows it.
|
||||
pub name: String,
|
||||
/// Secondary text: the field the match was found in when that was not the
|
||||
/// name, so a session found through its directory says so.
|
||||
pub meta: Option<String>,
|
||||
/// The field that won, and the ranges inside it. `None` for an empty
|
||||
/// query, which matches everything and highlights nothing.
|
||||
pub field: Option<MatchFieldName>,
|
||||
pub ranges: Vec<MatchRange>,
|
||||
pub dead: bool,
|
||||
}
|
||||
|
||||
impl BarRow {
|
||||
/// Whether the highlight belongs on [`Self::meta`] rather than the name.
|
||||
fn meta_is_matched(&self) -> bool {
|
||||
!matches!(self.field, None | Some(MatchFieldName::Name))
|
||||
}
|
||||
}
|
||||
|
||||
/// One kind's slice of the ranked list, as a header plus the rows under it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BarGroup {
|
||||
pub kind: CandidateKind,
|
||||
pub title: &'static str,
|
||||
/// Index of this group's first row in [`CommandBar::rows`].
|
||||
pub start: usize,
|
||||
pub len: usize,
|
||||
}
|
||||
|
||||
fn kind_title(kind: CandidateKind) -> &'static str {
|
||||
match kind {
|
||||
CandidateKind::Session => "Sessions",
|
||||
CandidateKind::Command => "Commands",
|
||||
CandidateKind::Directory => "Directories",
|
||||
}
|
||||
}
|
||||
|
||||
/// What a keystroke asked the bar to do.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BarOutcome {
|
||||
/// The bar stays up.
|
||||
Stay,
|
||||
/// Escape: close and give the keyboard back.
|
||||
Close,
|
||||
/// Enter on a row: close and open what it points at.
|
||||
Open(BarTarget),
|
||||
}
|
||||
|
||||
/// The empty-query order (`docs/COMMAND-BAR.md`, "Empty query"): most recently
|
||||
/// focused first; a session that has never been focused sorts after every
|
||||
/// session that has, most recently created first among those; and a dead
|
||||
/// session sorts after every live one regardless of recency, because a session
|
||||
/// you cannot attach to is not where you just were.
|
||||
///
|
||||
/// This is also the input order for a non-empty query, which is what the
|
||||
/// matcher's last tie-break preserves. Mirrors the web's
|
||||
/// `orderSessionsForBar`.
|
||||
pub fn order_sessions_for_bar(sessions: &[Session]) -> Vec<&Session> {
|
||||
let mut ordered: Vec<&Session> = sessions.iter().collect();
|
||||
ordered.sort_by(|a, b| {
|
||||
let dead = |s: &Session| u8::from(s.status == SessionStatus::Dead);
|
||||
dead(a)
|
||||
.cmp(&dead(b))
|
||||
.then_with(|| {
|
||||
a.last_focused_at
|
||||
.is_none()
|
||||
.cmp(&b.last_focused_at.is_none())
|
||||
})
|
||||
.then_with(|| match (a.last_focused_at, b.last_focused_at) {
|
||||
(Some(x), Some(y)) => y.cmp(&x),
|
||||
_ => std::cmp::Ordering::Equal,
|
||||
})
|
||||
.then_with(|| b.created_at.cmp(&a.created_at))
|
||||
});
|
||||
ordered
|
||||
}
|
||||
|
||||
/// One session's candidate: the fields `docs/COMMAND-BAR.md`'s candidate table
|
||||
/// names, with the directory abbreviated the way the sidebar shows it.
|
||||
pub fn session_candidate(session: &Session, home_dir: &str) -> SessionCandidate {
|
||||
SessionCandidate {
|
||||
name: crate::sidebar::name_for(session),
|
||||
directory: session_tree_path(session).map(|path| abbreviate_dir(&path, home_dir)),
|
||||
command: (!session.command.is_empty()).then(|| session.command.clone()),
|
||||
tool: command_tool(&session.command).map(str::to_string),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bar's state while it is up: the query buffer, the candidates it was
|
||||
/// opened over, the rows the current query produces, and the highlight.
|
||||
#[derive(Debug)]
|
||||
pub struct CommandBar {
|
||||
input: TextInput,
|
||||
/// Matcher input, in the empty-query order. Never reordered — the matcher's
|
||||
/// last tie-break is what keeps that order meaningful.
|
||||
candidates: Vec<MatchCandidate>,
|
||||
/// What each candidate opens, parallel to `candidates`.
|
||||
targets: Vec<BarTarget>,
|
||||
/// Whether each candidate's session is dead, parallel to `candidates`.
|
||||
dead: Vec<bool>,
|
||||
rows: Vec<BarRow>,
|
||||
highlight: usize,
|
||||
}
|
||||
|
||||
impl CommandBar {
|
||||
/// Open the bar over the sessions the catalog has right now.
|
||||
pub fn new(sessions: &[Session], home_dir: &str) -> Self {
|
||||
let ordered = order_sessions_for_bar(sessions);
|
||||
let candidates = ordered
|
||||
.iter()
|
||||
.map(|s| MatchCandidate::Session(session_candidate(s, home_dir)))
|
||||
.collect();
|
||||
let targets = ordered.iter().map(|s| BarTarget::Session(s.id)).collect();
|
||||
let dead = ordered
|
||||
.iter()
|
||||
.map(|s| s.status == SessionStatus::Dead)
|
||||
.collect();
|
||||
let mut bar = Self {
|
||||
input: TextInput::default(),
|
||||
candidates,
|
||||
targets,
|
||||
dead,
|
||||
rows: Vec::new(),
|
||||
highlight: 0,
|
||||
};
|
||||
bar.recompute();
|
||||
bar
|
||||
}
|
||||
|
||||
pub fn query(&self) -> &str {
|
||||
self.input.value()
|
||||
}
|
||||
|
||||
pub fn rows(&self) -> &[BarRow] {
|
||||
&self.rows
|
||||
}
|
||||
|
||||
pub fn highlight(&self) -> usize {
|
||||
self.highlight
|
||||
}
|
||||
|
||||
/// The row Enter would open.
|
||||
pub fn selected(&self) -> Option<&BarRow> {
|
||||
self.rows.get(self.highlight)
|
||||
}
|
||||
|
||||
/// Group the ranked rows by kind for rendering. Grouping never reorders:
|
||||
/// a group holds its matches in rank order, and groups appear in the order
|
||||
/// their best-scoring member does — so the first row under the first
|
||||
/// header is the globally best result.
|
||||
pub fn groups(&self) -> Vec<BarGroup> {
|
||||
let mut groups: Vec<BarGroup> = Vec::new();
|
||||
for (index, row) in self.rows.iter().enumerate() {
|
||||
match groups.iter_mut().find(|g| g.kind == row.kind) {
|
||||
Some(group) => group.len += 1,
|
||||
None => groups.push(BarGroup {
|
||||
kind: row.kind,
|
||||
title: kind_title(row.kind),
|
||||
start: index,
|
||||
len: 1,
|
||||
}),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
/// Move the highlight. It does not wrap: it stops at the first and last
|
||||
/// row.
|
||||
pub fn move_highlight(&mut self, delta: isize) {
|
||||
if self.rows.is_empty() {
|
||||
self.highlight = 0;
|
||||
return;
|
||||
}
|
||||
let last = self.rows.len() as isize - 1;
|
||||
let next = (self.highlight as isize + delta).clamp(0, last);
|
||||
self.highlight = next as usize;
|
||||
}
|
||||
|
||||
/// Feed the bar a key. Everything the key table (`docs/COMMAND-BAR.md`,
|
||||
/// "Keys") does not claim is ordinary editing.
|
||||
pub fn handle_key(&mut self, key: &InputKey) -> BarOutcome {
|
||||
match key {
|
||||
InputKey::Esc => BarOutcome::Close,
|
||||
InputKey::Enter => match self.selected() {
|
||||
Some(row) => BarOutcome::Open(row.target),
|
||||
// Nothing to open: the bar stays up rather than closing on a
|
||||
// key that did nothing.
|
||||
None => BarOutcome::Stay,
|
||||
},
|
||||
InputKey::Up
|
||||
| InputKey::Char {
|
||||
c: 'p', ctrl: true, ..
|
||||
} => {
|
||||
self.move_highlight(-1);
|
||||
BarOutcome::Stay
|
||||
}
|
||||
InputKey::Down
|
||||
| InputKey::Char {
|
||||
c: 'n', ctrl: true, ..
|
||||
} => {
|
||||
self.move_highlight(1);
|
||||
BarOutcome::Stay
|
||||
}
|
||||
// Tab drills into the highlighted session's action page (#155).
|
||||
// Until then it is inert rather than a literal tab in the query.
|
||||
InputKey::Tab | InputKey::BackTab => BarOutcome::Stay,
|
||||
other => {
|
||||
let before = self.input.value().to_string();
|
||||
self.input.handle_key(other);
|
||||
if self.input.value() != before {
|
||||
self.recompute();
|
||||
}
|
||||
BarOutcome::Stay
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-rank for the current query. The highlight starts on the globally
|
||||
/// best row every time the list changes: an old index would point at a
|
||||
/// different result.
|
||||
fn recompute(&mut self) {
|
||||
let rows: Vec<BarRow> = {
|
||||
let results = match_and_rank(self.input.value(), &self.candidates);
|
||||
results
|
||||
.iter()
|
||||
.map(|result| {
|
||||
let index = self
|
||||
.candidates
|
||||
.iter()
|
||||
.position(|c| std::ptr::eq(c, result.candidate))
|
||||
.expect("every result borrows one of this bar's candidates");
|
||||
let MatchCandidate::Session(session) = result.candidate else {
|
||||
unreachable!("sessions are the only kind the bar builds (#153)")
|
||||
};
|
||||
BarRow {
|
||||
kind: CandidateKind::Session,
|
||||
target: self.targets[index],
|
||||
name: session.name.clone(),
|
||||
meta: meta_text(session, result.field),
|
||||
field: result.field,
|
||||
ranges: result.ranges.clone(),
|
||||
dead: self.dead[index],
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
self.rows = rows;
|
||||
self.highlight = 0;
|
||||
}
|
||||
|
||||
/// Draw the bar and return where the terminal cursor belongs.
|
||||
pub fn render(&self, f: &mut Frame, parent: Rect) -> Option<(u16, u16)> {
|
||||
let pal = palette::active();
|
||||
let height = parent.height.saturating_sub(4).clamp(5, 20);
|
||||
let area = centered(parent, 72, height);
|
||||
f.render_widget(Clear, area);
|
||||
let block = Block::default()
|
||||
.title(" go to ")
|
||||
.borders(Borders::ALL)
|
||||
.style(pal.card.base())
|
||||
.border_style(pal.border_style(true));
|
||||
let inner = block.inner(area);
|
||||
f.render_widget(block, area);
|
||||
if inner.height < 3 || inner.width == 0 {
|
||||
return None;
|
||||
}
|
||||
let row = |offset: u16| Rect {
|
||||
x: inner.x,
|
||||
y: inner.y + offset,
|
||||
width: inner.width,
|
||||
height: 1,
|
||||
};
|
||||
|
||||
// Query line, then the results, then the key hint on the last row.
|
||||
let query = row(0);
|
||||
let col = self
|
||||
.input
|
||||
.render(query, f.buffer_mut(), pal.card.text_style());
|
||||
f.render_widget(
|
||||
Paragraph::new(Line::from(Span::styled(
|
||||
"[enter] open [esc] close",
|
||||
pal.card.dim_style(),
|
||||
))),
|
||||
row(inner.height - 1),
|
||||
);
|
||||
|
||||
let list_height = inner.height.saturating_sub(2) as usize;
|
||||
if list_height > 0 {
|
||||
for (offset, line) in self.visible_lines(list_height).into_iter().enumerate() {
|
||||
f.render_widget(Paragraph::new(line), row(1 + offset as u16));
|
||||
}
|
||||
}
|
||||
Some((col, query.y))
|
||||
}
|
||||
|
||||
/// The result lines that fit in `height`, scrolled so the highlighted row
|
||||
/// is on screen.
|
||||
fn visible_lines(&self, height: usize) -> Vec<Line<'static>> {
|
||||
let pal = palette::active();
|
||||
if self.rows.is_empty() {
|
||||
return vec![Line::from(Span::styled(
|
||||
"No matches",
|
||||
pal.card.muted_style(),
|
||||
))];
|
||||
}
|
||||
// Headers and rows, in one list, remembering which line the highlight
|
||||
// sits on so the scroll can keep it visible.
|
||||
let mut lines: Vec<Line<'static>> = Vec::new();
|
||||
let mut highlight_line = 0usize;
|
||||
for group in self.groups() {
|
||||
lines.push(Line::from(Span::styled(
|
||||
group.title.to_string(),
|
||||
pal.group_row_style(),
|
||||
)));
|
||||
for index in group.start..group.start + group.len {
|
||||
if index == self.highlight {
|
||||
highlight_line = lines.len();
|
||||
}
|
||||
lines.push(self.row_line(index));
|
||||
}
|
||||
}
|
||||
let scroll = highlight_line.saturating_sub(height.saturating_sub(1));
|
||||
lines.into_iter().skip(scroll).take(height).collect()
|
||||
}
|
||||
|
||||
fn row_line(&self, index: usize) -> Line<'static> {
|
||||
let pal = palette::active();
|
||||
let row = &self.rows[index];
|
||||
let selected = index == self.highlight;
|
||||
let surface = pal.surface(selected);
|
||||
let base = if row.dead {
|
||||
surface.dim_style()
|
||||
} else {
|
||||
surface.text_style()
|
||||
};
|
||||
let hit = base.add_modifier(Modifier::BOLD | Modifier::UNDERLINED);
|
||||
|
||||
let mut spans = vec![Span::styled(if selected { "› " } else { " " }, base)];
|
||||
let name_ranges: &[MatchRange] = if row.meta_is_matched() {
|
||||
&[]
|
||||
} else {
|
||||
&row.ranges
|
||||
};
|
||||
spans.extend(highlighted_spans(&row.name, name_ranges, base, hit));
|
||||
if let Some(meta) = &row.meta {
|
||||
let meta_style = surface.muted_style();
|
||||
let meta_hit = meta_style.add_modifier(Modifier::BOLD | Modifier::UNDERLINED);
|
||||
spans.push(Span::styled(" ", base));
|
||||
let meta_ranges: &[MatchRange] = if row.meta_is_matched() {
|
||||
&row.ranges
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
spans.extend(highlighted_spans(meta, meta_ranges, meta_style, meta_hit));
|
||||
}
|
||||
Line::from(spans)
|
||||
}
|
||||
}
|
||||
|
||||
/// The secondary line under a row's name: the field the match was found in
|
||||
/// when that was not the name, so a session found through its directory says
|
||||
/// so. Mirrors the web's `metaText`.
|
||||
fn meta_text(session: &SessionCandidate, field: Option<MatchFieldName>) -> Option<String> {
|
||||
match field {
|
||||
Some(MatchFieldName::Directory) => session.directory.clone(),
|
||||
Some(MatchFieldName::Command) => session.command.clone(),
|
||||
Some(MatchFieldName::Tool) => session.tool.clone(),
|
||||
_ => session.directory.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `text` into styled spans, with the matcher's `[start, end)` character
|
||||
/// ranges carrying `hit` and everything else `base`.
|
||||
fn highlighted_spans(
|
||||
text: &str,
|
||||
ranges: &[MatchRange],
|
||||
base: Style,
|
||||
hit: Style,
|
||||
) -> Vec<Span<'static>> {
|
||||
let chars: Vec<char> = text.chars().collect();
|
||||
let slice = |from: usize, to: usize| -> String {
|
||||
chars[from.min(chars.len())..to.min(chars.len())]
|
||||
.iter()
|
||||
.collect()
|
||||
};
|
||||
let mut spans = Vec::new();
|
||||
let mut cursor = 0usize;
|
||||
for &(start, end) in ranges {
|
||||
if start > cursor {
|
||||
spans.push(Span::styled(slice(cursor, start), base));
|
||||
}
|
||||
spans.push(Span::styled(slice(start, end), hit));
|
||||
cursor = end;
|
||||
}
|
||||
if cursor < chars.len() {
|
||||
spans.push(Span::styled(slice(cursor, chars.len()), base));
|
||||
}
|
||||
spans
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use ratatui::backend::TestBackend;
|
||||
use ratatui::Terminal;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn at(secs: i64) -> DateTime<Utc> {
|
||||
Utc.timestamp_opt(1_700_000_000 + secs, 0).unwrap()
|
||||
}
|
||||
|
||||
fn session(n: u128, command: &str) -> Session {
|
||||
Session {
|
||||
id: Uuid::from_u128(n),
|
||||
cwd: PathBuf::from("/home/me/dev/api"),
|
||||
command: command.to_string(),
|
||||
env: HashMap::new(),
|
||||
metadata: HashMap::new(),
|
||||
worktree: None,
|
||||
status: SessionStatus::Running,
|
||||
created_at: at(0),
|
||||
foreground: None,
|
||||
activity: Default::default(),
|
||||
activity_detail: None,
|
||||
last_activity_at: at(0),
|
||||
activity_since: at(0),
|
||||
current_cwd: None,
|
||||
blocked_work: None,
|
||||
last_focused_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn named(n: u128, name: &str) -> Session {
|
||||
let mut s = session(n, "bash");
|
||||
s.metadata
|
||||
.insert("name".into(), serde_json::Value::String(name.to_string()));
|
||||
s
|
||||
}
|
||||
|
||||
fn ids(rows: &[BarRow]) -> Vec<Uuid> {
|
||||
rows.iter()
|
||||
.map(|r| match r.target {
|
||||
BarTarget::Session(id) => id,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn typed(bar: &mut CommandBar, text: &str) {
|
||||
for c in text.chars() {
|
||||
bar.handle_key(&InputKey::Char {
|
||||
c,
|
||||
ctrl: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_query_lists_sessions_most_recently_focused_first() {
|
||||
let mut a = named(1, "alpha");
|
||||
a.last_focused_at = Some(at(10));
|
||||
let mut b = named(2, "bravo");
|
||||
b.last_focused_at = Some(at(30));
|
||||
let mut c = named(3, "charlie");
|
||||
c.last_focused_at = Some(at(20));
|
||||
|
||||
let bar = CommandBar::new(&[a, b, c], "/home/me");
|
||||
assert_eq!(
|
||||
ids(bar.rows()),
|
||||
vec![Uuid::from_u128(2), Uuid::from_u128(3), Uuid::from_u128(1)]
|
||||
);
|
||||
// Every row matches with no ranges, so nothing is highlighted inside.
|
||||
assert!(bar.rows().iter().all(|r| r.ranges.is_empty()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn never_focused_sessions_sort_after_focused_ones_newest_first() {
|
||||
let mut focused = named(1, "focused");
|
||||
focused.last_focused_at = Some(at(5));
|
||||
let mut older = named(2, "older");
|
||||
older.created_at = at(10);
|
||||
let mut newer = named(3, "newer");
|
||||
newer.created_at = at(20);
|
||||
|
||||
let bar = CommandBar::new(&[older, newer, focused], "/home/me");
|
||||
assert_eq!(
|
||||
ids(bar.rows()),
|
||||
vec![Uuid::from_u128(1), Uuid::from_u128(3), Uuid::from_u128(2)]
|
||||
);
|
||||
}
|
||||
|
||||
/// A session you cannot attach to is not where you just were.
|
||||
#[test]
|
||||
fn dead_sessions_sort_after_live_ones_however_recent() {
|
||||
let mut dead = named(1, "dead");
|
||||
dead.status = SessionStatus::Dead;
|
||||
dead.last_focused_at = Some(at(99));
|
||||
let live = named(2, "live");
|
||||
|
||||
let bar = CommandBar::new(&[dead, live], "/home/me");
|
||||
assert_eq!(
|
||||
ids(bar.rows()),
|
||||
vec![Uuid::from_u128(2), Uuid::from_u128(1)]
|
||||
);
|
||||
assert!(bar.rows()[1].dead);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typing_ranks_through_the_matcher_and_returns_ranges() {
|
||||
let mut bar = CommandBar::new(&[named(1, "web-search"), named(2, "websearch")], "/home/me");
|
||||
typed(&mut bar, "ws");
|
||||
// F9: the `s` after `-` earns the boundary bonus.
|
||||
assert_eq!(
|
||||
ids(bar.rows()),
|
||||
vec![Uuid::from_u128(1), Uuid::from_u128(2)]
|
||||
);
|
||||
assert_eq!(bar.rows()[0].ranges, vec![(0, 1), (4, 5)]);
|
||||
assert_eq!(bar.rows()[0].field, Some(MatchFieldName::Name));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_query_matching_nothing_leaves_no_rows() {
|
||||
let mut bar = CommandBar::new(&[named(1, "alpha")], "/home/me");
|
||||
typed(&mut bar, "zzz");
|
||||
assert!(bar.rows().is_empty());
|
||||
assert!(bar.selected().is_none());
|
||||
}
|
||||
|
||||
/// A session found through its directory highlights inside the directory,
|
||||
/// which is also what the row's meta text shows.
|
||||
#[test]
|
||||
fn a_directory_match_highlights_in_the_meta_text() {
|
||||
let mut worker = named(1, "worker");
|
||||
worker.cwd = PathBuf::from("/home/me/dev/api");
|
||||
let mut bar = CommandBar::new(&[worker], "/home/me");
|
||||
typed(&mut bar, "api");
|
||||
assert_eq!(bar.rows()[0].field, Some(MatchFieldName::Directory));
|
||||
assert_eq!(bar.rows()[0].meta.as_deref(), Some("~/dev/api"));
|
||||
assert_eq!(bar.rows()[0].ranges, vec![(6, 9)]);
|
||||
}
|
||||
|
||||
/// The candidate's `tool` is the mark the card's icon stands for, so
|
||||
/// `claude` reaches a session whose name says nothing about it.
|
||||
#[test]
|
||||
fn the_tool_field_is_a_candidate_field() {
|
||||
let mut nameless = named(1, "nameless");
|
||||
nameless.command = "claude --resume".into();
|
||||
let mut bar = CommandBar::new(&[nameless, named(2, "clay")], "/home/me");
|
||||
typed(&mut bar, "claude");
|
||||
assert_eq!(ids(bar.rows()), vec![Uuid::from_u128(1)]);
|
||||
assert_eq!(bar.rows()[0].field, Some(MatchFieldName::Tool));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn results_group_under_kind_headers_with_the_best_row_first() {
|
||||
let bar = CommandBar::new(&[named(1, "alpha"), named(2, "bravo")], "/home/me");
|
||||
let groups = bar.groups();
|
||||
assert_eq!(groups.len(), 1);
|
||||
assert_eq!(groups[0].title, "Sessions");
|
||||
assert_eq!(groups[0].kind, CandidateKind::Session);
|
||||
assert_eq!((groups[0].start, groups[0].len), (0, 2));
|
||||
// The highlight starts on the globally best row.
|
||||
assert_eq!(bar.highlight(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrows_and_ctrl_pn_move_the_highlight_without_wrapping() {
|
||||
let mut bar = CommandBar::new(
|
||||
&[named(1, "alpha"), named(2, "bravo"), named(3, "charlie")],
|
||||
"/home/me",
|
||||
);
|
||||
assert_eq!(bar.handle_key(&InputKey::Down), BarOutcome::Stay);
|
||||
assert_eq!(bar.highlight(), 1);
|
||||
bar.handle_key(&InputKey::Char {
|
||||
c: 'n',
|
||||
ctrl: true,
|
||||
alt: false,
|
||||
shift: false,
|
||||
});
|
||||
assert_eq!(bar.highlight(), 2);
|
||||
// Stops at the last row rather than wrapping to the first.
|
||||
bar.handle_key(&InputKey::Down);
|
||||
assert_eq!(bar.highlight(), 2);
|
||||
bar.handle_key(&InputKey::Char {
|
||||
c: 'p',
|
||||
ctrl: true,
|
||||
alt: false,
|
||||
shift: false,
|
||||
});
|
||||
assert_eq!(bar.highlight(), 1);
|
||||
bar.handle_key(&InputKey::Up);
|
||||
bar.handle_key(&InputKey::Up);
|
||||
assert_eq!(bar.highlight(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_opens_the_highlighted_session_and_escape_closes() {
|
||||
let mut bar = CommandBar::new(&[named(1, "alpha"), named(2, "bravo")], "/home/me");
|
||||
bar.handle_key(&InputKey::Down);
|
||||
assert_eq!(
|
||||
bar.handle_key(&InputKey::Enter),
|
||||
BarOutcome::Open(BarTarget::Session(Uuid::from_u128(2)))
|
||||
);
|
||||
assert_eq!(bar.handle_key(&InputKey::Esc), BarOutcome::Close);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_with_no_results_leaves_the_bar_up() {
|
||||
let mut bar = CommandBar::new(&[named(1, "alpha")], "/home/me");
|
||||
typed(&mut bar, "zzz");
|
||||
assert_eq!(bar.handle_key(&InputKey::Enter), BarOutcome::Stay);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_the_query_re_ranks_and_resets_the_highlight() {
|
||||
let mut bar = CommandBar::new(&[named(1, "alpha"), named(2, "alpine")], "/home/me");
|
||||
bar.handle_key(&InputKey::Down);
|
||||
assert_eq!(bar.highlight(), 1);
|
||||
typed(&mut bar, "alp");
|
||||
assert_eq!(bar.query(), "alp");
|
||||
assert_eq!(bar.highlight(), 0);
|
||||
bar.handle_key(&InputKey::Backspace);
|
||||
assert_eq!(bar.query(), "al");
|
||||
assert_eq!(bar.rows().len(), 2);
|
||||
}
|
||||
|
||||
/// Backspacing back to an empty query is not a special key: the list
|
||||
/// becomes the recency order again.
|
||||
#[test]
|
||||
fn backspacing_to_an_empty_query_restores_the_recency_order() {
|
||||
let mut recent = named(1, "alpha");
|
||||
recent.last_focused_at = Some(at(50));
|
||||
let older = named(2, "alpine");
|
||||
let mut bar = CommandBar::new(&[older, recent], "/home/me");
|
||||
typed(&mut bar, "alpi");
|
||||
assert_eq!(ids(bar.rows()), vec![Uuid::from_u128(2)]);
|
||||
for _ in 0..4 {
|
||||
bar.handle_key(&InputKey::Backspace);
|
||||
}
|
||||
assert_eq!(bar.query(), "");
|
||||
assert_eq!(
|
||||
ids(bar.rows()),
|
||||
vec![Uuid::from_u128(1), Uuid::from_u128(2)]
|
||||
);
|
||||
}
|
||||
|
||||
fn render_to_string(bar: &CommandBar, w: u16, h: u16) -> String {
|
||||
let backend = TestBackend::new(w, h);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| {
|
||||
bar.render(f, f.area());
|
||||
})
|
||||
.unwrap();
|
||||
let buf = terminal.backend().buffer().clone();
|
||||
let mut out = String::new();
|
||||
for y in 0..buf.area.height {
|
||||
for x in 0..buf.area.width {
|
||||
out.push_str(buf[(x, y)].symbol());
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_the_query_the_headers_and_the_rows() {
|
||||
let mut bar = CommandBar::new(&[named(1, "alpha"), named(2, "alpine")], "/home/me");
|
||||
typed(&mut bar, "alp");
|
||||
let rendered = render_to_string(&bar, 90, 20);
|
||||
assert!(rendered.contains("go to"), "{rendered}");
|
||||
assert!(rendered.contains("alp"), "{rendered}");
|
||||
assert!(rendered.contains("Sessions"), "{rendered}");
|
||||
assert!(rendered.contains("alpha"), "{rendered}");
|
||||
assert!(rendered.contains("alpine"), "{rendered}");
|
||||
assert!(rendered.contains("[esc] close"), "{rendered}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_a_no_results_state() {
|
||||
let mut bar = CommandBar::new(&[named(1, "alpha")], "/home/me");
|
||||
typed(&mut bar, "zzz");
|
||||
let rendered = render_to_string(&bar, 90, 20);
|
||||
assert!(rendered.contains("No matches"), "{rendered}");
|
||||
}
|
||||
|
||||
/// The matched characters are drawn bold, so the row shows why it matched.
|
||||
#[test]
|
||||
fn matched_ranges_are_styled_apart_from_the_rest_of_the_row() {
|
||||
let mut bar = CommandBar::new(&[named(1, "web-search")], "/home/me");
|
||||
typed(&mut bar, "ws");
|
||||
let backend = TestBackend::new(90, 20);
|
||||
let mut terminal = Terminal::new(backend).unwrap();
|
||||
terminal
|
||||
.draw(|f| {
|
||||
bar.render(f, f.area());
|
||||
})
|
||||
.unwrap();
|
||||
let buf = terminal.backend().buffer().clone();
|
||||
let mut bold: Vec<String> = Vec::new();
|
||||
for y in 0..buf.area.height {
|
||||
for x in 0..buf.area.width {
|
||||
let cell = &buf[(x, y)];
|
||||
if cell.style().add_modifier.contains(Modifier::BOLD)
|
||||
&& cell.style().add_modifier.contains(Modifier::UNDERLINED)
|
||||
{
|
||||
bold.push(cell.symbol().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(bold, vec!["w", "s"], "bold cells: {bold:?}");
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,9 @@ const DEFAULT_NORMAL: &[(&str, &str)] = &[
|
||||
("pageup", "ScrollPanePageUp"),
|
||||
("pagedown", "ScrollPanePageDown"),
|
||||
// Chrome
|
||||
// The command bar (#153). An ordinary entry, so it is rebindable and the
|
||||
// help overlay picks it up from the live keymap.
|
||||
("ctrl-k", "OpenCommandBar"),
|
||||
("ctrl-w b", "ToggleSidebar"),
|
||||
("?", "ShowHelp"),
|
||||
("ctrl-w q", "Quit"),
|
||||
@@ -75,13 +78,17 @@ const DEFAULT_NORMAL: &[(&str, &str)] = &[
|
||||
("mouse:dblclick(sidebar-row)", "AttachHighlighted"),
|
||||
];
|
||||
|
||||
/// Default Insert-mode bindings — deliberately empty. Every key typed in
|
||||
/// Default Insert-mode bindings — almost empty on purpose. Every key typed in
|
||||
/// Insert mode belongs to the session, `esc` included: full-screen apps read
|
||||
/// it constantly, so binding it here would make it unreachable. The only way
|
||||
/// back to the sidebar is the leader (`LeaveInsert`), which
|
||||
/// [`TuiConfig::load`] inserts dynamically so rebinding the leader rebinds
|
||||
/// the Insert escape with it.
|
||||
const DEFAULT_INSERT: &[(&str, &str)] = &[];
|
||||
///
|
||||
/// The one exception is the command bar (#153): `ctrl-k` opens it from inside
|
||||
/// a pane too, so `docs/COMMAND-BAR.md`'s "from anywhere" holds. Readline's
|
||||
/// kill-to-end-of-line is given back through the leader (#156).
|
||||
const DEFAULT_INSERT: &[(&str, &str)] = &[("ctrl-k", "OpenCommandBar")];
|
||||
|
||||
impl TuiConfig {
|
||||
/// Build a runtime config from a [`TuiSection`] (typically the `tui`
|
||||
|
||||
@@ -6,6 +6,7 @@ pub mod action;
|
||||
pub mod app;
|
||||
pub mod catalog;
|
||||
pub mod cli;
|
||||
pub mod command_bar;
|
||||
pub mod config;
|
||||
pub mod daemon_link;
|
||||
pub mod draft;
|
||||
|
||||
@@ -86,6 +86,9 @@ pub struct RenderInputs<'a> {
|
||||
pub help: &'a HelpOverlay,
|
||||
/// Edit buffer behind the rename prompt (#125).
|
||||
pub rename_input: &'a crate::text_input::TextInput,
|
||||
/// The command bar behind [`OverlayKind::CommandBar`] (#153), when one is
|
||||
/// up.
|
||||
pub command_bar: Option<&'a crate::command_bar::CommandBar>,
|
||||
/// Liveness + release of the daemon, for the status bar's indicator and the
|
||||
/// restart overlay (`docs/RESTART.md`).
|
||||
pub link: &'a crate::daemon_link::LinkStatus,
|
||||
@@ -198,6 +201,14 @@ pub fn draw(f: &mut Frame, inputs: RenderInputs<'_>) -> RegionMap {
|
||||
}
|
||||
map.modal = Some(area);
|
||||
}
|
||||
Some(OverlayKind::CommandBar) => {
|
||||
if let Some(bar) = inputs.command_bar {
|
||||
if let Some((x, y)) = bar.render(f, area) {
|
||||
f.set_cursor_position((x, y));
|
||||
}
|
||||
map.modal = Some(area);
|
||||
}
|
||||
}
|
||||
Some(OverlayKind::Help) => {
|
||||
inputs.help.render(f, area);
|
||||
map.modal = Some(area);
|
||||
@@ -428,6 +439,7 @@ mod tests {
|
||||
state: &state,
|
||||
help: &help,
|
||||
rename_input: &crate::text_input::TextInput::default(),
|
||||
command_bar: None,
|
||||
link,
|
||||
};
|
||||
let backend = ratatui::backend::TestBackend::new(120, 24);
|
||||
@@ -524,6 +536,7 @@ mod tests {
|
||||
state: &state,
|
||||
help: &help,
|
||||
rename_input: &crate::text_input::TextInput::default(),
|
||||
command_bar: None,
|
||||
link: &online_link(),
|
||||
};
|
||||
|
||||
@@ -578,6 +591,7 @@ mod tests {
|
||||
state: &state,
|
||||
help: &help,
|
||||
rename_input: &crate::text_input::TextInput::default(),
|
||||
command_bar: None,
|
||||
link: &online_link(),
|
||||
};
|
||||
let backend = ratatui::backend::TestBackend::new(80, 24);
|
||||
@@ -619,6 +633,7 @@ mod tests {
|
||||
state: &state,
|
||||
help: &help,
|
||||
rename_input: &crate::text_input::TextInput::default(),
|
||||
command_bar: None,
|
||||
link: &online_link(),
|
||||
};
|
||||
let backend = ratatui::backend::TestBackend::new(80, 24);
|
||||
|
||||
@@ -52,6 +52,10 @@ pub enum OverlayKind {
|
||||
/// so this stays comparable.
|
||||
Rename(Uuid),
|
||||
Help,
|
||||
/// The `ctrl-k` command bar (#153). Its query buffer and result list live
|
||||
/// on `App` as [`crate::command_bar::CommandBar`], for the same reason the
|
||||
/// rename buffer does — so this stays comparable.
|
||||
CommandBar,
|
||||
Toast(String),
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,10 @@ export interface AttachConnection {
|
||||
onUnmount(): void;
|
||||
/** Put the keyboard back into this terminal — what leaving the sidebar does. */
|
||||
focusTerminal(): void;
|
||||
/** Type raw bytes straight into the PTY, bypassing the terminal's own key
|
||||
* handling — the leader's literal Ctrl-K escape hatch
|
||||
* (docs/COMMAND-BAR.md). */
|
||||
sendInput(data: string): void;
|
||||
/** Fully disconnect: close the WS, dispose the terminal, remove the element. */
|
||||
dispose(): void;
|
||||
}
|
||||
@@ -506,6 +510,9 @@ export function createAttachConnection(
|
||||
focusTerminal() {
|
||||
term.focus();
|
||||
},
|
||||
// The closure above: the same bytes-out path keystrokes and the mobile key
|
||||
// bar already take.
|
||||
sendInput,
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
|
||||
+240
-5
@@ -6,13 +6,19 @@ import {
|
||||
barGroups,
|
||||
barRows,
|
||||
closeCommandBar,
|
||||
commandBarCandidates,
|
||||
dedupeCommands,
|
||||
directoryBarCandidates,
|
||||
directoryCandidate,
|
||||
isCommandBarOpen,
|
||||
openCommandBar,
|
||||
orderSessionsForBar,
|
||||
parseBarQuery,
|
||||
sessionBarCandidates,
|
||||
sessionCandidate,
|
||||
SPAWN_DIRECTORY_EVENT,
|
||||
} from "./commandBar.js";
|
||||
import { COMMAND_SPECS } from "./commands.js";
|
||||
import { COMMAND_SPECS, type Command } from "./commands.js";
|
||||
import type { Session } from "./types.js";
|
||||
|
||||
function session(id: string, over: Partial<Session> = {}): Session {
|
||||
@@ -173,8 +179,12 @@ describe("the overlay", () => {
|
||||
session("notes", { metadata: { name: "notes" }, current_cwd: "/home/me/notes" }),
|
||||
];
|
||||
|
||||
// Sessions only: the mixed list's command half is the sigil describe's
|
||||
// business, and the registry is whatever another test file happened to bind.
|
||||
function open(over: Parameters<typeof openCommandBar>[0] | null = null) {
|
||||
return openCommandBar(over ?? { sessions, homeDir: "/home/me", onOpenSession: () => {} });
|
||||
return openCommandBar(
|
||||
over ?? { sessions, homeDir: "/home/me", commands: [], onOpenSession: () => {} },
|
||||
);
|
||||
}
|
||||
|
||||
it("is a registry command, so the help overlay lists it", () => {
|
||||
@@ -252,7 +262,7 @@ describe("the overlay", () => {
|
||||
const seen: string[] = [];
|
||||
const listener = (e: Event) => seen.push((e as CustomEvent<string>).detail);
|
||||
document.addEventListener(SESSION_SELECT_EVENT, listener);
|
||||
openCommandBar({ sessions, homeDir: "/home/me" });
|
||||
openCommandBar({ sessions, homeDir: "/home/me", commands: [] });
|
||||
press("ArrowDown");
|
||||
press("Enter");
|
||||
document.removeEventListener(SESSION_SELECT_EVENT, listener);
|
||||
@@ -262,7 +272,7 @@ describe("the overlay", () => {
|
||||
|
||||
it("Enter on an empty result list does nothing", () => {
|
||||
const onOpenSession = vi.fn();
|
||||
open({ sessions, homeDir: "/home/me", onOpenSession });
|
||||
open({ sessions, homeDir: "/home/me", commands: [], onOpenSession });
|
||||
type("zzz");
|
||||
press("Enter");
|
||||
expect(onOpenSession).not.toHaveBeenCalled();
|
||||
@@ -301,9 +311,234 @@ describe("the overlay", () => {
|
||||
|
||||
it("clicking a row opens that session", () => {
|
||||
const onOpenSession = vi.fn();
|
||||
open({ sessions, homeDir: "/home/me", onOpenSession });
|
||||
open({ sessions, homeDir: "/home/me", commands: [], onOpenSession });
|
||||
(document.querySelectorAll(".cmdbar-row")[1] as HTMLElement).click();
|
||||
expect(onOpenSession).toHaveBeenCalledWith("worker");
|
||||
expect(isCommandBarOpen()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---- the sigils (#150) ----
|
||||
|
||||
function command(id: string, label: string, keys: string[], run = () => {}): Command {
|
||||
return { id, label, group: "Test", keys, scope: "global", run };
|
||||
}
|
||||
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
|
||||
function rowKeys(): string[][] {
|
||||
return [...document.querySelectorAll(".cmdbar-row-keys")].map((el) =>
|
||||
[...el.querySelectorAll("kbd")].map((k) => k.textContent ?? ""),
|
||||
);
|
||||
}
|
||||
|
||||
describe("parsing the query line", () => {
|
||||
it("reads a sigil only in first position", () => {
|
||||
expect(parseBarQuery(">kill")).toEqual({ sigil: ">", query: "kill" });
|
||||
expect(parseBarQuery("~/dev")).toEqual({ sigil: "~", query: "/dev" });
|
||||
expect(parseBarQuery("")).toEqual({ sigil: null, query: "" });
|
||||
expect(parseBarQuery("api")).toEqual({ sigil: null, query: "api" });
|
||||
});
|
||||
|
||||
it("leaves a sigil character elsewhere in the query literal", () => {
|
||||
expect(parseBarQuery("api>x")).toEqual({ sigil: null, query: "api>x" });
|
||||
// The case that matters: the second `~` of a directory query reaches the
|
||||
// matcher.
|
||||
expect(parseBarQuery("~~/dev")).toEqual({ sigil: "~", query: "~/dev" });
|
||||
});
|
||||
|
||||
it("returns to the mixed list when the sigil is backspaced away", () => {
|
||||
expect(parseBarQuery(">").sigil).toBe(">");
|
||||
expect(parseBarQuery("").sigil).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("command candidates", () => {
|
||||
it("dedupes by action, not by chord", () => {
|
||||
const run = () => {};
|
||||
const kill = command("a.kill", "Kill the session", ["x"], run);
|
||||
const alias = command("b.kill", "Kill the session", ["ctrl-x"], run);
|
||||
const other = command("c.rename", "Rename the session", ["r"]);
|
||||
expect(dedupeCommands([kill, alias, other]).map((c) => c.id)).toEqual(["a.kill", "c.rename"]);
|
||||
});
|
||||
|
||||
it("matches on the label only, and keeps the chord for display", () => {
|
||||
const candidates = commandBarCandidates([command("a", "Open the spawn form", ["ctrl-k"])]);
|
||||
expect(candidates[0].fields).toEqual({ label: "Open the spawn form" });
|
||||
expect(candidates[0].command.keys).toEqual(["ctrl-k"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("directory candidates", () => {
|
||||
it("abbreviates the path it shows and keeps the one it spawns in", () => {
|
||||
const c = directoryCandidate("/home/me/dev/api", "/home/me");
|
||||
expect(c).toEqual({ kind: "directory", path: "/home/me/dev/api", fields: { path: "~/dev/api" } });
|
||||
});
|
||||
|
||||
it("expands a typed `~` and dedupes by the directory spawned in", () => {
|
||||
const paths = ["~/dev/api", "/home/me/dev/api", "/tmp/scratch"];
|
||||
expect(directoryBarCandidates(paths, "/home/me").map((c) => c.path)).toEqual([
|
||||
"/home/me/dev/api",
|
||||
"/tmp/scratch",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the sigils in the overlay", () => {
|
||||
const sessions = [session("api", { metadata: { name: "api" }, current_cwd: "/home/me/dev/api" })];
|
||||
const ran: string[] = [];
|
||||
const commands = [
|
||||
command("spawn.open", "Open the spawn form", ["n"], () => ran.push("spawn.open")),
|
||||
command("list.kill", "Kill the highlighted session", ["x"], () => ran.push("list.kill")),
|
||||
];
|
||||
|
||||
afterEach(() => {
|
||||
ran.length = 0;
|
||||
});
|
||||
|
||||
function open(over: Partial<Parameters<typeof openCommandBar>[0]> = {}) {
|
||||
return openCommandBar({
|
||||
sessions,
|
||||
homeDir: "/home/me",
|
||||
commands,
|
||||
onOpenSession: () => {},
|
||||
loadDirectories: async () => [],
|
||||
listDirEntries: async () => [],
|
||||
onSpawnDirectory: () => {},
|
||||
...over,
|
||||
});
|
||||
}
|
||||
|
||||
it("lists every command in registry order under `>`, with its chord and no header", () => {
|
||||
open();
|
||||
type(">");
|
||||
expect(rowNames()).toEqual(["Open the spawn form", "Kill the highlighted session"]);
|
||||
expect(rowKeys()).toEqual([["n"], ["x"]]);
|
||||
expect(document.querySelectorAll(".cmdbar-group-title")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("matches a command on its label and never on its chord", () => {
|
||||
open();
|
||||
type(">kill");
|
||||
expect(rowNames()).toEqual(["Kill the highlighted session"]);
|
||||
// `n` and `x` are chords, not label text: querying one finds nothing that
|
||||
// the label does not also justify.
|
||||
type(">ctrlx");
|
||||
expect(rowNames()).toEqual([]);
|
||||
});
|
||||
|
||||
it("runs the highlighted command on Enter", () => {
|
||||
open();
|
||||
type(">kill");
|
||||
press("Enter");
|
||||
expect(ran).toEqual(["list.kill"]);
|
||||
expect(isCommandBarOpen()).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the list mixed with no sigil, and returns to it when the sigil goes", () => {
|
||||
open();
|
||||
type("s");
|
||||
expect([...document.querySelectorAll(".cmdbar-group-title")].map((h) => h.textContent)).toEqual([
|
||||
"Sessions",
|
||||
"Commands",
|
||||
]);
|
||||
type(">spawn");
|
||||
expect(rowNames()).toEqual(["Open the spawn form"]);
|
||||
// Backspacing the sigil away is ordinary editing.
|
||||
type("spawn");
|
||||
expect(rowNames()).toContain("Open the spawn form");
|
||||
type("");
|
||||
expect(rowNames()).toEqual(["api"]);
|
||||
});
|
||||
|
||||
it("lists recent dirs then projects under `~`", async () => {
|
||||
open({ loadDirectories: async () => ["/home/me/dev/api", "/srv/www"] });
|
||||
type("~");
|
||||
await flush();
|
||||
expect(rowNames()).toEqual(["~/dev/api", "/srv/www"]);
|
||||
expect(document.querySelectorAll(".cmdbar-group-title")).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("fills the list in from /api/dirs as a path is typed", async () => {
|
||||
const asked: string[] = [];
|
||||
open({
|
||||
loadDirectories: async () => ["/home/me/notes"],
|
||||
listDirEntries: async (dir) => {
|
||||
asked.push(dir);
|
||||
return ["maestro", "api"];
|
||||
},
|
||||
});
|
||||
// The second `~` is a literal query character and reaches the matcher.
|
||||
type("~~/dev/mae");
|
||||
await flush();
|
||||
expect(asked).toEqual(["~/dev/"]);
|
||||
expect(rowNames()).toEqual(["~/dev/maestro"]);
|
||||
});
|
||||
|
||||
it("spawns in the highlighted directory on Enter", async () => {
|
||||
const spawned: string[] = [];
|
||||
open({
|
||||
loadDirectories: async () => ["~/dev/api"],
|
||||
onSpawnDirectory: (path) => spawned.push(path),
|
||||
});
|
||||
type("~api");
|
||||
await flush();
|
||||
press("Enter");
|
||||
expect(spawned).toEqual(["/home/me/dev/api"]);
|
||||
expect(isCommandBarOpen()).toBe(false);
|
||||
});
|
||||
|
||||
it("raises the spawn event when the caller supplies no handler", async () => {
|
||||
const seen: string[] = [];
|
||||
const listener = (e: Event) => seen.push((e as CustomEvent<string>).detail);
|
||||
document.addEventListener(SPAWN_DIRECTORY_EVENT, listener);
|
||||
openCommandBar({
|
||||
sessions,
|
||||
homeDir: "/home/me",
|
||||
commands,
|
||||
onOpenSession: () => {},
|
||||
loadDirectories: async () => ["/home/me/dev/api"],
|
||||
listDirEntries: async () => [],
|
||||
});
|
||||
type("~");
|
||||
await flush();
|
||||
press("Enter");
|
||||
document.removeEventListener(SPAWN_DIRECTORY_EVENT, listener);
|
||||
expect(seen).toEqual(["/home/me/dev/api"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the focus round-trip over a pane (#152)", () => {
|
||||
function terminalTextarea(): HTMLTextAreaElement {
|
||||
const ta = document.createElement("textarea");
|
||||
ta.className = "xterm-helper-textarea";
|
||||
document.body.appendChild(ta);
|
||||
return ta;
|
||||
}
|
||||
|
||||
it("hands the keyboard back to the terminal that had it", () => {
|
||||
const ta = terminalTextarea();
|
||||
ta.focus();
|
||||
openCommandBar({ sessions: [], commands: [] });
|
||||
expect(document.activeElement).toBe(document.querySelector(".cmdbar-input"));
|
||||
press("Escape");
|
||||
expect(document.activeElement).toBe(ta);
|
||||
});
|
||||
|
||||
it("reports no focus change to the daemon, opening or closing", () => {
|
||||
const fetchMock = vi.fn(() => Promise.resolve(new Response(null, { status: 204 })));
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
try {
|
||||
const ta = terminalTextarea();
|
||||
ta.focus();
|
||||
openCommandBar({ sessions: [], commands: [] });
|
||||
press("Escape");
|
||||
const focusCalls = fetchMock.mock.calls.filter(([url]: unknown[]) =>
|
||||
String(url).includes("/focus"),
|
||||
);
|
||||
expect(focusCalls).toEqual([]);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
+316
-30
@@ -1,33 +1,47 @@
|
||||
// The `ctrl-k` command bar (docs/COMMAND-BAR.md): a query line over a result
|
||||
// list, opened from the sidebar, closed with Escape.
|
||||
//
|
||||
// Sessions are the only kind here (#149); the sigils, the action page and the
|
||||
// terminal-focus binding land in #150-#152.
|
||||
// Three kinds live here: sessions and commands, ranked together by default,
|
||||
// and directories, which need the `~` sigil. The action page and the
|
||||
// terminal-focus binding land in #151-#152.
|
||||
|
||||
import { listDir, projects as fetchProjects, recentDirs } from "./api.js";
|
||||
import { SESSION_SELECT_EVENT } from "./catalog.js";
|
||||
import { keyCaps, publishedCommands, type Command } from "./commands.js";
|
||||
import {
|
||||
matchAndRank,
|
||||
type CandidateKind,
|
||||
type CommandCandidate,
|
||||
type DirectoryCandidate,
|
||||
type MatchRange,
|
||||
type MatchResult,
|
||||
type SessionCandidate,
|
||||
} from "./matcher.js";
|
||||
import { splitPath } from "./paths.js";
|
||||
import { splitCommand } from "./toolIcon.js";
|
||||
import { abbreviateCwd, sessionName, sessionTreePath, type Session } from "./types.js";
|
||||
|
||||
/** A matcher candidate that remembers which session it came from, so a result
|
||||
* can be acted on without a second lookup. The extra property is invisible to
|
||||
* the matcher, which only ever reads `kind` and `fields`. */
|
||||
/** A matcher candidate that remembers what it came from, so a result can be
|
||||
* acted on without a second lookup. The extra property is invisible to the
|
||||
* matcher, which only ever reads `kind` and `fields`. */
|
||||
export type SessionBarCandidate = SessionCandidate & { session: Session };
|
||||
export type CommandBarCandidate = CommandCandidate & { command: Command };
|
||||
/** `fields.path` is the abbreviated path the operator reads and the matcher
|
||||
* ranks; `path` is the one a spawn is made in. */
|
||||
export type DirectoryBarCandidate = DirectoryCandidate & { path: string };
|
||||
|
||||
export type BarCandidate = SessionBarCandidate;
|
||||
export type BarCandidate = SessionBarCandidate | CommandBarCandidate | DirectoryBarCandidate;
|
||||
export type BarResult = MatchResult<BarCandidate>;
|
||||
|
||||
/** Raised when Enter lands on a directory row. The bar picks the directory; the
|
||||
* shell owns the spawn, which is the same fast-forward path `N` takes. */
|
||||
export const SPAWN_DIRECTORY_EVENT = "cmdbar-spawn-directory";
|
||||
|
||||
/** One kind's slice of the ranked list, in rank order. */
|
||||
export interface BarGroup {
|
||||
export interface BarGroup<C extends BarCandidate = BarCandidate> {
|
||||
kind: CandidateKind;
|
||||
title: string;
|
||||
results: BarResult[];
|
||||
results: MatchResult<C>[];
|
||||
}
|
||||
|
||||
const KIND_TITLES: Record<CandidateKind, string> = {
|
||||
@@ -36,6 +50,29 @@ const KIND_TITLES: Record<CandidateKind, string> = {
|
||||
directory: "Directories",
|
||||
};
|
||||
|
||||
// ---- the sigils ----
|
||||
|
||||
export type BarSigil = ">" | "~";
|
||||
|
||||
export interface BarQuery {
|
||||
/** The sigil in force, or null for the mixed list. */
|
||||
sigil: BarSigil | null;
|
||||
/** What the matcher sees: everything after a sigil, or the whole query. */
|
||||
query: string;
|
||||
}
|
||||
|
||||
/** Split a raw query line into its sigil and the query proper.
|
||||
*
|
||||
* A sigil is only a sigil in first position: `>` or `~` anywhere else is a
|
||||
* literal query character, which is what a directory query with a second `~`
|
||||
* in it depends on. Backspacing past a sigil needs no special case either —
|
||||
* the first character goes and the query is a mixed one again. */
|
||||
export function parseBarQuery(raw: string): BarQuery {
|
||||
const first = raw[0];
|
||||
if (first === ">" || first === "~") return { sigil: first, query: raw.slice(1) };
|
||||
return { sigil: null, query: raw };
|
||||
}
|
||||
|
||||
// ---- candidates ----
|
||||
|
||||
function focusedAt(s: Session): number | null {
|
||||
@@ -99,14 +136,92 @@ export function sessionBarCandidates(
|
||||
return orderSessionsForBar(sessions).map((s) => sessionCandidate(s, homeDir));
|
||||
}
|
||||
|
||||
/** Drop the commands that would list twice. Several chords can be bound to one
|
||||
* action — the registry already carries its aliases on one entry, but nothing
|
||||
* stops two entries running the same handler, and listed naively that is two
|
||||
* identical rows. The dedupe is by **action**, never by chord: the chord is
|
||||
* displayed, so a command with two of them is still one row. */
|
||||
export function dedupeCommands(commands: readonly Command[]): Command[] {
|
||||
const seenRun = new Set<Command["run"]>();
|
||||
const seenLabel = new Set<string>();
|
||||
const kept: Command[] = [];
|
||||
for (const command of commands) {
|
||||
if (seenRun.has(command.run) || seenLabel.has(command.label)) continue;
|
||||
seenRun.add(command.run);
|
||||
seenLabel.add(command.label);
|
||||
kept.push(command);
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
/** Every bound command as a candidate, in registry order. Only the label is a
|
||||
* field: the chord is displayed beside the row, never matched, because
|
||||
* matching it would make `>` results depend on a user's rebinds. */
|
||||
export function commandBarCandidates(commands: readonly Command[]): CommandBarCandidate[] {
|
||||
return dedupeCommands(commands).map((command) => ({
|
||||
kind: "command",
|
||||
command,
|
||||
fields: { label: command.label },
|
||||
}));
|
||||
}
|
||||
|
||||
/** `~/dev/api` back to `/home/me/dev/api` — the inverse of `abbreviateCwd`, for
|
||||
* a path the operator typed or `/api/dirs` completed. */
|
||||
export function expandHome(path: string, homeDir?: string): string {
|
||||
if (!homeDir) return path;
|
||||
if (path === "~") return homeDir;
|
||||
return path.startsWith("~/") ? `${homeDir}${path.slice(1)}` : path;
|
||||
}
|
||||
|
||||
export function directoryCandidate(path: string, homeDir?: string): DirectoryBarCandidate {
|
||||
const absolute = expandHome(path, homeDir);
|
||||
return { kind: "directory", path: absolute, fields: { path: abbreviateCwd(absolute, homeDir) } };
|
||||
}
|
||||
|
||||
/** Candidates for `~`, deduped by the directory they spawn in and keeping the
|
||||
* first mention of each — recent dirs (newest first) ahead of the project
|
||||
* list, which is the empty-query order the contract asks for. */
|
||||
export function directoryBarCandidates(
|
||||
paths: readonly string[],
|
||||
homeDir?: string,
|
||||
): DirectoryBarCandidate[] {
|
||||
const seen = new Set<string>();
|
||||
const out: DirectoryBarCandidate[] = [];
|
||||
for (const path of paths) {
|
||||
if (path === "") continue;
|
||||
const candidate = directoryCandidate(path, homeDir);
|
||||
if (seen.has(candidate.path)) continue;
|
||||
seen.add(candidate.path);
|
||||
out.push(candidate);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The directory list the bar starts from: what the spawn form already knows —
|
||||
* `GET /api/recent-dirs` and the project list — either alone if the other
|
||||
* fails. */
|
||||
export async function loadBarDirectories(): Promise<string[]> {
|
||||
const [recents, discovered] = await Promise.all([
|
||||
recentDirs()
|
||||
.then((r) => r.dirs.map((d) => d.cwd))
|
||||
.catch(() => [] as string[]),
|
||||
fetchProjects()
|
||||
.then((list) => list.map((p) => p.path))
|
||||
.catch(() => [] as string[]),
|
||||
]);
|
||||
return [...recents, ...discovered];
|
||||
}
|
||||
|
||||
// ---- grouping ----
|
||||
|
||||
/** Bucket a ranked list by kind for rendering. Grouping is a rendering of the
|
||||
* ranking, never a reordering of it: a group holds its matches in rank order,
|
||||
* and groups appear in the order their best-scoring member does — so the first
|
||||
* row under the first header is the globally best result. */
|
||||
export function barGroups(results: readonly BarResult[]): BarGroup[] {
|
||||
const groups: BarGroup[] = [];
|
||||
export function barGroups<C extends BarCandidate>(
|
||||
results: readonly MatchResult<C>[],
|
||||
): BarGroup<C>[] {
|
||||
const groups: BarGroup<C>[] = [];
|
||||
for (const result of results) {
|
||||
const kind = result.candidate.kind;
|
||||
let group = groups.find((g) => g.kind === kind);
|
||||
@@ -122,7 +237,10 @@ export function barGroups(results: readonly BarResult[]): BarGroup[] {
|
||||
/** The rows a query produces, flat and in rank order — what the highlight walks
|
||||
* and what Enter acts on. Headers are labels, not rows, so they are never in
|
||||
* this list. */
|
||||
export function barRows(query: string, candidates: readonly BarCandidate[]): BarResult[] {
|
||||
export function barRows<C extends BarCandidate>(
|
||||
query: string,
|
||||
candidates: readonly C[],
|
||||
): MatchResult<C>[] {
|
||||
return matchAndRank(query, candidates);
|
||||
}
|
||||
|
||||
@@ -145,9 +263,25 @@ export function renderHighlighted(text: string, ranges: readonly MatchRange[]):
|
||||
return frag;
|
||||
}
|
||||
|
||||
/** The secondary line under a row's name: the field the match was found in when
|
||||
* that was not the name, so a session found through its directory says so. */
|
||||
/** The name line of a row: the session's name, the command's label, or the
|
||||
* directory's path. */
|
||||
function rowName(candidate: BarCandidate): string {
|
||||
switch (candidate.kind) {
|
||||
case "session":
|
||||
return candidate.fields.name;
|
||||
case "command":
|
||||
return candidate.fields.label;
|
||||
case "directory":
|
||||
return candidate.fields.path;
|
||||
}
|
||||
}
|
||||
|
||||
/** The secondary line under a session row: the field the match was found in
|
||||
* when that was not the name, so a session found through its directory says
|
||||
* so. Only sessions have one — a command shows keycaps instead, and a
|
||||
* directory's path is already the name. */
|
||||
function metaText(result: BarResult): string | undefined {
|
||||
if (result.candidate.kind !== "session") return undefined;
|
||||
const fields = result.candidate.fields;
|
||||
switch (result.field) {
|
||||
case "directory":
|
||||
@@ -162,22 +296,44 @@ function metaText(result: BarResult): string | undefined {
|
||||
}
|
||||
|
||||
function renderRow(result: BarResult, index: number): HTMLElement {
|
||||
const candidate = result.candidate;
|
||||
const row = document.createElement("div");
|
||||
row.className = "cmdbar-row";
|
||||
row.setAttribute("role", "option");
|
||||
row.id = `cmdbar-row-${index}`;
|
||||
row.dataset.index = String(index);
|
||||
row.dataset.sessionId = result.candidate.session.id;
|
||||
if (result.candidate.session.status === "Dead") row.classList.add("is-dead");
|
||||
row.dataset.kind = candidate.kind;
|
||||
if (candidate.kind === "session") {
|
||||
row.dataset.sessionId = candidate.session.id;
|
||||
if (candidate.session.status === "Dead") row.classList.add("is-dead");
|
||||
} else if (candidate.kind === "command") {
|
||||
row.dataset.commandId = candidate.command.id;
|
||||
} else {
|
||||
row.dataset.path = candidate.path;
|
||||
}
|
||||
|
||||
const name = document.createElement("span");
|
||||
name.className = "cmdbar-row-name";
|
||||
const nameText = result.candidate.fields.name;
|
||||
name.append(
|
||||
result.field === "name" ? renderHighlighted(nameText, result.ranges) : nameText,
|
||||
);
|
||||
const nameText = rowName(candidate);
|
||||
const nameMatched =
|
||||
result.field === "name" || result.field === "label" || result.field === "path";
|
||||
name.append(nameMatched ? renderHighlighted(nameText, result.ranges) : nameText);
|
||||
row.appendChild(name);
|
||||
|
||||
// The chord is teaching material, not a match target: it is rendered from
|
||||
// the live registry entry and never fed to the matcher.
|
||||
if (candidate.kind === "command") {
|
||||
const keys = document.createElement("span");
|
||||
keys.className = "cmdbar-row-keys";
|
||||
for (const cap of keyCaps(candidate.command.keys[0])) {
|
||||
const kbd = document.createElement("kbd");
|
||||
kbd.textContent = cap;
|
||||
keys.appendChild(kbd);
|
||||
}
|
||||
row.appendChild(keys);
|
||||
return row;
|
||||
}
|
||||
|
||||
const meta = metaText(result);
|
||||
if (meta) {
|
||||
const el = document.createElement("span");
|
||||
@@ -189,6 +345,12 @@ function renderRow(result: BarResult, index: number): HTMLElement {
|
||||
return row;
|
||||
}
|
||||
|
||||
const PLACEHOLDERS: Record<"mixed" | BarSigil, string> = {
|
||||
mixed: "Go to a session…",
|
||||
">": "Run a command…",
|
||||
"~": "Spawn in a directory…",
|
||||
};
|
||||
|
||||
// ---- the overlay ----
|
||||
|
||||
export interface CommandBarOptions {
|
||||
@@ -200,6 +362,18 @@ export interface CommandBarOptions {
|
||||
* sidebar's click event — which is what the contract requires; tests pass
|
||||
* their own. */
|
||||
onOpenSession?: (sessionId: string) => void;
|
||||
/** The command registry to list under `>`. Defaults to every bound command,
|
||||
* in registry order. */
|
||||
commands?: readonly Command[];
|
||||
/** The directory list behind `~`, fetched once on first use. */
|
||||
loadDirectories?: () => Promise<string[]>;
|
||||
/** One directory's subdirectories, for filling the list in as a path is
|
||||
* typed. Defaults to `GET /api/dirs`. */
|
||||
listDirEntries?: (dir: string) => Promise<string[]>;
|
||||
/** Spawn a session in the highlighted directory. Defaults to raising
|
||||
* `SPAWN_DIRECTORY_EVENT`, which the shell turns into a fast-forward
|
||||
* spawn. */
|
||||
onSpawnDirectory?: (path: string) => void;
|
||||
}
|
||||
|
||||
interface OpenBar {
|
||||
@@ -228,8 +402,21 @@ export function openCommandBar(opts: CommandBarOptions): HTMLElement {
|
||||
const openSession =
|
||||
opts.onOpenSession ??
|
||||
((id: string) => document.dispatchEvent(new CustomEvent(SESSION_SELECT_EVENT, { detail: id })));
|
||||
const spawnDirectory =
|
||||
opts.onSpawnDirectory ??
|
||||
((path: string) =>
|
||||
document.dispatchEvent(new CustomEvent(SPAWN_DIRECTORY_EVENT, { detail: path })));
|
||||
const loadDirectories = opts.loadDirectories ?? loadBarDirectories;
|
||||
const listEntries =
|
||||
opts.listDirEntries ?? ((dir: string) => listDir(dir).then((listing) => listing.entries));
|
||||
|
||||
const candidates: BarCandidate[] = sessionBarCandidates(opts.sessions, opts.homeDir);
|
||||
const sessionCandidates: SessionBarCandidate[] = sessionBarCandidates(
|
||||
opts.sessions,
|
||||
opts.homeDir,
|
||||
);
|
||||
const commandCandidates: CommandBarCandidate[] = commandBarCandidates(
|
||||
opts.commands ?? publishedCommands(),
|
||||
);
|
||||
|
||||
const el = document.createElement("div");
|
||||
el.className = "cmdbar-overlay";
|
||||
@@ -246,10 +433,10 @@ export function openCommandBar(opts: CommandBarOptions): HTMLElement {
|
||||
input.setAttribute("role", "combobox");
|
||||
input.setAttribute("aria-expanded", "true");
|
||||
input.setAttribute("aria-controls", "cmdbar-results");
|
||||
input.setAttribute("aria-label", "Search sessions");
|
||||
input.setAttribute("aria-label", "Search sessions, commands and directories");
|
||||
input.setAttribute("autocomplete", "off");
|
||||
input.spellcheck = false;
|
||||
input.placeholder = "Go to a session…";
|
||||
input.placeholder = PLACEHOLDERS.mixed;
|
||||
|
||||
const results = document.createElement("div");
|
||||
results.className = "cmdbar-results";
|
||||
@@ -263,6 +450,90 @@ export function openCommandBar(opts: CommandBarOptions): HTMLElement {
|
||||
let rows: BarResult[] = [];
|
||||
let highlighted = 0;
|
||||
|
||||
// `~`'s candidates: the recents-and-projects list, fetched once, plus
|
||||
// whatever `/api/dirs` has filled in for the directory being typed.
|
||||
let directories: DirectoryBarCandidate[] = [];
|
||||
let directoriesRequested = false;
|
||||
let probed: DirectoryBarCandidate[] = [];
|
||||
let probedDir: string | null = null;
|
||||
const listings = new Map<string, string[]>();
|
||||
|
||||
function alive(): boolean {
|
||||
return current?.el === el;
|
||||
}
|
||||
|
||||
/** Fetch the recents-and-projects list the first time `~` is used. */
|
||||
function ensureDirectories(): void {
|
||||
if (directoriesRequested) return;
|
||||
directoriesRequested = true;
|
||||
loadDirectories()
|
||||
.then((paths) => {
|
||||
directories = directoryBarCandidates(paths, opts.homeDir);
|
||||
if (alive()) render();
|
||||
})
|
||||
.catch(() => {
|
||||
/* no directories is a shorter list, not an error state */
|
||||
});
|
||||
}
|
||||
|
||||
/** Fill the list in from `GET /api/dirs` once the query looks like a path:
|
||||
* the directory it names is listed and its children join the candidates, so
|
||||
* `~` reaches a directory that was never spawned in. */
|
||||
function probeDirectories(query: string): void {
|
||||
const { dir } = splitPath(query);
|
||||
if (dir === "") {
|
||||
probed = [];
|
||||
probedDir = null;
|
||||
return;
|
||||
}
|
||||
if (dir === probedDir) return;
|
||||
probedDir = dir;
|
||||
const cached = listings.get(dir);
|
||||
if (cached) {
|
||||
probed = directoryBarCandidates(
|
||||
cached.map((entry) => `${dir}${entry}`),
|
||||
opts.homeDir,
|
||||
);
|
||||
return;
|
||||
}
|
||||
probed = [];
|
||||
listEntries(dir)
|
||||
.then((entries) => {
|
||||
listings.set(dir, entries);
|
||||
if (!alive() || probedDir !== dir) return;
|
||||
probed = directoryBarCandidates(
|
||||
entries.map((entry) => `${dir}${entry}`),
|
||||
opts.homeDir,
|
||||
);
|
||||
render();
|
||||
})
|
||||
.catch(() => {
|
||||
/* an unreadable directory contributes nothing */
|
||||
});
|
||||
}
|
||||
|
||||
/** What the matcher sees for the query line as it stands. With no sigil the
|
||||
* list is mixed — sessions and commands together — except on an empty query,
|
||||
* where the bar is a session switcher. */
|
||||
function candidatesFor(parsed: BarQuery): BarCandidate[] {
|
||||
switch (parsed.sigil) {
|
||||
case ">":
|
||||
return [...commandCandidates];
|
||||
case "~": {
|
||||
ensureDirectories();
|
||||
probeDirectories(parsed.query);
|
||||
const seen = new Set<string>();
|
||||
return [...directories, ...probed].filter((c) =>
|
||||
seen.has(c.path) ? false : (seen.add(c.path), true),
|
||||
);
|
||||
}
|
||||
default:
|
||||
return parsed.query === ""
|
||||
? [...sessionCandidates]
|
||||
: [...sessionCandidates, ...commandCandidates];
|
||||
}
|
||||
}
|
||||
|
||||
function paintHighlight(): void {
|
||||
for (const row of results.querySelectorAll<HTMLElement>(".cmdbar-row")) {
|
||||
const active = Number(row.dataset.index) === highlighted;
|
||||
@@ -277,7 +548,9 @@ export function openCommandBar(opts: CommandBarOptions): HTMLElement {
|
||||
}
|
||||
|
||||
function render(): void {
|
||||
rows = barRows(input.value, candidates);
|
||||
const parsed = parseBarQuery(input.value);
|
||||
input.placeholder = PLACEHOLDERS[parsed.sigil ?? "mixed"];
|
||||
rows = barRows(parsed.query, candidatesFor(parsed));
|
||||
// The highlight starts on the globally best row every time the list
|
||||
// changes: an old index would point at a different result.
|
||||
highlighted = 0;
|
||||
@@ -294,11 +567,14 @@ export function openCommandBar(opts: CommandBarOptions): HTMLElement {
|
||||
|
||||
let index = 0;
|
||||
for (const group of barGroups(rows)) {
|
||||
const header = document.createElement("div");
|
||||
header.className = "cmdbar-group-title";
|
||||
header.setAttribute("role", "presentation");
|
||||
header.textContent = group.title;
|
||||
results.appendChild(header);
|
||||
// While a sigil is in force there is one kind, so the header is dropped.
|
||||
if (parsed.sigil === null) {
|
||||
const header = document.createElement("div");
|
||||
header.className = "cmdbar-group-title";
|
||||
header.setAttribute("role", "presentation");
|
||||
header.textContent = group.title;
|
||||
results.appendChild(header);
|
||||
}
|
||||
for (const result of group.results) {
|
||||
const at = index;
|
||||
const row = renderRow(result, at);
|
||||
@@ -320,9 +596,19 @@ export function openCommandBar(opts: CommandBarOptions): HTMLElement {
|
||||
function activate(index: number): void {
|
||||
const result = rows[index];
|
||||
if (!result) return;
|
||||
const sessionId = result.candidate.session.id;
|
||||
const candidate = result.candidate;
|
||||
close();
|
||||
openSession(sessionId);
|
||||
switch (candidate.kind) {
|
||||
case "session":
|
||||
openSession(candidate.session.id);
|
||||
return;
|
||||
case "command":
|
||||
candidate.command.run();
|
||||
return;
|
||||
case "directory":
|
||||
spawnDirectory(candidate.path);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function onKeydown(e: KeyboardEvent): void {
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
DEFAULT_LEADER,
|
||||
canonicalizeKey,
|
||||
defineCommands,
|
||||
isBarTypingTarget,
|
||||
isTerminalTextarea,
|
||||
isTypingTarget,
|
||||
keyCaps,
|
||||
publishedCommands,
|
||||
@@ -234,3 +236,74 @@ describe("isTypingTarget", () => {
|
||||
expect(isTypingTarget(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isTerminalTextarea", () => {
|
||||
it("recognises xterm's offscreen textarea, and nothing else", () => {
|
||||
expect(isTerminalTextarea(el('<textarea class="xterm-helper-textarea"></textarea>'))).toBe(true);
|
||||
expect(isTerminalTextarea(el("<textarea></textarea>"))).toBe(false);
|
||||
expect(isTerminalTextarea(el("<input>"))).toBe(false);
|
||||
expect(isTerminalTextarea(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isBarTypingTarget", () => {
|
||||
it("holds the bar's keys out of real form fields", () => {
|
||||
expect(isBarTypingTarget(el("<input>"))).toBe(true);
|
||||
expect(isBarTypingTarget(el("<textarea></textarea>"))).toBe(true);
|
||||
});
|
||||
|
||||
it("does not count the terminal's textarea, so ctrl-k reaches the bar there", () => {
|
||||
expect(isBarTypingTarget(el('<textarea class="xterm-helper-textarea"></textarea>'))).toBe(false);
|
||||
expect(isBarTypingTarget(el("<button></button>"))).toBe(false);
|
||||
expect(isBarTypingTarget(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ctrl-k over a focused pane (#152)", () => {
|
||||
const terminal = () => el('<textarea class="xterm-helper-textarea"></textarea>');
|
||||
|
||||
/** The global listener's routing: the bar's set only sees a key that is not
|
||||
* aimed at a real form field. */
|
||||
function route(set: CommandSet, target: HTMLElement, k: string, init?: KeyboardEventInit) {
|
||||
if (isBarTypingTarget(target)) return false;
|
||||
return pressOn(set, target, k, init);
|
||||
}
|
||||
|
||||
it("opens the bar when the terminal has the keyboard", () => {
|
||||
const open = vi.fn();
|
||||
const set = new CommandSet(defineCommands({ "bar.open": open }));
|
||||
expect(route(set, terminal(), "k", { ctrlKey: true })).toBe(true);
|
||||
expect(open).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("leaves the spawn form's inputs their own Ctrl-K", () => {
|
||||
const open = vi.fn();
|
||||
const set = new CommandSet(defineCommands({ "bar.open": open }));
|
||||
expect(route(set, el("<input>"), "k", { ctrlKey: true })).toBe(false);
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sends the literal 0x0B after the leader, without opening the bar", () => {
|
||||
const open = vi.fn();
|
||||
const literal = vi.fn();
|
||||
const bar = new CommandSet(defineCommands({ "bar.open": open }));
|
||||
const set = new CommandSet(defineCommands({ "pane.literalCtrlK": literal }), {
|
||||
leader: DEFAULT_LEADER,
|
||||
});
|
||||
const target = terminal();
|
||||
expect(pressOn(set, target, "a", { ctrlKey: true })).toBe(true);
|
||||
const e = key("k", { ctrlKey: true });
|
||||
Object.defineProperty(e, "target", { value: target });
|
||||
expect(set.handle(e)).toBe(true);
|
||||
expect(literal).toHaveBeenCalledTimes(1);
|
||||
// The leader's set consumed the key, so the bar's set never sees it.
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
expect(bar.handle(e)).toBe(true); // sanity: it would have opened otherwise
|
||||
expect(open).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("binds the escape hatch behind the default leader", () => {
|
||||
const spec = COMMAND_SPECS.find((s) => s.id === "pane.literalCtrlK");
|
||||
expect(spec?.keys).toEqual([`${DEFAULT_LEADER} ctrl-k`]);
|
||||
});
|
||||
});
|
||||
|
||||
+20
-5
@@ -32,6 +32,10 @@ export interface Command extends CommandSpec {
|
||||
run: () => void;
|
||||
}
|
||||
|
||||
/** Default leader, mirroring the TUI's `[tui].leader`. `ctrl-a` is select-all
|
||||
* in a browser, so a set that owns the leader `preventDefault`s it. */
|
||||
export const DEFAULT_LEADER = "ctrl-a";
|
||||
|
||||
/** Every command the web client has. The single list this issue exists to
|
||||
* create: labels, chords and grouping live here and nowhere else. */
|
||||
export const COMMAND_SPECS: readonly CommandSpec[] = [
|
||||
@@ -56,6 +60,13 @@ export const COMMAND_SPECS: readonly CommandSpec[] = [
|
||||
keys: ["ctrl-k"],
|
||||
scope: "global",
|
||||
},
|
||||
{
|
||||
id: "pane.literalCtrlK",
|
||||
label: "Send a literal Ctrl-K to the pane",
|
||||
group: "Pane",
|
||||
keys: [`${DEFAULT_LEADER} ctrl-k`],
|
||||
scope: "global",
|
||||
},
|
||||
{
|
||||
id: "focus.toggle",
|
||||
label: "Move the keyboard between the session list and the pane",
|
||||
@@ -241,11 +252,19 @@ export function isTypingTarget(target: EventTarget | null): boolean {
|
||||
/** xterm's offscreen textarea. It is a typing target like any other, but it is
|
||||
* also where the leader has to work — a pane is exactly where the operator
|
||||
* needs the escape hatch (docs/COMMAND-BAR.md). */
|
||||
function isTerminalTextarea(target: EventTarget | null): boolean {
|
||||
export function isTerminalTextarea(target: EventTarget | null): boolean {
|
||||
const el = target as HTMLElement | null;
|
||||
return !!el && typeof el.className === "string" && el.classList?.contains("xterm-helper-textarea");
|
||||
}
|
||||
|
||||
/** True where the command bar's own keys must stay out of the way: a real form
|
||||
* field, and not the pane. `ctrl-k` is intercepted ahead of xterm
|
||||
* (docs/COMMAND-BAR.md, "Opening"), so a focused terminal opens the bar, while
|
||||
* the spawn form's inputs keep their own Ctrl-K. */
|
||||
export function isBarTypingTarget(target: EventTarget | null): boolean {
|
||||
return isTypingTarget(target) && !isTerminalTextarea(target);
|
||||
}
|
||||
|
||||
// ---- display ----
|
||||
|
||||
const CAPS: Record<string, string> = {
|
||||
@@ -292,10 +311,6 @@ export function keyCaps(chord: string): string[] {
|
||||
|
||||
// ---- dispatch ----
|
||||
|
||||
/** Default leader, mirroring the TUI's `[tui].leader`. `ctrl-a` is select-all
|
||||
* in a browser, so a set that owns the leader `preventDefault`s it. */
|
||||
export const DEFAULT_LEADER = "ctrl-a";
|
||||
|
||||
/** How long a partial chord waits for its next key — the TUI's
|
||||
* `chord_timeout_ms` default. */
|
||||
export const DEFAULT_CHORD_TIMEOUT_MS = 1000;
|
||||
|
||||
@@ -3,6 +3,23 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ConnectionPool } from "./connections.js";
|
||||
|
||||
// The pane's own bytes-out path, stubbed: the escape hatch only needs to know
|
||||
// the pool reaches the focused connection with them.
|
||||
const sent: { id: string; data: string }[] = [];
|
||||
vi.mock("./attach.js", () => ({
|
||||
createAttachConnection: (id: string) => ({
|
||||
sessionId: id,
|
||||
el: document.createElement("div"),
|
||||
onMount() {},
|
||||
onUnmount() {},
|
||||
focusTerminal() {},
|
||||
sendInput(data: string) {
|
||||
sent.push({ id, data });
|
||||
},
|
||||
dispose() {},
|
||||
}),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
@@ -85,3 +102,26 @@ describe("ConnectionPool.setFocus", () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ConnectionPool.sendToFocused", () => {
|
||||
it("types the bytes into the focused session's PTY", () => {
|
||||
mockFetch();
|
||||
sent.length = 0;
|
||||
const pool = new ConnectionPool();
|
||||
const pane = document.createElement("div");
|
||||
pool.mount(A, pane);
|
||||
pool.setFocus(A);
|
||||
|
||||
expect(pool.sendToFocused("\x0b")).toBe(true);
|
||||
expect(sent).toEqual([{ id: A, data: "\x0b" }]);
|
||||
});
|
||||
|
||||
it("is a no-op with nothing focused", () => {
|
||||
mockFetch();
|
||||
sent.length = 0;
|
||||
const pool = new ConnectionPool();
|
||||
|
||||
expect(pool.sendToFocused("\x0b")).toBe(false);
|
||||
expect(sent).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -159,6 +159,18 @@ export class ConnectionPool {
|
||||
this.cache.get(this.focusedId)?.focusTerminal();
|
||||
}
|
||||
|
||||
/** Type raw bytes into the focused session's PTY. Returns false when there is
|
||||
* nothing focused, or its connection is gone — the leader's literal Ctrl-K
|
||||
* is a no-op over the welcome pane rather than an error
|
||||
* (docs/COMMAND-BAR.md). */
|
||||
sendToFocused(data: string): boolean {
|
||||
if (this.focusedId === null) return false;
|
||||
const conn = this.cache.get(this.focusedId);
|
||||
if (!conn) return false;
|
||||
conn.sendInput(data);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Fully disconnect + forget a session. */
|
||||
close(id: Uuid): void {
|
||||
const conn = this.cache.get(id);
|
||||
|
||||
+65
-13
@@ -7,8 +7,8 @@ import { ConnectionPool } from "./connections.js";
|
||||
import { installDrawer, installDrawerSwipe, requestToggleDrawer } from "./drawer.js";
|
||||
import { installHudKeybind } from "./debug.js";
|
||||
import { installHelpKeybind, isHelpOpen } from "./help.js";
|
||||
import { CommandSet, DEFAULT_LEADER, defineCommands, isTypingTarget } from "./commands.js";
|
||||
import { isCommandBarOpen, openCommandBar } from "./commandBar.js";
|
||||
import { CommandSet, DEFAULT_LEADER, defineCommands, isBarTypingTarget } from "./commands.js";
|
||||
import { isCommandBarOpen, openCommandBar, SPAWN_DIRECTORY_EVENT } from "./commandBar.js";
|
||||
import { DaemonLink } from "./daemonLink.js";
|
||||
import { CatalogStore } from "./events.js";
|
||||
import { installRestartOverlay } from "./restartOverlay.js";
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
createSession,
|
||||
fetchNames,
|
||||
getDaemonInfo,
|
||||
gitRoot,
|
||||
projects as fetchProjects,
|
||||
} from "./api.js";
|
||||
import {
|
||||
@@ -337,6 +338,16 @@ function mountSpawned(session: Session, placement?: { newTab?: boolean }): void
|
||||
// a new branch named after that name. Anything unresolvable (no projects
|
||||
// known yet, no command, no generated name) opens the form pre-filled with
|
||||
// what did resolve instead.
|
||||
async function spawnPresets(): Promise<SpawnPreset[]> {
|
||||
try {
|
||||
const info = await getDaemonInfo();
|
||||
if (info.presets?.length) return info.presets;
|
||||
} catch {
|
||||
/* keep fallbacks */
|
||||
}
|
||||
return FALLBACK_PRESETS;
|
||||
}
|
||||
|
||||
async function requestFastForward(): Promise<void> {
|
||||
const [discovered, name] = await Promise.all([
|
||||
fetchProjects().catch(() => [] as Project[]),
|
||||
@@ -344,13 +355,7 @@ async function requestFastForward(): Promise<void> {
|
||||
.then((batch) => batch.names[0])
|
||||
.catch(() => undefined),
|
||||
]);
|
||||
let presets: SpawnPreset[] = FALLBACK_PRESETS;
|
||||
try {
|
||||
const info = await getDaemonInfo();
|
||||
if (info.presets?.length) presets = info.presets;
|
||||
} catch {
|
||||
/* keep fallbacks */
|
||||
}
|
||||
const presets = await spawnPresets();
|
||||
const resolved = resolveFastForward(discovered, presets, name, focusedProjectCwd());
|
||||
const req = buildFastForwardRequest(resolved);
|
||||
if (req) {
|
||||
@@ -372,13 +377,54 @@ async function requestFastForward(): Promise<void> {
|
||||
});
|
||||
}
|
||||
|
||||
// Enter on a `~` row in the command bar (docs/COMMAND-BAR.md): the same
|
||||
// fast-forward spawn, aimed at the chosen directory instead of the most recent
|
||||
// project. A directory the project scan never saw stands in as its own project;
|
||||
// one outside any repo spawns without a worktree, since there is no repo to cut
|
||||
// a branch from. Anything still unresolved opens the pre-filled form.
|
||||
async function requestSpawnInDirectory(path: string): Promise<void> {
|
||||
const [discovered, name] = await Promise.all([
|
||||
fetchProjects().catch(() => [] as Project[]),
|
||||
fetchNames(1)
|
||||
.then((batch) => batch.names[0])
|
||||
.catch(() => undefined),
|
||||
]);
|
||||
const presets = await spawnPresets();
|
||||
const known = discovered.find((p) => p.path === path);
|
||||
const project: Project = known ?? { path, name: path.split("/").filter(Boolean).pop() ?? path };
|
||||
const resolved = resolveFastForward([project], presets, name, path);
|
||||
const req = buildFastForwardRequest(resolved);
|
||||
if (req) {
|
||||
const inRepo =
|
||||
known !== undefined ||
|
||||
(await gitRoot(path)
|
||||
.then((r) => !!r.root)
|
||||
.catch(() => false));
|
||||
if (!inRepo) delete req.worktree;
|
||||
try {
|
||||
mountSpawned(await createSession(req));
|
||||
return;
|
||||
} catch {
|
||||
// A failed POST degrades to the pre-filled form, never a dead row.
|
||||
}
|
||||
}
|
||||
openSpawnModal({
|
||||
seed: fastForwardSeed(resolved),
|
||||
onSuccess: (session) => mountSpawned(session),
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener(SPAWN_DIRECTORY_EVENT, (ev) => {
|
||||
void requestSpawnInDirectory((ev as CustomEvent<string>).detail);
|
||||
});
|
||||
|
||||
// The global half of the command registry (#148). Two sets, because they
|
||||
// differ in one thing: the help overlay owns the keyboard while it is up, so
|
||||
// the plain keys go deaf behind it while the focus chord does not — an
|
||||
// attached terminal must never be able to trap the focus keys.
|
||||
//
|
||||
// `n` opens the spawn modal, `N` fast-forwards a spawn (#67). Both are plain
|
||||
// keys, so `isTypingTarget` keeps them out of form fields and the terminal's
|
||||
// keys, so `isTypingTarget` inside the set keeps them out of form fields and the terminal's
|
||||
// hidden textarea.
|
||||
const spawnKeys = new CommandSet(
|
||||
defineCommands({
|
||||
@@ -405,6 +451,11 @@ const focusKeys = new CommandSet(
|
||||
sidebar.focusList();
|
||||
}
|
||||
},
|
||||
// The escape hatch: binding ctrl-k takes readline's kill-to-end-of-line
|
||||
// away from every pane, and leader ctrl-k gives it back as the literal
|
||||
// 0x0B byte (docs/COMMAND-BAR.md). It resolves in this set, ahead of the
|
||||
// bar's, so the chord never opens the bar.
|
||||
"pane.literalCtrlK": () => pool.sendToFocused("\x0b"),
|
||||
}),
|
||||
{ leader: DEFAULT_LEADER },
|
||||
);
|
||||
@@ -433,9 +484,10 @@ window.addEventListener(
|
||||
if (focusKeys.handle(e)) return;
|
||||
// The help overlay owns the keyboard while it is up.
|
||||
if (isHelpOpen()) return;
|
||||
// Opening the bar over a focused terminal is #152; until then the pane's
|
||||
// hidden textarea keeps its Ctrl+K, like any other typing target.
|
||||
if (!isTypingTarget(e.target) && barKeys.handle(e)) return;
|
||||
// The pane's hidden textarea is not a typing target for the bar: ctrl-k is
|
||||
// seen ahead of xterm and opens the bar (#152). A real form field — the
|
||||
// spawn form's inputs — keeps its own Ctrl+K.
|
||||
if (!isBarTypingTarget(e.target) && barKeys.handle(e)) return;
|
||||
spawnKeys.handle(e);
|
||||
},
|
||||
true,
|
||||
|
||||
@@ -1517,6 +1517,25 @@ input.leaf-rename:focus {
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* A command row's chord, shown so the bar teaches the keymap. */
|
||||
.cmdbar-row-keys {
|
||||
flex: 1 1 auto;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--sp-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cmdbar-row-keys kbd {
|
||||
font-family: var(--font-mono);
|
||||
font-size: var(--fs-11);
|
||||
color: var(--muted);
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--r-1);
|
||||
padding: 0 var(--sp-1);
|
||||
}
|
||||
|
||||
.cmdbar-hit {
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
|
||||
Reference in New Issue
Block a user