Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59ede15d2b | ||
|
|
331039df11 | ||
|
|
151438094e | ||
|
|
c1c283c0f8 | ||
|
|
1b260b5c20 | ||
|
|
3eb1d7ddbe | ||
|
|
9d6b69cc49 | ||
|
|
b2cbb23fe2 | ||
|
|
9fe9fe4628 | ||
|
|
e6a254b734 | ||
|
|
dc783778c8 | ||
|
|
f8b434dd1d | ||
|
|
83741d7203 | ||
|
|
b618b7dd27 | ||
|
|
f37ff681ea | ||
|
|
8dde63a2ab | ||
|
|
1fe2ae6575 | ||
|
|
5df23b8714 | ||
|
|
46a000aa68 | ||
|
|
b46ba9dd26 | ||
|
|
cd37ac5d6d | ||
|
|
7a3287f231 |
@@ -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.
|
/// `FOO=bar`, the shell's own prefix for one command's environment.
|
||||||
fn is_env_assignment(word: &str) -> bool {
|
fn is_env_assignment(word: &str) -> bool {
|
||||||
let mut chars = word.chars();
|
let mut chars = word.chars();
|
||||||
@@ -476,4 +511,22 @@ mod tests {
|
|||||||
assert_eq!(command_program("sudo"), "sudo");
|
assert_eq!(command_program("sudo"), "sudo");
|
||||||
assert_eq!(command_program(""), "");
|
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,17 @@ pub enum Action {
|
|||||||
RenameHighlighted,
|
RenameHighlighted,
|
||||||
|
|
||||||
// Chrome
|
// Chrome
|
||||||
|
/// Open the `ctrl-k` command bar (`docs/COMMAND-BAR.md`) — a query line
|
||||||
|
/// over the sessions, ranked by the shared matcher.
|
||||||
|
OpenCommandBar,
|
||||||
|
/// Escape hatch (#156): leader then `ctrl-k` sends the literal `0x0B`
|
||||||
|
/// byte to the focused pane instead of opening the command bar, giving
|
||||||
|
/// readline's kill-to-end-of-line back.
|
||||||
|
SendLiteralCtrlK,
|
||||||
|
/// Escape hatch (#158): the leader pressed twice sends one literal
|
||||||
|
/// leader byte to the focused pane and drops the pending chord, the way
|
||||||
|
/// tmux resolves a doubled prefix key.
|
||||||
|
SendLiteralLeader,
|
||||||
ToggleSidebar,
|
ToggleSidebar,
|
||||||
ShowHelp,
|
ShowHelp,
|
||||||
Quit,
|
Quit,
|
||||||
@@ -94,6 +105,9 @@ impl Action {
|
|||||||
Action::FastForwardSpawn => "Create session with defaults".into(),
|
Action::FastForwardSpawn => "Create session with defaults".into(),
|
||||||
Action::KillHighlighted => "Kill selected session".into(),
|
Action::KillHighlighted => "Kill selected session".into(),
|
||||||
Action::RenameHighlighted => "Rename selected session".into(),
|
Action::RenameHighlighted => "Rename selected session".into(),
|
||||||
|
Action::OpenCommandBar => "Go to a session".into(),
|
||||||
|
Action::SendLiteralCtrlK => "Send literal Ctrl-K to session".into(),
|
||||||
|
Action::SendLiteralLeader => "Send literal leader key to session".into(),
|
||||||
Action::ToggleSidebar => "Show or hide sidebar".into(),
|
Action::ToggleSidebar => "Show or hide sidebar".into(),
|
||||||
Action::ShowHelp => "Show help".into(),
|
Action::ShowHelp => "Show help".into(),
|
||||||
Action::Quit => "Quit Maestro".into(),
|
Action::Quit => "Quit Maestro".into(),
|
||||||
@@ -120,6 +134,9 @@ impl Action {
|
|||||||
"FastForwardSpawn" => return Ok(Action::FastForwardSpawn),
|
"FastForwardSpawn" => return Ok(Action::FastForwardSpawn),
|
||||||
"KillHighlighted" => return Ok(Action::KillHighlighted),
|
"KillHighlighted" => return Ok(Action::KillHighlighted),
|
||||||
"RenameHighlighted" => return Ok(Action::RenameHighlighted),
|
"RenameHighlighted" => return Ok(Action::RenameHighlighted),
|
||||||
|
"OpenCommandBar" => return Ok(Action::OpenCommandBar),
|
||||||
|
"SendLiteralCtrlK" => return Ok(Action::SendLiteralCtrlK),
|
||||||
|
"SendLiteralLeader" => return Ok(Action::SendLiteralLeader),
|
||||||
"ToggleSidebar" => return Ok(Action::ToggleSidebar),
|
"ToggleSidebar" => return Ok(Action::ToggleSidebar),
|
||||||
"ShowHelp" => return Ok(Action::ShowHelp),
|
"ShowHelp" => return Ok(Action::ShowHelp),
|
||||||
"Quit" => return Ok(Action::Quit),
|
"Quit" => return Ok(Action::Quit),
|
||||||
@@ -239,10 +256,38 @@ 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The escape hatch (#156) is an ordinary action like any other.
|
||||||
|
#[test]
|
||||||
|
fn send_literal_ctrl_k_round_trips() {
|
||||||
|
assert_eq!(
|
||||||
|
Action::parse("SendLiteralCtrlK").unwrap(),
|
||||||
|
Action::SendLiteralCtrlK
|
||||||
|
);
|
||||||
|
assert_eq!(Action::SendLiteralCtrlK.to_string(), "SendLiteralCtrlK");
|
||||||
|
assert_eq!(
|
||||||
|
Action::SendLiteralCtrlK.help_label(),
|
||||||
|
"Send literal Ctrl-K to session"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn display_round_trips() {
|
fn display_round_trips() {
|
||||||
for a in [
|
for a in [
|
||||||
Action::EnterInsert,
|
Action::EnterInsert,
|
||||||
|
Action::OpenCommandBar,
|
||||||
|
Action::SendLiteralCtrlK,
|
||||||
Action::RenameHighlighted,
|
Action::RenameHighlighted,
|
||||||
Action::Quit,
|
Action::Quit,
|
||||||
Action::OpenSpawnModal,
|
Action::OpenSpawnModal,
|
||||||
|
|||||||
+885
-54
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -65,6 +65,9 @@ const DEFAULT_NORMAL: &[(&str, &str)] = &[
|
|||||||
("pageup", "ScrollPanePageUp"),
|
("pageup", "ScrollPanePageUp"),
|
||||||
("pagedown", "ScrollPanePageDown"),
|
("pagedown", "ScrollPanePageDown"),
|
||||||
// Chrome
|
// 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"),
|
("ctrl-w b", "ToggleSidebar"),
|
||||||
("?", "ShowHelp"),
|
("?", "ShowHelp"),
|
||||||
("ctrl-w q", "Quit"),
|
("ctrl-w q", "Quit"),
|
||||||
@@ -75,13 +78,17 @@ const DEFAULT_NORMAL: &[(&str, &str)] = &[
|
|||||||
("mouse:dblclick(sidebar-row)", "AttachHighlighted"),
|
("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
|
/// 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
|
/// it constantly, so binding it here would make it unreachable. The only way
|
||||||
/// back to the sidebar is the leader (`LeaveInsert`), which
|
/// back to the sidebar is the leader (`LeaveInsert`), which
|
||||||
/// [`TuiConfig::load`] inserts dynamically so rebinding the leader rebinds
|
/// [`TuiConfig::load`] inserts dynamically so rebinding the leader rebinds
|
||||||
/// the Insert escape with it.
|
/// 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 {
|
impl TuiConfig {
|
||||||
/// Build a runtime config from a [`TuiSection`] (typically the `tui`
|
/// Build a runtime config from a [`TuiSection`] (typically the `tui`
|
||||||
@@ -139,6 +146,25 @@ impl TuiConfig {
|
|||||||
keymap
|
keymap
|
||||||
.set(Mode::Insert, &leader.canonical(), "LeaveInsert")
|
.set(Mode::Insert, &leader.canonical(), "LeaveInsert")
|
||||||
.expect("leader canonical form is valid by construction");
|
.expect("leader canonical form is valid by construction");
|
||||||
|
// Leader, ctrl-k → the literal-Ctrl-K escape hatch (#156), built from
|
||||||
|
// the same leader spec so rebinding leader rebinds this chord too.
|
||||||
|
keymap
|
||||||
|
.set(
|
||||||
|
Mode::Insert,
|
||||||
|
&format!("{} ctrl-k", leader.canonical()),
|
||||||
|
"SendLiteralCtrlK",
|
||||||
|
)
|
||||||
|
.expect("leader canonical form is valid by construction");
|
||||||
|
// Leader, leader → the literal-leader escape hatch (#158), tmux-style:
|
||||||
|
// pressing it twice sends the leader byte itself. Built from the same
|
||||||
|
// leader spec, so rebinding leader rebinds this chord too.
|
||||||
|
keymap
|
||||||
|
.set(
|
||||||
|
Mode::Insert,
|
||||||
|
&format!("{} {}", leader.canonical(), leader.canonical()),
|
||||||
|
"SendLiteralLeader",
|
||||||
|
)
|
||||||
|
.expect("leader canonical form is valid by construction");
|
||||||
|
|
||||||
for (input, action) in §ion.keymap_normal {
|
for (input, action) in §ion.keymap_normal {
|
||||||
keymap.set(Mode::Normal, input, action).map_err(|source| {
|
keymap.set(Mode::Normal, input, action).map_err(|source| {
|
||||||
@@ -271,6 +297,60 @@ mod tests {
|
|||||||
assert_eq!(cfg.keymap.resolve(Mode::Insert, "ctrl-a"), None);
|
assert_eq!(cfg.keymap.resolve(Mode::Insert, "ctrl-a"), None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The literal-Ctrl-K escape hatch (#156) is chorded off the default
|
||||||
|
/// leader, `ctrl-a ctrl-k` — not the command bar.
|
||||||
|
#[test]
|
||||||
|
fn default_leader_escapes_a_literal_ctrl_k() {
|
||||||
|
let cfg = TuiConfig::load(&TuiSection::default()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
cfg.keymap.resolve(Mode::Insert, "ctrl-a ctrl-k"),
|
||||||
|
Some(Action::SendLiteralCtrlK),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebinding the leader must rebind the literal-Ctrl-K chord with it, not
|
||||||
|
/// just the Insert escape — proving the chord is built from the
|
||||||
|
/// configured leader rather than a hardcoded `ctrl-a`.
|
||||||
|
#[test]
|
||||||
|
fn rebinding_leader_moves_the_literal_ctrl_k_chord() {
|
||||||
|
let mut section = TuiSection::default();
|
||||||
|
section.leader = Some("ctrl-b".into());
|
||||||
|
let cfg = TuiConfig::load(§ion).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
cfg.keymap.resolve(Mode::Insert, "ctrl-b ctrl-k"),
|
||||||
|
Some(Action::SendLiteralCtrlK),
|
||||||
|
);
|
||||||
|
// The old leader's chord is gone along with its Insert escape.
|
||||||
|
assert_eq!(cfg.keymap.resolve(Mode::Insert, "ctrl-a ctrl-k"), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The literal-leader escape hatch (#158) is chorded off the leader
|
||||||
|
/// doubled: `ctrl-a ctrl-a` — tmux's doubled-prefix resolution.
|
||||||
|
#[test]
|
||||||
|
fn default_leader_escapes_a_literal_leader() {
|
||||||
|
let cfg = TuiConfig::load(&TuiSection::default()).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
cfg.keymap.resolve(Mode::Insert, "ctrl-a ctrl-a"),
|
||||||
|
Some(Action::SendLiteralLeader),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebinding the leader must rebind the literal-leader chord with it,
|
||||||
|
/// not just the Insert escape and the Ctrl-K chord — proving it too is
|
||||||
|
/// built from the configured leader rather than a hardcoded `ctrl-a`.
|
||||||
|
#[test]
|
||||||
|
fn rebinding_leader_moves_the_literal_leader_chord() {
|
||||||
|
let mut section = TuiSection::default();
|
||||||
|
section.leader = Some("ctrl-b".into());
|
||||||
|
let cfg = TuiConfig::load(§ion).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
cfg.keymap.resolve(Mode::Insert, "ctrl-b ctrl-b"),
|
||||||
|
Some(Action::SendLiteralLeader),
|
||||||
|
);
|
||||||
|
// The old leader's chord is gone along with the rest of its bindings.
|
||||||
|
assert_eq!(cfg.keymap.resolve(Mode::Insert, "ctrl-a ctrl-a"), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn user_normal_override_replaces_default() {
|
fn user_normal_override_replaces_default() {
|
||||||
let mut section = TuiSection::default();
|
let mut section = TuiSection::default();
|
||||||
|
|||||||
@@ -228,6 +228,10 @@ pub struct DraftPane {
|
|||||||
/// respawns there without touching the picker. Consumed by the first
|
/// respawns there without touching the picker. Consumed by the first
|
||||||
/// [`Self::set_projects`]; `None` once applied or when nothing seeded it.
|
/// [`Self::set_projects`]; `None` once applied or when nothing seeded it.
|
||||||
pub seed_cwd: Option<PathBuf>,
|
pub seed_cwd: Option<PathBuf>,
|
||||||
|
/// Command to preselect once the preset list lands — "spawn similar"'s
|
||||||
|
/// half of the clone (#155). Consumed by the first [`Self::set_presets`];
|
||||||
|
/// `None` once applied or when nothing seeded it.
|
||||||
|
pub seed_command: Option<String>,
|
||||||
/// The repository picked in step one ([`group_key`] of its main box),
|
/// The repository picked in step one ([`group_key`] of its main box),
|
||||||
/// `None` until a box is picked. Looked up fresh in `groups` rather than
|
/// `None` until a box is picked. Looked up fresh in `groups` rather than
|
||||||
/// cached, so a project-list refresh can't leave it stale.
|
/// cached, so a project-list refresh can't leave it stale.
|
||||||
@@ -291,6 +295,7 @@ impl Default for DraftPane {
|
|||||||
id: NEXT_DRAFT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
id: NEXT_DRAFT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
|
||||||
presets,
|
presets,
|
||||||
selected_preset: 0,
|
selected_preset: 0,
|
||||||
|
seed_command: None,
|
||||||
custom_command: crate::text_input::TextInput::default(),
|
custom_command: crate::text_input::TextInput::default(),
|
||||||
groups: Vec::new(),
|
groups: Vec::new(),
|
||||||
filter: crate::text_input::TextInput::default(),
|
filter: crate::text_input::TextInput::default(),
|
||||||
@@ -342,6 +347,27 @@ impl DraftPane {
|
|||||||
.iter()
|
.iter()
|
||||||
.position(|p| !p.command.is_empty())
|
.position(|p| !p.command.is_empty())
|
||||||
.unwrap_or(0);
|
.unwrap_or(0);
|
||||||
|
self.apply_seed_command();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Land a seeded command on the tile that runs it: its own preset when the
|
||||||
|
/// daemon offers one, otherwise the custom escape hatch with the command
|
||||||
|
/// typed in.
|
||||||
|
fn apply_seed_command(&mut self) {
|
||||||
|
let Some(command) = self.seed_command.take() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match self.presets.iter().position(|p| p.command == command) {
|
||||||
|
Some(index) => self.selected_preset = index,
|
||||||
|
None => {
|
||||||
|
self.selected_preset = self
|
||||||
|
.presets
|
||||||
|
.iter()
|
||||||
|
.position(|p| p.command.is_empty())
|
||||||
|
.unwrap_or(self.selected_preset);
|
||||||
|
self.custom_command = crate::text_input::TextInput::with_value(command);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replace the project snapshot: sort fresh-first (#54), group by
|
/// Replace the project snapshot: sort fresh-first (#54), group by
|
||||||
@@ -1688,6 +1714,48 @@ mod tests {
|
|||||||
assert_eq!(draft.presets.last().unwrap().id, "custom");
|
assert_eq!(draft.presets.last().unwrap().id, "custom");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// "Spawn similar" (#155) seeds the cloned session's command: it lands on
|
||||||
|
/// the tile that runs it when the daemon offers one.
|
||||||
|
#[test]
|
||||||
|
fn a_seeded_command_selects_its_own_preset() {
|
||||||
|
let mut draft = DraftPane {
|
||||||
|
seed_command: Some("aider".into()),
|
||||||
|
..DraftPane::default()
|
||||||
|
};
|
||||||
|
draft.set_presets(vec![
|
||||||
|
SpawnPreset {
|
||||||
|
id: "claude".into(),
|
||||||
|
label: "Claude".into(),
|
||||||
|
command: "claude".into(),
|
||||||
|
},
|
||||||
|
SpawnPreset {
|
||||||
|
id: "aider".into(),
|
||||||
|
label: "Aider".into(),
|
||||||
|
command: "aider".into(),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
assert_eq!(draft.command(), "aider");
|
||||||
|
assert!(!draft.is_custom());
|
||||||
|
assert_eq!(draft.seed_command, None, "consumed by the first load");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A command no preset runs falls back to the custom tile with the command
|
||||||
|
/// typed in, so the clone still spawns what it cloned.
|
||||||
|
#[test]
|
||||||
|
fn a_seeded_command_with_no_preset_fills_the_custom_tile() {
|
||||||
|
let mut draft = DraftPane {
|
||||||
|
seed_command: Some("bash -l".into()),
|
||||||
|
..DraftPane::default()
|
||||||
|
};
|
||||||
|
draft.set_presets(vec![SpawnPreset {
|
||||||
|
id: "claude".into(),
|
||||||
|
label: "Claude".into(),
|
||||||
|
command: "claude".into(),
|
||||||
|
}]);
|
||||||
|
assert!(draft.is_custom());
|
||||||
|
assert_eq!(draft.command(), "bash -l");
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn left_right_cycles_presets_wrapping_into_custom() {
|
fn left_right_cycles_presets_wrapping_into_custom() {
|
||||||
let mut draft = DraftPane {
|
let mut draft = DraftPane {
|
||||||
|
|||||||
@@ -49,6 +49,33 @@ pub fn resolve(
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.next()
|
.next()
|
||||||
});
|
});
|
||||||
|
defaults(project, presets, handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve the defaults for a spawn pinned to one directory — the command
|
||||||
|
/// bar's `~` (#154), where the operator named the directory and nothing may
|
||||||
|
/// override it. Unlike [`resolve`] there is no recency fallback: a directory
|
||||||
|
/// the project scan does not know leaves `project` `None`, which is an
|
||||||
|
/// unresolvable default, so the keystroke opens the pre-filled form instead of
|
||||||
|
/// spawning somewhere else.
|
||||||
|
pub fn resolve_at(
|
||||||
|
dir: &std::path::Path,
|
||||||
|
projects: &[Project],
|
||||||
|
presets: &[SpawnPreset],
|
||||||
|
handle: Option<String>,
|
||||||
|
) -> FastForwardDefaults {
|
||||||
|
let project = projects.iter().find(|p| p.path == dir).cloned();
|
||||||
|
defaults(project, presets, handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The project's last command, or the first non-custom preset, wrapped up with
|
||||||
|
/// the rest of the defaults. Shared by both resolvers so the two entry points
|
||||||
|
/// can never settle on different commands.
|
||||||
|
fn defaults(
|
||||||
|
project: Option<Project>,
|
||||||
|
presets: &[SpawnPreset],
|
||||||
|
handle: Option<String>,
|
||||||
|
) -> FastForwardDefaults {
|
||||||
let command = project
|
let command = project
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|p| p.last_command.clone())
|
.and_then(|p| p.last_command.clone())
|
||||||
@@ -159,6 +186,46 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The command bar's `~` names the directory; nothing may override it.
|
||||||
|
#[test]
|
||||||
|
fn resolve_at_pins_the_directory_over_the_recency_ranking() {
|
||||||
|
let projects = vec![
|
||||||
|
project("/repos/fresh", 0, Some("aider")),
|
||||||
|
project("/repos/pinned", 30, Some("zsh")),
|
||||||
|
];
|
||||||
|
let resolved = resolve_at(
|
||||||
|
std::path::Path::new("/repos/pinned"),
|
||||||
|
&projects,
|
||||||
|
&[preset("claude", "claude")],
|
||||||
|
Some("otter".into()),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
resolved.project.as_ref().map(|p| p.path.clone()),
|
||||||
|
Some(PathBuf::from("/repos/pinned"))
|
||||||
|
);
|
||||||
|
assert_eq!(resolved.command.as_deref(), Some("zsh"));
|
||||||
|
let req = resolved.build_request().expect("every default resolved");
|
||||||
|
assert_eq!(req.cwd, PathBuf::from("/repos/pinned"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A directory the scan does not know resolves no project, so there is no
|
||||||
|
/// request to build — the caller opens the pre-filled form instead of
|
||||||
|
/// spawning somewhere else.
|
||||||
|
#[test]
|
||||||
|
fn resolve_at_takes_no_fallback_for_an_unknown_directory() {
|
||||||
|
let projects = vec![project("/repos/fresh", 0, Some("aider"))];
|
||||||
|
let resolved = resolve_at(
|
||||||
|
std::path::Path::new("/elsewhere"),
|
||||||
|
&projects,
|
||||||
|
&[preset("claude", "claude")],
|
||||||
|
Some("otter".into()),
|
||||||
|
);
|
||||||
|
assert_eq!(resolved.project, None);
|
||||||
|
// The preset still resolves; the missing project is what blocks it.
|
||||||
|
assert_eq!(resolved.command.as_deref(), Some("claude"));
|
||||||
|
assert_eq!(resolved.build_request(), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn resolves_every_default_from_the_most_recent_project() {
|
fn resolves_every_default_from_the_most_recent_project() {
|
||||||
let projects = vec![
|
let projects = vec![
|
||||||
|
|||||||
@@ -387,6 +387,9 @@ pub struct ChordState {
|
|||||||
held: Vec<String>,
|
held: Vec<String>,
|
||||||
last_press: Option<Instant>,
|
last_press: Option<Instant>,
|
||||||
timeout: Duration,
|
timeout: Duration,
|
||||||
|
/// A key bumped out of an abandoned chord (see [`Self::feed`]), waiting
|
||||||
|
/// to be replayed as a fresh keystroke by the caller.
|
||||||
|
replay: Option<InputKey>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ChordState {
|
impl ChordState {
|
||||||
@@ -395,6 +398,7 @@ impl ChordState {
|
|||||||
held: Vec::new(),
|
held: Vec::new(),
|
||||||
last_press: None,
|
last_press: None,
|
||||||
timeout,
|
timeout,
|
||||||
|
replay: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -404,6 +408,13 @@ impl ChordState {
|
|||||||
/// binding; wait for the next key.
|
/// binding; wait for the next key.
|
||||||
/// * `Resolved(s)` — `s` is the canonical chord (or single key) to look
|
/// * `Resolved(s)` — `s` is the canonical chord (or single key) to look
|
||||||
/// up in the keymap. The held buffer is cleared.
|
/// up in the keymap. The held buffer is cleared.
|
||||||
|
///
|
||||||
|
/// A held prefix that is itself directly bound (e.g. a leader key bound
|
||||||
|
/// alone as well as chorded, like `ctrl-a` and `ctrl-a ctrl-k`) resolves
|
||||||
|
/// to that binding the moment the next key fails to extend it, rather
|
||||||
|
/// than swallowing the held key and losing its meaning — the new key
|
||||||
|
/// never belonged to the chord and is handed back via [`Self::take_replay`]
|
||||||
|
/// so the caller can process it as its own keystroke.
|
||||||
pub fn feed(&mut self, key: &InputKey, known_bindings: &HashSet<String>) -> ChordResult {
|
pub fn feed(&mut self, key: &InputKey, known_bindings: &HashSet<String>) -> ChordResult {
|
||||||
if let Some(t) = self.last_press {
|
if let Some(t) = self.last_press {
|
||||||
if t.elapsed() > self.timeout {
|
if t.elapsed() > self.timeout {
|
||||||
@@ -428,11 +439,31 @@ impl ChordState {
|
|||||||
|
|
||||||
if is_prefix {
|
if is_prefix {
|
||||||
self.held.push(key_s);
|
self.held.push(key_s);
|
||||||
ChordResult::Pending
|
return ChordResult::Pending;
|
||||||
} else {
|
|
||||||
self.held.clear();
|
|
||||||
ChordResult::Resolved(candidate)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if known_bindings.contains(&candidate) {
|
||||||
|
self.held.clear();
|
||||||
|
return ChordResult::Resolved(candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.held.is_empty() {
|
||||||
|
let held_str = self.held.join(" ");
|
||||||
|
self.held.clear();
|
||||||
|
if known_bindings.contains(&held_str) {
|
||||||
|
self.replay = Some(key.clone());
|
||||||
|
return ChordResult::Resolved(held_str);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ChordResult::Resolved(candidate)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Take the key bumped out of an abandoned chord by the last [`Self::feed`]
|
||||||
|
/// call, if any. The caller feeds it through again as a brand new
|
||||||
|
/// keystroke.
|
||||||
|
pub fn take_replay(&mut self) -> Option<InputKey> {
|
||||||
|
self.replay.take()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -733,6 +764,41 @@ mod tests {
|
|||||||
assert_eq!(r, ChordResult::Resolved("g x".into()));
|
assert_eq!(r, ChordResult::Resolved("g x".into()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A key bound both alone and as a chord prefix (the leader: `ctrl-a` and
|
||||||
|
/// `ctrl-a ctrl-k`) must still fire its own binding when the next key
|
||||||
|
/// doesn't complete the chord — the held key's meaning isn't lost, and
|
||||||
|
/// the new key comes back via `take_replay` for the caller to process on
|
||||||
|
/// its own (#156).
|
||||||
|
#[test]
|
||||||
|
fn a_bound_prefix_resolves_itself_and_replays_the_breaking_key() {
|
||||||
|
let mut chord = ChordState::new(Duration::from_secs(10));
|
||||||
|
let known: HashSet<String> = ["ctrl-a".into(), "ctrl-a ctrl-k".into()]
|
||||||
|
.into_iter()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let r = chord.feed(&InputKey::ctrl_char('a'), &known);
|
||||||
|
assert_eq!(r, ChordResult::Pending);
|
||||||
|
|
||||||
|
let r = chord.feed(&InputKey::char('j'), &known);
|
||||||
|
assert_eq!(r, ChordResult::Resolved("ctrl-a".into()));
|
||||||
|
assert_eq!(chord.take_replay(), Some(InputKey::char('j')));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The full chord still resolves normally when the next key completes
|
||||||
|
/// it — no replay, no early fire of the shorter binding.
|
||||||
|
#[test]
|
||||||
|
fn a_completed_chord_off_a_bound_prefix_has_no_replay() {
|
||||||
|
let mut chord = ChordState::new(Duration::from_secs(10));
|
||||||
|
let known: HashSet<String> = ["ctrl-a".into(), "ctrl-a ctrl-k".into()]
|
||||||
|
.into_iter()
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
chord.feed(&InputKey::ctrl_char('a'), &known);
|
||||||
|
let r = chord.feed(&InputKey::ctrl_char('k'), &known);
|
||||||
|
assert_eq!(r, ChordResult::Resolved("ctrl-a ctrl-k".into()));
|
||||||
|
assert_eq!(chord.take_replay(), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn chord_state_lone_key_resolves_immediately() {
|
fn chord_state_lone_key_resolves_immediately() {
|
||||||
let mut chord = ChordState::new(Duration::from_secs(10));
|
let mut chord = ChordState::new(Duration::from_secs(10));
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ pub mod action;
|
|||||||
pub mod app;
|
pub mod app;
|
||||||
pub mod catalog;
|
pub mod catalog;
|
||||||
pub mod cli;
|
pub mod cli;
|
||||||
|
pub mod command_bar;
|
||||||
pub mod config;
|
pub mod config;
|
||||||
pub mod daemon_link;
|
pub mod daemon_link;
|
||||||
pub mod draft;
|
pub mod draft;
|
||||||
@@ -13,6 +14,7 @@ pub mod emulators;
|
|||||||
pub mod fast_forward;
|
pub mod fast_forward;
|
||||||
pub mod input;
|
pub mod input;
|
||||||
pub mod keymap;
|
pub mod keymap;
|
||||||
|
pub mod matcher;
|
||||||
pub mod overlays;
|
pub mod overlays;
|
||||||
pub mod palette;
|
pub mod palette;
|
||||||
pub mod pane;
|
pub mod pane;
|
||||||
|
|||||||
@@ -0,0 +1,750 @@
|
|||||||
|
//! Pure match-and-rank function for the `ctrl-k` command bar.
|
||||||
|
//!
|
||||||
|
//! Implements exactly the algorithm in `docs/COMMAND-BAR.md` ("What a
|
||||||
|
//! candidate is", "Match and rank", "Fixtures"). Must produce the same order
|
||||||
|
//! and scores as `web/src/matcher.ts` for the same input.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum CandidateKind {
|
||||||
|
Session,
|
||||||
|
Command,
|
||||||
|
Directory,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
|
pub enum MatchFieldName {
|
||||||
|
Name,
|
||||||
|
Directory,
|
||||||
|
Command,
|
||||||
|
Tool,
|
||||||
|
Label,
|
||||||
|
Path,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct SessionCandidate {
|
||||||
|
pub name: String,
|
||||||
|
pub directory: Option<String>,
|
||||||
|
pub command: Option<String>,
|
||||||
|
pub tool: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct CommandCandidate {
|
||||||
|
pub label: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct DirectoryCandidate {
|
||||||
|
pub path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum MatchCandidate {
|
||||||
|
Session(SessionCandidate),
|
||||||
|
Command(CommandCandidate),
|
||||||
|
Directory(DirectoryCandidate),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type MatchRange = (usize, usize);
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub struct MatchResult<'c> {
|
||||||
|
pub candidate: &'c MatchCandidate,
|
||||||
|
pub score: i32,
|
||||||
|
pub field: Option<MatchFieldName>,
|
||||||
|
pub ranges: Vec<MatchRange>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Field<'c> {
|
||||||
|
name: MatchFieldName,
|
||||||
|
text: &'c str,
|
||||||
|
weight: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MatchCandidate {
|
||||||
|
fn kind(&self) -> CandidateKind {
|
||||||
|
match self {
|
||||||
|
MatchCandidate::Session(_) => CandidateKind::Session,
|
||||||
|
MatchCandidate::Command(_) => CandidateKind::Command,
|
||||||
|
MatchCandidate::Directory(_) => CandidateKind::Directory,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fields(&self) -> Vec<Field<'_>> {
|
||||||
|
match self {
|
||||||
|
MatchCandidate::Session(session) => {
|
||||||
|
let mut fields = vec![Field {
|
||||||
|
name: MatchFieldName::Name,
|
||||||
|
text: &session.name,
|
||||||
|
weight: 0,
|
||||||
|
}];
|
||||||
|
if let Some(directory) = &session.directory {
|
||||||
|
fields.push(Field {
|
||||||
|
name: MatchFieldName::Directory,
|
||||||
|
text: directory,
|
||||||
|
weight: -24,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Some(command) = &session.command {
|
||||||
|
fields.push(Field {
|
||||||
|
name: MatchFieldName::Command,
|
||||||
|
text: command,
|
||||||
|
weight: -32,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if let Some(tool) = &session.tool {
|
||||||
|
fields.push(Field {
|
||||||
|
name: MatchFieldName::Tool,
|
||||||
|
text: tool,
|
||||||
|
weight: -40,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
fields
|
||||||
|
}
|
||||||
|
MatchCandidate::Command(command) => vec![Field {
|
||||||
|
name: MatchFieldName::Label,
|
||||||
|
text: &command.label,
|
||||||
|
weight: 0,
|
||||||
|
}],
|
||||||
|
MatchCandidate::Directory(directory) => vec![Field {
|
||||||
|
name: MatchFieldName::Path,
|
||||||
|
text: &directory.path,
|
||||||
|
weight: 0,
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kind_order(kind: CandidateKind) -> u8 {
|
||||||
|
match kind {
|
||||||
|
CandidateKind::Session => 0,
|
||||||
|
CandidateKind::Command => 1,
|
||||||
|
CandidateKind::Directory => 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lower_char(c: char) -> char {
|
||||||
|
c.to_lowercase().next().unwrap_or(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lower_chars(chars: &[char]) -> Vec<char> {
|
||||||
|
chars.iter().copied().map(lower_char).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalize_query(query: &str) -> Vec<char> {
|
||||||
|
query
|
||||||
|
.chars()
|
||||||
|
.filter(|c| !c.is_whitespace())
|
||||||
|
.map(lower_char)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
const SEPARATORS: [char; 6] = ['/', '\\', '-', '_', '.', ':'];
|
||||||
|
|
||||||
|
fn boundary_bonus(text: &[char], position: usize) -> i32 {
|
||||||
|
if position == 0 {
|
||||||
|
return 18;
|
||||||
|
}
|
||||||
|
|
||||||
|
let previous = text[position - 1];
|
||||||
|
if previous == ' ' || SEPARATORS.contains(&previous) {
|
||||||
|
return 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
let current = text[position];
|
||||||
|
if current.is_uppercase() && previous.is_lowercase() {
|
||||||
|
return 12;
|
||||||
|
}
|
||||||
|
|
||||||
|
let is_digit = current.is_ascii_digit();
|
||||||
|
let previous_is_digit = previous.is_ascii_digit();
|
||||||
|
if is_digit && !previous_is_digit {
|
||||||
|
return 12;
|
||||||
|
}
|
||||||
|
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contribution(text: &[char], position: usize, previous_position: isize) -> i32 {
|
||||||
|
let gap = position as isize - previous_position - 1;
|
||||||
|
16 + boundary_bonus(text, position) + if gap == 0 { 8 } else { -gap.min(12) as i32 }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct Embedding {
|
||||||
|
score: i32,
|
||||||
|
positions: Vec<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_better_embedding(candidate: &Embedding, incumbent: Option<&Embedding>) -> bool {
|
||||||
|
let Some(incumbent) = incumbent else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
if candidate.score != incumbent.score {
|
||||||
|
return candidate.score > incumbent.score;
|
||||||
|
}
|
||||||
|
for (c, i) in candidate.positions.iter().zip(incumbent.positions.iter()) {
|
||||||
|
if c != i {
|
||||||
|
return c < i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The dynamic program over `(query index, text position)` described in
|
||||||
|
/// "Which embedding": greedy leftmost-first matching is insufficient (e.g.
|
||||||
|
/// `mtu` against `maestro-tui`), so every reachable position at each query
|
||||||
|
/// index carries its best score and position vector forward.
|
||||||
|
fn best_embedding(query: &[char], text: &[char]) -> Option<Embedding> {
|
||||||
|
let lower_text = lower_chars(text);
|
||||||
|
let mut previous_states: HashMap<usize, Embedding> = HashMap::new();
|
||||||
|
|
||||||
|
for (query_index, &qc) in query.iter().enumerate() {
|
||||||
|
let mut states: HashMap<usize, Embedding> = HashMap::new();
|
||||||
|
|
||||||
|
for (position, &text_char) in lower_text.iter().enumerate() {
|
||||||
|
if text_char != qc {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if query_index == 0 {
|
||||||
|
states.insert(
|
||||||
|
position,
|
||||||
|
Embedding {
|
||||||
|
score: contribution(text, position, -1),
|
||||||
|
positions: vec![position],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (&previous_position, previous) in previous_states.iter() {
|
||||||
|
if previous_position >= position {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut positions = previous.positions.clone();
|
||||||
|
positions.push(position);
|
||||||
|
let candidate = Embedding {
|
||||||
|
score: previous.score
|
||||||
|
+ contribution(text, position, previous_position as isize),
|
||||||
|
positions,
|
||||||
|
};
|
||||||
|
if is_better_embedding(&candidate, states.get(&position)) {
|
||||||
|
states.insert(position, candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if states.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
previous_states = states;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut best: Option<Embedding> = None;
|
||||||
|
for embedding in previous_states.into_values() {
|
||||||
|
if is_better_embedding(&embedding, best.as_ref()) {
|
||||||
|
best = Some(embedding);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
best
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_ranges(positions: &[usize]) -> Vec<MatchRange> {
|
||||||
|
let mut ranges: Vec<MatchRange> = Vec::new();
|
||||||
|
for &position in positions {
|
||||||
|
if let Some(last) = ranges.last_mut() {
|
||||||
|
if last.1 == position {
|
||||||
|
last.1 = position + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ranges.push((position, position + 1));
|
||||||
|
}
|
||||||
|
ranges
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compact(text: &str) -> String {
|
||||||
|
text.chars()
|
||||||
|
.filter(|c| !c.is_whitespace())
|
||||||
|
.map(lower_char)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Ranked<'c> {
|
||||||
|
candidate: &'c MatchCandidate,
|
||||||
|
score: i32,
|
||||||
|
field: Option<MatchFieldName>,
|
||||||
|
ranges: Vec<MatchRange>,
|
||||||
|
matched_text: String,
|
||||||
|
input_index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(query, candidates) -> ranked subset with matched ranges`. Knows nothing
|
||||||
|
/// about sessions, panes or the network — see docs/COMMAND-BAR.md.
|
||||||
|
pub fn match_and_rank<'c>(query: &str, candidates: &'c [MatchCandidate]) -> Vec<MatchResult<'c>> {
|
||||||
|
let normalized_query = normalize_query(query);
|
||||||
|
|
||||||
|
if normalized_query.is_empty() {
|
||||||
|
return candidates
|
||||||
|
.iter()
|
||||||
|
.map(|candidate| MatchResult {
|
||||||
|
candidate,
|
||||||
|
score: 0,
|
||||||
|
field: None,
|
||||||
|
ranges: Vec::new(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut results: Vec<Ranked<'c>> = Vec::new();
|
||||||
|
|
||||||
|
for (input_index, candidate) in candidates.iter().enumerate() {
|
||||||
|
let mut best: Option<(MatchFieldName, &str, i32, Vec<usize>)> = None;
|
||||||
|
|
||||||
|
for field in candidate.fields() {
|
||||||
|
let text_chars: Vec<char> = field.text.chars().collect();
|
||||||
|
let Some(embedding) = best_embedding(&normalized_query, &text_chars) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
let compact_text = compact(field.text);
|
||||||
|
let normalized_query_str: String = normalized_query.iter().collect();
|
||||||
|
let adjustment = if compact_text == normalized_query_str {
|
||||||
|
64
|
||||||
|
} else if compact_text.starts_with(&normalized_query_str) {
|
||||||
|
32
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
let score = embedding.score + adjustment + field.weight;
|
||||||
|
|
||||||
|
let is_better = match &best {
|
||||||
|
None => true,
|
||||||
|
Some((_, _, best_score, _)) => score > *best_score,
|
||||||
|
};
|
||||||
|
if is_better {
|
||||||
|
best = Some((field.name, field.text, score, embedding.positions));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((field_name, field_text, score, positions)) = best {
|
||||||
|
results.push(Ranked {
|
||||||
|
candidate,
|
||||||
|
score,
|
||||||
|
field: Some(field_name),
|
||||||
|
ranges: to_ranges(&positions),
|
||||||
|
matched_text: field_text.to_string(),
|
||||||
|
input_index,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
results.sort_by(|a, b| {
|
||||||
|
b.score
|
||||||
|
.cmp(&a.score)
|
||||||
|
.then_with(|| kind_order(a.candidate.kind()).cmp(&kind_order(b.candidate.kind())))
|
||||||
|
.then_with(|| {
|
||||||
|
a.matched_text
|
||||||
|
.chars()
|
||||||
|
.count()
|
||||||
|
.cmp(&b.matched_text.chars().count())
|
||||||
|
})
|
||||||
|
.then_with(|| a.matched_text.cmp(&b.matched_text))
|
||||||
|
.then_with(|| a.input_index.cmp(&b.input_index))
|
||||||
|
});
|
||||||
|
|
||||||
|
results
|
||||||
|
.into_iter()
|
||||||
|
.map(|ranked| MatchResult {
|
||||||
|
candidate: ranked.candidate,
|
||||||
|
score: ranked.score,
|
||||||
|
field: ranked.field,
|
||||||
|
ranges: ranked.ranges,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn session(
|
||||||
|
name: &str,
|
||||||
|
directory: Option<&str>,
|
||||||
|
command: Option<&str>,
|
||||||
|
tool: Option<&str>,
|
||||||
|
) -> MatchCandidate {
|
||||||
|
MatchCandidate::Session(SessionCandidate {
|
||||||
|
name: name.to_string(),
|
||||||
|
directory: directory.map(str::to_string),
|
||||||
|
command: command.map(str::to_string),
|
||||||
|
tool: tool.map(str::to_string),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command(label: &str) -> MatchCandidate {
|
||||||
|
MatchCandidate::Command(CommandCandidate {
|
||||||
|
label: label.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn directory(path: &str) -> MatchCandidate {
|
||||||
|
MatchCandidate::Directory(DirectoryCandidate {
|
||||||
|
path: path.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn label(candidate: &MatchCandidate) -> String {
|
||||||
|
match candidate {
|
||||||
|
MatchCandidate::Session(s) => format!("session:{}", s.name),
|
||||||
|
MatchCandidate::Command(c) => format!("command:{}", c.label),
|
||||||
|
MatchCandidate::Directory(d) => format!("directory:{}", d.path),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn positions(result: &MatchResult) -> Vec<usize> {
|
||||||
|
result
|
||||||
|
.ranges
|
||||||
|
.iter()
|
||||||
|
.flat_map(|&(start, end)| start..end)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
|
fn expect_results(
|
||||||
|
query: &str,
|
||||||
|
candidates: &[MatchCandidate],
|
||||||
|
expected: &[(&str, i32, Option<MatchFieldName>, &[usize])],
|
||||||
|
) {
|
||||||
|
let results = match_and_rank(query, candidates);
|
||||||
|
|
||||||
|
let actual: Vec<(String, i32)> = results
|
||||||
|
.iter()
|
||||||
|
.map(|r| (label(r.candidate), r.score))
|
||||||
|
.collect();
|
||||||
|
let expected_labels: Vec<(String, i32)> = expected
|
||||||
|
.iter()
|
||||||
|
.map(|(l, s, _, _)| (l.to_string(), *s))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(actual, expected_labels, "order/scores for query {query:?}");
|
||||||
|
|
||||||
|
let actual_fields: Vec<Option<MatchFieldName>> = results.iter().map(|r| r.field).collect();
|
||||||
|
let expected_fields: Vec<Option<MatchFieldName>> =
|
||||||
|
expected.iter().map(|(_, _, f, _)| *f).collect();
|
||||||
|
assert_eq!(actual_fields, expected_fields, "fields for query {query:?}");
|
||||||
|
|
||||||
|
let actual_positions: Vec<Vec<usize>> = results.iter().map(positions).collect();
|
||||||
|
let expected_positions: Vec<Vec<usize>> =
|
||||||
|
expected.iter().map(|(_, _, _, p)| p.to_vec()).collect();
|
||||||
|
assert_eq!(
|
||||||
|
actual_positions, expected_positions,
|
||||||
|
"positions for query {query:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f1_empty_query_keeps_input_order() {
|
||||||
|
expect_results(
|
||||||
|
"",
|
||||||
|
&[
|
||||||
|
session("kill", Some("~/dev/api"), Some("bash"), None),
|
||||||
|
session(
|
||||||
|
"killer-app",
|
||||||
|
Some("~/dev/killer-app"),
|
||||||
|
Some("claude --resume"),
|
||||||
|
Some("claude"),
|
||||||
|
),
|
||||||
|
command("Kill selected session"),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
("session:kill", 0, None, &[]),
|
||||||
|
("session:killer-app", 0, None, &[]),
|
||||||
|
("command:Kill selected session", 0, None, &[]),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f2_exact_session_name_beats_prefix_kind_breaks_tie() {
|
||||||
|
expect_results(
|
||||||
|
"kill",
|
||||||
|
&[
|
||||||
|
session("kill", Some("~/dev/api"), Some("bash"), None),
|
||||||
|
session(
|
||||||
|
"killer-app",
|
||||||
|
Some("~/dev/killer-app"),
|
||||||
|
Some("claude --resume"),
|
||||||
|
Some("claude"),
|
||||||
|
),
|
||||||
|
command("Kill selected session"),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"session:kill",
|
||||||
|
178,
|
||||||
|
Some(MatchFieldName::Name),
|
||||||
|
&[0, 1, 2, 3],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"session:killer-app",
|
||||||
|
146,
|
||||||
|
Some(MatchFieldName::Name),
|
||||||
|
&[0, 1, 2, 3],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"command:Kill selected session",
|
||||||
|
146,
|
||||||
|
Some(MatchFieldName::Label),
|
||||||
|
&[0, 1, 2, 3],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f3_path_segment_boundaries_beat_mid_segment() {
|
||||||
|
expect_results(
|
||||||
|
"foo",
|
||||||
|
&[
|
||||||
|
directory("~/dev/foobar"),
|
||||||
|
directory("~/src/myfoo"),
|
||||||
|
directory("~/foo"),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"directory:~/foo",
|
||||||
|
78,
|
||||||
|
Some(MatchFieldName::Path),
|
||||||
|
&[2, 3, 4],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"directory:~/dev/foobar",
|
||||||
|
74,
|
||||||
|
Some(MatchFieldName::Path),
|
||||||
|
&[6, 7, 8],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"directory:~/src/myfoo",
|
||||||
|
56,
|
||||||
|
Some(MatchFieldName::Path),
|
||||||
|
&[8, 9, 10],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f4_no_match_returns_empty() {
|
||||||
|
expect_results(
|
||||||
|
"zzz",
|
||||||
|
&[
|
||||||
|
session("kill", Some("~/dev/api"), Some("bash"), None),
|
||||||
|
command("Kill selected session"),
|
||||||
|
],
|
||||||
|
&[],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f5_highest_scoring_embedding_beats_greedy() {
|
||||||
|
expect_results(
|
||||||
|
"mtu",
|
||||||
|
&[
|
||||||
|
session("maestro-tui", None, None, None),
|
||||||
|
session("maestro-daemon", None, None, None),
|
||||||
|
session("mtui-scratch", None, None, None),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"session:mtui-scratch",
|
||||||
|
122,
|
||||||
|
Some(MatchFieldName::Name),
|
||||||
|
&[0, 1, 2],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"session:maestro-tui",
|
||||||
|
91,
|
||||||
|
Some(MatchFieldName::Name),
|
||||||
|
&[0, 8, 9],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f6_name_beats_weighted_directory() {
|
||||||
|
expect_results(
|
||||||
|
"api",
|
||||||
|
&[
|
||||||
|
session("api", Some("~/dev/web"), Some("bash"), None),
|
||||||
|
session("worker", Some("~/dev/api"), Some("bash"), None),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
("session:api", 154, Some(MatchFieldName::Name), &[0, 1, 2]),
|
||||||
|
(
|
||||||
|
"session:worker",
|
||||||
|
50,
|
||||||
|
Some(MatchFieldName::Directory),
|
||||||
|
&[6, 7, 8],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f7_case_insensitive_length_breaks_tie() {
|
||||||
|
expect_results(
|
||||||
|
"api",
|
||||||
|
&[
|
||||||
|
session("API-Gateway", None, None, None),
|
||||||
|
session("apiary", None, None, None),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"session:apiary",
|
||||||
|
122,
|
||||||
|
Some(MatchFieldName::Name),
|
||||||
|
&[0, 1, 2],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"session:API-Gateway",
|
||||||
|
122,
|
||||||
|
Some(MatchFieldName::Name),
|
||||||
|
&[0, 1, 2],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f8_exact_tool_beats_command_field() {
|
||||||
|
expect_results(
|
||||||
|
"claude",
|
||||||
|
&[
|
||||||
|
session(
|
||||||
|
"nameless",
|
||||||
|
Some("~/dev/x"),
|
||||||
|
Some("claude --resume"),
|
||||||
|
Some("claude"),
|
||||||
|
),
|
||||||
|
session("clay", Some("~/dev/y"), Some("bash"), None),
|
||||||
|
],
|
||||||
|
&[(
|
||||||
|
"session:nameless",
|
||||||
|
186,
|
||||||
|
Some(MatchFieldName::Tool),
|
||||||
|
&[0, 1, 2, 3, 4, 5],
|
||||||
|
)],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f9_separator_earns_word_boundary_bonus() {
|
||||||
|
expect_results(
|
||||||
|
"ws",
|
||||||
|
&[
|
||||||
|
session("websearch", None, None, None),
|
||||||
|
session("web-search", None, None, None),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"session:web-search",
|
||||||
|
71,
|
||||||
|
Some(MatchFieldName::Name),
|
||||||
|
&[0, 4],
|
||||||
|
),
|
||||||
|
("session:websearch", 56, Some(MatchFieldName::Name), &[0, 3]),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f10_command_labels_rank_by_boundary_and_gap() {
|
||||||
|
expect_results(
|
||||||
|
"se",
|
||||||
|
&[
|
||||||
|
command("Kill selected session"),
|
||||||
|
command("Create a session"),
|
||||||
|
command("Show help"),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"command:Show help",
|
||||||
|
53,
|
||||||
|
Some(MatchFieldName::Label),
|
||||||
|
&[0, 6],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"command:Kill selected session",
|
||||||
|
51,
|
||||||
|
Some(MatchFieldName::Label),
|
||||||
|
&[5, 6],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"command:Create a session",
|
||||||
|
47,
|
||||||
|
Some(MatchFieldName::Label),
|
||||||
|
&[9, 10],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f11_directory_matches_separate_on_initial_gap() {
|
||||||
|
expect_results(
|
||||||
|
"dev",
|
||||||
|
&[
|
||||||
|
session("api", Some("~/dev/api"), Some("bash"), None),
|
||||||
|
session("notes", Some("~/documents/dev-notes"), Some("nvim"), None),
|
||||||
|
session("scratch", Some("~/srv/devops"), Some("bash"), None),
|
||||||
|
],
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"session:api",
|
||||||
|
54,
|
||||||
|
Some(MatchFieldName::Directory),
|
||||||
|
&[2, 3, 4],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"session:scratch",
|
||||||
|
50,
|
||||||
|
Some(MatchFieldName::Directory),
|
||||||
|
&[6, 7, 8],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"session:notes",
|
||||||
|
44,
|
||||||
|
Some(MatchFieldName::Directory),
|
||||||
|
&[12, 13, 14],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn f12_exact_beats_prefix() {
|
||||||
|
expect_results(
|
||||||
|
"quit",
|
||||||
|
&[command("Quit Maestro"), command("Quit")],
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"command:Quit",
|
||||||
|
178,
|
||||||
|
Some(MatchFieldName::Label),
|
||||||
|
&[0, 1, 2, 3],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"command:Quit Maestro",
|
||||||
|
146,
|
||||||
|
Some(MatchFieldName::Label),
|
||||||
|
&[0, 1, 2, 3],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -813,6 +813,21 @@ impl Palette {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Background for the card whose session the pane is showing
|
||||||
|
/// (`docs/SIDEBAR.md`). It sits partway from the card surface to the
|
||||||
|
/// selection surface, so the sidebar reads as one ladder: unfilled, half
|
||||||
|
/// filled for the session in the pane, fully filled under the cursor.
|
||||||
|
///
|
||||||
|
/// Blended rather than added as a third `Surface` — a new surface means
|
||||||
|
/// eight more colours hand-picked seventeen times — which is also why it
|
||||||
|
/// borrows the *selection* surface's foregrounds: those are the ones
|
||||||
|
/// already picked for a filled row. A preset whose colours the terminal
|
||||||
|
/// owns (`ansi`) has nothing to blend, so it keeps the card background and
|
||||||
|
/// says "in the pane" with the filled glyph alone.
|
||||||
|
pub fn pane_row_bg(&self) -> Color {
|
||||||
|
mix(self.card.bg, self.selection.bg, 0.55)
|
||||||
|
}
|
||||||
|
|
||||||
/// Border style for a panel, by whether it holds focus.
|
/// Border style for a panel, by whether it holds focus.
|
||||||
pub fn border_style(&self, focused: bool) -> Style {
|
pub fn border_style(&self, focused: bool) -> Style {
|
||||||
if focused {
|
if focused {
|
||||||
@@ -873,6 +888,16 @@ pub fn active() -> Palette {
|
|||||||
*active_slot().read().expect("active palette lock poisoned")
|
*active_slot().read().expect("active palette lock poisoned")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Blend `amount` of `to` into `from`, in plain sRGB. Both must be RGB, or
|
||||||
|
/// there is nothing to blend and `from` comes back unchanged.
|
||||||
|
fn mix(from: Color, to: Color, amount: f64) -> Color {
|
||||||
|
let (Color::Rgb(fr, fg, fb), Color::Rgb(tr, tg, tb)) = (from, to) else {
|
||||||
|
return from;
|
||||||
|
};
|
||||||
|
let lerp = |a: u8, b: u8| (a as f64 + (b as f64 - a as f64) * amount).round() as u8;
|
||||||
|
Color::Rgb(lerp(fr, tr), lerp(fg, tg), lerp(fb, tb))
|
||||||
|
}
|
||||||
|
|
||||||
/// WCAG relative luminance of an RGB role. Non-RGB colours have no fixed
|
/// WCAG relative luminance of an RGB role. Non-RGB colours have no fixed
|
||||||
/// luminance — they are whatever the terminal theme says — so they return
|
/// luminance — they are whatever the terminal theme says — so they return
|
||||||
/// `None` and cannot be contrast-checked.
|
/// `None` and cannot be contrast-checked.
|
||||||
@@ -937,6 +962,43 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The pane row is the middle rung: a visible fill against the card, still
|
||||||
|
/// a different surface from the cursor's, and carrying the selection
|
||||||
|
/// surface's foregrounds, which it borrows rather than shipping its own.
|
||||||
|
#[test]
|
||||||
|
fn the_pane_row_is_a_rung_between_the_card_and_the_selection() {
|
||||||
|
for (preset, p) in rgb_presets() {
|
||||||
|
let bg = p.pane_row_bg();
|
||||||
|
let from_card = contrast_ratio(p.card.bg, bg)
|
||||||
|
.unwrap_or_else(|| panic!("{preset}.pane_row_bg must be RGB"));
|
||||||
|
assert!(
|
||||||
|
from_card >= 1.15,
|
||||||
|
"{preset}: pane row {from_card:.2} from the card background is not a visible fill"
|
||||||
|
);
|
||||||
|
let from_selection =
|
||||||
|
contrast_ratio(p.selection.bg, bg).expect("selection.bg must be RGB");
|
||||||
|
assert!(
|
||||||
|
from_selection >= 1.15,
|
||||||
|
"{preset}: pane row {from_selection:.2} from the cursor's fill — the highlight would vanish on the session already in the pane"
|
||||||
|
);
|
||||||
|
for (role, color) in p.selection.roles() {
|
||||||
|
let ratio = contrast_ratio(bg, color).expect("selection role must be RGB");
|
||||||
|
let floor = if role == "dim" { 3.0 } else { 4.5 };
|
||||||
|
assert!(
|
||||||
|
ratio >= floor,
|
||||||
|
"{preset}.selection.{role} on the pane row is {ratio:.2}, below {floor}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A preset the terminal themes has nothing to blend from.
|
||||||
|
#[test]
|
||||||
|
fn ansi_keeps_the_card_background_for_the_pane_row() {
|
||||||
|
let p = Palette::ANSI;
|
||||||
|
assert_eq!(p.pane_row_bg(), p.card.bg);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn every_preset_supplies_every_role() {
|
fn every_preset_supplies_every_role() {
|
||||||
for (name, p) in Palette::presets() {
|
for (name, p) in Palette::presets() {
|
||||||
|
|||||||
@@ -86,6 +86,9 @@ pub struct RenderInputs<'a> {
|
|||||||
pub help: &'a HelpOverlay,
|
pub help: &'a HelpOverlay,
|
||||||
/// Edit buffer behind the rename prompt (#125).
|
/// Edit buffer behind the rename prompt (#125).
|
||||||
pub rename_input: &'a crate::text_input::TextInput,
|
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
|
/// Liveness + release of the daemon, for the status bar's indicator and the
|
||||||
/// restart overlay (`docs/RESTART.md`).
|
/// restart overlay (`docs/RESTART.md`).
|
||||||
pub link: &'a crate::daemon_link::LinkStatus,
|
pub link: &'a crate::daemon_link::LinkStatus,
|
||||||
@@ -198,6 +201,14 @@ pub fn draw(f: &mut Frame, inputs: RenderInputs<'_>) -> RegionMap {
|
|||||||
}
|
}
|
||||||
map.modal = Some(area);
|
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) => {
|
Some(OverlayKind::Help) => {
|
||||||
inputs.help.render(f, area);
|
inputs.help.render(f, area);
|
||||||
map.modal = Some(area);
|
map.modal = Some(area);
|
||||||
@@ -415,6 +426,7 @@ mod tests {
|
|||||||
sessions: Vec::new(),
|
sessions: Vec::new(),
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: HashSet::new(),
|
attached: HashSet::new(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let help = HelpOverlay { lines: Vec::new() };
|
let help = HelpOverlay { lines: Vec::new() };
|
||||||
let state = AppState::new();
|
let state = AppState::new();
|
||||||
@@ -427,6 +439,7 @@ mod tests {
|
|||||||
state: &state,
|
state: &state,
|
||||||
help: &help,
|
help: &help,
|
||||||
rename_input: &crate::text_input::TextInput::default(),
|
rename_input: &crate::text_input::TextInput::default(),
|
||||||
|
command_bar: None,
|
||||||
link,
|
link,
|
||||||
};
|
};
|
||||||
let backend = ratatui::backend::TestBackend::new(120, 24);
|
let backend = ratatui::backend::TestBackend::new(120, 24);
|
||||||
@@ -511,6 +524,7 @@ mod tests {
|
|||||||
sessions: Vec::new(),
|
sessions: Vec::new(),
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: HashSet::new(),
|
attached: HashSet::new(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let help = HelpOverlay { lines: Vec::new() };
|
let help = HelpOverlay { lines: Vec::new() };
|
||||||
let inputs = RenderInputs {
|
let inputs = RenderInputs {
|
||||||
@@ -522,6 +536,7 @@ mod tests {
|
|||||||
state: &state,
|
state: &state,
|
||||||
help: &help,
|
help: &help,
|
||||||
rename_input: &crate::text_input::TextInput::default(),
|
rename_input: &crate::text_input::TextInput::default(),
|
||||||
|
command_bar: None,
|
||||||
link: &online_link(),
|
link: &online_link(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -561,6 +576,7 @@ mod tests {
|
|||||||
sessions: Vec::new(),
|
sessions: Vec::new(),
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: HashSet::new(),
|
attached: HashSet::new(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let help = HelpOverlay { lines: Vec::new() };
|
let help = HelpOverlay { lines: Vec::new() };
|
||||||
let draw_map = |focus| {
|
let draw_map = |focus| {
|
||||||
@@ -575,6 +591,7 @@ mod tests {
|
|||||||
state: &state,
|
state: &state,
|
||||||
help: &help,
|
help: &help,
|
||||||
rename_input: &crate::text_input::TextInput::default(),
|
rename_input: &crate::text_input::TextInput::default(),
|
||||||
|
command_bar: None,
|
||||||
link: &online_link(),
|
link: &online_link(),
|
||||||
};
|
};
|
||||||
let backend = ratatui::backend::TestBackend::new(80, 24);
|
let backend = ratatui::backend::TestBackend::new(80, 24);
|
||||||
@@ -601,6 +618,7 @@ mod tests {
|
|||||||
sessions: Vec::new(),
|
sessions: Vec::new(),
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: HashSet::new(),
|
attached: HashSet::new(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let help = HelpOverlay { lines: Vec::new() };
|
let help = HelpOverlay { lines: Vec::new() };
|
||||||
let render = |focus| {
|
let render = |focus| {
|
||||||
@@ -615,6 +633,7 @@ mod tests {
|
|||||||
state: &state,
|
state: &state,
|
||||||
help: &help,
|
help: &help,
|
||||||
rename_input: &crate::text_input::TextInput::default(),
|
rename_input: &crate::text_input::TextInput::default(),
|
||||||
|
command_bar: None,
|
||||||
link: &online_link(),
|
link: &online_link(),
|
||||||
};
|
};
|
||||||
let backend = ratatui::backend::TestBackend::new(80, 24);
|
let backend = ratatui::backend::TestBackend::new(80, 24);
|
||||||
|
|||||||
@@ -37,14 +37,39 @@ const META_INDENT: &str = " ";
|
|||||||
/// both card rows, replacing the old inline dot glyph on the meta line.
|
/// both card rows, replacing the old inline dot glyph on the meta line.
|
||||||
const RAIL: &str = "▌";
|
const RAIL: &str = "▌";
|
||||||
|
|
||||||
/// Cards use the selection surface only while the sidebar owns focus. An
|
/// Which fill a session card wears (docs/SIDEBAR.md). The cursor's fill wins
|
||||||
|
/// on its own row: a highlight that lands on the session already in the pane
|
||||||
|
/// still has to be visible.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum CardFill {
|
||||||
|
/// An ordinary card, on the card surface.
|
||||||
|
None,
|
||||||
|
/// The session the pane is showing.
|
||||||
|
Pane,
|
||||||
|
/// Under the cursor, with the sidebar holding the keyboard.
|
||||||
|
Cursor,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CardFill {
|
||||||
|
/// Both filled tiers carry the selection surface's foregrounds — those are
|
||||||
|
/// the colours picked for a filled row, and a colour chosen for the card
|
||||||
|
/// background is not legible on one.
|
||||||
|
fn filled(self) -> bool {
|
||||||
|
self != CardFill::None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cards take the cursor's fill only while the sidebar owns focus. An
|
||||||
/// unfocused highlight remains an edge-marked cursor without claiming the
|
/// unfocused highlight remains an edge-marked cursor without claiming the
|
||||||
/// keyboard via a filled selection background.
|
/// keyboard via a filled selection background.
|
||||||
fn card_base(highlighted: bool, focused: bool) -> Style {
|
fn card_base(fill: CardFill, focused: bool) -> Style {
|
||||||
let palette = palette::active();
|
let palette = palette::active();
|
||||||
let mut style = palette.surface(highlighted && focused).text_style();
|
let mut style = palette.surface(fill.filled()).text_style();
|
||||||
if focused && !highlighted {
|
match fill {
|
||||||
style = style.bg(palette.sidebar_focus_bg);
|
CardFill::Cursor => {}
|
||||||
|
CardFill::Pane => style = style.bg(palette.pane_row_bg()),
|
||||||
|
CardFill::None if focused => style = style.bg(palette.sidebar_focus_bg),
|
||||||
|
CardFill::None => {}
|
||||||
}
|
}
|
||||||
style
|
style
|
||||||
}
|
}
|
||||||
@@ -55,6 +80,9 @@ pub struct Sidebar {
|
|||||||
pub sessions: Vec<Session>,
|
pub sessions: Vec<Session>,
|
||||||
pub highlight: Option<SidebarItem>,
|
pub highlight: Option<SidebarItem>,
|
||||||
pub attached: HashSet<Uuid>,
|
pub attached: HashSet<Uuid>,
|
||||||
|
/// The session the active tab's pane is showing. It wears a fill of its
|
||||||
|
/// own, so "in the pane" is not carried by the ● glyph alone.
|
||||||
|
pub pane_session: Option<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
@@ -113,8 +141,7 @@ impl Sidebar {
|
|||||||
lines.push(Line::from(self.group_row(&group, width, focused, home)));
|
lines.push(Line::from(self.group_row(&group, width, focused, home)));
|
||||||
if !group.collapsed {
|
if !group.collapsed {
|
||||||
for s in &group.sessions {
|
for s in &group.sessions {
|
||||||
let highlighted = self.highlight == Some(SidebarItem::Session(s.id));
|
let base = card_base(self.card_fill(s, focused), focused);
|
||||||
let base = card_base(highlighted, focused);
|
|
||||||
lines.push(Line::from(self.name_row(s, width, focused)));
|
lines.push(Line::from(self.name_row(s, width, focused)));
|
||||||
let meta = self.meta_row(s, width, focused);
|
let meta = self.meta_row(s, width, focused);
|
||||||
lines.push(Line::from(pad_to_width(meta, width, base)));
|
lines.push(Line::from(pad_to_width(meta, width, base)));
|
||||||
@@ -226,6 +253,18 @@ impl Sidebar {
|
|||||||
pad_to_width(spans, width, base)
|
pad_to_width(spans, width, base)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Which fill this session's card wears. The cursor wins on its own row,
|
||||||
|
/// so a highlight parked on the session already in the pane stays visible.
|
||||||
|
fn card_fill(&self, s: &Session, focused: bool) -> CardFill {
|
||||||
|
if focused && self.highlight == Some(SidebarItem::Session(s.id)) {
|
||||||
|
CardFill::Cursor
|
||||||
|
} else if self.pane_session == Some(s.id) {
|
||||||
|
CardFill::Pane
|
||||||
|
} else {
|
||||||
|
CardFill::None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn name_row(&self, s: &Session, width: usize, focused: bool) -> Vec<Span<'static>> {
|
fn name_row(&self, s: &Session, width: usize, focused: bool) -> Vec<Span<'static>> {
|
||||||
let glyph = match (s.status, self.attached.contains(&s.id)) {
|
let glyph = match (s.status, self.attached.contains(&s.id)) {
|
||||||
(SessionStatus::Dead, _) => "✗",
|
(SessionStatus::Dead, _) => "✗",
|
||||||
@@ -233,12 +272,13 @@ impl Sidebar {
|
|||||||
(SessionStatus::Running, false) => "○",
|
(SessionStatus::Running, false) => "○",
|
||||||
};
|
};
|
||||||
let highlighted = self.highlight == Some(SidebarItem::Session(s.id));
|
let highlighted = self.highlight == Some(SidebarItem::Session(s.id));
|
||||||
let base = card_base(highlighted, focused);
|
let fill = self.card_fill(s, focused);
|
||||||
|
let base = card_base(fill, focused);
|
||||||
let prefix = 1 + INDENT.chars().count() + 2;
|
let prefix = 1 + INDENT.chars().count() + 2;
|
||||||
let name_budget = width.saturating_sub(prefix);
|
let name_budget = width.saturating_sub(prefix);
|
||||||
|
|
||||||
let edge = highlighted && !focused;
|
let edge = highlighted && !focused;
|
||||||
let rail_style = base.fg(activity_color(s.activity, highlighted, focused));
|
let rail_style = base.fg(activity_color(s.activity, fill));
|
||||||
let mut spans: Vec<Span<'static>> = vec![
|
let mut spans: Vec<Span<'static>> = vec![
|
||||||
Span::styled(RAIL, rail_style),
|
Span::styled(RAIL, rail_style),
|
||||||
Span::styled(
|
Span::styled(
|
||||||
@@ -257,7 +297,7 @@ impl Sidebar {
|
|||||||
let name_style = if maestro_protocol::display::is_provisional_name(s) {
|
let name_style = if maestro_protocol::display::is_provisional_name(s) {
|
||||||
base.patch(
|
base.patch(
|
||||||
palette::active()
|
palette::active()
|
||||||
.surface(highlighted && focused)
|
.surface(fill.filled())
|
||||||
.muted_style()
|
.muted_style()
|
||||||
.bg(base.bg.unwrap_or(palette::active().chrome_bg)),
|
.bg(base.bg.unwrap_or(palette::active().chrome_bg)),
|
||||||
)
|
)
|
||||||
@@ -283,11 +323,11 @@ impl Sidebar {
|
|||||||
let blocked = s.blocked_work.filter(|b| !b.is_clear());
|
let blocked = s.blocked_work.filter(|b| !b.is_clear());
|
||||||
let dead = s.status == SessionStatus::Dead;
|
let dead = s.status == SessionStatus::Dead;
|
||||||
let highlighted = self.highlight == Some(SidebarItem::Session(s.id));
|
let highlighted = self.highlight == Some(SidebarItem::Session(s.id));
|
||||||
let base = card_base(highlighted, focused);
|
let fill = self.card_fill(s, focused);
|
||||||
let rail_style =
|
let base = card_base(fill, focused);
|
||||||
base.patch(Style::default().fg(activity_color(s.activity, highlighted, focused)));
|
let rail_style = base.patch(Style::default().fg(activity_color(s.activity, fill)));
|
||||||
let muted = palette::active()
|
let muted = palette::active()
|
||||||
.surface(highlighted && focused)
|
.surface(fill.filled())
|
||||||
.muted_style()
|
.muted_style()
|
||||||
.bg(base.bg.unwrap_or(palette::active().chrome_bg));
|
.bg(base.bg.unwrap_or(palette::active().chrome_bg));
|
||||||
let edge = highlighted && !focused;
|
let edge = highlighted && !focused;
|
||||||
@@ -308,7 +348,7 @@ impl Sidebar {
|
|||||||
let mut tail: Vec<Span<'static>> = Vec::new();
|
let mut tail: Vec<Span<'static>> = Vec::new();
|
||||||
if let Some(b) = blocked {
|
if let Some(b) = blocked {
|
||||||
let palette = palette::active();
|
let palette = palette::active();
|
||||||
let surface = palette.surface(highlighted && focused);
|
let surface = palette.surface(fill.filled());
|
||||||
for (kind, text) in b.stats() {
|
for (kind, text) in b.stats() {
|
||||||
let style = match kind {
|
let style = match kind {
|
||||||
StatKind::Added => muted.fg(surface.active),
|
StatKind::Added => muted.fg(surface.active),
|
||||||
@@ -352,10 +392,8 @@ impl Sidebar {
|
|||||||
/// state word is never spelled out — this colour carries it. The highlighted
|
/// state word is never spelled out — this colour carries it. The highlighted
|
||||||
/// card takes its state colours from the selection surface: a colour picked
|
/// card takes its state colours from the selection surface: a colour picked
|
||||||
/// for the dark card background is not legible on the selection background.
|
/// for the dark card background is not legible on the selection background.
|
||||||
fn activity_color(state: ActivityState, highlighted: bool, focused: bool) -> Color {
|
fn activity_color(state: ActivityState, fill: CardFill) -> Color {
|
||||||
palette::active()
|
palette::active().surface(fill.filled()).activity(state)
|
||||||
.surface(highlighted && focused)
|
|
||||||
.activity(state)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// docs/SIDEBAR.md duration format — floored whole seconds / minutes / hours,
|
/// docs/SIDEBAR.md duration format — floored whole seconds / minutes / hours,
|
||||||
@@ -521,6 +559,7 @@ mod tests {
|
|||||||
sessions: vec![session_named(1, "claude"), session_named(2, "bash")],
|
sessions: vec![session_named(1, "claude"), session_named(2, "bash")],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let rendered = render_to_string(&draw(&sb, 28, 12));
|
let rendered = render_to_string(&draw(&sb, 28, 12));
|
||||||
assert!(
|
assert!(
|
||||||
@@ -545,6 +584,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
})
|
})
|
||||||
.groups(&HashSet::new());
|
.groups(&HashSet::new());
|
||||||
assert_eq!(groups[0].key, PathBuf::from("/home/u/repos/maestro"));
|
assert_eq!(groups[0].key, PathBuf::from("/home/u/repos/maestro"));
|
||||||
@@ -556,6 +596,7 @@ mod tests {
|
|||||||
sessions: Vec::new(),
|
sessions: Vec::new(),
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
assert!(sidebar.groups(&HashSet::new()).is_empty());
|
assert!(sidebar.groups(&HashSet::new()).is_empty());
|
||||||
assert!(sidebar.rendered_items().is_empty());
|
assert!(sidebar.rendered_items().is_empty());
|
||||||
@@ -567,6 +608,7 @@ mod tests {
|
|||||||
sessions: vec![session_named(1, "claude"), session_named(2, "bash")],
|
sessions: vec![session_named(1, "claude"), session_named(2, "bash")],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let key = PathBuf::from("/tmp");
|
let key = PathBuf::from("/tmp");
|
||||||
let mut collapsed = HashSet::new();
|
let mut collapsed = HashSet::new();
|
||||||
@@ -591,6 +633,7 @@ mod tests {
|
|||||||
sessions: vec![session],
|
sessions: vec![session],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let key = PathBuf::from("/very/long/project/path/extraordinarily-long-project-name");
|
let key = PathBuf::from("/very/long/project/path/extraordinarily-long-project-name");
|
||||||
let collapsed = HashSet::from([key]);
|
let collapsed = HashSet::from([key]);
|
||||||
@@ -621,6 +664,7 @@ mod tests {
|
|||||||
sessions: vec![session_named(1, "claude")],
|
sessions: vec![session_named(1, "claude")],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sidebar, 40, 8));
|
let all = rows(&draw(&sidebar, 40, 8));
|
||||||
assert!(all[1].contains("/tmp"));
|
assert!(all[1].contains("/tmp"));
|
||||||
@@ -636,6 +680,7 @@ mod tests {
|
|||||||
sessions: vec![session_named(1, "claude")],
|
sessions: vec![session_named(1, "claude")],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: [sid].into_iter().collect(),
|
attached: [sid].into_iter().collect(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 28, 6));
|
let all = rows(&draw(&sb, 28, 6));
|
||||||
let line = row_containing(&all, "claude");
|
let line = row_containing(&all, "claude");
|
||||||
@@ -646,6 +691,87 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether any cell in the buffer is painted on `bg`.
|
||||||
|
fn any_cell_on(buf: &Buffer, bg: Color) -> bool {
|
||||||
|
(0..buf.area.height)
|
||||||
|
.any(|y| (0..buf.area.width).any(|x| buf[(x, y)].style().bg == Some(bg)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// docs/SIDEBAR.md: the session the pane is showing wears a fill, so it is
|
||||||
|
/// not the ● glyph alone carrying "this is the one on screen".
|
||||||
|
#[test]
|
||||||
|
fn the_session_in_the_pane_wears_the_pane_fill() {
|
||||||
|
let sid = Uuid::from_u128(1);
|
||||||
|
let p = palette::active();
|
||||||
|
let sb = Sidebar {
|
||||||
|
sessions: vec![session_named(1, "claude")],
|
||||||
|
highlight: None,
|
||||||
|
attached: [sid].into_iter().collect(),
|
||||||
|
pane_session: Some(sid),
|
||||||
|
};
|
||||||
|
assert!(any_cell_on(&draw(&sb, 28, 6), p.pane_row_bg()));
|
||||||
|
|
||||||
|
let none = Sidebar {
|
||||||
|
pane_session: None,
|
||||||
|
..sb
|
||||||
|
};
|
||||||
|
assert!(!any_cell_on(&draw(&none, 28, 6), p.pane_row_bg()));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cursor's fill wins on its own row: a highlight that lands on the
|
||||||
|
/// session already in the pane has to stay visible.
|
||||||
|
#[test]
|
||||||
|
fn the_cursor_outranks_the_pane_fill_on_its_own_row() {
|
||||||
|
let sid = Uuid::from_u128(1);
|
||||||
|
let p = palette::active();
|
||||||
|
let sb = Sidebar {
|
||||||
|
sessions: vec![session_named(1, "claude")],
|
||||||
|
highlight: Some(SidebarItem::Session(sid)),
|
||||||
|
attached: [sid].into_iter().collect(),
|
||||||
|
pane_session: Some(sid),
|
||||||
|
};
|
||||||
|
let buf = draw_with_focus(&sb, 28, 6, true);
|
||||||
|
assert!(any_cell_on(&buf, p.selection.bg), "cursor fill is missing");
|
||||||
|
assert!(
|
||||||
|
!any_cell_on(&buf, p.pane_row_bg()),
|
||||||
|
"the pane fill is showing through the cursor's own row"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A card the pane is showing is a filled row, so it takes the selection
|
||||||
|
/// surface's foregrounds — a colour picked for the card background is not
|
||||||
|
/// legible on a fill.
|
||||||
|
#[test]
|
||||||
|
fn the_pane_row_carries_selection_foregrounds() {
|
||||||
|
let sid = Uuid::from_u128(1);
|
||||||
|
let p = palette::active();
|
||||||
|
let mut sess = session_named(1, "claude");
|
||||||
|
sess.activity = ActivityState::AwaitingInput;
|
||||||
|
let sb = Sidebar {
|
||||||
|
sessions: vec![sess],
|
||||||
|
highlight: None,
|
||||||
|
attached: [sid].into_iter().collect(),
|
||||||
|
pane_session: Some(sid),
|
||||||
|
};
|
||||||
|
let buf = draw(&sb, 28, 6);
|
||||||
|
let on_pane_row = |fg: Color| {
|
||||||
|
(0..buf.area.height).any(|y| {
|
||||||
|
(0..buf.area.width).any(|x| {
|
||||||
|
let st = buf[(x, y)].style();
|
||||||
|
st.bg == Some(p.pane_row_bg()) && st.fg == Some(fg)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
on_pane_row(p.selection.activity(ActivityState::AwaitingInput)),
|
||||||
|
"the rail must carry the state in the filled surface's colours"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!on_pane_row(p.card.activity(ActivityState::AwaitingInput)),
|
||||||
|
"a card surface colour is painted onto the pane fill"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dead_session_uses_cross_glyph() {
|
fn dead_session_uses_cross_glyph() {
|
||||||
let mut sess = session_named(1, "claude");
|
let mut sess = session_named(1, "claude");
|
||||||
@@ -654,6 +780,7 @@ mod tests {
|
|||||||
sessions: vec![sess],
|
sessions: vec![sess],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw(&sb, 28, 6);
|
let buf = draw(&sb, 28, 6);
|
||||||
let all = rows(&buf);
|
let all = rows(&buf);
|
||||||
@@ -682,6 +809,7 @@ mod tests {
|
|||||||
sessions: vec![blocked, clear, unprobed],
|
sessions: vec![blocked, clear, unprobed],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 44, 10));
|
let all = rows(&draw(&sb, 44, 10));
|
||||||
|
|
||||||
@@ -728,6 +856,7 @@ mod tests {
|
|||||||
sessions: vec![generated, settled],
|
sessions: vec![generated, settled],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw(&sb, 44, 8);
|
let buf = draw(&sb, 44, 8);
|
||||||
let palette = palette::active();
|
let palette = palette::active();
|
||||||
@@ -760,6 +889,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw(&sb, 44, 8);
|
let buf = draw(&sb, 44, 8);
|
||||||
let palette = palette::active();
|
let palette = palette::active();
|
||||||
@@ -786,6 +916,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 28, 8));
|
let all = rows(&draw(&sb, 28, 8));
|
||||||
assert_eq!(content(&all[0]), "sessions");
|
assert_eq!(content(&all[0]), "sessions");
|
||||||
@@ -817,6 +948,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 28, 8));
|
let all = rows(&draw(&sb, 28, 8));
|
||||||
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
||||||
@@ -856,6 +988,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw(&sb, 28, 8);
|
let buf = draw(&sb, 28, 8);
|
||||||
let found = (0..buf.area.height)
|
let found = (0..buf.area.height)
|
||||||
@@ -884,6 +1017,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw(&sb, 28, 8);
|
let buf = draw(&sb, 28, 8);
|
||||||
let on_selection = |fg: Color| {
|
let on_selection = |fg: Color| {
|
||||||
@@ -923,6 +1057,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 28, 8));
|
let all = rows(&draw(&sb, 28, 8));
|
||||||
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
||||||
@@ -942,6 +1077,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 60, 6));
|
let all = rows(&draw(&sb, 60, 6));
|
||||||
let meta = content(&all[3]);
|
let meta = content(&all[3]);
|
||||||
@@ -970,6 +1106,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 28, 8));
|
let all = rows(&draw(&sb, 28, 8));
|
||||||
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
||||||
@@ -999,6 +1136,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 40, 8));
|
let all = rows(&draw(&sb, 40, 8));
|
||||||
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
||||||
@@ -1026,6 +1164,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 40, 8));
|
let all = rows(&draw(&sb, 40, 8));
|
||||||
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
||||||
@@ -1054,6 +1193,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 42, 8));
|
let all = rows(&draw(&sb, 42, 8));
|
||||||
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
let idx = all.iter().position(|l| l.contains("claude")).unwrap();
|
||||||
@@ -1087,6 +1227,7 @@ mod tests {
|
|||||||
sessions: vec![legacy],
|
sessions: vec![legacy],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let rendered = render_to_string(&draw(&sb, 40, 8));
|
let rendered = render_to_string(&draw(&sb, 40, 8));
|
||||||
assert!(
|
assert!(
|
||||||
@@ -1130,6 +1271,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let rendered = render_to_string(&draw(&sb, 28, 6));
|
let rendered = render_to_string(&draw(&sb, 28, 6));
|
||||||
assert!(
|
assert!(
|
||||||
@@ -1145,6 +1287,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 40, 6));
|
let all = rows(&draw(&sb, 40, 6));
|
||||||
assert!(
|
assert!(
|
||||||
@@ -1166,6 +1309,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 9, 6));
|
let all = rows(&draw(&sb, 9, 6));
|
||||||
assert!(
|
assert!(
|
||||||
@@ -1192,6 +1336,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 29, 6));
|
let all = rows(&draw(&sb, 29, 6));
|
||||||
assert!(all[3].contains("~1"), "{:?}", all[3]);
|
assert!(all[3].contains("~1"), "{:?}", all[3]);
|
||||||
@@ -1216,6 +1361,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 40, 6));
|
let all = rows(&draw(&sb, 40, 6));
|
||||||
assert!(all[3].contains("~1"), "{:?}", all[3]);
|
assert!(all[3].contains("~1"), "{:?}", all[3]);
|
||||||
@@ -1237,6 +1383,7 @@ mod tests {
|
|||||||
sessions: vec![highlighted],
|
sessions: vec![highlighted],
|
||||||
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw(&sb, 28, 8);
|
let buf = draw(&sb, 28, 8);
|
||||||
for y in 0..buf.area.height {
|
for y in 0..buf.area.height {
|
||||||
@@ -1262,6 +1409,7 @@ mod tests {
|
|||||||
sessions: vec![one, two],
|
sessions: vec![one, two],
|
||||||
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw(&sb, 28, 8);
|
let buf = draw(&sb, 28, 8);
|
||||||
let all = rows(&buf);
|
let all = rows(&buf);
|
||||||
@@ -1297,6 +1445,7 @@ mod tests {
|
|||||||
sessions: vec![session_named(1, "claude")],
|
sessions: vec![session_named(1, "claude")],
|
||||||
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw_with_focus(&sb, 28, 8, false);
|
let buf = draw_with_focus(&sb, 28, 8, false);
|
||||||
let y = (0..buf.area.height)
|
let y = (0..buf.area.height)
|
||||||
@@ -1316,6 +1465,7 @@ mod tests {
|
|||||||
sessions: vec![session_named(1, "claude")],
|
sessions: vec![session_named(1, "claude")],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
},
|
},
|
||||||
28,
|
28,
|
||||||
8,
|
8,
|
||||||
@@ -1336,6 +1486,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: None,
|
highlight: None,
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let buf = draw(&sb, 28, 8);
|
let buf = draw(&sb, 28, 8);
|
||||||
let y = buf.content.iter().position(|c| c.symbol() == "c").unwrap() as u16 / buf.area.width;
|
let y = buf.content.iter().position(|c| c.symbol() == "c").unwrap() as u16 / buf.area.width;
|
||||||
@@ -1354,6 +1505,7 @@ mod tests {
|
|||||||
sessions: vec![session_named(1, "claude")],
|
sessions: vec![session_named(1, "claude")],
|
||||||
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 28, 8));
|
let all = rows(&draw(&sb, 28, 8));
|
||||||
let line = content(row_containing(&all, "claude"));
|
let line = content(row_containing(&all, "claude"));
|
||||||
@@ -1371,6 +1523,7 @@ mod tests {
|
|||||||
sessions: vec![one, two],
|
sessions: vec![one, two],
|
||||||
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 28, 8));
|
let all = rows(&draw(&sb, 28, 8));
|
||||||
let line = row_containing(&all, "bash");
|
let line = row_containing(&all, "bash");
|
||||||
@@ -1390,6 +1543,7 @@ mod tests {
|
|||||||
sessions: vec![s],
|
sessions: vec![s],
|
||||||
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
highlight: Some(SidebarItem::Session(Uuid::from_u128(1))),
|
||||||
attached: Default::default(),
|
attached: Default::default(),
|
||||||
|
pane_session: None,
|
||||||
};
|
};
|
||||||
let all = rows(&draw(&sb, 28, 8));
|
let all = rows(&draw(&sb, 28, 8));
|
||||||
let line = row_containing(&all, "an-unreasonably");
|
let line = row_containing(&all, "an-unreasonably");
|
||||||
|
|||||||
@@ -52,6 +52,10 @@ pub enum OverlayKind {
|
|||||||
/// so this stays comparable.
|
/// so this stays comparable.
|
||||||
Rename(Uuid),
|
Rename(Uuid),
|
||||||
Help,
|
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),
|
Toast(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+9
-2
@@ -45,8 +45,15 @@ mirroring the TUI's. `ctrl-a` is select-all in a browser; the web
|
|||||||
`preventDefault`s it, since selecting all of a terminal pane does nothing
|
`preventDefault`s it, since selecting all of a terminal pane does nothing
|
||||||
useful.
|
useful.
|
||||||
|
|
||||||
Only Ctrl-K gets an escape hatch. No other control character is intercepted, so
|
The leader itself needs the same kind of way back: holding it consumes every
|
||||||
none of them needs one.
|
press, on both clients, even before anything is bound behind it. Pressing it
|
||||||
|
twice — `ctrl-a ctrl-a` by default — sends one literal leader byte to the
|
||||||
|
focused pane and clears the pending chord, the way tmux resolves a doubled
|
||||||
|
prefix key. This chord is also built from the configured leader, so a
|
||||||
|
rebound leader carries its own escape hatch with it.
|
||||||
|
|
||||||
|
Only Ctrl-K and the leader itself get an escape hatch. No other control
|
||||||
|
character is intercepted, so none of them needs one.
|
||||||
|
|
||||||
### Focus round-trip
|
### Focus round-trip
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,33 @@ The throwaway tab never counts as an open session: the tab bar does not appear
|
|||||||
because of it, the mobile shell does not switch away from the session list for
|
because of it, the mobile shell does not switch away from the session list for
|
||||||
it, and the sidebar does not mark the session as open.
|
it, and the sidebar does not mark the session as open.
|
||||||
|
|
||||||
|
## How a preview reads
|
||||||
|
|
||||||
|
A preview is provisional, so it never wears the accent — the accent is what
|
||||||
|
says "this is the one you picked". It has a hue of its own, and every surface
|
||||||
|
involved in the preview carries that same hue, so the pane and the row it came
|
||||||
|
from read as one thing rather than two unrelated highlights.
|
||||||
|
|
||||||
|
Web client (`--preview` and friends in `web/src/styles.css`):
|
||||||
|
|
||||||
|
| Surface | While previewing |
|
||||||
|
|---|---|
|
||||||
|
| The previewed pane's titlebar | Tinted in the preview hue, at full strength, in place of the focused pane's accent tint. |
|
||||||
|
| The canvas | A `preview` chip, top right, and a dashed inset ring. |
|
||||||
|
| A throwaway tab | Dashed border, italic label. |
|
||||||
|
| The sidebar row being previewed | Filled with the preview hue, over whatever open state the row already had — but the row of the session already showing in the pane keeps its accent fill, since previewing it changes nothing on screen. |
|
||||||
|
| A hovered sidebar row, and the keyboard cursor on a session | A lighter wash of the same hue, because both are what previews a row. |
|
||||||
|
|
||||||
|
Rows say it with fill, not with an edge — see the tier ladder in
|
||||||
|
`docs/SIDEBAR.md`, which previewing sits at the bottom of. The dashed edges
|
||||||
|
belong to the pane: the canvas ring and the throwaway tab.
|
||||||
|
|
||||||
|
The hue is a palette token, not a fixed colour: a palette whose accent already
|
||||||
|
sits on it moves it (`--preview-h`), so "previewing" and "picked" never collide.
|
||||||
|
|
||||||
|
The TUI marks a preview in text only — the title bar reads `<name> · preview`
|
||||||
|
— and has no preview colour role yet.
|
||||||
|
|
||||||
## What ends a preview
|
## What ends a preview
|
||||||
|
|
||||||
- The highlight moves to another session — that session is previewed instead.
|
- The highlight moves to another session — that session is previewed instead.
|
||||||
|
|||||||
@@ -177,6 +177,38 @@ surface; a colour chosen for the card background is never painted onto the
|
|||||||
selection background. Contrast is a property of the palette (values are RGB)
|
selection background. Contrast is a property of the palette (values are RGB)
|
||||||
and is asserted in the palette's tests, not left to the terminal theme.
|
and is asserted in the palette's tests, not left to the terminal theme.
|
||||||
|
|
||||||
|
## Which row is filled
|
||||||
|
|
||||||
|
Both clients say every one of these with a **background fill**, never an edge.
|
||||||
|
A row is usually several of them at once, so they form a ladder: the tier
|
||||||
|
furthest down wins the paint.
|
||||||
|
|
||||||
|
| Tier | Web | TUI |
|
||||||
|
|---|---|---|
|
||||||
|
| Alive | 6% accent wash | — (the rail carries it) |
|
||||||
|
| Under the pointer or the keyboard walk | preview hue, light | selection surface, while the sidebar holds the keyboard |
|
||||||
|
| Open in some pane, not the focused one | 6% accent wash (`.is-open`) | — (the `●` glyph carries it) |
|
||||||
|
| Showing in the pane | `--accent-fill` | `pane_row_bg()` — partway from the card surface to the selection surface |
|
||||||
|
| Previewing (`docs/PREVIEW.md`), unless that row is the one showing in the pane | `--preview-tint` | — (no preview colour role yet) |
|
||||||
|
|
||||||
|
The web ladder is written as one ordered run of equal-specificity rules in
|
||||||
|
`styles.css`, every qualifier inside `:where()`, so the order they appear in
|
||||||
|
*is* the precedence. Add a tier where it belongs in that run, never by piling
|
||||||
|
on another class to out-weigh the rule above it.
|
||||||
|
|
||||||
|
The TUI's two filled tiers both carry the **selection** surface's foregrounds,
|
||||||
|
since those are the colours picked for a filled row. `pane_row_bg()` is
|
||||||
|
blended from the two surfaces rather than shipped as a third one — a third
|
||||||
|
surface would mean eight more colours hand-picked seventeen times — and the
|
||||||
|
palette tests assert it stays a visible step from both. The cursor's fill wins
|
||||||
|
on its own row, so a highlight parked on the session already in the pane is
|
||||||
|
still visible.
|
||||||
|
|
||||||
|
The one edge left in either list is the TUI's `▏` marker, which stands in for
|
||||||
|
the cursor's fill while the pane holds the keyboard, and the web's ring on a
|
||||||
|
highlighted **folder** row — a folder previews nothing, so it has no fill to
|
||||||
|
step up to.
|
||||||
|
|
||||||
The duration text inherits its state's colour; the exited and command
|
The duration text inherits its state's colour; the exited and command
|
||||||
fragments use the surface's `muted` role, as do the diff stat's `~`, `?` and
|
fragments use the surface's `muted` role, as do the diff stat's `~`, `?` and
|
||||||
`↑` fragments. Only `+` and `-` step outside the surface's muted role, and they
|
`↑` fragments. Only `+` and `-` step outside the surface's muted role, and they
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ export interface AttachConnection {
|
|||||||
onUnmount(): void;
|
onUnmount(): void;
|
||||||
/** Put the keyboard back into this terminal — what leaving the sidebar does. */
|
/** Put the keyboard back into this terminal — what leaving the sidebar does. */
|
||||||
focusTerminal(): void;
|
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. */
|
/** Fully disconnect: close the WS, dispose the terminal, remove the element. */
|
||||||
dispose(): void;
|
dispose(): void;
|
||||||
}
|
}
|
||||||
@@ -506,6 +510,9 @@ export function createAttachConnection(
|
|||||||
focusTerminal() {
|
focusTerminal() {
|
||||||
term.focus();
|
term.focus();
|
||||||
},
|
},
|
||||||
|
// The closure above: the same bytes-out path keystrokes and the mobile key
|
||||||
|
// bar already take.
|
||||||
|
sendInput,
|
||||||
dispose() {
|
dispose() {
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
disposed = true;
|
disposed = true;
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
// @vitest-environment happy-dom
|
||||||
|
//
|
||||||
|
// The sidebar's half of the command bar's action page (#151): the bar picks
|
||||||
|
// kill or rename and raises the flow the card already has, so what the page
|
||||||
|
// runs is what the ✕ button and the `r` key run.
|
||||||
|
import { afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { KILL_SESSION_EVENT, RENAME_SESSION_EVENT, renderSidebar } from "./catalog.js";
|
||||||
|
import type { CatalogListener, CatalogStore } from "./events.js";
|
||||||
|
import type { Session } from "./types.js";
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
Object.defineProperty(window, "localStorage", {
|
||||||
|
value: { getItem: () => null, setItem: () => {} },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
let mounted: { el: HTMLElement; dispose: () => void } | null = null;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
document.querySelector(".kill-dialog")?.remove();
|
||||||
|
mounted?.dispose();
|
||||||
|
mounted = null;
|
||||||
|
document.body.replaceChildren();
|
||||||
|
});
|
||||||
|
|
||||||
|
function session(overrides: Partial<Session> = {}): Session {
|
||||||
|
return {
|
||||||
|
id: "aaaaaaaa-0000-0000-0000-0000000000ff",
|
||||||
|
cwd: "/home/naps/tea/maestro",
|
||||||
|
command: "claude",
|
||||||
|
env: {},
|
||||||
|
metadata: { name: "amber-falcon" },
|
||||||
|
status: "Running",
|
||||||
|
created_at: "2026-08-24T10:00:00Z",
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function storeWith(sessions: Session[]): CatalogStore {
|
||||||
|
const state = { sessions: new Map(sessions.map((s) => [s.id, s])) };
|
||||||
|
return {
|
||||||
|
snapshot: () => state,
|
||||||
|
subscribe: (fn: CatalogListener) => {
|
||||||
|
fn(state);
|
||||||
|
return () => {};
|
||||||
|
},
|
||||||
|
} as unknown as CatalogStore;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mount(s: Session): HTMLElement {
|
||||||
|
const handle = renderSidebar(storeWith([s]));
|
||||||
|
mounted = handle;
|
||||||
|
document.body.appendChild(handle.el);
|
||||||
|
return handle.el;
|
||||||
|
}
|
||||||
|
|
||||||
|
function raise(name: string, s: Session): void {
|
||||||
|
document.dispatchEvent(new CustomEvent(name, { detail: s }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Let the kill chain's awaits (fetch, its json body) settle. */
|
||||||
|
async function flush(): Promise<void> {
|
||||||
|
for (let i = 0; i < 8; i++) await Promise.resolve();
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("kill from the action page", () => {
|
||||||
|
it("goes through the daemon, without a first confirmation", async () => {
|
||||||
|
const calls: string[] = [];
|
||||||
|
window.fetch = ((url: string, init?: RequestInit) => {
|
||||||
|
calls.push(`${init?.method ?? "GET"} ${url}`);
|
||||||
|
return Promise.resolve(new Response(null, { status: 204 }));
|
||||||
|
}) as typeof fetch;
|
||||||
|
const s = session();
|
||||||
|
mount(s);
|
||||||
|
raise(KILL_SESSION_EVENT, s);
|
||||||
|
await flush();
|
||||||
|
expect(calls).toContain(`DELETE /api/sessions/${s.id}`);
|
||||||
|
expect(document.querySelector(".kill-dialog")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("raises the existing confirm-and-blockers dialog on a guarded refusal", async () => {
|
||||||
|
window.fetch = ((url: string) => {
|
||||||
|
if (String(url).includes("force=true")) {
|
||||||
|
return Promise.resolve(new Response(null, { status: 204 }));
|
||||||
|
}
|
||||||
|
return Promise.resolve(
|
||||||
|
new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: {
|
||||||
|
code: "kill_guarded",
|
||||||
|
message: "worktree has unsaved work",
|
||||||
|
unsaved_work: { untracked_files: 1 },
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
{ status: 409, headers: { "content-type": "application/json" } },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}) as typeof fetch;
|
||||||
|
const s = session({ blocked_work: { untracked_files: 1 } });
|
||||||
|
mount(s);
|
||||||
|
raise(KILL_SESSION_EVENT, s);
|
||||||
|
await flush();
|
||||||
|
const dialog = document.querySelector(".kill-dialog");
|
||||||
|
expect(dialog?.getAttribute("aria-label")).toBe("Kill amber-falcon");
|
||||||
|
expect(dialog?.textContent).toContain("1 untracked file");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rename from the action page", () => {
|
||||||
|
it("expands the folder hiding the card, since the prompt lives in the card", () => {
|
||||||
|
window.fetch = (() => Promise.reject(new Error("offline"))) as typeof fetch;
|
||||||
|
const s = session();
|
||||||
|
const el = mount(s);
|
||||||
|
const folder = el.querySelector<HTMLElement>(".tree-folder-header");
|
||||||
|
folder?.click();
|
||||||
|
expect(el.querySelector(`[data-session-id="${s.id}"]`)).toBeNull();
|
||||||
|
raise(RENAME_SESSION_EVENT, s);
|
||||||
|
expect(el.querySelector<HTMLInputElement>(".leaf-rename")?.value).toBe("amber-falcon");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("raises the card's own prompt, pre-filled with the session's name", () => {
|
||||||
|
window.fetch = (() => Promise.reject(new Error("offline"))) as typeof fetch;
|
||||||
|
const s = session();
|
||||||
|
const el = mount(s);
|
||||||
|
raise(RENAME_SESSION_EVENT, s);
|
||||||
|
const input = el.querySelector<HTMLInputElement>(".leaf-rename");
|
||||||
|
expect(input?.value).toBe("amber-falcon");
|
||||||
|
expect(input?.getAttribute("aria-label")).toBe("Rename amber-falcon");
|
||||||
|
});
|
||||||
|
});
|
||||||
+97
-17
@@ -7,6 +7,7 @@ import { CommandSet, defineCommands } from "./commands.js";
|
|||||||
import { CatalogStore } from "./events.js";
|
import { CatalogStore } from "./events.js";
|
||||||
import type { InTheWay, Session } from "./types.js";
|
import type { InTheWay, Session } from "./types.js";
|
||||||
import {
|
import {
|
||||||
|
abbreviateCwd,
|
||||||
abbreviateFolderName,
|
abbreviateFolderName,
|
||||||
blockerStats,
|
blockerStats,
|
||||||
customSessionName,
|
customSessionName,
|
||||||
@@ -16,6 +17,7 @@ import {
|
|||||||
sessionBlockers,
|
sessionBlockers,
|
||||||
isProvisionalName,
|
isProvisionalName,
|
||||||
sessionName,
|
sessionName,
|
||||||
|
sessionTreePath,
|
||||||
} from "./types.js";
|
} from "./types.js";
|
||||||
import { splitCommand, toolIconSvg } from "./toolIcon.js";
|
import { splitCommand, toolIconSvg } from "./toolIcon.js";
|
||||||
import {
|
import {
|
||||||
@@ -37,6 +39,15 @@ export function requestOpenSpawn(): void {
|
|||||||
document.dispatchEvent(new CustomEvent(OPEN_SPAWN_EVENT));
|
document.dispatchEvent(new CustomEvent(OPEN_SPAWN_EVENT));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Ask the shell to open the command bar with an empty query. Dispatched by
|
||||||
|
* the sidebar's search field, which is the touch entry point to the bar
|
||||||
|
* (#157, docs/COMMAND-BAR.md "Touch entry"): there is no `ctrl-k` on a phone.
|
||||||
|
* Handled in main.ts, which owns the session snapshot the bar needs. */
|
||||||
|
export const OPEN_COMMAND_BAR_EVENT = "catalog-open-command-bar";
|
||||||
|
export function requestOpenCommandBar(): void {
|
||||||
|
document.dispatchEvent(new CustomEvent(OPEN_COMMAND_BAR_EVENT));
|
||||||
|
}
|
||||||
|
|
||||||
/** Ask the shell to hand the keyboard back to the focused pane's terminal —
|
/** Ask the shell to hand the keyboard back to the focused pane's terminal —
|
||||||
* what Tab in the sidebar list does. Handled in main.ts, which owns the
|
* what Tab in the sidebar list does. Handled in main.ts, which owns the
|
||||||
* connection pool. */
|
* connection pool. */
|
||||||
@@ -50,6 +61,17 @@ export const FOCUS_SIDEBAR_EVENT = "catalog-focus-sidebar";
|
|||||||
* ("Spawn similar"). Detail is the session being cloned. */
|
* ("Spawn similar"). Detail is the session being cloned. */
|
||||||
export const SPAWN_SIMILAR_EVENT = "catalog-spawn-similar";
|
export const SPAWN_SIMILAR_EVENT = "catalog-spawn-similar";
|
||||||
|
|
||||||
|
/** Ask the sidebar to kill a session — the command bar's action page picking
|
||||||
|
* `kill` (#151). Detail is the session. Handled here, so the kill goes
|
||||||
|
* through the same confirm-and-blockers flow the card's ✕ does
|
||||||
|
* (`docs/WORKTREES.md`); the bar never reimplements it. */
|
||||||
|
export const KILL_SESSION_EVENT = "catalog-kill-session";
|
||||||
|
|
||||||
|
/** Ask the sidebar to rename a session — the command bar's action page picking
|
||||||
|
* `rename` (#151). Detail is the session. The prompt is the card's own inline
|
||||||
|
* field, pre-filled with the session's name (`docs/SIDEBAR.md`). */
|
||||||
|
export const RENAME_SESSION_EVENT = "catalog-rename-session";
|
||||||
|
|
||||||
/** A session row was clicked (issue #133). The row's `href` drives normal
|
/** A session row was clicked (issue #133). The row's `href` drives normal
|
||||||
* hash navigation, but a split/drag can move focus without ever touching
|
* hash navigation, but a split/drag can move focus without ever touching
|
||||||
* `location.hash` — so a click back onto a session whose hash still
|
* `location.hash` — so a click back onto a session whose hash still
|
||||||
@@ -348,16 +370,12 @@ function beginRename(row: HTMLElement, s: Session): void {
|
|||||||
input.select();
|
input.select();
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderEmpty(filtering: boolean, onSpawn: () => void): HTMLElement {
|
// The tree has one empty state: no sessions at all. The old "No matches" one
|
||||||
|
// belonged to the inline substring filter, which the command bar replaced
|
||||||
|
// (#157) — the bar's own no-results state took over with it.
|
||||||
|
function renderEmpty(onSpawn: () => void): HTMLElement {
|
||||||
const el = document.createElement("div");
|
const el = document.createElement("div");
|
||||||
el.className = "empty";
|
el.className = "empty";
|
||||||
if (filtering) {
|
|
||||||
el.innerHTML = `
|
|
||||||
<div class="empty-glyph" aria-hidden="true">⌕</div>
|
|
||||||
<div class="empty-title">No matches</div>
|
|
||||||
<p class="empty-hint">No sessions match your search. Clear it to see everything.</p>`;
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
el.innerHTML = `
|
el.innerHTML = `
|
||||||
<div class="empty-glyph" aria-hidden="true">+</div>
|
<div class="empty-glyph" aria-hidden="true">+</div>
|
||||||
<div class="empty-title">No sessions yet</div>
|
<div class="empty-title">No sessions yet</div>
|
||||||
@@ -388,6 +406,9 @@ export interface SidebarHandle {
|
|||||||
setActive(id: string | null): void;
|
setActive(id: string | null): void;
|
||||||
/** Apply the full open/focused highlight state. */
|
/** Apply the full open/focused highlight state. */
|
||||||
setHighlights(h: SidebarHighlights): void;
|
setHighlights(h: SidebarHighlights): void;
|
||||||
|
/** Mark the row the content pane is previewing (docs/PREVIEW.md), or clear it
|
||||||
|
* with `null`. A preview is a view, not state, so this only paints. */
|
||||||
|
setPreview(sessionId: string | null): void;
|
||||||
/** Hand the keyboard to the session list, highlighting a row to walk from. */
|
/** Hand the keyboard to the session list, highlighting a row to walk from. */
|
||||||
focusList(): void;
|
focusList(): void;
|
||||||
/** Whether the session list currently holds DOM focus. */
|
/** Whether the session list currently holds DOM focus. */
|
||||||
@@ -425,12 +446,16 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
|||||||
// renders with absolute paths until it lands.
|
// renders with absolute paths until it lands.
|
||||||
let homeDir: string | undefined;
|
let homeDir: string | undefined;
|
||||||
|
|
||||||
|
// The field never holds a query: it is the touch entry point to the command
|
||||||
|
// bar (#157), so it is `readonly` — a tap opens the bar instead of raising an
|
||||||
|
// on-screen keyboard over a field nothing is typed into.
|
||||||
const searchHeader = document.createElement("header");
|
const searchHeader = document.createElement("header");
|
||||||
searchHeader.className = "sidebar-search";
|
searchHeader.className = "sidebar-search";
|
||||||
searchHeader.innerHTML = `
|
searchHeader.innerHTML = `
|
||||||
<input
|
<input
|
||||||
type="search"
|
type="search"
|
||||||
class="search"
|
class="search"
|
||||||
|
readonly
|
||||||
placeholder="Search sessions…"
|
placeholder="Search sessions…"
|
||||||
aria-label="Search sessions"
|
aria-label="Search sessions"
|
||||||
autocomplete="off"
|
autocomplete="off"
|
||||||
@@ -539,14 +564,30 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
|||||||
handle.addEventListener("pointerup", endDrag);
|
handle.addEventListener("pointerup", endDrag);
|
||||||
handle.addEventListener("pointercancel", endDrag);
|
handle.addEventListener("pointercancel", endDrag);
|
||||||
|
|
||||||
|
// Touch entry (#157): the field is a button that looks like a field. It
|
||||||
|
// never holds a query — focusing or tapping it hands the keyboard straight
|
||||||
|
// to the bar's own input, which is also why it blurs first: leaving the
|
||||||
|
// focus here would make the bar impossible to close without reopening it.
|
||||||
const search = searchHeader.querySelector(".search") as HTMLInputElement;
|
const search = searchHeader.querySelector(".search") as HTMLInputElement;
|
||||||
let filter = "";
|
const openBar = () => {
|
||||||
search.addEventListener("input", () => {
|
search.value = "";
|
||||||
filter = search.value;
|
search.blur();
|
||||||
refresh();
|
requestOpenCommandBar();
|
||||||
|
};
|
||||||
|
search.addEventListener("focus", openBar);
|
||||||
|
// A tap can land without a focus event (iOS Safari on a blurred field), so
|
||||||
|
// the pointer path opens the bar too; the blur above keeps the two from
|
||||||
|
// stacking two overlays.
|
||||||
|
search.addEventListener("pointerdown", (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
openBar();
|
||||||
});
|
});
|
||||||
|
|
||||||
let highlights: SidebarHighlights = { open: new Set(), focused: null };
|
let highlights: SidebarHighlights = { open: new Set(), focused: null };
|
||||||
|
// The previewed row is painted alongside the open/focused tiers so a
|
||||||
|
// re-render can't drop it, but it is never part of `highlights`: a preview
|
||||||
|
// is a view, and nothing about it is durable (docs/PREVIEW.md).
|
||||||
|
let previewing: string | null = null;
|
||||||
const applyHighlights = () => {
|
const applyHighlights = () => {
|
||||||
for (const n of treeHost.querySelectorAll<HTMLElement>(".tree-leaf")) {
|
for (const n of treeHost.querySelectorAll<HTMLElement>(".tree-leaf")) {
|
||||||
const id = n.dataset.sessionId;
|
const id = n.dataset.sessionId;
|
||||||
@@ -555,6 +596,7 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
|||||||
const open = highlights.open.has(id);
|
const open = highlights.open.has(id);
|
||||||
n.classList.toggle("is-active", focused);
|
n.classList.toggle("is-active", focused);
|
||||||
n.classList.toggle("is-open", open && !focused);
|
n.classList.toggle("is-open", open && !focused);
|
||||||
|
n.classList.toggle("is-previewing", previewing === id);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -695,8 +737,8 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
|||||||
if (renamingId !== null) return;
|
if (renamingId !== null) return;
|
||||||
const state = store.snapshot();
|
const state = store.snapshot();
|
||||||
const sessions = [...state.sessions.values()];
|
const sessions = [...state.sessions.values()];
|
||||||
const tree = buildTree(sessions, homeDir, filter);
|
const tree = buildTree(sessions, homeDir);
|
||||||
const signature = sessions.length === 0 ? `EMPTY:${filter.trim()}` : treeSignature(tree);
|
const signature = sessions.length === 0 ? "EMPTY" : treeSignature(tree);
|
||||||
if (signature === renderedSignature) {
|
if (signature === renderedSignature) {
|
||||||
for (const row of treeHost.querySelectorAll<HTMLElement>(".tree-leaf")) {
|
for (const row of treeHost.querySelectorAll<HTMLElement>(".tree-leaf")) {
|
||||||
const s = row.dataset.sessionId ? state.sessions.get(row.dataset.sessionId) : undefined;
|
const s = row.dataset.sessionId ? state.sessions.get(row.dataset.sessionId) : undefined;
|
||||||
@@ -707,9 +749,7 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
|||||||
renderedSignature = signature;
|
renderedSignature = signature;
|
||||||
treeHost.replaceChildren();
|
treeHost.replaceChildren();
|
||||||
if (sessions.length === 0) {
|
if (sessions.length === 0) {
|
||||||
treeHost.appendChild(
|
treeHost.appendChild(renderEmpty(() => requestOpenSpawn()));
|
||||||
renderEmpty(filter.trim().length > 0, () => requestOpenSpawn()),
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (tree.kind === "folder") {
|
if (tree.kind === "folder") {
|
||||||
@@ -737,6 +777,40 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
|||||||
};
|
};
|
||||||
document.addEventListener("catalog-rerender", rerenderHandler);
|
document.addEventListener("catalog-rerender", rerenderHandler);
|
||||||
|
|
||||||
|
// The command bar's action page (#151) picks an action and hands it here:
|
||||||
|
// both flows are the ones the card already has, reached by session rather
|
||||||
|
// than by row.
|
||||||
|
const killHandler = (ev: Event) => {
|
||||||
|
const s = (ev as CustomEvent<Session>).detail;
|
||||||
|
void requestKill(s, sessionName(s));
|
||||||
|
};
|
||||||
|
const renameHandler = (ev: Event) => {
|
||||||
|
const s = (ev as CustomEvent<Session>).detail;
|
||||||
|
const row = rowForSession(s);
|
||||||
|
if (row) beginRename(row, s);
|
||||||
|
};
|
||||||
|
document.addEventListener(KILL_SESSION_EVENT, killHandler);
|
||||||
|
document.addEventListener(RENAME_SESSION_EVENT, renameHandler);
|
||||||
|
|
||||||
|
/** The card a session is rendered as, expanding whatever folder hides it
|
||||||
|
* first: the rename prompt lives inside the card, so a collapsed folder
|
||||||
|
* would otherwise swallow the request. */
|
||||||
|
function rowForSession(s: Session): HTMLElement | null {
|
||||||
|
const find = () => treeHost.querySelector<HTMLElement>(`.tree-leaf[data-session-id="${s.id}"]`);
|
||||||
|
const found = find();
|
||||||
|
if (found) return found;
|
||||||
|
// Folder paths are the abbreviated directory's segments joined back up
|
||||||
|
// (see buildTree), so the session's own path is normalised the same way
|
||||||
|
// before it is compared against them.
|
||||||
|
const cwd = sessionTreePath(s);
|
||||||
|
const path = (cwd ? abbreviateCwd(cwd, homeDir) : "").split("/").filter(Boolean).join("/");
|
||||||
|
for (const folder of [...collapsed]) {
|
||||||
|
if (path === folder || path.startsWith(`${folder}/`)) collapsed.delete(folder);
|
||||||
|
}
|
||||||
|
rerenderHandler();
|
||||||
|
return find();
|
||||||
|
}
|
||||||
|
|
||||||
// "Spawn similar" (#28) is dispatched here and handled in main.ts, where the
|
// "Spawn similar" (#28) is dispatched here and handled in main.ts, where the
|
||||||
// multi-view controller can seed the spawn modal with the session's dir/command.
|
// multi-view controller can seed the spawn modal with the session's dir/command.
|
||||||
|
|
||||||
@@ -762,6 +836,10 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
|||||||
highlights = h;
|
highlights = h;
|
||||||
applyHighlights();
|
applyHighlights();
|
||||||
},
|
},
|
||||||
|
setPreview(sessionId: string | null) {
|
||||||
|
previewing = sessionId;
|
||||||
|
applyHighlights();
|
||||||
|
},
|
||||||
focusList() {
|
focusList() {
|
||||||
// Start from the session on screen — that is where the user's attention
|
// Start from the session on screen — that is where the user's attention
|
||||||
// already is — falling back to the standing highlight, then the top row.
|
// already is — falling back to the standing highlight, then the top row.
|
||||||
@@ -782,6 +860,8 @@ export function renderSidebar(store: CatalogStore, opts: SidebarOptions = {}): S
|
|||||||
// refusing to refresh.
|
// refusing to refresh.
|
||||||
renamingId = null;
|
renamingId = null;
|
||||||
document.removeEventListener("catalog-rerender", rerenderHandler);
|
document.removeEventListener("catalog-rerender", rerenderHandler);
|
||||||
|
document.removeEventListener(KILL_SESSION_EVENT, killHandler);
|
||||||
|
document.removeEventListener(RENAME_SESSION_EVENT, renameHandler);
|
||||||
unsubscribe();
|
unsubscribe();
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,723 @@
|
|||||||
|
// @vitest-environment happy-dom
|
||||||
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
import {
|
||||||
|
KILL_SESSION_EVENT,
|
||||||
|
RENAME_SESSION_EVENT,
|
||||||
|
SESSION_SELECT_EVENT,
|
||||||
|
SPAWN_SIMILAR_EVENT,
|
||||||
|
} from "./catalog.js";
|
||||||
|
import {
|
||||||
|
barGroups,
|
||||||
|
barRows,
|
||||||
|
closeCommandBar,
|
||||||
|
commandBarCandidates,
|
||||||
|
dedupeCommands,
|
||||||
|
directoryBarCandidates,
|
||||||
|
directoryCandidate,
|
||||||
|
isCommandBarOpen,
|
||||||
|
openCommandBar,
|
||||||
|
orderSessionsForBar,
|
||||||
|
parseBarQuery,
|
||||||
|
sessionBarCandidates,
|
||||||
|
sessionActionCandidates,
|
||||||
|
sessionCandidate,
|
||||||
|
SPAWN_DIRECTORY_EVENT,
|
||||||
|
} from "./commandBar.js";
|
||||||
|
import { COMMAND_SPECS, type Command } from "./commands.js";
|
||||||
|
import type { Session } from "./types.js";
|
||||||
|
|
||||||
|
function session(id: string, over: Partial<Session> = {}): Session {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
cwd: "/home/me/dev/api",
|
||||||
|
command: "bash",
|
||||||
|
env: {},
|
||||||
|
metadata: { name: id },
|
||||||
|
status: "Running",
|
||||||
|
created_at: "2026-01-01T00:00:00Z",
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
closeCommandBar();
|
||||||
|
document.body.replaceChildren();
|
||||||
|
});
|
||||||
|
|
||||||
|
function press(key: string, init: KeyboardEventInit = {}): void {
|
||||||
|
const input = document.querySelector(".cmdbar-input") as HTMLInputElement;
|
||||||
|
input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, ...init }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function type(value: string): void {
|
||||||
|
const input = document.querySelector(".cmdbar-input") as HTMLInputElement;
|
||||||
|
input.value = value;
|
||||||
|
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowNames(): string[] {
|
||||||
|
return [...document.querySelectorAll(".cmdbar-row-name")].map((r) => r.textContent ?? "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function activeName(): string | undefined {
|
||||||
|
return document.querySelector(".cmdbar-row.is-active .cmdbar-row-name")?.textContent ?? undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("empty-query ordering", () => {
|
||||||
|
it("sorts most recently focused first", () => {
|
||||||
|
const older = session("older", { last_focused_at: "2026-01-01T10:00:00Z" });
|
||||||
|
const newer = session("newer", { last_focused_at: "2026-01-01T11:00:00Z" });
|
||||||
|
expect(orderSessionsForBar([older, newer]).map((s) => s.id)).toEqual(["newer", "older"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sorts a never-focused session after every focused one, newest created first", () => {
|
||||||
|
const focused = session("focused", {
|
||||||
|
last_focused_at: "2020-01-01T00:00:00Z",
|
||||||
|
created_at: "2020-01-01T00:00:00Z",
|
||||||
|
});
|
||||||
|
const oldFresh = session("old-fresh", { created_at: "2026-01-01T00:00:00Z" });
|
||||||
|
const newFresh = session("new-fresh", { created_at: "2026-06-01T00:00:00Z" });
|
||||||
|
expect(orderSessionsForBar([oldFresh, newFresh, focused]).map((s) => s.id)).toEqual([
|
||||||
|
"focused",
|
||||||
|
"new-fresh",
|
||||||
|
"old-fresh",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sorts dead sessions after live ones regardless of recency", () => {
|
||||||
|
const deadRecent = session("dead", {
|
||||||
|
status: "Dead",
|
||||||
|
last_focused_at: "2026-06-01T00:00:00Z",
|
||||||
|
});
|
||||||
|
const liveStale = session("live", { last_focused_at: "2020-01-01T00:00:00Z" });
|
||||||
|
const liveNever = session("never");
|
||||||
|
expect(orderSessionsForBar([deadRecent, liveNever, liveStale]).map((s) => s.id)).toEqual([
|
||||||
|
"live",
|
||||||
|
"never",
|
||||||
|
"dead",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats a null last_focused_at as never focused", () => {
|
||||||
|
const nulled = session("nulled", { last_focused_at: null });
|
||||||
|
const stamped = session("stamped", { last_focused_at: "2020-01-01T00:00:00Z" });
|
||||||
|
expect(orderSessionsForBar([nulled, stamped]).map((s) => s.id)).toEqual(["stamped", "nulled"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("session candidates", () => {
|
||||||
|
it("carries the candidate table's fields, with the directory abbreviated", () => {
|
||||||
|
const s = session("api", {
|
||||||
|
metadata: { name: "api" },
|
||||||
|
command: "claude --resume",
|
||||||
|
current_cwd: "/home/me/dev/api",
|
||||||
|
});
|
||||||
|
expect(sessionCandidate(s, "/home/me")).toEqual({
|
||||||
|
kind: "session",
|
||||||
|
session: s,
|
||||||
|
fields: {
|
||||||
|
name: "api",
|
||||||
|
directory: "~/dev/api",
|
||||||
|
command: "claude --resume",
|
||||||
|
tool: "claude",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves the tool out when the program has no mark, and groups a worktree by its repo", () => {
|
||||||
|
const s = session("edit", {
|
||||||
|
metadata: {},
|
||||||
|
command: "hx src/",
|
||||||
|
worktree: { path: "/home/me/dev/api/wt/x", base_repo: "/home/me/dev/api" },
|
||||||
|
});
|
||||||
|
const candidate = sessionCandidate(s, "/home/me");
|
||||||
|
expect(candidate.fields.tool).toBeUndefined();
|
||||||
|
expect(candidate.fields.directory).toBe("~/dev/api");
|
||||||
|
// No `metadata.name`: the sidebar's fallback is the command line.
|
||||||
|
expect(candidate.fields.name).toBe("hx src/");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("builds candidates in the empty-query order", () => {
|
||||||
|
const a = session("a", { last_focused_at: "2026-01-01T10:00:00Z" });
|
||||||
|
const b = session("b", { last_focused_at: "2026-01-01T11:00:00Z" });
|
||||||
|
expect(sessionBarCandidates([a, b]).map((c) => c.session.id)).toEqual(["b", "a"]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("rows and grouping", () => {
|
||||||
|
it("an empty query keeps every session in input order", () => {
|
||||||
|
const candidates = sessionBarCandidates([session("a"), session("b")]);
|
||||||
|
expect(barRows("", candidates).map((r) => r.candidate.session.id)).toEqual(["a", "b"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("groups by kind without reordering the ranking", () => {
|
||||||
|
const candidates = sessionBarCandidates([
|
||||||
|
session("worker", { metadata: { name: "worker" }, current_cwd: "/home/me/dev/api" }),
|
||||||
|
session("api", { metadata: { name: "api" }, current_cwd: "/home/me/dev/web" }),
|
||||||
|
]);
|
||||||
|
const rows = barRows("api", candidates);
|
||||||
|
const groups = barGroups(rows);
|
||||||
|
expect(groups).toHaveLength(1);
|
||||||
|
expect(groups[0].title).toBe("Sessions");
|
||||||
|
expect(groups[0].results.map((r) => r.candidate.session.id)).toEqual(
|
||||||
|
rows.map((r) => r.candidate.session.id),
|
||||||
|
);
|
||||||
|
// F6: the name beats the directory, and the directory match highlights
|
||||||
|
// inside the directory.
|
||||||
|
expect(groups[0].results[0].candidate.session.id).toBe("api");
|
||||||
|
expect(groups[0].results[1].field).toBe("directory");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the overlay", () => {
|
||||||
|
const sessions = [
|
||||||
|
session("api", {
|
||||||
|
metadata: { name: "api" },
|
||||||
|
current_cwd: "/home/me/dev/api",
|
||||||
|
last_focused_at: "2026-01-01T11:00:00Z",
|
||||||
|
}),
|
||||||
|
session("worker", {
|
||||||
|
metadata: { name: "worker" },
|
||||||
|
current_cwd: "/home/me/dev/worker",
|
||||||
|
last_focused_at: "2026-01-01T10:00:00Z",
|
||||||
|
}),
|
||||||
|
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", commands: [], onOpenSession: () => {} },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
it("is a registry command, so the help overlay lists it", () => {
|
||||||
|
const spec = COMMAND_SPECS.find((s) => s.id === "bar.open");
|
||||||
|
expect(spec?.keys).toEqual(["ctrl-k"]);
|
||||||
|
expect(spec?.scope).toBe("global");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lists sessions by recency under a kind header on an empty query", () => {
|
||||||
|
open();
|
||||||
|
expect([...document.querySelectorAll(".cmdbar-group-title")].map((h) => h.textContent)).toEqual([
|
||||||
|
"Sessions",
|
||||||
|
]);
|
||||||
|
expect(rowNames()).toEqual(["api", "worker", "notes"]);
|
||||||
|
expect(activeName()).toBe("api");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opening twice leaves one overlay", () => {
|
||||||
|
open();
|
||||||
|
open();
|
||||||
|
expect(document.querySelectorAll(".cmdbar-overlay")).toHaveLength(1);
|
||||||
|
expect(isCommandBarOpen()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ranks a typed query through the matcher and highlights the matched range", () => {
|
||||||
|
open();
|
||||||
|
type("wor");
|
||||||
|
expect(rowNames()).toEqual(["worker"]);
|
||||||
|
const marks = [...document.querySelectorAll(".cmdbar-row-name mark")].map((m) => m.textContent);
|
||||||
|
expect(marks).toEqual(["wor"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("highlights inside the directory when that is the field that matched", () => {
|
||||||
|
open();
|
||||||
|
type("notes");
|
||||||
|
const row = document.querySelector(".cmdbar-row") as HTMLElement;
|
||||||
|
expect(row.dataset.sessionId).toBe("notes");
|
||||||
|
type("dev/wor");
|
||||||
|
expect(rowNames()).toEqual(["worker"]);
|
||||||
|
expect(
|
||||||
|
[...document.querySelectorAll(".cmdbar-row-meta mark")].map((m) => m.textContent).join(""),
|
||||||
|
).toBe("dev/wor");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders a no-results state rather than an empty list", () => {
|
||||||
|
open();
|
||||||
|
type("zzz");
|
||||||
|
expect(rowNames()).toEqual([]);
|
||||||
|
expect(document.querySelector(".cmdbar-empty")?.textContent).toBe("No matches");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("moves the highlight with the arrows and ctrl-p/ctrl-n, without wrapping", () => {
|
||||||
|
open();
|
||||||
|
press("ArrowUp");
|
||||||
|
expect(activeName()).toBe("api");
|
||||||
|
press("ArrowDown");
|
||||||
|
expect(activeName()).toBe("worker");
|
||||||
|
press("n", { ctrlKey: true });
|
||||||
|
expect(activeName()).toBe("notes");
|
||||||
|
press("ArrowDown");
|
||||||
|
expect(activeName()).toBe("notes");
|
||||||
|
press("p", { ctrlKey: true });
|
||||||
|
expect(activeName()).toBe("worker");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("puts the highlight back on the best row whenever the query changes", () => {
|
||||||
|
open();
|
||||||
|
press("ArrowDown");
|
||||||
|
expect(activeName()).toBe("worker");
|
||||||
|
type("o");
|
||||||
|
expect(activeName()).toBe(document.querySelector(".cmdbar-row-name")?.textContent);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opens the highlighted session through the shared open path on Enter", () => {
|
||||||
|
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", commands: [] });
|
||||||
|
press("ArrowDown");
|
||||||
|
press("Enter");
|
||||||
|
document.removeEventListener(SESSION_SELECT_EVENT, listener);
|
||||||
|
expect(seen).toEqual(["worker"]);
|
||||||
|
expect(isCommandBarOpen()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("Enter on an empty result list does nothing", () => {
|
||||||
|
const onOpenSession = vi.fn();
|
||||||
|
open({ sessions, homeDir: "/home/me", commands: [], onOpenSession });
|
||||||
|
type("zzz");
|
||||||
|
press("Enter");
|
||||||
|
expect(onOpenSession).not.toHaveBeenCalled();
|
||||||
|
expect(isCommandBarOpen()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("closes on Escape and on a press outside the panel", () => {
|
||||||
|
open();
|
||||||
|
press("Escape");
|
||||||
|
expect(isCommandBarOpen()).toBe(false);
|
||||||
|
|
||||||
|
open();
|
||||||
|
(document.querySelector(".cmdbar-overlay") as HTMLElement).dispatchEvent(
|
||||||
|
new MouseEvent("mousedown", { bubbles: true }),
|
||||||
|
);
|
||||||
|
expect(isCommandBarOpen()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stays open for a press inside the panel", () => {
|
||||||
|
open();
|
||||||
|
(document.querySelector(".cmdbar-panel") as HTMLElement).dispatchEvent(
|
||||||
|
new MouseEvent("mousedown", { bubbles: true }),
|
||||||
|
);
|
||||||
|
expect(isCommandBarOpen()).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns the keyboard to whatever held it when it opened", () => {
|
||||||
|
const before = document.createElement("button");
|
||||||
|
document.body.appendChild(before);
|
||||||
|
before.focus();
|
||||||
|
open();
|
||||||
|
expect(document.activeElement).toBe(document.querySelector(".cmdbar-input"));
|
||||||
|
press("Escape");
|
||||||
|
expect(document.activeElement).toBe(before);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("clicking a row opens that session", () => {
|
||||||
|
const onOpenSession = vi.fn();
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the session action page (#151)", () => {
|
||||||
|
const sessions = [
|
||||||
|
session("api", {
|
||||||
|
metadata: { name: "api" },
|
||||||
|
current_cwd: "/home/me/dev/api",
|
||||||
|
last_focused_at: "2026-01-01T11:00:00Z",
|
||||||
|
}),
|
||||||
|
session("worker", {
|
||||||
|
metadata: { name: "worker" },
|
||||||
|
current_cwd: "/home/me/dev/worker",
|
||||||
|
last_focused_at: "2026-01-01T10:00:00Z",
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
|
||||||
|
function open(over: Partial<Parameters<typeof openCommandBar>[0]> = {}) {
|
||||||
|
return openCommandBar({
|
||||||
|
sessions,
|
||||||
|
homeDir: "/home/me",
|
||||||
|
commands: [],
|
||||||
|
onOpenSession: () => {},
|
||||||
|
...over,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function headerText(): string | undefined {
|
||||||
|
return document.querySelector(".cmdbar-page-header")?.textContent ?? undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
it("lists kill, rename and spawn similar for the highlighted session", () => {
|
||||||
|
open();
|
||||||
|
press("Tab");
|
||||||
|
expect(rowNames()).toEqual(["Kill session", "Rename session", "Spawn similar"]);
|
||||||
|
expect(activeName()).toBe("Kill session");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("names the session being acted on", () => {
|
||||||
|
open();
|
||||||
|
press("ArrowDown");
|
||||||
|
press("Tab");
|
||||||
|
expect(headerText()).toContain("worker");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("drops the kind headers, since the page is one kind", () => {
|
||||||
|
open();
|
||||||
|
press("Tab");
|
||||||
|
expect(document.querySelectorAll(".cmdbar-group-title")).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stays fuzzy-searchable over the three actions", () => {
|
||||||
|
open();
|
||||||
|
press("Tab");
|
||||||
|
type("ren");
|
||||||
|
expect(rowNames()).toEqual(["Rename session"]);
|
||||||
|
type("spwn");
|
||||||
|
expect(rowNames()).toEqual(["Spawn similar"]);
|
||||||
|
type("zzz");
|
||||||
|
expect(document.querySelector(".cmdbar-empty")?.textContent).toBe("No matches");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does nothing on a command row", () => {
|
||||||
|
openCommandBar({
|
||||||
|
sessions,
|
||||||
|
homeDir: "/home/me",
|
||||||
|
commands: [{ ...COMMAND_SPECS[0], run: () => {} } as Command],
|
||||||
|
onOpenSession: () => {},
|
||||||
|
});
|
||||||
|
type(">");
|
||||||
|
const before = rowNames();
|
||||||
|
press("Tab");
|
||||||
|
expect(rowNames()).toEqual(before);
|
||||||
|
expect(headerText()).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does nothing on a directory row", async () => {
|
||||||
|
open({ loadDirectories: () => Promise.resolve(["/home/me/dev/api"]) });
|
||||||
|
type("~");
|
||||||
|
await Promise.resolve();
|
||||||
|
press("Tab");
|
||||||
|
expect(rowNames()).toEqual(["~/dev/api"]);
|
||||||
|
expect(headerText()).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns to the result list on Escape, with the previous query intact", () => {
|
||||||
|
open();
|
||||||
|
type("wor");
|
||||||
|
press("Tab");
|
||||||
|
expect(headerText()).toContain("worker");
|
||||||
|
press("Escape");
|
||||||
|
expect(isCommandBarOpen()).toBe(true);
|
||||||
|
expect(headerText()).toBeUndefined();
|
||||||
|
expect((document.querySelector(".cmdbar-input") as HTMLInputElement).value).toBe("wor");
|
||||||
|
expect(rowNames()).toEqual(["worker"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns to the result list on backspace at an empty query", () => {
|
||||||
|
open();
|
||||||
|
type("wor");
|
||||||
|
press("Tab");
|
||||||
|
type("");
|
||||||
|
press("Backspace");
|
||||||
|
expect(headerText()).toBeUndefined();
|
||||||
|
expect((document.querySelector(".cmdbar-input") as HTMLInputElement).value).toBe("wor");
|
||||||
|
expect(rowNames()).toEqual(["worker"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps backspace ordinary while the page's query has text", () => {
|
||||||
|
open();
|
||||||
|
press("Tab");
|
||||||
|
type("ren");
|
||||||
|
press("Backspace");
|
||||||
|
expect(headerText()).toContain("api");
|
||||||
|
expect(rowNames()).toEqual(["Rename session"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("closes the bar when the page's Escape has already been used", () => {
|
||||||
|
open();
|
||||||
|
press("Tab");
|
||||||
|
press("Escape");
|
||||||
|
press("Escape");
|
||||||
|
expect(isCommandBarOpen()).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("raises kill, rename and spawn similar with the session, closing the bar", () => {
|
||||||
|
const seen: string[] = [];
|
||||||
|
for (const [hook, key] of [
|
||||||
|
["onKillSession", "Kill session"],
|
||||||
|
["onRenameSession", "Rename session"],
|
||||||
|
["onSpawnSimilar", "Spawn similar"],
|
||||||
|
] as const) {
|
||||||
|
open({ [hook]: (s: Session) => seen.push(`${hook}:${s.id}`) });
|
||||||
|
type("wor");
|
||||||
|
press("Tab");
|
||||||
|
type(key);
|
||||||
|
press("Enter");
|
||||||
|
expect(isCommandBarOpen()).toBe(false);
|
||||||
|
}
|
||||||
|
expect(seen).toEqual([
|
||||||
|
"onKillSession:worker",
|
||||||
|
"onRenameSession:worker",
|
||||||
|
"onSpawnSimilar:worker",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("hands each action to the flow it already has, by default", () => {
|
||||||
|
const seen: string[] = [];
|
||||||
|
const listeners: Array<[string, EventListener]> = [
|
||||||
|
[KILL_SESSION_EVENT, (e) => seen.push(`kill:${(e as CustomEvent<Session>).detail.id}`)],
|
||||||
|
[RENAME_SESSION_EVENT, (e) => seen.push(`rename:${(e as CustomEvent<Session>).detail.id}`)],
|
||||||
|
[SPAWN_SIMILAR_EVENT, (e) => seen.push(`similar:${(e as CustomEvent<Session>).detail.id}`)],
|
||||||
|
];
|
||||||
|
for (const [name, fn] of listeners) document.addEventListener(name, fn);
|
||||||
|
try {
|
||||||
|
for (const action of ["Kill session", "Rename session", "Spawn similar"]) {
|
||||||
|
open();
|
||||||
|
press("Tab");
|
||||||
|
type(action);
|
||||||
|
press("Enter");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
for (const [name, fn] of listeners) document.removeEventListener(name, fn);
|
||||||
|
}
|
||||||
|
expect(seen).toEqual(["kill:api", "rename:api", "similar:api"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("offers no action beyond the three", () => {
|
||||||
|
expect(sessionActionCandidates().map((c) => c.action.id)).toEqual([
|
||||||
|
"kill",
|
||||||
|
"rename",
|
||||||
|
"spawn-similar",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,809 @@
|
|||||||
|
// The `ctrl-k` command bar (docs/COMMAND-BAR.md): a query line over a result
|
||||||
|
// list, opened from the sidebar, closed with Escape.
|
||||||
|
//
|
||||||
|
// Three kinds live here: sessions and commands, ranked together by default,
|
||||||
|
// and directories, which need the `~` sigil. `tab` on a session drills into
|
||||||
|
// its action page (#151), which is the same overlay over three actions.
|
||||||
|
|
||||||
|
import { listDir, projects as fetchProjects, recentDirs } from "./api.js";
|
||||||
|
import {
|
||||||
|
KILL_SESSION_EVENT,
|
||||||
|
RENAME_SESSION_EVENT,
|
||||||
|
SESSION_SELECT_EVENT,
|
||||||
|
SPAWN_SIMILAR_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 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 };
|
||||||
|
|
||||||
|
/** One row of a session's action page. It is a `command` to the matcher — a
|
||||||
|
* single `label` field, ranked exactly like a registry command — and carries
|
||||||
|
* the action it stands for instead of a registry entry. */
|
||||||
|
export type ActionBarCandidate = CommandCandidate & { action: SessionAction };
|
||||||
|
|
||||||
|
export type BarCandidate =
|
||||||
|
SessionBarCandidate | CommandBarCandidate | ActionBarCandidate | 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<C extends BarCandidate = BarCandidate> {
|
||||||
|
kind: CandidateKind;
|
||||||
|
title: string;
|
||||||
|
results: MatchResult<C>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const KIND_TITLES: Record<CandidateKind, string> = {
|
||||||
|
session: "Sessions",
|
||||||
|
command: "Commands",
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the session action page ----
|
||||||
|
|
||||||
|
/** The actions a session's action page offers, and no others: the bar picks
|
||||||
|
* one and hands off to the flow that already implements it
|
||||||
|
* (docs/COMMAND-BAR.md, "Drill-in"). */
|
||||||
|
export type SessionActionId = "kill" | "rename" | "spawn-similar";
|
||||||
|
|
||||||
|
export interface SessionAction {
|
||||||
|
id: SessionActionId;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const SESSION_ACTIONS: readonly SessionAction[] = [
|
||||||
|
{ id: "kill", label: "Kill session" },
|
||||||
|
{ id: "rename", label: "Rename session" },
|
||||||
|
{ id: "spawn-similar", label: "Spawn similar" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** The action page's candidates, in the order above — which is the order an
|
||||||
|
* empty query lists them in, since the matcher keeps input order. */
|
||||||
|
export function sessionActionCandidates(): ActionBarCandidate[] {
|
||||||
|
return SESSION_ACTIONS.map((action) => ({
|
||||||
|
kind: "command",
|
||||||
|
action,
|
||||||
|
fields: { label: action.label },
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Narrow a `command` candidate to an action row. Both share the matcher's
|
||||||
|
* `command` kind, so what separates them is what they carry. */
|
||||||
|
export function isActionCandidate(candidate: BarCandidate): candidate is ActionBarCandidate {
|
||||||
|
return candidate.kind === "command" && "action" in candidate;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- candidates ----
|
||||||
|
|
||||||
|
function focusedAt(s: Session): number | null {
|
||||||
|
const stamp = s.last_focused_at;
|
||||||
|
if (typeof stamp !== "string" || stamp === "") return null;
|
||||||
|
const ms = Date.parse(stamp);
|
||||||
|
return Number.isNaN(ms) ? null : ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
function createdAt(s: Session): number {
|
||||||
|
const ms = Date.parse(s.created_at ?? "");
|
||||||
|
return Number.isNaN(ms) ? 0 : ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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. */
|
||||||
|
export function orderSessionsForBar(sessions: readonly Session[]): Session[] {
|
||||||
|
return [...sessions].sort((a, b) => {
|
||||||
|
const deadA = a.status === "Dead" ? 1 : 0;
|
||||||
|
const deadB = b.status === "Dead" ? 1 : 0;
|
||||||
|
if (deadA !== deadB) return deadA - deadB;
|
||||||
|
|
||||||
|
const focusA = focusedAt(a);
|
||||||
|
const focusB = focusedAt(b);
|
||||||
|
if ((focusA === null) !== (focusB === null)) return focusA === null ? 1 : -1;
|
||||||
|
if (focusA !== null && focusB !== null && focusA !== focusB) return focusB - focusA;
|
||||||
|
|
||||||
|
return createdAt(b) - createdAt(a);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build one session's candidate: the fields docs/COMMAND-BAR.md's candidate
|
||||||
|
* table names, with the directory abbreviated the way the sidebar shows it. */
|
||||||
|
export function sessionCandidate(s: Session, homeDir?: string): SessionBarCandidate {
|
||||||
|
const treePath = sessionTreePath(s);
|
||||||
|
const directory = treePath ? abbreviateCwd(treePath, homeDir) : undefined;
|
||||||
|
const tool = splitCommand(s.command).tool ?? undefined;
|
||||||
|
return {
|
||||||
|
kind: "session",
|
||||||
|
session: s,
|
||||||
|
fields: {
|
||||||
|
name: sessionName(s),
|
||||||
|
...(directory ? { directory } : {}),
|
||||||
|
...(s.command ? { command: s.command } : {}),
|
||||||
|
...(tool ? { tool } : {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every session as a candidate, in the empty-query order. */
|
||||||
|
export function sessionBarCandidates(
|
||||||
|
sessions: readonly Session[],
|
||||||
|
homeDir?: string,
|
||||||
|
): SessionBarCandidate[] {
|
||||||
|
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<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);
|
||||||
|
if (!group) {
|
||||||
|
group = { kind, title: KIND_TITLES[kind], results: [] };
|
||||||
|
groups.push(group);
|
||||||
|
}
|
||||||
|
group.results.push(result);
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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<C extends BarCandidate>(
|
||||||
|
query: string,
|
||||||
|
candidates: readonly C[],
|
||||||
|
): MatchResult<C>[] {
|
||||||
|
return matchAndRank(query, candidates);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- rendering ----
|
||||||
|
|
||||||
|
/** Text with its matched ranges wrapped in `<mark>`. Ranges come from the
|
||||||
|
* matcher as `[start, end)` character pairs over the field that won. */
|
||||||
|
export function renderHighlighted(text: string, ranges: readonly MatchRange[]): DocumentFragment {
|
||||||
|
const frag = document.createDocumentFragment();
|
||||||
|
let cursor = 0;
|
||||||
|
for (const [start, end] of ranges) {
|
||||||
|
if (start > cursor) frag.append(text.slice(cursor, start));
|
||||||
|
const mark = document.createElement("mark");
|
||||||
|
mark.className = "cmdbar-hit";
|
||||||
|
mark.textContent = text.slice(start, end);
|
||||||
|
frag.append(mark);
|
||||||
|
cursor = end;
|
||||||
|
}
|
||||||
|
if (cursor < text.length) frag.append(text.slice(cursor));
|
||||||
|
return frag;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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":
|
||||||
|
return fields.directory;
|
||||||
|
case "command":
|
||||||
|
return fields.command;
|
||||||
|
case "tool":
|
||||||
|
return fields.tool;
|
||||||
|
default:
|
||||||
|
return fields.directory;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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.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 (isActionCandidate(candidate)) {
|
||||||
|
row.dataset.actionId = candidate.action.id;
|
||||||
|
} 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 = 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" && !isActionCandidate(candidate)) {
|
||||||
|
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");
|
||||||
|
el.className = "cmdbar-row-meta";
|
||||||
|
const highlighted = result.field !== undefined && result.field !== "name";
|
||||||
|
el.append(highlighted ? renderHighlighted(meta, result.ranges) : meta);
|
||||||
|
row.appendChild(el);
|
||||||
|
}
|
||||||
|
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 {
|
||||||
|
/** Sessions to build candidates from, as the store has them right now. */
|
||||||
|
sessions: readonly Session[];
|
||||||
|
/** The daemon's home dir, for the directory field's `~/…` abbreviation. */
|
||||||
|
homeDir?: string;
|
||||||
|
/** Open the highlighted session. Defaults to the shared open path — the
|
||||||
|
* 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;
|
||||||
|
/** The action page's three actions (#151). Each defaults to raising the
|
||||||
|
* event the flow that already implements it listens on — the sidebar's
|
||||||
|
* confirm-and-blockers kill, its inline rename prompt, the spawn form
|
||||||
|
* seeded from the session. The bar picks the action and nothing more. */
|
||||||
|
onKillSession?: (session: Session) => void;
|
||||||
|
onRenameSession?: (session: Session) => void;
|
||||||
|
onSpawnSimilar?: (session: Session) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OpenBar {
|
||||||
|
el: HTMLElement;
|
||||||
|
dispose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
let current: OpenBar | null = null;
|
||||||
|
|
||||||
|
export function isCommandBarOpen(): boolean {
|
||||||
|
return current !== null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function closeCommandBar(): void {
|
||||||
|
current?.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mount the bar. Opening while one is up replaces it, so a stray second call
|
||||||
|
* can never stack two overlays. */
|
||||||
|
export function openCommandBar(opts: CommandBarOptions): HTMLElement {
|
||||||
|
closeCommandBar();
|
||||||
|
|
||||||
|
// Closing returns the keyboard to whatever held it when the bar opened: a
|
||||||
|
// round trip through the bar never silently moves focus.
|
||||||
|
const previouslyFocused = document.activeElement as HTMLElement | null;
|
||||||
|
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 sessionEvent =
|
||||||
|
(name: string) =>
|
||||||
|
(session: Session): void => {
|
||||||
|
document.dispatchEvent(new CustomEvent(name, { detail: session }));
|
||||||
|
};
|
||||||
|
const killSession = opts.onKillSession ?? sessionEvent(KILL_SESSION_EVENT);
|
||||||
|
const renameSession = opts.onRenameSession ?? sessionEvent(RENAME_SESSION_EVENT);
|
||||||
|
const spawnSimilar = opts.onSpawnSimilar ?? sessionEvent(SPAWN_SIMILAR_EVENT);
|
||||||
|
const loadDirectories = opts.loadDirectories ?? loadBarDirectories;
|
||||||
|
const listEntries =
|
||||||
|
opts.listDirEntries ?? ((dir: string) => listDir(dir).then((listing) => listing.entries));
|
||||||
|
|
||||||
|
const sessionCandidates: SessionBarCandidate[] = sessionBarCandidates(
|
||||||
|
opts.sessions,
|
||||||
|
opts.homeDir,
|
||||||
|
);
|
||||||
|
const commandCandidates: CommandBarCandidate[] = commandBarCandidates(
|
||||||
|
opts.commands ?? publishedCommands(),
|
||||||
|
);
|
||||||
|
|
||||||
|
const el = document.createElement("div");
|
||||||
|
el.className = "cmdbar-overlay";
|
||||||
|
el.setAttribute("role", "dialog");
|
||||||
|
el.setAttribute("aria-modal", "true");
|
||||||
|
el.setAttribute("aria-label", "Command bar");
|
||||||
|
|
||||||
|
const panel = document.createElement("div");
|
||||||
|
panel.className = "cmdbar-panel";
|
||||||
|
|
||||||
|
const input = document.createElement("input");
|
||||||
|
input.type = "text";
|
||||||
|
input.className = "cmdbar-input";
|
||||||
|
input.setAttribute("role", "combobox");
|
||||||
|
input.setAttribute("aria-expanded", "true");
|
||||||
|
input.setAttribute("aria-controls", "cmdbar-results");
|
||||||
|
input.setAttribute("aria-label", "Search sessions, commands and directories");
|
||||||
|
input.setAttribute("autocomplete", "off");
|
||||||
|
input.spellcheck = false;
|
||||||
|
input.placeholder = PLACEHOLDERS.mixed;
|
||||||
|
|
||||||
|
const results = document.createElement("div");
|
||||||
|
results.className = "cmdbar-results";
|
||||||
|
results.id = "cmdbar-results";
|
||||||
|
results.setAttribute("role", "listbox");
|
||||||
|
|
||||||
|
panel.append(input, results);
|
||||||
|
el.appendChild(panel);
|
||||||
|
document.body.appendChild(el);
|
||||||
|
|
||||||
|
let rows: BarResult[] = [];
|
||||||
|
let highlighted = 0;
|
||||||
|
|
||||||
|
// The action page (#151). `page` is the session being acted on, `stashed`
|
||||||
|
// the result-list query it was drilled into from — backing out restores it,
|
||||||
|
// so the round trip costs the operator nothing.
|
||||||
|
let page: Session | null = null;
|
||||||
|
let stashed = "";
|
||||||
|
let header: HTMLElement | null = null;
|
||||||
|
|
||||||
|
// `~`'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[] {
|
||||||
|
if (page) return sessionActionCandidates();
|
||||||
|
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;
|
||||||
|
row.classList.toggle("is-active", active);
|
||||||
|
row.setAttribute("aria-selected", active ? "true" : "false");
|
||||||
|
if (active) {
|
||||||
|
row.scrollIntoView({ block: "nearest" });
|
||||||
|
input.setAttribute("aria-activedescendant", row.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rows.length === 0) input.removeAttribute("aria-activedescendant");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The line naming the session being acted on, so the target is never
|
||||||
|
* ambiguous. Present only while the action page is up. */
|
||||||
|
function paintHeader(): void {
|
||||||
|
header?.remove();
|
||||||
|
header = null;
|
||||||
|
if (!page) return;
|
||||||
|
header = document.createElement("div");
|
||||||
|
header.className = "cmdbar-page-header";
|
||||||
|
header.setAttribute("role", "presentation");
|
||||||
|
header.textContent = `Actions for "${sessionName(page)}"`;
|
||||||
|
panel.insertBefore(header, results);
|
||||||
|
}
|
||||||
|
|
||||||
|
function render(): void {
|
||||||
|
// On the action page the query line is over the three actions, so there is
|
||||||
|
// no sigil to read: `>` and `~` are ordinary characters there.
|
||||||
|
const parsed = page ? { sigil: null, query: input.value } : parseBarQuery(input.value);
|
||||||
|
input.placeholder = page
|
||||||
|
? `Act on ${sessionName(page)}…`
|
||||||
|
: PLACEHOLDERS[parsed.sigil ?? "mixed"];
|
||||||
|
paintHeader();
|
||||||
|
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;
|
||||||
|
results.replaceChildren();
|
||||||
|
|
||||||
|
if (rows.length === 0) {
|
||||||
|
const empty = document.createElement("div");
|
||||||
|
empty.className = "cmdbar-empty";
|
||||||
|
empty.textContent = "No matches";
|
||||||
|
results.appendChild(empty);
|
||||||
|
paintHighlight();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let index = 0;
|
||||||
|
for (const group of barGroups(rows)) {
|
||||||
|
// While a sigil is in force there is one kind, so the header is
|
||||||
|
// dropped — and the action page is one kind too.
|
||||||
|
if (parsed.sigil === null && !page) {
|
||||||
|
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);
|
||||||
|
row.addEventListener("click", () => activate(at));
|
||||||
|
results.appendChild(row);
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
paintHighlight();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The highlight does not wrap: it stops at the first and last row. */
|
||||||
|
function move(delta: number): void {
|
||||||
|
if (rows.length === 0) return;
|
||||||
|
highlighted = Math.min(rows.length - 1, Math.max(0, highlighted + delta));
|
||||||
|
paintHighlight();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `tab`: drill into the highlighted session's action page. No effect on any
|
||||||
|
* other kind, and none on the page itself, which has no session rows. */
|
||||||
|
function drillIn(): void {
|
||||||
|
const candidate = rows[highlighted]?.candidate;
|
||||||
|
if (page || candidate?.kind !== "session") return;
|
||||||
|
page = candidate.session;
|
||||||
|
stashed = input.value;
|
||||||
|
input.value = "";
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Escape, or backspace at an empty query: back to the result list with the
|
||||||
|
* query the drill-in was made from. */
|
||||||
|
function leavePage(): void {
|
||||||
|
page = null;
|
||||||
|
input.value = stashed;
|
||||||
|
stashed = "";
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
function runAction(action: SessionAction, session: Session): void {
|
||||||
|
close();
|
||||||
|
switch (action.id) {
|
||||||
|
case "kill":
|
||||||
|
killSession(session);
|
||||||
|
return;
|
||||||
|
case "rename":
|
||||||
|
renameSession(session);
|
||||||
|
return;
|
||||||
|
case "spawn-similar":
|
||||||
|
spawnSimilar(session);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function activate(index: number): void {
|
||||||
|
const result = rows[index];
|
||||||
|
if (!result) return;
|
||||||
|
const candidate = result.candidate;
|
||||||
|
if (isActionCandidate(candidate)) {
|
||||||
|
// The page cannot be up without a session to act on.
|
||||||
|
if (page) runAction(candidate.action, page);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
close();
|
||||||
|
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 {
|
||||||
|
switch (e.key) {
|
||||||
|
case "Escape":
|
||||||
|
e.preventDefault();
|
||||||
|
// On an action page Escape is one level up, not the way out.
|
||||||
|
if (page) leavePage();
|
||||||
|
else close();
|
||||||
|
return;
|
||||||
|
case "Tab":
|
||||||
|
e.preventDefault();
|
||||||
|
drillIn();
|
||||||
|
return;
|
||||||
|
case "Backspace":
|
||||||
|
// Ordinary editing, except at an empty query on the action page.
|
||||||
|
if (page && input.value === "") {
|
||||||
|
e.preventDefault();
|
||||||
|
leavePage();
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
case "Enter":
|
||||||
|
e.preventDefault();
|
||||||
|
activate(highlighted);
|
||||||
|
return;
|
||||||
|
case "ArrowDown":
|
||||||
|
e.preventDefault();
|
||||||
|
move(1);
|
||||||
|
return;
|
||||||
|
case "ArrowUp":
|
||||||
|
e.preventDefault();
|
||||||
|
move(-1);
|
||||||
|
return;
|
||||||
|
case "n":
|
||||||
|
if (e.ctrlKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
move(1);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
case "p":
|
||||||
|
if (e.ctrlKey) {
|
||||||
|
e.preventDefault();
|
||||||
|
move(-1);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function close(): void {
|
||||||
|
if (current?.el !== el) return;
|
||||||
|
current = null;
|
||||||
|
el.remove();
|
||||||
|
// Restoring focus is what makes the bar a view over the app rather than a
|
||||||
|
// place in it; a detached node cannot take it.
|
||||||
|
if (previouslyFocused?.isConnected) previouslyFocused.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
input.addEventListener("keydown", onKeydown);
|
||||||
|
input.addEventListener("input", render);
|
||||||
|
// A press on the scrim closes; one inside the panel is left alone.
|
||||||
|
el.addEventListener("mousedown", (ev) => {
|
||||||
|
if (!panel.contains(ev.target as Node)) close();
|
||||||
|
});
|
||||||
|
|
||||||
|
current = { el, dispose: close };
|
||||||
|
render();
|
||||||
|
input.focus();
|
||||||
|
return el;
|
||||||
|
}
|
||||||
@@ -6,10 +6,14 @@ import {
|
|||||||
CommandSet,
|
CommandSet,
|
||||||
DEFAULT_LEADER,
|
DEFAULT_LEADER,
|
||||||
canonicalizeKey,
|
canonicalizeKey,
|
||||||
|
controlByte,
|
||||||
defineCommands,
|
defineCommands,
|
||||||
|
isBarTypingTarget,
|
||||||
|
isTerminalTextarea,
|
||||||
isTypingTarget,
|
isTypingTarget,
|
||||||
keyCaps,
|
keyCaps,
|
||||||
publishedCommands,
|
publishedCommands,
|
||||||
|
type Command,
|
||||||
} from "./commands.js";
|
} from "./commands.js";
|
||||||
|
|
||||||
function key(k: string, init: KeyboardEventInit = {}): KeyboardEvent {
|
function key(k: string, init: KeyboardEventInit = {}): KeyboardEvent {
|
||||||
@@ -234,3 +238,133 @@ describe("isTypingTarget", () => {
|
|||||||
expect(isTypingTarget(null)).toBe(false);
|
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`]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("leader pressed twice (#158)", () => {
|
||||||
|
it("sends one literal leader byte and clears the pending chord", () => {
|
||||||
|
const literal = vi.fn();
|
||||||
|
const run = vi.fn();
|
||||||
|
const set = new CommandSet(
|
||||||
|
defineCommands({ "pane.literalLeader": literal, "spawn.open": run }),
|
||||||
|
{ leader: DEFAULT_LEADER },
|
||||||
|
);
|
||||||
|
const target = el('<textarea class="xterm-helper-textarea"></textarea>');
|
||||||
|
expect(pressOn(set, target, "a", { ctrlKey: true })).toBe(true);
|
||||||
|
expect(pressOn(set, target, "a", { ctrlKey: true })).toBe(true);
|
||||||
|
expect(literal).toHaveBeenCalledTimes(1);
|
||||||
|
// The chord is cleared, not still held: the next key is ordinary again.
|
||||||
|
expect(set.handle(key("n"))).toBe(true);
|
||||||
|
expect(run).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("binds the escape hatch behind the default leader", () => {
|
||||||
|
const spec = COMMAND_SPECS.find((s) => s.id === "pane.literalLeader");
|
||||||
|
expect(spec?.keys).toEqual([`${DEFAULT_LEADER} ${DEFAULT_LEADER}`]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Not just the default: the chord is resolved from whatever leader this
|
||||||
|
// set was constructed with, so a rebound leader carries the escape hatch
|
||||||
|
// with it — the same proof #156 wrote for the TUI. The web has no config
|
||||||
|
// for this yet (#159), but the mechanism must not be hardcoded to ctrl-a.
|
||||||
|
it("follows a rebound leader, not just the default", () => {
|
||||||
|
const literal = vi.fn();
|
||||||
|
const rebound: Command = {
|
||||||
|
id: "pane.literalLeader",
|
||||||
|
label: "Send a literal leader key to the pane",
|
||||||
|
group: "Pane",
|
||||||
|
scope: "global",
|
||||||
|
keys: ["ctrl-b ctrl-b"],
|
||||||
|
run: literal,
|
||||||
|
};
|
||||||
|
const set = new CommandSet([rebound], { leader: "ctrl-b" });
|
||||||
|
const target = el('<textarea class="xterm-helper-textarea"></textarea>');
|
||||||
|
expect(pressOn(set, target, "b", { ctrlKey: true })).toBe(true);
|
||||||
|
expect(pressOn(set, target, "b", { ctrlKey: true })).toBe(true);
|
||||||
|
expect(literal).toHaveBeenCalledTimes(1);
|
||||||
|
// The old leader no longer does anything special.
|
||||||
|
expect(pressOn(set, target, "a", { ctrlKey: true })).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("controlByte", () => {
|
||||||
|
it("computes the raw control byte from a plain ctrl chord", () => {
|
||||||
|
expect(controlByte("ctrl-a")).toBe("\x01");
|
||||||
|
expect(controlByte("ctrl-k")).toBe("\x0b");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects anything that isn't a single plain ctrl chord", () => {
|
||||||
|
expect(() => controlByte("ctrl-shift-a")).toThrow();
|
||||||
|
expect(() => controlByte("a")).toThrow();
|
||||||
|
expect(() => controlByte("ctrl-a ctrl-a")).toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
+43
-5
@@ -32,6 +32,10 @@ export interface Command extends CommandSpec {
|
|||||||
run: () => void;
|
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
|
/** Every command the web client has. The single list this issue exists to
|
||||||
* create: labels, chords and grouping live here and nowhere else. */
|
* create: labels, chords and grouping live here and nowhere else. */
|
||||||
export const COMMAND_SPECS: readonly CommandSpec[] = [
|
export const COMMAND_SPECS: readonly CommandSpec[] = [
|
||||||
@@ -49,6 +53,27 @@ export const COMMAND_SPECS: readonly CommandSpec[] = [
|
|||||||
keys: ["N"],
|
keys: ["N"],
|
||||||
scope: "global",
|
scope: "global",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "bar.open",
|
||||||
|
label: "Open the command bar",
|
||||||
|
group: "Sessions",
|
||||||
|
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: "pane.literalLeader",
|
||||||
|
label: "Send a literal leader key to the pane",
|
||||||
|
group: "Pane",
|
||||||
|
keys: [`${DEFAULT_LEADER} ${DEFAULT_LEADER}`],
|
||||||
|
scope: "global",
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: "focus.toggle",
|
id: "focus.toggle",
|
||||||
label: "Move the keyboard between the session list and the pane",
|
label: "Move the keyboard between the session list and the pane",
|
||||||
@@ -209,6 +234,15 @@ export function canonicalizeKey(e: KeyboardEvent): string | null {
|
|||||||
return out + e.key.toLowerCase();
|
return out + e.key.toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The raw control byte for a canonical `ctrl-<letter>` chord — `ctrl-a` is
|
||||||
|
* `0x01` — mirroring the TUI's `encode_key`. Built from the chord string
|
||||||
|
* itself so a different leader sends its own byte, not a hardcoded one. */
|
||||||
|
export function controlByte(chord: string): string {
|
||||||
|
const m = /^ctrl-([a-z])$/.exec(chord);
|
||||||
|
if (!m) throw new Error(`not a plain ctrl chord: ${chord}`);
|
||||||
|
return String.fromCharCode(m[1].charCodeAt(0) - 96);
|
||||||
|
}
|
||||||
|
|
||||||
const MOD_PREFIX = /^(ctrl|alt|meta|shift)-/;
|
const MOD_PREFIX = /^(ctrl|alt|meta|shift)-/;
|
||||||
|
|
||||||
/** True when a chord carries a modifier or more than one key. Plain single-key
|
/** True when a chord carries a modifier or more than one key. Plain single-key
|
||||||
@@ -234,11 +268,19 @@ export function isTypingTarget(target: EventTarget | null): boolean {
|
|||||||
/** xterm's offscreen textarea. It is a typing target like any other, but it is
|
/** 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
|
* also where the leader has to work — a pane is exactly where the operator
|
||||||
* needs the escape hatch (docs/COMMAND-BAR.md). */
|
* 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;
|
const el = target as HTMLElement | null;
|
||||||
return !!el && typeof el.className === "string" && el.classList?.contains("xterm-helper-textarea");
|
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 ----
|
// ---- display ----
|
||||||
|
|
||||||
const CAPS: Record<string, string> = {
|
const CAPS: Record<string, string> = {
|
||||||
@@ -285,10 +327,6 @@ export function keyCaps(chord: string): string[] {
|
|||||||
|
|
||||||
// ---- dispatch ----
|
// ---- 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
|
/** How long a partial chord waits for its next key — the TUI's
|
||||||
* `chord_timeout_ms` default. */
|
* `chord_timeout_ms` default. */
|
||||||
export const DEFAULT_CHORD_TIMEOUT_MS = 1000;
|
export const DEFAULT_CHORD_TIMEOUT_MS = 1000;
|
||||||
|
|||||||
@@ -3,6 +3,23 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
|||||||
|
|
||||||
import { ConnectionPool } from "./connections.js";
|
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(() => {
|
afterEach(() => {
|
||||||
vi.unstubAllGlobals();
|
vi.unstubAllGlobals();
|
||||||
});
|
});
|
||||||
@@ -85,3 +102,26 @@ describe("ConnectionPool.setFocus", () => {
|
|||||||
await Promise.resolve();
|
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();
|
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. */
|
/** Fully disconnect + forget a session. */
|
||||||
close(id: Uuid): void {
|
close(id: Uuid): void {
|
||||||
const conn = this.cache.get(id);
|
const conn = this.cache.get(id);
|
||||||
|
|||||||
@@ -129,6 +129,7 @@ export function renderKit(): HTMLElement {
|
|||||||
"--muted",
|
"--muted",
|
||||||
"--faint",
|
"--faint",
|
||||||
"--accent",
|
"--accent",
|
||||||
|
"--preview",
|
||||||
"--danger",
|
"--danger",
|
||||||
"--warn",
|
"--warn",
|
||||||
];
|
];
|
||||||
|
|||||||
+111
-15
@@ -7,7 +7,8 @@ import { ConnectionPool } from "./connections.js";
|
|||||||
import { installDrawer, installDrawerSwipe, requestToggleDrawer } from "./drawer.js";
|
import { installDrawer, installDrawerSwipe, requestToggleDrawer } from "./drawer.js";
|
||||||
import { installHudKeybind } from "./debug.js";
|
import { installHudKeybind } from "./debug.js";
|
||||||
import { installHelpKeybind, isHelpOpen } from "./help.js";
|
import { installHelpKeybind, isHelpOpen } from "./help.js";
|
||||||
import { CommandSet, DEFAULT_LEADER, defineCommands } from "./commands.js";
|
import { CommandSet, DEFAULT_LEADER, controlByte, defineCommands, isBarTypingTarget } from "./commands.js";
|
||||||
|
import { isCommandBarOpen, openCommandBar, SPAWN_DIRECTORY_EVENT } from "./commandBar.js";
|
||||||
import { DaemonLink } from "./daemonLink.js";
|
import { DaemonLink } from "./daemonLink.js";
|
||||||
import { CatalogStore } from "./events.js";
|
import { CatalogStore } from "./events.js";
|
||||||
import { installRestartOverlay } from "./restartOverlay.js";
|
import { installRestartOverlay } from "./restartOverlay.js";
|
||||||
@@ -16,6 +17,7 @@ import {
|
|||||||
createSession,
|
createSession,
|
||||||
fetchNames,
|
fetchNames,
|
||||||
getDaemonInfo,
|
getDaemonInfo,
|
||||||
|
gitRoot,
|
||||||
projects as fetchProjects,
|
projects as fetchProjects,
|
||||||
} from "./api.js";
|
} from "./api.js";
|
||||||
import {
|
import {
|
||||||
@@ -34,6 +36,7 @@ import { createPreviewSchedule } from "./previewSchedule.js";
|
|||||||
import {
|
import {
|
||||||
FOCUS_PANE_EVENT,
|
FOCUS_PANE_EVENT,
|
||||||
FOCUS_SIDEBAR_EVENT,
|
FOCUS_SIDEBAR_EVENT,
|
||||||
|
OPEN_COMMAND_BAR_EVENT,
|
||||||
OPEN_SPAWN_EVENT,
|
OPEN_SPAWN_EVENT,
|
||||||
SESSION_SELECT_EVENT,
|
SESSION_SELECT_EVENT,
|
||||||
SPAWN_SIMILAR_EVENT,
|
SPAWN_SIMILAR_EVENT,
|
||||||
@@ -80,6 +83,15 @@ async function bootApp(): Promise<void> {
|
|||||||
|
|
||||||
const store = new CatalogStore();
|
const store = new CatalogStore();
|
||||||
|
|
||||||
|
// The daemon's home dir, for the command bar's `~/…` directory abbreviation.
|
||||||
|
// Absolute paths are a fine fallback until it lands.
|
||||||
|
let homeDir: string | undefined;
|
||||||
|
void getDaemonInfo()
|
||||||
|
.then((info) => (homeDir = info.home_dir))
|
||||||
|
.catch(() => {
|
||||||
|
/* absolute paths are a fine fallback */
|
||||||
|
});
|
||||||
|
|
||||||
// The daemon's identity and liveness: names the release in the sidebar's status
|
// The daemon's identity and liveness: names the release in the sidebar's status
|
||||||
// dot, and blocks the UI behind the restart overlay while the daemon is away
|
// dot, and blocks the UI behind the restart overlay while the daemon is away
|
||||||
// (docs/RESTART.md). The events socket is the trigger — it dies first.
|
// (docs/RESTART.md). The events socket is the trigger — it dies first.
|
||||||
@@ -327,6 +339,16 @@ function mountSpawned(session: Session, placement?: { newTab?: boolean }): void
|
|||||||
// a new branch named after that name. Anything unresolvable (no projects
|
// a new branch named after that name. Anything unresolvable (no projects
|
||||||
// known yet, no command, no generated name) opens the form pre-filled with
|
// known yet, no command, no generated name) opens the form pre-filled with
|
||||||
// what did resolve instead.
|
// 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> {
|
async function requestFastForward(): Promise<void> {
|
||||||
const [discovered, name] = await Promise.all([
|
const [discovered, name] = await Promise.all([
|
||||||
fetchProjects().catch(() => [] as Project[]),
|
fetchProjects().catch(() => [] as Project[]),
|
||||||
@@ -334,13 +356,7 @@ async function requestFastForward(): Promise<void> {
|
|||||||
.then((batch) => batch.names[0])
|
.then((batch) => batch.names[0])
|
||||||
.catch(() => undefined),
|
.catch(() => undefined),
|
||||||
]);
|
]);
|
||||||
let presets: SpawnPreset[] = FALLBACK_PRESETS;
|
const presets = await spawnPresets();
|
||||||
try {
|
|
||||||
const info = await getDaemonInfo();
|
|
||||||
if (info.presets?.length) presets = info.presets;
|
|
||||||
} catch {
|
|
||||||
/* keep fallbacks */
|
|
||||||
}
|
|
||||||
const resolved = resolveFastForward(discovered, presets, name, focusedProjectCwd());
|
const resolved = resolveFastForward(discovered, presets, name, focusedProjectCwd());
|
||||||
const req = buildFastForwardRequest(resolved);
|
const req = buildFastForwardRequest(resolved);
|
||||||
if (req) {
|
if (req) {
|
||||||
@@ -362,13 +378,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
|
// 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
|
// 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
|
// 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.
|
// 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
|
// `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.
|
// hidden textarea.
|
||||||
const spawnKeys = new CommandSet(
|
const spawnKeys = new CommandSet(
|
||||||
defineCommands({
|
defineCommands({
|
||||||
@@ -395,16 +452,55 @@ const focusKeys = new CommandSet(
|
|||||||
sidebar.focusList();
|
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"),
|
||||||
|
// The leader itself, pressed twice, tmux-style: sends one literal leader
|
||||||
|
// byte and clears the pending chord instead of resolving as a dead chord
|
||||||
|
// (docs/COMMAND-BAR.md, #158). Built from `DEFAULT_LEADER`, not a
|
||||||
|
// hardcoded byte, so a different leader would send its own.
|
||||||
|
"pane.literalLeader": () => pool.sendToFocused(controlByte(DEFAULT_LEADER)),
|
||||||
}),
|
}),
|
||||||
{ leader: DEFAULT_LEADER },
|
{ leader: DEFAULT_LEADER },
|
||||||
);
|
);
|
||||||
|
|
||||||
window.addEventListener("keydown", (e) => {
|
// Ctrl+K opens the command bar (docs/COMMAND-BAR.md). It is a registry command
|
||||||
if (focusKeys.handle(e)) return;
|
// like any other, so the `?` overlay lists it without a second list.
|
||||||
// The help overlay owns the keyboard while it is up.
|
const openBar = () => {
|
||||||
if (isHelpOpen()) return;
|
// Opening while a session is previewed discards the preview first, like
|
||||||
spawnKeys.handle(e);
|
// any other real change (docs/PREVIEW.md): the bar is not previewed into.
|
||||||
});
|
schedulePreview.cancel();
|
||||||
|
mv?.previewSession(null);
|
||||||
|
openCommandBar({ sessions: [...store.snapshot().sessions.values()], homeDir });
|
||||||
|
};
|
||||||
|
|
||||||
|
const barKeys = new CommandSet(defineCommands({ "bar.open": () => openBar() }));
|
||||||
|
|
||||||
|
// The sidebar's search field is the touch entry point (#157): no `ctrl-k` on a
|
||||||
|
// phone, so the field the operator already reaches for opens the same bar.
|
||||||
|
document.addEventListener(OPEN_COMMAND_BAR_EVENT, () => openBar());
|
||||||
|
|
||||||
|
// Capture phase: an attached xterm swallows every keystroke it is given, so the
|
||||||
|
// bar's binding has to be seen ahead of the terminal (docs/COMMAND-BAR.md).
|
||||||
|
window.addEventListener(
|
||||||
|
"keydown",
|
||||||
|
(e) => {
|
||||||
|
// The bar owns the keyboard while it is up; its own input handles the keys.
|
||||||
|
if (isCommandBarOpen()) return;
|
||||||
|
if (focusKeys.handle(e)) return;
|
||||||
|
// The help overlay owns the keyboard while it is up.
|
||||||
|
if (isHelpOpen()) 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,
|
||||||
|
);
|
||||||
|
|
||||||
|
|
||||||
// Tab in the session list hands the keyboard to the pane; Escape in the pane
|
// Tab in the session list hands the keyboard to the pane; Escape in the pane
|
||||||
// hands it back — the pair the TUI gets from `tab` and `esc`.
|
// hands it back — the pair the TUI gets from `tab` and `esc`.
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ function fakeSidebar(): SidebarHandle {
|
|||||||
el: document.createElement("aside"),
|
el: document.createElement("aside"),
|
||||||
setActive() {},
|
setActive() {},
|
||||||
setHighlights() {},
|
setHighlights() {},
|
||||||
|
setPreview() {},
|
||||||
focusList() {},
|
focusList() {},
|
||||||
hasListFocus() {
|
hasListFocus() {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -221,6 +221,12 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
|||||||
const tab = activeTab(layout);
|
const tab = activeTab(layout);
|
||||||
for (const pane of canvas.querySelectorAll<HTMLElement>(".mv-pane")) {
|
for (const pane of canvas.querySelectorAll<HTMLElement>(".mv-pane")) {
|
||||||
pane.classList.toggle("is-focused", pane.dataset.leafId === tab.focusedLeafId);
|
pane.classList.toggle("is-focused", pane.dataset.leafId === tab.focusedLeafId);
|
||||||
|
// The previewed pane's titlebar wears the preview colour instead of the
|
||||||
|
// accent tint a focused pane gets (docs/PREVIEW.md).
|
||||||
|
pane.classList.toggle(
|
||||||
|
"is-preview",
|
||||||
|
preview !== null && pane.dataset.sessionId === preview.sessionId,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
// A preview is not a focused pane: reporting it would clear the session's
|
// A preview is not a focused pane: reporting it would clear the session's
|
||||||
// `AwaitingInput` glow just because the operator scrolled past it.
|
// `AwaitingInput` glow just because the operator scrolled past it.
|
||||||
@@ -229,6 +235,9 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
|||||||
open: realOpenSessions(),
|
open: realOpenSessions(),
|
||||||
focused: focusedLeafSession(),
|
focused: focusedLeafSession(),
|
||||||
});
|
});
|
||||||
|
// The row the preview came from wears the same colour, so the sidebar and
|
||||||
|
// the pane read as one thing rather than two unrelated highlights.
|
||||||
|
sidebar.setPreview(preview?.sessionId ?? null);
|
||||||
}
|
}
|
||||||
|
|
||||||
function focusLeaf(leafId: string): void {
|
function focusLeaf(leafId: string): void {
|
||||||
@@ -549,6 +558,7 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
|||||||
if (!preview) pool.setFocus(null);
|
if (!preview) pool.setFocus(null);
|
||||||
canvas.appendChild(renderWelcome());
|
canvas.appendChild(renderWelcome());
|
||||||
sidebar.setHighlights({ open: realOpenSessions(), focused: null });
|
sidebar.setHighlights({ open: realOpenSessions(), focused: null });
|
||||||
|
sidebar.setPreview(preview?.sessionId ?? null);
|
||||||
persist();
|
persist();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -588,6 +598,7 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
|||||||
|
|
||||||
const pane = buildPane(focused);
|
const pane = buildPane(focused);
|
||||||
pane.el.classList.add("is-focused"); // the only pane — never dimmed
|
pane.el.classList.add("is-focused"); // the only pane — never dimmed
|
||||||
|
if (preview && focused.sessionId === preview.sessionId) pane.el.classList.add("is-preview");
|
||||||
wrap.appendChild(pane.el);
|
wrap.appendChild(pane.el);
|
||||||
canvas.appendChild(wrap);
|
canvas.appendChild(wrap);
|
||||||
|
|
||||||
@@ -598,6 +609,7 @@ export function createMultiView(opts: MultiViewOptions): MultiView {
|
|||||||
);
|
);
|
||||||
if (!preview) pool.setFocus(focused.sessionId ?? null);
|
if (!preview) pool.setFocus(focused.sessionId ?? null);
|
||||||
sidebar.setHighlights({ open: realOpenSessions(), focused: focused.sessionId ?? null });
|
sidebar.setHighlights({ open: realOpenSessions(), focused: focused.sessionId ?? null });
|
||||||
|
sidebar.setPreview(preview?.sessionId ?? null);
|
||||||
}
|
}
|
||||||
|
|
||||||
function closeSession(sessionId: string): void {
|
function closeSession(sessionId: string): void {
|
||||||
|
|||||||
@@ -45,11 +45,17 @@ function fakePool(): Spy {
|
|||||||
return { pool, visible: () => visible, focusCalls, mountedWithFocus };
|
return { pool, visible: () => visible, focusCalls, mountedWithFocus };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Last value the controller pushed to `SidebarHandle.setPreview`. */
|
||||||
|
const previewRow: { id: string | null } = { id: null };
|
||||||
|
|
||||||
function fakeSidebar(): SidebarHandle {
|
function fakeSidebar(): SidebarHandle {
|
||||||
return {
|
return {
|
||||||
el: document.createElement("aside"),
|
el: document.createElement("aside"),
|
||||||
setActive() {},
|
setActive() {},
|
||||||
setHighlights() {},
|
setHighlights() {},
|
||||||
|
setPreview(id: string | null) {
|
||||||
|
previewRow.id = id;
|
||||||
|
},
|
||||||
focusList() {},
|
focusList() {},
|
||||||
hasListFocus() {
|
hasListFocus() {
|
||||||
return false;
|
return false;
|
||||||
@@ -88,6 +94,7 @@ describe("sidebar preview", () => {
|
|||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
stubFetch();
|
stubFetch();
|
||||||
document.body.replaceChildren();
|
document.body.replaceChildren();
|
||||||
|
previewRow.id = null;
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -110,6 +117,23 @@ describe("sidebar preview", () => {
|
|||||||
expect(serializeLayout(layout)).toEqual(before);
|
expect(serializeLayout(layout)).toEqual(before);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("marks the previewed pane and its sidebar row, and unmarks them after", () => {
|
||||||
|
const layout = twoTabs();
|
||||||
|
const spy = fakePool();
|
||||||
|
const mv = makeMv(layout, spy.pool);
|
||||||
|
|
||||||
|
mv.previewSession("s1");
|
||||||
|
expect(previewRow.id).toBe("s1");
|
||||||
|
expect(mv.el.querySelectorAll(".mv-pane.is-preview")).toHaveLength(1);
|
||||||
|
expect(
|
||||||
|
(mv.el.querySelector(".mv-pane.is-preview") as HTMLElement).dataset.sessionId,
|
||||||
|
).toBe("s1");
|
||||||
|
|
||||||
|
mv.previewSession(null);
|
||||||
|
expect(previewRow.id).toBeNull();
|
||||||
|
expect(mv.el.querySelectorAll(".mv-pane.is-preview")).toHaveLength(0);
|
||||||
|
});
|
||||||
|
|
||||||
it("shows a session no pane holds in a throwaway tab that leaves no trace", () => {
|
it("shows a session no pane holds in a throwaway tab that leaves no trace", () => {
|
||||||
const layout = twoTabs();
|
const layout = twoTabs();
|
||||||
const before = serializeLayout(layout);
|
const before = serializeLayout(layout);
|
||||||
|
|||||||
@@ -0,0 +1,135 @@
|
|||||||
|
// @vitest-environment happy-dom
|
||||||
|
//
|
||||||
|
// The sidebar's search field is the touch entry point to the command bar
|
||||||
|
// (#157, docs/COMMAND-BAR.md "Touch entry"): tapping or focusing it asks the
|
||||||
|
// shell to open the bar with an empty query, instead of filtering the tree.
|
||||||
|
import { beforeAll, describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { OPEN_COMMAND_BAR_EVENT, renderSidebar } from "./catalog.js";
|
||||||
|
import { sessionBarCandidates } from "./commandBar.js";
|
||||||
|
import { matchAndRank } from "./matcher.js";
|
||||||
|
import type { CatalogListener, CatalogStore } from "./events.js";
|
||||||
|
import type { Session } from "./types.js";
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
Object.defineProperty(window, "localStorage", {
|
||||||
|
value: { getItem: () => null, setItem: () => {} },
|
||||||
|
});
|
||||||
|
window.fetch = () => Promise.reject(new Error("offline"));
|
||||||
|
});
|
||||||
|
|
||||||
|
function session(id: string, cwd: string): Session {
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
name: id,
|
||||||
|
cwd,
|
||||||
|
command: "claude",
|
||||||
|
env: {},
|
||||||
|
metadata: {},
|
||||||
|
status: "Running",
|
||||||
|
created_at: "2026-08-24T10:00:00Z",
|
||||||
|
} as Session;
|
||||||
|
}
|
||||||
|
|
||||||
|
function storeWith(sessions: Session[]): CatalogStore {
|
||||||
|
const state = { sessions: new Map(sessions.map((s) => [s.id, s])) };
|
||||||
|
return {
|
||||||
|
snapshot: () => state,
|
||||||
|
subscribe: (fn: CatalogListener) => {
|
||||||
|
fn(state);
|
||||||
|
return () => {};
|
||||||
|
},
|
||||||
|
} as unknown as CatalogStore;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mount(sessions: Session[] = [session("alpha", "/home/n/alpha")]) {
|
||||||
|
const handle = renderSidebar(storeWith(sessions));
|
||||||
|
document.body.appendChild(handle.el);
|
||||||
|
const search = handle.el.querySelector<HTMLInputElement>(".search")!;
|
||||||
|
const opens: number[] = [];
|
||||||
|
const listener = () => opens.push(1);
|
||||||
|
document.addEventListener(OPEN_COMMAND_BAR_EVENT, listener);
|
||||||
|
return {
|
||||||
|
handle,
|
||||||
|
search,
|
||||||
|
opens,
|
||||||
|
dispose: () => {
|
||||||
|
document.removeEventListener(OPEN_COMMAND_BAR_EVENT, listener);
|
||||||
|
handle.dispose();
|
||||||
|
handle.el.remove();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("sidebar search field opens the command bar (#157)", () => {
|
||||||
|
it("asks the shell to open the bar when the field is focused", () => {
|
||||||
|
const t = mount();
|
||||||
|
t.search.dispatchEvent(new FocusEvent("focus"));
|
||||||
|
expect(t.opens).toHaveLength(1);
|
||||||
|
t.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opens on a tap, where a focus event may never arrive", () => {
|
||||||
|
const t = mount();
|
||||||
|
t.search.dispatchEvent(new Event("pointerdown", { bubbles: true }));
|
||||||
|
expect(t.opens).toHaveLength(1);
|
||||||
|
t.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not trap the keyboard in the field: it gives focus up on open", () => {
|
||||||
|
const t = mount();
|
||||||
|
t.search.focus();
|
||||||
|
expect(document.activeElement).not.toBe(t.search);
|
||||||
|
t.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("opens the bar with an empty query — the field never holds one", () => {
|
||||||
|
const t = mount();
|
||||||
|
t.search.focus();
|
||||||
|
expect(t.search.value).toBe("");
|
||||||
|
t.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is readonly: no on-screen keyboard over a field nothing is typed into", () => {
|
||||||
|
const t = mount();
|
||||||
|
expect(t.search.readOnly).toBe(true);
|
||||||
|
t.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("no longer filters the tree in place", () => {
|
||||||
|
const t = mount([session("alpha", "/home/n/alpha"), session("beta", "/home/n/beta")]);
|
||||||
|
t.search.value = "alpha";
|
||||||
|
t.search.dispatchEvent(new Event("input"));
|
||||||
|
expect(t.handle.el.querySelectorAll(".tree-leaf")).toHaveLength(2);
|
||||||
|
t.dispose();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("has no 'No matches' state left: an empty catalog is empty, not filtered", () => {
|
||||||
|
const t = mount([]);
|
||||||
|
expect(t.handle.el.querySelector(".empty-title")?.textContent).toBe("No sessions yet");
|
||||||
|
t.dispose();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// The inline filter matched a session on its name and its directory, case- and
|
||||||
|
// whitespace-insensitively. That behaviour did not go away with the field — it
|
||||||
|
// moved into the bar, which ranks the same two fields (docs/COMMAND-BAR.md).
|
||||||
|
describe("what the retired inline filter did, the bar now does", () => {
|
||||||
|
it("matches a session on both its name and its directory", () => {
|
||||||
|
const sessions = [session("alpha", "/home/n/alpha"), session("beta", "/home/n/beta")];
|
||||||
|
const candidates = sessionBarCandidates(sessions, "/home/n");
|
||||||
|
|
||||||
|
const byName = matchAndRank("alpha", candidates).map((r) => r.candidate.session.id);
|
||||||
|
expect(byName).toEqual(["alpha"]);
|
||||||
|
|
||||||
|
const byDir = matchAndRank("beta", candidates).map((r) => r.candidate.session.id);
|
||||||
|
expect(byDir).toEqual(["beta"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("ignores case and surrounding whitespace, and shows nothing on no match", () => {
|
||||||
|
const candidates = sessionBarCandidates([session("alpha", "/home/n/Alpha")], "/home/n");
|
||||||
|
|
||||||
|
expect(matchAndRank(" ALPHA ", candidates)).toHaveLength(1);
|
||||||
|
expect(matchAndRank("zzz", candidates)).toHaveLength(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
+250
-32
@@ -87,6 +87,30 @@
|
|||||||
--accent-tint: oklch(0.92 0.005 256 / 0.1);
|
--accent-tint: oklch(0.92 0.005 256 / 0.1);
|
||||||
--accent-ring: oklch(0.92 0.005 256 / 0.5);
|
--accent-ring: oklch(0.92 0.005 256 / 0.5);
|
||||||
|
|
||||||
|
/* preview (docs/PREVIEW.md): a provisional view needs a colour that is not
|
||||||
|
the accent, because the accent is what says "this is the one you picked".
|
||||||
|
Defined once, off a single hue variable, so a palette whose accent already
|
||||||
|
sits on that hue can move it (see periwinkle/orchid below); `light-dark()`
|
||||||
|
keeps the light pair here instead of in all eighteen theme blocks. */
|
||||||
|
--preview-h: 305;
|
||||||
|
--preview: light-dark(
|
||||||
|
oklch(0.55 0.16 var(--preview-h)),
|
||||||
|
oklch(0.78 0.14 var(--preview-h))
|
||||||
|
);
|
||||||
|
--preview-ink: light-dark(
|
||||||
|
oklch(0.99 0.005 var(--preview-h)),
|
||||||
|
oklch(0.19 0.045 var(--preview-h))
|
||||||
|
);
|
||||||
|
/* Opaque, not a wash: session rows read as fills, and a fill has to land on
|
||||||
|
the same colour whatever tier the row was already painted. `--accent-fill`
|
||||||
|
is the same recipe on the accent, so the two tiers differ by hue alone. */
|
||||||
|
--preview-tint: color-mix(in oklab, var(--preview) 30%, var(--surface-2));
|
||||||
|
--accent-fill: color-mix(in oklab, var(--accent) 30%, var(--surface-2));
|
||||||
|
--preview-ring: light-dark(
|
||||||
|
oklch(0.55 0.16 var(--preview-h) / 0.5),
|
||||||
|
oklch(0.78 0.14 var(--preview-h) / 0.6)
|
||||||
|
);
|
||||||
|
|
||||||
--live: oklch(0.84 0.17 152);
|
--live: oklch(0.84 0.17 152);
|
||||||
--live-glow: oklch(0.84 0.17 152 / 0.55);
|
--live-glow: oklch(0.84 0.17 152 / 0.55);
|
||||||
|
|
||||||
@@ -256,6 +280,9 @@
|
|||||||
--accent-ink: oklch(0.18 0.04 278);
|
--accent-ink: oklch(0.18 0.04 278);
|
||||||
--accent-tint: oklch(0.75 0.125 275 / 0.14);
|
--accent-tint: oklch(0.75 0.125 275 / 0.14);
|
||||||
--accent-ring: oklch(0.75 0.125 275 / 0.55);
|
--accent-ring: oklch(0.75 0.125 275 / 0.55);
|
||||||
|
/* This accent is already violet, so preview moves to cyan to stay legible
|
||||||
|
as "not the accent". Set once here: the light blocks below don't touch it. */
|
||||||
|
--preview-h: 195;
|
||||||
--term-bg: oklch(0.155 0.018 278);
|
--term-bg: oklch(0.155 0.018 278);
|
||||||
}
|
}
|
||||||
:root[data-palette="periwinkle"][data-theme="light"],
|
:root[data-palette="periwinkle"][data-theme="light"],
|
||||||
@@ -437,6 +464,8 @@
|
|||||||
--accent-ink: oklch(0.22 0.05 310);
|
--accent-ink: oklch(0.22 0.05 310);
|
||||||
--accent-tint: oklch(0.78 0.13 310 / 0.14);
|
--accent-tint: oklch(0.78 0.13 310 / 0.14);
|
||||||
--accent-ring: oklch(0.78 0.13 310 / 0.55);
|
--accent-ring: oklch(0.78 0.13 310 / 0.55);
|
||||||
|
/* Same collision as periwinkle: an orchid accent needs a non-purple preview. */
|
||||||
|
--preview-h: 195;
|
||||||
--term-bg: oklch(0.155 0.014 305);
|
--term-bg: oklch(0.155 0.014 305);
|
||||||
}
|
}
|
||||||
:root[data-palette="orchid"][data-theme="light"],
|
:root[data-palette="orchid"][data-theme="light"],
|
||||||
@@ -1114,35 +1143,42 @@ textarea {
|
|||||||
border-radius: var(--r-1);
|
border-radius: var(--r-1);
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
position: relative;
|
position: relative;
|
||||||
/* No transition on `background`: it is what hover paints, and easing it puts
|
/* No transition on `background`: it is what hover, the keyboard cursor and
|
||||||
a visible delay between the pointer landing on a row and the row admitting
|
the preview all paint, and easing it puts a visible delay between the input
|
||||||
it. The ring (`.is-highlighted`, `.is-active`) still eases — that one
|
landing on a row and the row admitting it. `.is-active`'s ring still eases
|
||||||
follows a keyboard walk, not the pointer. */
|
— being open in a pane is a state, not a response to the pointer. */
|
||||||
transition: box-shadow var(--dur-fast) var(--ease-out);
|
transition: box-shadow var(--dur-fast) var(--ease-out);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* "Alive" reads as a faint wash on the row itself — no per-row status icon. */
|
/* Session-row tiers (docs/SIDEBAR.md). A row is usually several of these at
|
||||||
.tree-leaf[data-status="running"] {
|
once, so every qualifier below sits in `:where()`: each rule is worth the
|
||||||
|
same specificity and the ladder is decided purely by the order they appear
|
||||||
|
in, latest wins. Add a tier where it belongs in that order, not by piling on
|
||||||
|
another class to out-weigh the rule above it. Each tier paints a background
|
||||||
|
and nothing else — the list says all of this with fill, never an edge. */
|
||||||
|
|
||||||
|
/* 1. Alive. A faint wash on the row itself — no per-row status icon. */
|
||||||
|
.tree-leaf:where([data-status="running"]) {
|
||||||
background: color-mix(in oklab, var(--accent) 6%, transparent);
|
background: color-mix(in oklab, var(--accent) 6%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.tree-leaf:hover {
|
/* 2. Under the pointer, or under the keyboard walk. Both are what previews a
|
||||||
background: var(--surface-2);
|
row (docs/PREVIEW.md), so both read in the preview hue — never the accent,
|
||||||
|
which belongs to the row actually open. */
|
||||||
|
.tree-leaf:where(:hover, .is-highlighted) {
|
||||||
|
background: color-mix(in oklab, var(--preview) 12%, var(--surface-2));
|
||||||
}
|
}
|
||||||
|
|
||||||
.tree-leaf[data-status="running"]:hover {
|
.tree-leaf:where([data-status="running"]):where(:hover, .is-highlighted) {
|
||||||
background: color-mix(in oklab, var(--accent) 13%, var(--surface-2));
|
background: color-mix(in oklab, var(--preview) 18%, var(--surface-2));
|
||||||
}
|
}
|
||||||
|
|
||||||
.tree-leaf:focus-visible {
|
.tree-leaf:where(:focus-visible) {
|
||||||
outline: none;
|
outline: none;
|
||||||
background: color-mix(in oklab, var(--accent) 16%, var(--surface-2));
|
background: color-mix(in oklab, var(--accent) 16%, var(--surface-2));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Where the keyboard walk (j/k) is standing. Distinct from `.is-active`: this
|
/* A folder row previews nothing, so its cursor stays a ring. */
|
||||||
is a cursor, not a statement about what is mounted, so it reads as a ring
|
|
||||||
rather than a fill and the two can sit on the same row. */
|
|
||||||
.tree-leaf.is-highlighted,
|
|
||||||
.tree-folder-header.is-highlighted {
|
.tree-folder-header.is-highlighted {
|
||||||
box-shadow: inset 0 0 0 2px var(--accent-ring);
|
box-shadow: inset 0 0 0 2px var(--accent-ring);
|
||||||
}
|
}
|
||||||
@@ -1151,17 +1187,28 @@ textarea {
|
|||||||
outline: none;
|
outline: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* The session currently mounted in the content pane. */
|
/* 3. Open in some pane, but not the focused one (issue #33). */
|
||||||
.tree-leaf.is-active,
|
.tree-leaf:where(.is-open) {
|
||||||
.tree-leaf.is-active[data-status="running"] {
|
background: color-mix(in oklab, var(--accent) 6%, transparent);
|
||||||
background: var(--accent-tint);
|
}
|
||||||
box-shadow: inset 0 0 0 1px var(--accent-ring);
|
|
||||||
|
/* 4. The session currently mounted in the content pane. */
|
||||||
|
.tree-leaf:where(.is-active) {
|
||||||
|
background: var(--accent-fill);
|
||||||
}
|
}
|
||||||
|
|
||||||
.tree-leaf.is-active .leaf-name {
|
.tree-leaf.is-active .leaf-name {
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 5. The row the content pane is previewing right now. Last, so previewing a
|
||||||
|
session that is already open still reads as provisional — except the session
|
||||||
|
already mounted in the pane (tier 4). Previewing that one changes nothing on
|
||||||
|
screen, so its accent stays put instead of blinking out under the pointer. */
|
||||||
|
.tree-leaf:where(.is-previewing):where(:not(.is-active)) {
|
||||||
|
background: var(--preview-tint);
|
||||||
|
}
|
||||||
|
|
||||||
/* Exited sessions recede: dimmed name + an "exited" badge carry status, so it's
|
/* Exited sessions recede: dimmed name + an "exited" badge carry status, so it's
|
||||||
never the running tint's absence alone doing the work. */
|
never the running tint's absence alone doing the work. */
|
||||||
.tree-leaf[data-status="dead"] {
|
.tree-leaf[data-status="dead"] {
|
||||||
@@ -1378,6 +1425,171 @@ input.leaf-rename:focus {
|
|||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---------- command bar (Ctrl+K) — docs/COMMAND-BAR.md ---------- */
|
||||||
|
/* Same family of surface as the spawn modal and the help overlay: the overlay
|
||||||
|
tokens below are theirs, not a third set. */
|
||||||
|
.cmdbar-overlay {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
z-index: var(--z-modal);
|
||||||
|
display: grid;
|
||||||
|
grid-template-rows: 12vh auto 1fr;
|
||||||
|
justify-items: center;
|
||||||
|
padding: var(--sp-4);
|
||||||
|
background: oklch(0 0 0 / 0.5);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-panel {
|
||||||
|
grid-row: 2;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
width: min(560px, 100%);
|
||||||
|
max-height: min(60vh, 520px);
|
||||||
|
overflow: hidden;
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
border-radius: var(--r-3);
|
||||||
|
box-shadow: var(--shadow-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-input {
|
||||||
|
appearance: none;
|
||||||
|
background: none;
|
||||||
|
border: 0;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
border-radius: 0;
|
||||||
|
color: var(--ink);
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: var(--fs-15);
|
||||||
|
padding: var(--sp-3) var(--sp-4);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-input:focus-visible {
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-results {
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: var(--sp-2) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The action page's header (#151): names the session being acted on, so the
|
||||||
|
target of kill/rename/spawn-similar is never ambiguous. */
|
||||||
|
.cmdbar-page-header {
|
||||||
|
padding: var(--sp-2) var(--sp-4);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
font-size: var(--fs-12);
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-group-title {
|
||||||
|
padding: var(--sp-2) var(--sp-4) var(--sp-1);
|
||||||
|
font-size: var(--fs-11);
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: var(--faint);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: var(--sp-3);
|
||||||
|
padding: var(--sp-1) var(--sp-4);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-row.is-active {
|
||||||
|
background: var(--surface-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-row-name {
|
||||||
|
font-size: var(--fs-13);
|
||||||
|
color: var(--ink);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* A dead session still lists — it just is not where you just were. */
|
||||||
|
.cmdbar-row.is-dead .cmdbar-row-name {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-row-meta {
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-width: 0;
|
||||||
|
font-size: var(--fs-11);
|
||||||
|
color: var(--faint);
|
||||||
|
text-align: right;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
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);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-empty {
|
||||||
|
padding: var(--sp-3) var(--sp-4);
|
||||||
|
font-size: var(--fs-13);
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Phone: the bottom-sheet treatment the spawn modal already uses. */
|
||||||
|
/* Bottom sheet at phone width, the same treatment (and the same 599px break)
|
||||||
|
the spawn modal uses: the bar is reached by thumb here, through the sidebar's
|
||||||
|
search field (#157), so it rides the bottom of the screen. */
|
||||||
|
@media (max-width: 599px) {
|
||||||
|
.cmdbar-overlay {
|
||||||
|
grid-template-rows: 1fr auto;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-panel {
|
||||||
|
grid-row: 2;
|
||||||
|
width: 100%;
|
||||||
|
max-height: 70dvh;
|
||||||
|
border-radius: var(--r-3) var(--r-3) 0 0;
|
||||||
|
border-bottom: 0;
|
||||||
|
padding-bottom: env(safe-area-inset-bottom, 0px);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Thumb-sized rows and a field that clears the on-screen keyboard's
|
||||||
|
zoom-on-focus threshold (16px). */
|
||||||
|
.cmdbar-input {
|
||||||
|
font-size: var(--fs-17);
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.cmdbar-row {
|
||||||
|
min-height: 44px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/* Line 2 — dot + duration in the state's colour, then muted fragments. The
|
/* Line 2 — dot + duration in the state's colour, then muted fragments. The
|
||||||
state word itself is never spelled out here; the colour carries it. */
|
state word itself is never spelled out here; the colour carries it. */
|
||||||
.card-line2 {
|
.card-line2 {
|
||||||
@@ -2885,10 +3097,14 @@ input.leaf-rename:focus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Preview (docs/PREVIEW.md): the content pane is showing a session the
|
/* Preview (docs/PREVIEW.md): the content pane is showing a session the
|
||||||
operator only highlighted, so it reads as provisional — a dashed tab and a
|
operator only highlighted, so it reads as provisional — the preview hue on
|
||||||
dashed inset ring on the canvas — and reverts when the highlight moves. */
|
the pane's titlebar, a dashed tab, a dashed inset ring on the canvas — and
|
||||||
|
reverts when the highlight moves. The hue is deliberately not the accent:
|
||||||
|
the accent means "this is what you picked", which a preview is not. */
|
||||||
.mv-tab.is-preview {
|
.mv-tab.is-preview {
|
||||||
border-style: dashed;
|
border-style: dashed;
|
||||||
|
border-color: var(--preview-ring);
|
||||||
|
color: var(--preview);
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
.mv.mv-previewing .mv-canvas::before {
|
.mv.mv-previewing .mv-canvas::before {
|
||||||
@@ -2901,8 +3117,8 @@ input.leaf-rename:focus {
|
|||||||
border-radius: var(--r-1);
|
border-radius: var(--r-1);
|
||||||
font: 500 var(--fs-11) / 1.5 var(--font-mono);
|
font: 500 var(--fs-11) / 1.5 var(--font-mono);
|
||||||
letter-spacing: 0.04em;
|
letter-spacing: 0.04em;
|
||||||
color: var(--accent-ink);
|
color: var(--preview-ink);
|
||||||
background: var(--accent);
|
background: var(--preview);
|
||||||
opacity: 0.85;
|
opacity: 0.85;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
@@ -2911,7 +3127,7 @@ input.leaf-rename:focus {
|
|||||||
position: absolute;
|
position: absolute;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
border: 1px dashed var(--accent-ring);
|
border: 1px dashed var(--preview-ring);
|
||||||
border-radius: var(--r-1);
|
border-radius: var(--r-1);
|
||||||
z-index: var(--z-sticky);
|
z-index: var(--z-sticky);
|
||||||
}
|
}
|
||||||
@@ -3029,6 +3245,15 @@ input.leaf-rename:focus {
|
|||||||
.mv-pane:not(.is-focused) .attach-header {
|
.mv-pane:not(.is-focused) .attach-header {
|
||||||
opacity: 0.7;
|
opacity: 0.7;
|
||||||
}
|
}
|
||||||
|
/* The previewed pane's titlebar carries the preview hue, so the chip is not the
|
||||||
|
only thing saying the pane is provisional — and so it is never mistaken for
|
||||||
|
the accent tint of the pane the operator actually focused. It keeps full
|
||||||
|
strength even though a preview never takes focus. */
|
||||||
|
.mv-pane.is-preview .attach-header,
|
||||||
|
.mv-pane.is-preview.is-focused .attach-header {
|
||||||
|
background: color-mix(in oklab, var(--preview) 34%, var(--surface));
|
||||||
|
opacity: 1;
|
||||||
|
}
|
||||||
/* A pane with no session yet: a quiet hint rather than blank terminal black. */
|
/* A pane with no session yet: a quiet hint rather than blank terminal black. */
|
||||||
.mv-pane-empty {
|
.mv-pane-empty {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
@@ -3118,13 +3343,6 @@ input.leaf-rename:focus {
|
|||||||
border-radius: var(--r-1);
|
border-radius: var(--r-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* sidebar two-tier highlight (issue #33).
|
|
||||||
.is-active = focused pane (loud, from existing rule); .is-open = open
|
|
||||||
elsewhere (quiet). */
|
|
||||||
.tree-leaf.is-open {
|
|
||||||
background: color-mix(in oklab, var(--accent) 6%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* =========================================================================
|
/* =========================================================================
|
||||||
multi-view mobile (#35): below 860px only the focused pane is shown — no tab
|
multi-view mobile (#35): below 860px only the focused pane is shown — no tab
|
||||||
bar, no pane switcher; the sidebar drawer (☰) is the navigation.
|
bar, no pane switcher; the sidebar drawer (☰) is the navigation.
|
||||||
|
|||||||
+2
-26
@@ -26,7 +26,6 @@ describe("buildTree", () => {
|
|||||||
const root = buildTree(
|
const root = buildTree(
|
||||||
[session("a", "/home/n/work"), session("b", "/home/n/work")],
|
[session("a", "/home/n/work"), session("b", "/home/n/work")],
|
||||||
"/home/n",
|
"/home/n",
|
||||||
"",
|
|
||||||
) as TreeFolder;
|
) as TreeFolder;
|
||||||
|
|
||||||
expect(names(root)).toEqual(["~/work"]);
|
expect(names(root)).toEqual(["~/work"]);
|
||||||
@@ -35,7 +34,7 @@ describe("buildTree", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("collapses a linear chain into one folder", () => {
|
it("collapses a linear chain into one folder", () => {
|
||||||
const root = buildTree([session("a", "/home/n/git/naps62/maestro")], "/home/n", "") as TreeFolder;
|
const root = buildTree([session("a", "/home/n/git/naps62/maestro")], "/home/n") as TreeFolder;
|
||||||
expect(names(root)).toEqual(["~/git/naps62/maestro"]);
|
expect(names(root)).toEqual(["~/git/naps62/maestro"]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -43,7 +42,6 @@ describe("buildTree", () => {
|
|||||||
const root = buildTree(
|
const root = buildTree(
|
||||||
[session("a", "/home/n/subvisual/bullish"), session("b", "/home/n/tea/maestro")],
|
[session("a", "/home/n/subvisual/bullish"), session("b", "/home/n/tea/maestro")],
|
||||||
"/home/n",
|
"/home/n",
|
||||||
"",
|
|
||||||
) as TreeFolder;
|
) as TreeFolder;
|
||||||
|
|
||||||
expect(names(root).sort()).toEqual(["~/subvisual/bullish", "~/tea/maestro"]);
|
expect(names(root).sort()).toEqual(["~/subvisual/bullish", "~/tea/maestro"]);
|
||||||
@@ -53,7 +51,6 @@ describe("buildTree", () => {
|
|||||||
const root = buildTree(
|
const root = buildTree(
|
||||||
[session("a", "/home/n/git/one"), session("b", "/home/n/git/two")],
|
[session("a", "/home/n/git/one"), session("b", "/home/n/git/two")],
|
||||||
"/home/n",
|
"/home/n",
|
||||||
"",
|
|
||||||
) as TreeFolder;
|
) as TreeFolder;
|
||||||
|
|
||||||
expect(names(root)).toEqual(["~/git"]);
|
expect(names(root)).toEqual(["~/git"]);
|
||||||
@@ -65,30 +62,11 @@ describe("buildTree", () => {
|
|||||||
const root = buildTree(
|
const root = buildTree(
|
||||||
[session("loose", ""), session("nested", "/home/n/work")],
|
[session("loose", ""), session("nested", "/home/n/work")],
|
||||||
"/home/n",
|
"/home/n",
|
||||||
"",
|
|
||||||
) as TreeFolder;
|
) as TreeFolder;
|
||||||
|
|
||||||
expect(root.children[0].kind).toBe("folder");
|
expect(root.children[0].kind).toBe("folder");
|
||||||
expect(root.children[1].kind).toBe("leaf");
|
expect(root.children[1].kind).toBe("leaf");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("filters on both session name and directory", () => {
|
|
||||||
const sessions = [session("a", "/home/n/alpha", "claude"), session("b", "/home/n/beta", "bash")];
|
|
||||||
|
|
||||||
const byDir = buildTree(sessions, "/home/n", "alpha") as TreeFolder;
|
|
||||||
expect(names(byDir)).toEqual(["~/alpha"]);
|
|
||||||
|
|
||||||
const byCommand = buildTree(sessions, "/home/n", "claude") as TreeFolder;
|
|
||||||
expect(names(byCommand)).toEqual(["~/alpha"]);
|
|
||||||
|
|
||||||
const noMatch = buildTree(sessions, "/home/n", "zzz") as TreeFolder;
|
|
||||||
expect(noMatch.children).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("ignores case and surrounding whitespace in the filter", () => {
|
|
||||||
const root = buildTree([session("a", "/home/n/Alpha")], "/home/n", " ALPHA ") as TreeFolder;
|
|
||||||
expect(root.children).toHaveLength(1);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("mergeLinear", () => {
|
describe("mergeLinear", () => {
|
||||||
@@ -127,7 +105,6 @@ describe("worktree sessions group under their repository (#99)", () => {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
"/home/n",
|
"/home/n",
|
||||||
"",
|
|
||||||
) as TreeFolder;
|
) as TreeFolder;
|
||||||
|
|
||||||
expect(topFolders(root)).toEqual(["~/tea/agent-skills"]);
|
expect(topFolders(root)).toEqual(["~/tea/agent-skills"]);
|
||||||
@@ -147,7 +124,6 @@ describe("worktree sessions group under their repository (#99)", () => {
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
"/home/n",
|
"/home/n",
|
||||||
"",
|
|
||||||
) as TreeFolder;
|
) as TreeFolder;
|
||||||
|
|
||||||
expect(topFolders(root)).toEqual(["~/tea/agent-skills"]);
|
expect(topFolders(root)).toEqual(["~/tea/agent-skills"]);
|
||||||
@@ -157,7 +133,7 @@ describe("worktree sessions group under their repository (#99)", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("leaves a session without a worktree where it is", () => {
|
it("leaves a session without a worktree where it is", () => {
|
||||||
const root = buildTree([session("a", "/home/n/tea/arr")], "/home/n", "") as TreeFolder;
|
const root = buildTree([session("a", "/home/n/tea/arr")], "/home/n") as TreeFolder;
|
||||||
expect(topFolders(root)).toEqual(["~/tea/arr"]);
|
expect(topFolders(root)).toEqual(["~/tea/arr"]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+1
-6
@@ -25,19 +25,14 @@ export function compareNodes(a: TreeNode, b: TreeNode): number {
|
|||||||
return an.localeCompare(bn);
|
return an.localeCompare(bn);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildTree(sessions: Session[], home: string | undefined, filter: string): TreeNode {
|
export function buildTree(sessions: Session[], home: string | undefined): TreeNode {
|
||||||
const root: TreeFolder = { kind: "folder", name: "", path: "", children: [] };
|
const root: TreeFolder = { kind: "folder", name: "", path: "", children: [] };
|
||||||
const lc = filter.trim().toLowerCase();
|
|
||||||
|
|
||||||
for (const s of sessions) {
|
for (const s of sessions) {
|
||||||
// Grouped by repository, so a worktree session lands under its repo
|
// Grouped by repository, so a worktree session lands under its repo
|
||||||
// rather than in a folder of its own (#99).
|
// rather than in a folder of its own (#99).
|
||||||
const cwd = sessionTreePath(s);
|
const cwd = sessionTreePath(s);
|
||||||
const dir = cwd ? abbreviateCwd(cwd, home) : "";
|
const dir = cwd ? abbreviateCwd(cwd, home) : "";
|
||||||
if (lc) {
|
|
||||||
const haystack = `${sessionName(s)} ${dir}`.toLowerCase();
|
|
||||||
if (!haystack.includes(lc)) continue;
|
|
||||||
}
|
|
||||||
const parts = dir ? dir.split("/").filter(Boolean) : [];
|
const parts = dir ? dir.split("/").filter(Boolean) : [];
|
||||||
let cursor = root;
|
let cursor = root;
|
||||||
for (const part of parts) {
|
for (const part of parts) {
|
||||||
|
|||||||
@@ -50,6 +50,12 @@ export interface Session {
|
|||||||
* create one. `base_repo` is the repository's main checkout, which is what
|
* create one. `base_repo` is the repository's main checkout, which is what
|
||||||
* the session tree groups by (#99). */
|
* the session tree groups by (#99). */
|
||||||
worktree?: SessionWorktree | null;
|
worktree?: SessionWorktree | null;
|
||||||
|
/** Wall-clock of when this session last became the pane a client was showing
|
||||||
|
* (#145) — stamped by both `POST /api/sessions/:id/focus` and opening
|
||||||
|
* `/api/attach/:id`. Absent until the session has been focused once, which is
|
||||||
|
* how the command bar's empty query sorts a never-focused session after every
|
||||||
|
* session that has one (`docs/COMMAND-BAR.md`). */
|
||||||
|
last_focused_at?: IsoTimestamp | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A session's daemon-created worktree (`SessionWorktree` on the wire). */
|
/** A session's daemon-created worktree (`SessionWorktree` on the wire). */
|
||||||
|
|||||||
Reference in New Issue
Block a user