diff --git a/README.md b/README.md index 66af05b..ed58229 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,14 @@ Authorization: Bearer {{token}} { "name": "Ada" } ``` +You can keep several collections open; each gets its own section in the +sidebar (**Open…** adds one, **×** closes it), and they are reopened on the next +start. A collection has its own environments, selected environment, cookies and +file watcher. The environment picker in the top bar belongs to the *current* +collection: the active tab's, or for a new untitled tab, the one you last +clicked or opened a request from. Folders that contain each other can't be open +at the same time. + Environments come from `http-client.env.json` (committed) and `http-client.private.env.json` (secrets, git-ignored) next to the `.http` files. Pick one in the top bar; **Edit…** opens the environment editor. Variables are @@ -60,6 +68,9 @@ Other things worth knowing: - **File → Import Postman collection…** converts a v2.1 collection into a folder of `.http` files plus `http-client.env.json`. Scripts are skipped and listed. The CLI does the same: `reqlite import postman coll.json out/ --env env.json`. +- Rename a request by double-clicking its tab, from the tab's or sidebar's + right-click menu, or **…** → *Rename…*. Right-clicking a tab also offers + *Close others* and *Close all*. - The **Source** tab shows the request as `.http` text; edits there and in the form stay in sync. - The **Auth** tab is a helper that writes the `Authorization` header. Basic @@ -79,6 +90,7 @@ Other things worth knowing: | Ctrl+S | Save | | Ctrl+T | New tab | | Ctrl+W | Close tab | +| Ctrl+Shift+W | Close all tabs | | Ctrl+L | Focus the URL bar | | Ctrl+P | Quick-open a request | | Ctrl+F | Find in the response | diff --git a/crates/app/src/action.rs b/crates/app/src/action.rs index ff4a7bf..edadfdc 100644 --- a/crates/app/src/action.rs +++ b/crates/app/src/action.rs @@ -26,6 +26,15 @@ pub enum Action { CloseTab(TabId), /// Close even with unsaved changes. DiscardAndCloseTab(TabId), + /// Close several tabs; asks once about the ones with unsaved changes. + CloseTabs(Vec), + DiscardAndCloseTabs(Vec), + /// Rename the tab's request: in its file right away if the tab has no + /// other unsaved edits, else as an edit that Save writes. + RenameTab { + tab: TabId, + title: String, + }, SelectTab(TabId), OpenRequest { file: PathBuf, @@ -73,14 +82,20 @@ pub enum Action { // Collections. PickCollection, OpenCollection(PathBuf), + CloseCollection(PathBuf), + /// Makes a collection the current one (environment picker, untitled tabs). + SetActiveCollection(PathBuf), CollectionLoaded(Result), /// The environments, and whether the private file exists without being git-ignored. - EnvironmentsLoaded(Result<(Environments, bool), String>), + EnvironmentsLoaded { + root: PathBuf, + result: Result<(Environments, bool), String>, + }, FileChangedOnDisk { path: PathBuf, text: Option, }, - Rescan, + Rescan(PathBuf), Save(TabId), /// `existing` is the current content of `path`, if it exists. SaveAs { @@ -130,8 +145,8 @@ pub enum Action { EnvEditorChanged(EnvEditor), EnvEditorSave, EnvEditorClose, - AddPrivateFileToGitignore, - DismissGitignoreOffer, + AddPrivateFileToGitignore(PathBuf), + DismissGitignoreOffer(PathBuf), // Import / export. CopyAsCurl(TabId), @@ -187,9 +202,55 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { state.dialog = None; close_tab(state, id); } + Action::CloseTabs(ids) => { + let mut dirty = Vec::new(); + for id in ids { + if state.tab(id).is_some_and(Tab::is_dirty) { + dirty.push(id); + } else { + close_tab(state, id); + } + } + if !dirty.is_empty() { + state.dialog = Some(Dialog::ConfirmCloseTabs(dirty)); + } + } + Action::DiscardAndCloseTabs(ids) => { + state.dialog = None; + for id in ids { + close_tab(state, id); + } + } + Action::RenameTab { tab, title } => { + state.dialog = None; + let Some(t) = state.tab(tab) else { return fx }; + let in_file = t + .origin + .as_ref() + .filter(|_| !t.is_dirty()) + .and_then(|o| Some((o.file.clone(), file_of(state, &o.file)?.find(&o.key)?))); + if let Some((file, index)) = in_file { + return update(state, Action::RenameRequest { file, index, title }); + } + let title = title.trim().to_string(); + edit(state, tab, |r| { + r.title = (!title.is_empty()).then_some(title); + if r.name.is_some() { + r.name = r.title.as_deref().map(slug_name); + } + }); + } Action::SelectTab(id) => { - if state.tab(id).is_some() { + if let Some(t) = state.tab(id) { + let root = t + .origin + .as_ref() + .and_then(|o| state.collection_of(&o.file)) + .map(|c| c.root.clone()); state.active = Some(id); + if root.is_some() { + state.active_collection = root; + } } } Action::OpenRequest { file, index } => open_request(state, &file, index), @@ -357,23 +418,78 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { // ---------------------------------------------------- collections Action::PickCollection => fx.push(Effect::PickCollectionFolder), Action::OpenCollection(root) => { + if state.collection(&root).is_some() { + state.active_collection = Some(root); + return fx; + } + if let Some(other) = state + .collections + .iter() + .find(|c| root.starts_with(&c.root) || c.root.starts_with(&root)) + { + state.set_error(format!( + "{} overlaps the open collection {}; close that one first", + root.display(), + other.root.display() + )); + return fx; + } state.settings.add_recent(root.clone()); + if !state.settings.open_collections.contains(&root) { + state.settings.open_collections.push(root.clone()); + } fx.push(Effect::SaveSettings(state.settings.clone())); fx.push(Effect::LoadCollection(root)); } + Action::CloseCollection(root) => { + let Some(pos) = state.collections.iter().position(|c| c.root == root) else { + return fx; + }; + state.collections.remove(pos); + fx.push(Effect::Unwatch(root.clone())); + state.settings.open_collections.retain(|r| r != &root); + fx.push(Effect::SaveSettings(state.settings.clone())); + state.cookie_jars.remove(&Some(root.clone())); + if state.env_editor.as_ref().is_some_and(|e| e.root == root) { + state.env_editor = None; + } + if state.active_collection.as_ref() == Some(&root) { + state.active_collection = state.collections.first().map(|c| c.root.clone()); + } + // Clean tabs from it close; tabs with edits stay, detached from their file. + let ids: Vec<(TabId, bool)> = state + .tabs + .iter() + .filter(|t| t.origin.as_ref().is_some_and(|o| o.file.starts_with(&root))) + .map(|t| (t.id, t.is_dirty())) + .collect(); + for (id, dirty) in ids { + if dirty { + if let Some(t) = state.tab_mut(id) { + t.origin = None; + t.orphaned = true; + } + } else { + close_tab(state, id); + } + } + } + Action::SetActiveCollection(root) => { + if state.collection(&root).is_some() { + state.active_collection = Some(root); + } + } Action::CollectionLoaded(Err(e)) => state.set_error(format!("Could not open the collection: {e}")), Action::CollectionLoaded(Ok(c)) => collection_loaded(state, c, &mut fx), - Action::EnvironmentsLoaded(res) => { - if let Some(c) = &mut state.collection { - match res { + Action::EnvironmentsLoaded { root, result } => { + if let Some(c) = state.collection_mut(&root) { + match result { Ok((envs, private_not_ignored)) => { c.envs = envs; c.env_error = None; c.private_not_ignored = private_not_ignored; - if let Some(sel) = &state.selected_env { - if !c.envs.names().contains(sel) { - state.selected_env = None; - } + if c.selected_env.as_ref().is_some_and(|sel| !c.envs.names().contains(sel)) { + c.selected_env = None; } } Err(e) => c.env_error = Some(e), @@ -381,9 +497,9 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { } } Action::FileChangedOnDisk { path, text } => file_changed(state, path, text, &mut fx), - Action::Rescan => { - if let Some(c) = &state.collection { - fx.push(Effect::LoadCollection(c.root.clone())); + Action::Rescan(root) => { + if state.collection(&root).is_some() { + fx.push(Effect::LoadCollection(root)); } } Action::Save(id) => save(state, id, &mut fx), @@ -410,7 +526,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { format!("{name}.http") }; let path = dir.join(name); - if state.collection.as_ref().is_some_and(|c| c.files.contains_key(&path)) { + if state.collection_of(&path).is_some_and(|c| c.files.contains_key(&path)) { state.set_error(format!("{} already exists", path.display())); return fx; } @@ -568,7 +684,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { } } } - if let Some(c) = &mut state.collection { + if let Some(c) = state.collection_of_mut(&path) { if let Some(f) = c.files.remove(&path) { c.files.insert(to, f); } @@ -586,7 +702,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { .map(|e| e.to_string_lossy().into_owned()) .unwrap_or("http".into()); let dir = path.parent().map(Path::to_path_buf).unwrap_or_default(); - let taken = |p: &PathBuf| state.collection.as_ref().is_some_and(|c| c.files.contains_key(p)); + let taken = |p: &PathBuf| state.collection_of(p).is_some_and(|c| c.files.contains_key(p)); let copy = std::iter::once(dir.join(format!("{stem} copy.{ext}"))) .chain((2..).map(|n| dir.join(format!("{stem} copy {n}.{ext}")))) .find(|p| !taken(p)) @@ -598,21 +714,30 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { state.dialog = None; fx.push(file_ops(state, vec![FileOp::Delete(path.clone())], true)); orphan_tabs(state, &path, None); - if let Some(c) = &mut state.collection { + if let Some(c) = state.collection_of_mut(&path) { c.files.remove(&path); } } // ---------------------------------------------------- environments - Action::SelectEnv(e) => state.selected_env = e, + Action::SelectEnv(e) => { + let Some(root) = state.current_collection().map(|c| c.root.clone()) else { + return fx; + }; + if let Some(c) = state.collection_mut(&root) { + c.selected_env = e; + } + state.active_collection = Some(root); + } Action::OpenEnvEditor => { - if let Some(c) = &state.collection { - let selected = state + if let Some(c) = state.current_collection() { + let selected = c .selected_env .clone() .or_else(|| c.envs.names().first().cloned()) .unwrap_or_else(|| "dev".into()); state.env_editor = Some(EnvEditor { + root: c.root.clone(), envs: c.envs.clone(), selected, revealed: Vec::new(), @@ -625,7 +750,8 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { Action::EnvEditorChanged(e) => state.env_editor = Some(e), Action::EnvEditorClose => state.env_editor = None, Action::EnvEditorSave => { - let (Some(ed), Some(c)) = (&mut state.env_editor, &mut state.collection) else { + let Some(ed) = &mut state.env_editor else { return fx }; + let Some(c) = state.collections.iter_mut().find(|c| c.root == ed.root) else { return fx; }; let mut ops = Vec::new(); @@ -643,14 +769,14 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { fx.push(Effect::LoadEnvironments(c.root.clone())); } } - Action::AddPrivateFileToGitignore => { - if let Some(c) = &mut state.collection { - fx.push(Effect::AppendGitignore(c.root.clone())); + Action::AddPrivateFileToGitignore(root) => { + if let Some(c) = state.collection_mut(&root) { + fx.push(Effect::AppendGitignore(root)); c.private_not_ignored = false; } } - Action::DismissGitignoreOffer => { - if let Some(c) = &mut state.collection { + Action::DismissGitignoreOffer(root) => { + if let Some(c) = state.collection_mut(&root) { c.gitignore_offer_dismissed = true; } } @@ -697,13 +823,14 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { Action::RestoreHistory(i) => { if let Some(e) = state.history.get(i) { let text = e.http.clone(); - if e.env.is_some() - && state - .collection - .as_ref() - .is_some_and(|c| c.envs.names().contains(e.env.as_ref().unwrap())) - { - state.selected_env = e.env.clone(); + let env = e.env.clone(); + let root = state.current_collection().map(|c| c.root.clone()); + if let (Some(env), Some(root)) = (env, root) { + if let Some(c) = state.collection_mut(&root) { + if c.envs.names().contains(&env) { + c.selected_env = Some(env); + } + } } return update(state, Action::NewTabFromHttp(text)); } @@ -713,11 +840,11 @@ pub fn update(state: &mut AppState, action: Action) -> Vec { fx.push(Effect::RewriteHistory(Vec::new())); } Action::ClearCookies => { - let key = state.collection.as_ref().map(|c| c.root.clone()); + let key = state.current_collection().map(|c| c.root.clone()); state.cookie_jars.entry(key).or_default().clear(); } Action::DeleteCookie(i) => { - let key = state.collection.as_ref().map(|c| c.root.clone()); + let key = state.current_collection().map(|c| c.root.clone()); state.cookie_jars.entry(key).or_default().remove(i); } Action::SettingsLoaded(s) => { @@ -795,23 +922,27 @@ fn close_tab(state: &mut AppState, id: TabId) { } fn file_of<'a>(state: &'a AppState, path: &Path) -> Option<&'a HttpFile> { - state.collection.as_ref()?.files.get(path) + state.collection_of(path)?.files.get(path) } fn insert_file(state: &mut AppState, path: &Path, text: String) { - if let Some(c) = &mut state.collection { + if let Some(c) = state.collection_of_mut(path) { c.files.insert(path.to_path_buf(), HttpFile::parse(text)); } } +/// File operations, followed by a rescan of the collection of the first +/// operation's file when `rescan` is set. fn file_ops(state: &AppState, ops: Vec, rescan: bool) -> Effect { + let first = ops.first().map(|op| match op { + FileOp::Write(p, _) | FileOp::Delete(p) | FileOp::Rename(p, _) => p.clone(), + }); Effect::FileOps { + rescan: first + .filter(|_| rescan) + .and_then(|p| state.collection_of(&p)) + .map(|c| c.root.clone()), ops, - rescan: if rescan { - state.collection.as_ref().map(|c| c.root.clone()) - } else { - None - }, } } @@ -830,6 +961,7 @@ fn open_request(state: &mut AppState, file: &Path, index: usize) { return; }; let (req, src) = (req.clone(), src.to_string()); + state.active_collection = state.collection_of(file).map(|c| c.root.clone()); new_tab( state, req, @@ -894,7 +1026,9 @@ fn send(state: &mut AppState, id: TabId, fx: &mut Vec) { } }; - let jar_key = (!t.request.directives.no_cookie_jar).then(|| state.collection.as_ref().map(|c| c.root.clone())); + let collection = state.collection_for_tab(t); + let jar_key = (!t.request.directives.no_cookie_jar).then(|| collection.map(|c| c.root.clone())); + let env = collection.and_then(|c| c.selected_env.clone()); if let Some(key) = &jar_key { let has_cookie = resolved.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("cookie")); if let Some(c) = state @@ -917,7 +1051,7 @@ fn send(state: &mut AppState, id: TabId, fx: &mut Vec) { url: resolved.url.clone(), status: None, duration_ms: 0, - env: state.selected_env.clone(), + env, http: if t.source.trim().is_empty() { render_request(&t.request, "\n") } else { @@ -1068,54 +1202,55 @@ fn recompute_search(t: &mut Tab) { } fn collection_loaded(state: &mut AppState, c: Collection, fx: &mut Vec) { - let same_root = state.collection.as_ref().is_some_and(|old| old.root == c.root); - let (envs, env_error, dismissed) = match state.collection.take() { - Some(old) if same_root => (old.envs, old.env_error, old.gitignore_offer_dismissed), - _ => (Environments::default(), None, false), - }; let root = c.root.clone(); - state.collection = Some(CollectionState { - root: c.root, - tree: c.tree, - files: c.files, - envs, - env_error, - private_not_ignored: false, - gitignore_offer_dismissed: dismissed, - }); - if !same_root { - // Tabs from another collection keep their content but lose their file. - for t in state.tabs.iter_mut() { - if t.origin.as_ref().is_some_and(|o| !o.file.starts_with(&root)) { - t.origin = None; - t.orphaned = true; - } - } - state.selected_env = None; - fx.push(Effect::Watch(Some(root.clone()))); - } else { - // Re-sync open tabs with what's on disk now. - let ids: Vec<(TabId, PathBuf)> = state - .tabs - .iter() - .filter_map(|t| t.origin.as_ref().map(|o| (t.id, o.file.clone()))) - .collect(); - for (id, file) in ids { - if file_of(state, &file).is_none() { - if let Some(t) = state.tab_mut(id) { - t.orphaned = true; + match state.collection_mut(&root) { + Some(existing) => { + // A rescan: keep environments and choices, take the new tree. + existing.tree = c.tree; + existing.files = c.files; + let ids: Vec<(TabId, PathBuf)> = state + .tabs + .iter() + .filter_map(|t| t.origin.as_ref().map(|o| (t.id, o.file.clone()))) + .filter(|(_, f)| f.starts_with(&root)) + .collect(); + for (id, file) in ids { + if file_of(state, &file).is_none() { + if let Some(t) = state.tab_mut(id) { + t.orphaned = true; + } } } } + None => { + state.collections.push(CollectionState { + root: c.root, + tree: c.tree, + files: c.files, + envs: Environments::default(), + selected_env: None, + env_error: None, + private_not_ignored: false, + gitignore_offer_dismissed: false, + }); + state.active_collection = Some(root.clone()); + fx.push(Effect::Watch(root.clone())); + } } fx.push(Effect::LoadEnvironments(root)); } fn file_changed(state: &mut AppState, path: PathBuf, text: Option, fx: &mut Vec) { - let Some(c) = &mut state.collection else { return }; + let Some(c) = state.collection_of_mut(&path) else { + return; + }; + let root = c.root.clone(); let name = path.file_name().and_then(|n| n.to_str()).unwrap_or(""); if name == env::PUBLIC_FILE || name == env::PRIVATE_FILE { - fx.push(Effect::LoadEnvironments(c.root.clone())); + // Only the env files at the collection root count. + if path.parent() == Some(root.as_path()) { + fx.push(Effect::LoadEnvironments(root)); + } return; } if !collection::is_http_file(&path) { @@ -1125,7 +1260,7 @@ fn file_changed(state: &mut AppState, path: PathBuf, text: Option, fx: & None => { if c.files.remove(&path).is_some() { orphan_tabs(state, &path, None); - fx.push(Effect::LoadCollection(state.collection.as_ref().unwrap().root.clone())); + fx.push(Effect::LoadCollection(root)); } } Some(text) => { @@ -1135,7 +1270,7 @@ fn file_changed(state: &mut AppState, path: PathBuf, text: Option, fx: & let is_new = !c.files.contains_key(&path); c.files.insert(path.clone(), HttpFile::parse(text)); if is_new { - fx.push(Effect::LoadCollection(c.root.clone())); + fx.push(Effect::LoadCollection(root)); } let ids: Vec = state .tabs @@ -1295,11 +1430,7 @@ fn save_as(state: &mut AppState, id: TabId, path: PathBuf, existing: Option Response { /// A loaded collection at `/c` with the given files. fn with_collection(s: &mut AppState, files: &[(&str, &str)]) -> PathBuf { - let root = PathBuf::from("/c"); + with_collection_at(s, "/c", files) +} + +/// Loads a collection at `root` with the given files. +fn with_collection_at(s: &mut AppState, root: &str, files: &[(&str, &str)]) -> PathBuf { + let root = PathBuf::from(root); let c = Collection { root: root.clone(), tree: Node::Folder { @@ -56,7 +61,7 @@ fn with_collection(s: &mut AppState, files: &[(&str, &str)]) -> PathBuf { .collect(), }; let fx = update(s, Action::CollectionLoaded(Ok(c))); - assert!(fx.iter().any(|e| matches!(e, Effect::Watch(Some(_))))); + assert!(fx.iter().any(|e| matches!(e, Effect::Watch(_)))); assert!(fx.iter().any(|e| matches!(e, Effect::LoadEnvironments(_)))); root } @@ -239,7 +244,13 @@ fn environments_resolve_and_switch() { .unwrap(), private: EnvFile::parse(r#"{"dev": {"token": "t-dev"}, "prod": {"token": "t-prod"}}"#, &root).unwrap(), }; - update(&mut s, Action::EnvironmentsLoaded(Ok((envs, false)))); + update( + &mut s, + Action::EnvironmentsLoaded { + root: root.clone(), + result: Ok((envs, false)), + }, + ); update( &mut s, Action::OpenRequest { @@ -260,7 +271,7 @@ fn environments_resolve_and_switch() { }; assert_eq!(request.url, url); assert_eq!(request.headers[0].1, auth); - assert!(s.is_private_var("token")); + assert!(s.is_private_var(s.tab(id).unwrap(), "token")); let seq = *seq; update( &mut s, @@ -607,7 +618,7 @@ fn create_rename_duplicate_move_delete() { }, ); assert!(s.tab(copy_tab).unwrap().orphaned); - assert_eq!(s.collection.as_ref().unwrap().files[&other].request_count(), 2); + assert_eq!(s.collection_of(&other).unwrap().files[&other].request_count(), 2); } #[test] @@ -710,7 +721,7 @@ fn env_editor_writes_both_files() { assert!(w .iter() .any(|(p, t)| p == &root.join(env::PRIVATE_FILE) && t.contains("\"token\": \"secret\""))); - assert_eq!(s.collection.as_ref().unwrap().envs.names(), vec!["dev"]); + assert_eq!(s.collection(&root).unwrap().envs.names(), vec!["dev"]); } #[test] @@ -759,3 +770,318 @@ fn concurrency_setting_reaches_the_runner() { let fx = update(&mut s, Action::SettingsChanged(changed)); assert!(fx.iter().any(|e| matches!(e, Effect::SetConcurrency(5)))); } + +// ------------------------------------------------- several collections + +fn load_envs(s: &mut AppState, root: &Path, public: &str) { + let envs = Environments { + public: EnvFile::parse(public, root).unwrap(), + private: EnvFile::default(), + }; + update( + s, + Action::EnvironmentsLoaded { + root: root.to_path_buf(), + result: Ok((envs, false)), + }, + ); +} + +fn sent_url(s: &mut AppState, id: TabId) -> String { + let fx = update(s, Action::Send(id)); + let Effect::SendRequest { request, seq, .. } = &fx[0] else { + panic!("{fx:?} / {:?}", s.tab(id).unwrap().error) + }; + let (url, seq) = (request.url.clone(), *seq); + update( + s, + Action::ResponseReceived { + tab: id, + seq, + result: Err(HttpError::Timeout), + }, + ); + url +} + +#[test] +fn each_collection_has_its_own_environment() { + let mut s = state(); + let a = with_collection_at(&mut s, "/a", &[("a.http", "### A\nGET {{base}}/a\n")]); + let b = with_collection_at(&mut s, "/b", &[("b.http", "### B\nGET {{base}}/b\n")]); + assert_eq!(s.collections.len(), 2); + load_envs(&mut s, &a, r#"{"dev": {"base": "http://a-dev"}}"#); + load_envs( + &mut s, + &b, + r#"{"dev": {"base": "http://b-dev"}, "prod": {"base": "https://b-prod"}}"#, + ); + + update( + &mut s, + Action::OpenRequest { + file: a.join("a.http"), + index: 0, + }, + ); + let ta = active(&s); + update(&mut s, Action::SelectEnv(Some("dev".into()))); + update( + &mut s, + Action::OpenRequest { + file: b.join("b.http"), + index: 0, + }, + ); + let tb = active(&s); + // The picker now acts on /b, which has no environment selected yet. + assert_eq!(s.current_collection().unwrap().root, b); + assert!(s.current_collection().unwrap().selected_env.is_none()); + update(&mut s, Action::SelectEnv(Some("prod".into()))); + + assert_eq!(sent_url(&mut s, ta), "http://a-dev/a"); + assert_eq!(sent_url(&mut s, tb), "https://b-prod/b"); + assert_eq!(s.collection(&a).unwrap().selected_env.as_deref(), Some("dev")); +} + +#[test] +fn untitled_tabs_use_the_active_collection() { + let mut s = state(); + let a = with_collection_at(&mut s, "/a", &[]); + let b = with_collection_at(&mut s, "/b", &[]); + load_envs(&mut s, &a, r#"{"dev": {"base": "http://a"}}"#); + load_envs(&mut s, &b, r#"{"dev": {"base": "http://b"}}"#); + for root in [&a, &b] { + update(&mut s, Action::SetActiveCollection(root.clone())); + update(&mut s, Action::SelectEnv(Some("dev".into()))); + } + update(&mut s, Action::NewTab); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "{{base}}/x".into())); + assert_eq!(sent_url(&mut s, id), "http://b/x", "the last opened/clicked collection"); + update(&mut s, Action::SetActiveCollection(a.clone())); + assert_eq!(sent_url(&mut s, id), "http://a/x"); +} + +#[test] +fn opening_a_collection_twice_or_nested_is_refused() { + let mut s = state(); + let a = with_collection_at(&mut s, "/work/api", &[]); + with_collection_at(&mut s, "/other", &[]); + // Already open: just becomes current, nothing is loaded again. + assert!(update(&mut s, Action::OpenCollection(a.clone())).is_empty()); + assert_eq!(s.active_collection.as_ref(), Some(&a)); + for overlapping in ["/work/api/sub", "/work"] { + assert!(update(&mut s, Action::OpenCollection(overlapping.into())).is_empty()); + assert!(s.status.as_ref().unwrap().is_error); + } + let fx = update(&mut s, Action::OpenCollection("/work/web".into())); + assert!(fx.iter().any(|e| matches!(e, Effect::LoadCollection(_)))); + assert_eq!(s.settings.open_collections, vec![PathBuf::from("/work/web")]); +} + +#[test] +fn closing_a_collection_closes_its_clean_tabs_and_keeps_edits() { + let mut s = state(); + let a = with_collection_at(&mut s, "/a", &[("a.http", "### A\nGET /a\n\n### A2\nGET /a2\n")]); + let b = with_collection_at(&mut s, "/b", &[("b.http", "### B\nGET /b\n")]); + s.settings.open_collections = vec![a.clone(), b.clone()]; + update( + &mut s, + Action::OpenRequest { + file: a.join("a.http"), + index: 0, + }, + ); + let clean = active(&s); + update( + &mut s, + Action::OpenRequest { + file: a.join("a.http"), + index: 1, + }, + ); + let dirty = active(&s); + update(&mut s, Action::UrlEdited(dirty, "/edited".into())); + update( + &mut s, + Action::OpenRequest { + file: b.join("b.http"), + index: 0, + }, + ); + let other = active(&s); + + let fx = update(&mut s, Action::CloseCollection(a.clone())); + assert!(fx.iter().any(|e| matches!(e, Effect::Unwatch(r) if r == &a))); + assert!(s.tab(clean).is_none()); + let t = s.tab(dirty).unwrap(); + assert!(t.orphaned && t.origin.is_none() && t.request.url == "/edited"); + assert!(s.tab(other).unwrap().origin.is_some()); + assert_eq!(s.collections.len(), 1); + assert_eq!(s.settings.open_collections, vec![b]); +} + +#[test] +fn moving_a_request_between_collections() { + let mut s = state(); + let a = with_collection_at(&mut s, "/a", &[("a.http", "### A\nGET /a\n")]); + let b = with_collection_at(&mut s, "/b", &[("b.http", "### B\nGET /b\n")]); + let fx = update( + &mut s, + Action::MoveRequest { + from: a.join("a.http"), + index: 0, + to: b.join("b.http"), + }, + ); + let w = writes(&fx); + assert!(w.contains(&(b.join("b.http"), "### B\nGET /b\n\n### A\nGET /a\n".into()))); + assert!(w.contains(&(a.join("a.http"), String::new()))); + assert_eq!(s.collection(&b).unwrap().files[&b.join("b.http")].request_count(), 2); +} + +#[test] +fn disk_changes_go_to_the_right_collection() { + let mut s = state(); + let a = with_collection_at(&mut s, "/a", &[("x.http", "GET /a\n")]); + let b = with_collection_at(&mut s, "/b", &[("x.http", "GET /b\n")]); + update( + &mut s, + Action::FileChangedOnDisk { + path: b.join("x.http"), + text: Some("GET /b2\n".into()), + }, + ); + assert_eq!(s.collection(&a).unwrap().files[&a.join("x.http")].text(), "GET /a\n"); + assert_eq!(s.collection(&b).unwrap().files[&b.join("x.http")].text(), "GET /b2\n"); + // Env files reload only their own collection, and only at its root. + let fx = update( + &mut s, + Action::FileChangedOnDisk { + path: a.join(env::PUBLIC_FILE), + text: Some("{}".into()), + }, + ); + assert!(matches!(&fx[..], [Effect::LoadEnvironments(r)] if r == &a)); + let fx = update( + &mut s, + Action::FileChangedOnDisk { + path: a.join("sub").join(env::PUBLIC_FILE), + text: Some("{}".into()), + }, + ); + assert!(fx.is_empty()); +} + +// ------------------------------------------------- close all, rename tabs + +#[test] +fn close_all_closes_clean_tabs_and_asks_once_about_the_rest() { + let mut s = state(); + for url in ["", "http://edited", "", "http://also-edited"] { + update(&mut s, Action::NewTab); + if !url.is_empty() { + let id = active(&s); + update(&mut s, Action::UrlEdited(id, url.into())); + } + } + let ids: Vec = s.tabs.iter().map(|t| t.id).collect(); + update(&mut s, Action::CloseTabs(ids.clone())); + assert_eq!(s.tabs.len(), 2, "the clean tabs are gone"); + let dirty = vec![ids[1], ids[3]]; + assert_eq!(s.dialog, Some(Dialog::ConfirmCloseTabs(dirty.clone()))); + update(&mut s, Action::DiscardAndCloseTabs(dirty)); + assert!(s.tabs.is_empty()); + assert!(s.active.is_none()); + assert!(s.dialog.is_none()); +} + +#[test] +fn close_others_keeps_the_chosen_tab() { + let mut s = state(); + for _ in 0..3 { + update(&mut s, Action::NewTab); + } + let keep = s.tabs[1].id; + let others = s.tabs.iter().map(|t| t.id).filter(|&t| t != keep).collect(); + update(&mut s, Action::CloseTabs(others)); + assert_eq!(s.tabs.len(), 1); + assert_eq!(s.active, Some(keep)); +} + +#[test] +fn renaming_a_clean_tab_renames_the_request_in_its_file() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + let file = root.join("users.http"); + update( + &mut s, + Action::OpenRequest { + file: file.clone(), + index: 0, + }, + ); + let id = active(&s); + let fx = update( + &mut s, + Action::RenameTab { + tab: id, + title: "All users".into(), + }, + ); + let w = writes(&fx); + assert_eq!( + w, + vec![(file.clone(), USERS.replace("### List users", "### All users"))] + ); + let t = s.tab(id).unwrap(); + assert_eq!(t.title(), "All users"); + assert!(!t.is_dirty()); + assert_eq!(t.origin.as_ref().unwrap().key.name.as_deref(), Some("All users")); +} + +#[test] +fn renaming_an_edited_or_untitled_tab_is_an_edit_that_save_writes() { + let mut s = state(); + let root = with_collection(&mut s, &[("users.http", USERS)]); + let file = root.join("users.http"); + // `create-user` has an @name, which follows the new title. + update( + &mut s, + Action::OpenRequest { + file: file.clone(), + index: 1, + }, + ); + let id = active(&s); + update(&mut s, Action::UrlEdited(id, "{{base}}/v2/users".into())); + let fx = update( + &mut s, + Action::RenameTab { + tab: id, + title: "Add user".into(), + }, + ); + assert!(writes(&fx).is_empty(), "nothing is written before Save"); + assert_eq!(s.tab(id).unwrap().title(), "add-user"); + let w = writes(&update(&mut s, Action::Save(id))); + assert!( + w[0].1 + .contains("### Add user\n# @name add-user\nPOST {{base}}/v2/users"), + "{}", + w[0].1 + ); + + update(&mut s, Action::NewTab); + let untitled = active(&s); + update( + &mut s, + Action::RenameTab { + tab: untitled, + title: "Scratch".into(), + }, + ); + assert_eq!(s.tab(untitled).unwrap().title(), "Scratch"); + assert!(s.tab(untitled).unwrap().source.starts_with("### Scratch\n")); +} diff --git a/crates/app/src/effects.rs b/crates/app/src/effects.rs index 727d392..99b7703 100644 --- a/crates/app/src/effects.rs +++ b/crates/app/src/effects.rs @@ -2,6 +2,7 @@ //! watching). Each effect runs as a Tokio task and reports back by sending an //! [`Action`] over a channel and waking the UI. +use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -42,8 +43,10 @@ pub enum Effect { }, LoadCollection(PathBuf), LoadEnvironments(PathBuf), - /// Watch a collection folder (or stop watching). - Watch(Option), + /// Start watching a collection folder. + Watch(PathBuf), + /// Stop watching a collection folder. + Unwatch(PathBuf), /// Run file operations in order, then rescan the collection if given. FileOps { ops: Vec, @@ -118,7 +121,8 @@ pub struct Runner { outbox: Outbox, client: Arc, semaphore: Mutex>, - watcher: Arc>>, + /// One watcher per open collection, by root. + watchers: Mutex>, paths: Option, /// Serializes history writes. history_lock: Arc>, @@ -142,7 +146,7 @@ impl Runner { outbox: Outbox { tx, ctx }, client, semaphore: Mutex::new(Arc::new(Semaphore::new(max_concurrent.max(1)))), - watcher: Arc::new(Mutex::new(None)), + watchers: Mutex::new(HashMap::new()), paths, history_lock: Arc::new(tokio::sync::Mutex::new(())), }, @@ -167,10 +171,15 @@ impl Runner { Err(_) => Settings::default(), }; let limit = settings.history_limit; - if let Some(last) = settings.recent_collections.first().cloned() { - if last.is_dir() { - out.send(Action::OpenCollection(last)); - } + // Reopen what was open last time (older settings only know the + // most recent collection). + let reopen = if settings.open_collections.is_empty() { + settings.recent_collections.first().cloned().into_iter().collect() + } else { + settings.open_collections.clone() + }; + for root in reopen.into_iter().filter(|r| r.is_dir()) { + out.send(Action::OpenCollection(root)); } out.send(Action::SettingsLoaded(settings)); if let Ok(text) = tokio::fs::read_to_string(paths.history_file()).await { @@ -230,17 +239,23 @@ impl Runner { } Effect::LoadEnvironments(root) => { self.handle.spawn(async move { - let r = tokio::task::spawn_blocking(move || { + let dir = root.clone(); + let result = tokio::task::spawn_blocking(move || { + let root = dir; let envs = Environments::load(&root).map_err(|e| e.to_string())?; let not_ignored = root.join(env::PRIVATE_FILE).exists() && !env::private_file_ignored(&root); Ok((envs, not_ignored)) }) .await .unwrap_or_else(|e| Err(e.to_string())); - out.send(Action::EnvironmentsLoaded(r)); + out.send(Action::EnvironmentsLoaded { root, result }); }); } Effect::Watch(root) => self.watch(root), + Effect::Unwatch(root) => { + // Dropping the watcher stops it and ends its event task. + self.watchers.lock().unwrap().remove(&root); + } Effect::FileOps { ops, rescan } => { self.handle.spawn(async move { for op in ops { @@ -412,10 +427,11 @@ impl Runner { /// Watches a collection with `notify`; changes are debounced and turned /// into `FileChangedOnDisk` actions (and a rescan when files come or go). - fn watch(&self, root: Option) { - let mut slot = self.watcher.lock().unwrap(); - *slot = None; // drops (stops) the old watcher - let Some(root) = root else { return }; + fn watch(&self, root: PathBuf) { + let mut watchers = self.watchers.lock().unwrap(); + if watchers.contains_key(&root) { + return; + } let (tx, mut rx) = mpsc::unbounded_channel::(); let watcher = notify::recommended_watcher(move |res: notify::Result| { if let Ok(ev) = res { @@ -435,7 +451,7 @@ impl Runner { .send(Action::Error(format!("Cannot watch {}: {e}", root.display()))); return; } - *slot = Some(watcher); + watchers.insert(root.clone(), watcher); let out = self.outbox(); self.handle.spawn(async move { while let Some(first) = rx.recv().await { @@ -474,7 +490,7 @@ impl Runner { out.send(Action::FileChangedOnDisk { path: p, text }); } if rescan { - out.send(Action::Rescan); + out.send(Action::Rescan(root.clone())); } } }); diff --git a/crates/app/src/settings.rs b/crates/app/src/settings.rs index b457781..1be6f12 100644 --- a/crates/app/src/settings.rs +++ b/crates/app/src/settings.rs @@ -39,6 +39,8 @@ pub struct Settings { pub max_concurrent_requests: usize, pub history_limit: usize, pub recent_collections: Vec, + /// Collections that were open when the app last ran. + pub open_collections: Vec, } impl Default for Settings { @@ -54,6 +56,7 @@ impl Default for Settings { max_concurrent_requests: 8, history_limit: 500, recent_collections: Vec::new(), + open_collections: Vec::new(), } } } diff --git a/crates/app/src/state.rs b/crates/app/src/state.rs index d6ff443..d470459 100644 --- a/crates/app/src/state.rs +++ b/crates/app/src/state.rs @@ -25,8 +25,11 @@ pub struct AppState { pub tabs: Vec, pub active: Option, pub next_tab_id: TabId, - pub collection: Option, - pub selected_env: Option, + /// Open collections, in the order they were opened. + pub collections: Vec, + /// The collection last chosen in the sidebar or through a tab. Untitled + /// tabs, the environment picker and the cookie viewer use it. + pub active_collection: Option, pub settings: Settings, /// Oldest first. pub history: Vec, @@ -61,6 +64,8 @@ pub struct Windows { pub enum Dialog { /// Closing a tab with unsaved changes. ConfirmCloseTab(TabId), + /// Closing several tabs, these of which have unsaved changes. + ConfirmCloseTabs(Vec), /// Quitting with unsaved changes. ConfirmQuit, /// The file of a tab with unsaved changes changed on disk. @@ -95,6 +100,7 @@ pub enum PromptKind { NewFile { dir: PathBuf }, RenameFile { path: PathBuf }, RenameRequest { file: PathBuf, index: usize }, + RenameTab { tab: TabId }, NewEnvironment, } @@ -107,6 +113,8 @@ pub struct QuickOpen { /// The environment editor works on a copy that is written on Save. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EnvEditor { + /// The collection whose env files are being edited. + pub root: PathBuf, pub envs: Environments, pub selected: String, /// Private values whose text is shown instead of `••••`. @@ -119,6 +127,7 @@ pub struct CollectionState { pub tree: Node, pub files: BTreeMap, pub envs: Environments, + pub selected_env: Option, pub env_error: Option, /// The private env file exists but is not git-ignored. pub private_not_ignored: bool, @@ -136,6 +145,14 @@ impl CollectionState { pub fn relative<'a>(&self, p: &'a Path) -> &'a Path { p.strip_prefix(&self.root).unwrap_or(p) } + + pub fn name(&self) -> &str { + self.tree.name() + } + + pub fn contains(&self, p: &Path) -> bool { + p.starts_with(&self.root) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] @@ -356,27 +373,68 @@ impl AppState { self.tabs.iter().any(Tab::is_dirty) } - /// File variables of the tab's file plus the selected environment. + /// The collection a path belongs to. + pub fn collection_of(&self, p: &Path) -> Option<&CollectionState> { + self.collections.iter().find(|c| c.contains(p)) + } + + pub fn collection_of_mut(&mut self, p: &Path) -> Option<&mut CollectionState> { + self.collections.iter_mut().find(|c| c.contains(p)) + } + + pub fn collection(&self, root: &Path) -> Option<&CollectionState> { + self.collections.iter().find(|c| c.root == root) + } + + pub fn collection_mut(&mut self, root: &Path) -> Option<&mut CollectionState> { + self.collections.iter_mut().find(|c| c.root == root) + } + + /// The collection the environment picker and untitled tabs use: the + /// active tab's, else the one last chosen, else the first. + pub fn current_collection(&self) -> Option<&CollectionState> { + if let Some(c) = self + .active_tab() + .and_then(|t| t.origin.as_ref()) + .and_then(|o| self.collection_of(&o.file)) + { + return Some(c); + } + self.active_collection + .as_deref() + .and_then(|r| self.collection(r)) + .or_else(|| self.collections.first()) + } + + /// The collection a tab belongs to (its file's, or the current one for + /// untitled tabs). + pub fn collection_for_tab(&self, tab: &Tab) -> Option<&CollectionState> { + match &tab.origin { + Some(o) => self.collection_of(&o.file), + None => self.current_collection(), + } + } + + /// File variables of the tab's file plus its collection's environment. pub fn resolver_for(&self, tab: &Tab) -> Resolver { let file_vars = tab .origin .as_ref() - .and_then(|o| self.collection.as_ref()?.files.get(&o.file)) + .and_then(|o| self.collection_of(&o.file)?.files.get(&o.file)) .map(|f| f.variables()) .unwrap_or_default(); - match &self.collection { - Some(c) => c.envs.resolver(self.selected_env.as_deref(), &file_vars), + match self.collection_for_tab(tab) { + Some(c) => c.envs.resolver(c.selected_env.as_deref(), &file_vars), None => Environments::default().resolver(None, &file_vars), } } /// Whether `name` comes from the private env file (shown masked). - pub fn is_private_var(&self, name: &str) -> bool { - match (&self.collection, &self.selected_env) { - (Some(c), Some(env)) => c.envs.is_private(env, name), - (Some(c), None) => c.envs.is_private(reqlite_core::env::SHARED_ENV, name), - _ => false, - } + pub fn is_private_var(&self, tab: &Tab, name: &str) -> bool { + self.collection_for_tab(tab).is_some_and(|c| { + let env = c.selected_env.as_deref().unwrap_or(reqlite_core::env::SHARED_ENV); + c.envs.is_private(env, name) + }) } /// Directory that relative file references in the tab resolve against. @@ -386,7 +444,7 @@ impl AppState { return p.to_path_buf(); } } - if let Some(c) = &self.collection { + if let Some(c) = self.current_collection() { return c.root.clone(); } std::env::current_dir().unwrap_or_default() diff --git a/crates/app/src/ui/mod.rs b/crates/app/src/ui/mod.rs index f7a981b..a231142 100644 --- a/crates/app/src/ui/mod.rs +++ b/crates/app/src/ui/mod.rs @@ -26,7 +26,7 @@ pub fn draw(ui: &mut Ui, state: &AppState, acts: &mut Vec) { match state.active_tab() { Some(tab) => { let resolver = state.resolver_for(tab); - let is_private = |n: &str| state.is_private_var(n); + let is_private = |n: &str| state.is_private_var(tab, n); let vars = VarCtx { resolver: &resolver, is_private: &is_private, @@ -76,6 +76,10 @@ fn shortcuts(ctx: &Context, state: &AppState, acts: &mut Vec) { if i.consume_shortcut(&cmd(Key::T)) { acts.push(Action::NewTab); } + // Before Ctrl+W, which would also match with Shift held. + if i.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND | Modifiers::SHIFT, Key::W)) { + acts.push(Action::CloseTabs(state.tabs.iter().map(|t| t.id).collect())); + } if i.consume_shortcut(&cmd(Key::W)) { if let Some(id) = active { acts.push(Action::CloseTab(id)); @@ -126,6 +130,13 @@ fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec) { acts.push(Action::Save(state.active.unwrap())); ui.close(); } + if ui + .add_enabled(has_tab, egui::Button::new("Close all tabs Ctrl+Shift+W")) + .clicked() + { + acts.push(Action::CloseTabs(state.tabs.iter().map(|t| t.id).collect())); + ui.close(); + } ui.separator(); if ui.button("Import Postman collection…").clicked() { acts.push(Action::ImportPostman); @@ -173,74 +184,99 @@ fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec) { // Environment picker on the right. ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if let Some(c) = &state.collection { + if let Some(c) = state.current_collection() { if ui.button("Edit…").on_hover_text("Edit environments").clicked() { acts.push(Action::OpenEnvEditor); } let names = c.envs.names(); - let label = state.selected_env.clone().unwrap_or_else(|| "No environment".into()); + let label = c.selected_env.clone().unwrap_or_else(|| "No environment".into()); egui::ComboBox::from_id_salt("env-picker") .selected_text(label) .width(150.0) .show_ui(ui, |ui| { if ui - .selectable_label(state.selected_env.is_none(), "No environment") + .selectable_label(c.selected_env.is_none(), "No environment") .clicked() { acts.push(Action::SelectEnv(None)); } for n in names { - if ui - .selectable_label(state.selected_env.as_ref() == Some(&n), &n) - .clicked() - { + if ui.selectable_label(c.selected_env.as_ref() == Some(&n), &n).clicked() { acts.push(Action::SelectEnv(Some(n.clone()))); } } }); - ui.label("Environment:"); + // With several collections, say whose environments these are. + if state.collections.len() > 1 { + ui.label(format!("{} environment:", c.name())) + .on_hover_text("The collection of the active tab, or the one last clicked in the sidebar"); + } else { + ui.label("Environment:"); + } } }); }); } fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec) { - egui::ScrollArea::horizontal().id_salt("tabs").show(ui, |ui| { - ui.horizontal(|ui| { - for t in &state.tabs { - let selected = state.active == Some(t.id); - let mut title = t.title(); - if t.is_dirty() { - title.push_str(" •"); - } - if t.in_flight.is_some() { - title.push_str(" ⏳"); - } - let resp = ui.selectable_label(selected, title); - let resp = match &t.origin { - Some(o) => resp.on_hover_text(o.file.display().to_string()), - None => resp, - }; - if resp.clicked() { - acts.push(Action::SelectTab(t.id)); - } - if resp.middle_clicked() { - acts.push(Action::CloseTab(t.id)); - } - resp.context_menu(|ui| { - if ui.button("Close").clicked() { - acts.push(Action::CloseTab(t.id)); - ui.close(); + // A non-floating scroll bar gets its own row under the tabs instead of + // being drawn over the tab names. + ui.scope(|ui| { + ui.spacing_mut().scroll.floating = false; + egui::ScrollArea::horizontal().id_salt("tabs").show(ui, |ui| { + ui.horizontal(|ui| { + for t in &state.tabs { + let selected = state.active == Some(t.id); + let mut title = t.title(); + if t.is_dirty() { + title.push_str(" •"); } - }); - if ui.small_button("×").on_hover_text("Close (Ctrl+W)").clicked() { - acts.push(Action::CloseTab(t.id)); + if t.in_flight.is_some() { + title.push_str(" ⏳"); + } + let resp = ui.selectable_label(selected, title); + let resp = match &t.origin { + Some(o) => resp.on_hover_text(o.file.display().to_string()), + None => resp, + }; + if resp.clicked() { + acts.push(Action::SelectTab(t.id)); + } + if resp.middle_clicked() { + acts.push(Action::CloseTab(t.id)); + } + if resp.double_clicked() { + acts.push(rename_tab_prompt(t)); + } + resp.context_menu(|ui| { + if ui.button("Rename…").clicked() { + acts.push(rename_tab_prompt(t)); + ui.close(); + } + ui.separator(); + if ui.button("Close").clicked() { + acts.push(Action::CloseTab(t.id)); + ui.close(); + } + if ui.button("Close others").clicked() { + let others = state.tabs.iter().map(|o| o.id).filter(|&o| o != t.id).collect(); + acts.push(Action::CloseTabs(others)); + ui.close(); + } + if ui.button("Close all").clicked() { + acts.push(Action::CloseTabs(state.tabs.iter().map(|o| o.id).collect())); + ui.close(); + } + }); + if ui.small_button("×").on_hover_text("Close (Ctrl+W)").clicked() { + acts.push(Action::CloseTab(t.id)); + } + ui.separator(); } - ui.separator(); - } - if ui.button("+").on_hover_text("New tab (Ctrl+T)").clicked() { - acts.push(Action::NewTab); - } + if ui.button("+").on_hover_text("New tab (Ctrl+T)").clicked() { + acts.push(Action::NewTab); + } + }); }); }); ui.separator(); @@ -290,3 +326,12 @@ fn welcome(ui: &mut Ui, acts: &mut Vec) { ui.label(RichText::new("Tip: paste a curl command into the URL bar to import it.").weak()); }); } + +/// The rename prompt for a tab, prefilled with its current name. +pub fn rename_tab_prompt(t: &crate::state::Tab) -> Action { + Action::ShowDialog(Some(crate::state::Dialog::Prompt(crate::state::Prompt { + kind: crate::state::PromptKind::RenameTab { tab: t.id }, + title: "Rename request".into(), + value: t.request.display_name().unwrap_or("").to_string(), + }))) +} diff --git a/crates/app/src/ui/request.rs b/crates/app/src/ui/request.rs index 1359733..d8dce39 100644 --- a/crates/app/src/ui/request.rs +++ b/crates/app/src/ui/request.rs @@ -84,6 +84,10 @@ pub fn url_bar(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &m acts.push(Action::CopyAsHttp(id)); ui.close(); } + if ui.button("Rename…").clicked() { + acts.push(super::rename_tab_prompt(tab)); + ui.close(); + } ui.separator(); let mut follow = !tab.request.directives.no_redirect; if ui.checkbox(&mut follow, "Follow redirects").changed() { diff --git a/crates/app/src/ui/sidebar.rs b/crates/app/src/ui/sidebar.rs index 6988b1d..6718fe1 100644 --- a/crates/app/src/ui/sidebar.rs +++ b/crates/app/src/ui/sidebar.rs @@ -10,7 +10,20 @@ use crate::action::Action; use crate::state::{AppState, CollectionState, DeleteTarget, Dialog, Prompt, PromptKind}; pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec) { - let Some(c) = &state.collection else { + ui.horizontal(|ui| { + ui.label(RichText::new("Collections").strong()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .small_button("Open…") + .on_hover_text("Open another collection folder") + .clicked() + { + acts.push(Action::PickCollection); + } + }); + }); + + if state.collections.is_empty() { ui.add_space(8.0); ui.label("No collection open."); ui.label(RichText::new("A collection is a folder of .http files.").weak()); @@ -32,46 +45,95 @@ pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec) { } } return; - }; - - ui.horizontal(|ui| { - ui.label(RichText::new(c.tree.name()).strong()) - .on_hover_text(c.root.display().to_string()); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.small_button("⟳").on_hover_text("Reload from disk").clicked() { - acts.push(Action::Rescan); - } - if ui.small_button("+").on_hover_text("New .http file").clicked() { - acts.push(new_file_prompt(&c.root)); - } - }); - }); - - if c.private_not_ignored && !c.gitignore_offer_dismissed { - egui::Frame::group(ui.style()).show(ui, |ui| { - ui.label( - RichText::new("http-client.private.env.json is not in .gitignore, so secrets could be committed.") - .color(ui.visuals().warn_fg_color), - ); - ui.horizontal(|ui| { - if ui.button("Add to .gitignore").clicked() { - acts.push(Action::AddPrivateFileToGitignore); - } - if ui.button("Dismiss").clicked() { - acts.push(Action::DismissGitignoreOffer); - } - }); - }); - } - if let Some(e) = &c.env_error { - ui.colored_label(ui.visuals().error_fg_color, format!("Environments: {e}")); } ui.separator(); + let current = state.current_collection().map(|c| c.root.clone()); egui::ScrollArea::vertical() .id_salt("tree") .auto_shrink(false) .show(ui, |ui| { + for c in &state.collections { + collection(ui, state, c, current.as_ref() == Some(&c.root), acts); + } + // Right-clicking the empty space below the tree. + let size = egui::vec2(ui.available_width(), ui.available_height().max(40.0)); + ui.allocate_response(size, egui::Sense::click()).context_menu(|ui| { + if ui.button("Open collection folder…").clicked() { + acts.push(Action::PickCollection); + ui.close(); + } + }); + }); +} + +/// One collection: a header with its buttons, then its tree. +fn collection(ui: &mut Ui, state: &AppState, c: &CollectionState, current: bool, acts: &mut Vec) { + let id = ui.make_persistent_id(("collection", &c.root)); + egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true) + .show_header(ui, |ui| { + let mut name = RichText::new(c.name()).strong(); + if current && state.collections.len() > 1 { + name = name.color(ui.visuals().strong_text_color()).underline(); + } + let resp = ui + .add(egui::Label::new(name).sense(egui::Sense::click())) + .on_hover_text(format!( + "{}\nClick to use its environments for new tabs", + c.root.display() + )); + if resp.clicked() { + acts.push(Action::SetActiveCollection(c.root.clone())); + } + resp.context_menu(|ui| { + if ui.button("New .http file…").clicked() { + acts.push(new_file_prompt(&c.root)); + ui.close(); + } + if ui.button("Reload from disk").clicked() { + acts.push(Action::Rescan(c.root.clone())); + ui.close(); + } + ui.separator(); + if ui.button("Close collection").clicked() { + acts.push(Action::CloseCollection(c.root.clone())); + ui.close(); + } + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.small_button("×").on_hover_text("Close this collection").clicked() { + acts.push(Action::CloseCollection(c.root.clone())); + } + if ui.small_button("⟳").on_hover_text("Reload from disk").clicked() { + acts.push(Action::Rescan(c.root.clone())); + } + if ui.small_button("+").on_hover_text("New .http file").clicked() { + acts.push(new_file_prompt(&c.root)); + } + }); + }) + .body(|ui| { + if c.private_not_ignored && !c.gitignore_offer_dismissed { + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.label( + RichText::new( + "http-client.private.env.json is not in .gitignore, so secrets could be committed.", + ) + .color(ui.visuals().warn_fg_color), + ); + ui.horizontal(|ui| { + if ui.button("Add to .gitignore").clicked() { + acts.push(Action::AddPrivateFileToGitignore(c.root.clone())); + } + if ui.button("Dismiss").clicked() { + acts.push(Action::DismissGitignoreOffer(c.root.clone())); + } + }); + }); + } + if let Some(e) = &c.env_error { + ui.colored_label(ui.visuals().error_fg_color, format!("Environments: {e}")); + } if let Node::Folder { children, .. } = &c.tree { if children.is_empty() { ui.label(RichText::new("No .http files yet.").weak()); @@ -83,14 +145,6 @@ pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec) { node(ui, state, c, child, acts); } } - // Right-clicking the empty space below the tree. - let size = egui::vec2(ui.available_width(), ui.available_height().max(40.0)); - ui.allocate_response(size, egui::Sense::click()).context_menu(|ui| { - if ui.button("New .http file…").clicked() { - acts.push(new_file_prompt(&c.root)); - ui.close(); - } - }); }); } @@ -189,8 +243,19 @@ fn node(ui: &mut Ui, state: &AppState, c: &CollectionState, n: &Node, acts: &mut ui.close(); } ui.menu_button("Move to", |ui| { - for other in c.files.keys().filter(|p| *p != path) { - if ui.button(c.relative(other).display().to_string()).clicked() { + let many = state.collections.len() > 1; + let targets = state + .collections + .iter() + .flat_map(|oc| oc.files.keys().map(move |p| (oc, p))) + .filter(|(_, p)| *p != path); + for (oc, other) in targets { + let label = if many { + format!("{} / {}", oc.name(), oc.relative(other).display()) + } else { + oc.relative(other).display().to_string() + }; + if ui.button(label).clicked() { acts.push(Action::MoveRequest { from: path.clone(), index: i, diff --git a/crates/app/src/ui/windows.rs b/crates/app/src/ui/windows.rs index b327c64..170cdf4 100644 --- a/crates/app/src/ui/windows.rs +++ b/crates/app/src/ui/windows.rs @@ -62,6 +62,24 @@ fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec) { } }); } + Dialog::ConfirmCloseTabs(ids) => { + ui.heading("Unsaved changes"); + ui.label(format!("{} tab(s) have changes that are not saved:", ids.len())); + for id in ids { + if let Some(t) = state.tab(*id) { + ui.label(format!("• {}", t.title())); + } + } + ui.add_space(8.0); + ui.horizontal(|ui| { + if ui.button("Discard and close").clicked() { + acts.push(Action::DiscardAndCloseTabs(ids.clone())); + } + if ui.button("Keep them open").clicked() { + acts.push(close()); + } + }); + } Dialog::ConfirmQuit => { let n = state.tabs.iter().filter(|t| t.is_dirty()).count(); ui.heading("Quit reqlite?"); @@ -192,6 +210,10 @@ fn prompt(ui: &mut egui::Ui, state: &AppState, p: &Prompt, acts: &mut Vec Action::RenameTab { + tab: *tab, + title: value.clone(), + }, PromptKind::NewEnvironment => { if let Some(ed) = &state.env_editor { let mut ed = ed.clone(); @@ -362,7 +384,7 @@ fn format_time(secs: u64) -> String { } fn cookies(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec) { - let key = state.collection.as_ref().map(|c| c.root.clone()); + let key = state.current_collection().map(|c| c.root.clone()); let jar = state.cookie_jars.get(&key); egui::Window::new("Cookies") .open(open) @@ -415,6 +437,7 @@ fn about(ctx: &Context, open: &mut bool) { ("Ctrl+S", "Save"), ("Ctrl+T", "New tab"), ("Ctrl+W", "Close tab"), + ("Ctrl+Shift+W", "Close all tabs"), ("Ctrl+L", "Focus the URL bar"), ("Ctrl+P", "Quick-open a request"), ("Ctrl+F", "Find in the response"), @@ -431,7 +454,14 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec) { let mut e = ed.clone(); let mut open = true; let mut save = false; - egui::Window::new(if ed.dirty { "Environments •" } else { "Environments" }) + let name = ed + .root + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let dirty = if ed.dirty { " •" } else { "" }; + egui::Window::new(format!("Environments: {name}{dirty}")) + .id(egui::Id::unique("env-editor")) .open(&mut open) .default_size([640.0, 380.0]) .show(ctx, |ui| { @@ -599,25 +629,27 @@ fn apply_rows(file: &mut EnvFile, env: &str, rows: &[(String, String, bool, bool } fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec) { - let Some(c) = &state.collection else { + if state.collections.is_empty() { acts.push(Action::QuickOpen(None)); acts.push(Action::Error("Open a collection to quick-open its requests".into())); return; - }; + } let query = q.query.to_lowercase(); - let mut items: Vec<(i32, std::path::PathBuf, usize, String, String)> = c - .all_requests() - .filter_map(|(path, i, r)| { + let many = state.collections.len() > 1; + let mut items: Vec<(i32, std::path::PathBuf, usize, String, String)> = state + .collections + .iter() + .flat_map(|c| c.all_requests().map(move |(p, i, r)| (c, p, i, r))) + .filter_map(|(c, path, i, r)| { let name = r.display_name().unwrap_or(&r.url).to_string(); - let hay = format!("{} {} {} {}", c.relative(path).display(), name, r.method, r.url); + let rel = if many { + format!("{} / {}", c.name(), c.relative(path).display()) + } else { + c.relative(path).display().to_string() + }; + let hay = format!("{rel} {name} {} {}", r.method, r.url); let score = fuzzy_score(&hay.to_lowercase(), &query)?; - Some(( - score, - path.clone(), - i, - name, - format!("{} {}", r.method, c.relative(path).display()), - )) + Some((score, path.clone(), i, name, format!("{} {rel}", r.method))) }) .collect(); items.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.3.cmp(&b.3))); diff --git a/crates/app/tests/render.rs b/crates/app/tests/render.rs index 071c95f..084f1c6 100644 --- a/crates/app/tests/render.rs +++ b/crates/app/tests/render.rs @@ -105,7 +105,7 @@ fn screenshots() { h.state_mut().dispatch(Action::OpenCollection(root.clone())); wait(&mut h, |a| { - a.state.collection.as_ref().is_some_and(|c| !c.envs.names().is_empty()) + a.state.collections.first().is_some_and(|c| !c.envs.names().is_empty()) }); h.state_mut().dispatch(Action::SelectEnv(Some("dev".into()))); h.state_mut().dispatch(Action::OpenRequest { @@ -145,4 +145,34 @@ fn screenshots() { h.state_mut().dispatch(Action::SetResponseTab(id, ResponseTab::Body)); h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Params)); shoot(&mut h, "07-light-theme"); + + // A second collection and enough tabs to need the tab scroll bar. + let mut s = h.state().state.settings.clone(); + s.theme = reqlite_app::settings::ThemeChoice::Dark; + h.state_mut().dispatch(Action::SettingsChanged(s)); + let second = tempfile::tempdir().unwrap(); + let root2 = second.path().canonicalize().unwrap(); + std::fs::write( + root2.join("billing.http"), + "### Invoices\nGET {{base_url}}/invoices\n\n### Refund\nPOST {{base_url}}/refunds\n", + ) + .unwrap(); + h.state_mut().dispatch(Action::OpenCollection(root2.clone())); + wait(&mut h, |a| a.state.collections.len() == 2); + for i in 0..2 { + h.state_mut().dispatch(Action::OpenRequest { + file: root2.join("billing.http"), + index: i, + }); + } + for i in 0..3 { + h.state_mut().dispatch(Action::OpenRequest { + file: root.join("users.http"), + index: i, + }); + } + for _ in 0..8 { + h.state_mut().dispatch(Action::NewTab); + } + shoot(&mut h, "08-two-collections-many-tabs"); } diff --git a/crates/app/tests/ui_smoke.rs b/crates/app/tests/ui_smoke.rs index 584b5e8..9e2e766 100644 --- a/crates/app/tests/ui_smoke.rs +++ b/crates/app/tests/ui_smoke.rs @@ -123,6 +123,15 @@ fn keyboard_shortcuts_open_and_close_tabs() { h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::W); h.step(); assert_eq!(h.state().state.tabs.len(), 1); + // Ctrl+Shift+W closes them all (and is not taken as Ctrl+W). + for _ in 0..3 { + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::T); + h.step(); + } + assert_eq!(h.state().state.tabs.len(), 4); + h.key_press_modifiers(egui::Modifiers::COMMAND | egui::Modifiers::SHIFT, egui::Key::W); + h.step(); + assert!(h.state().state.tabs.is_empty()); } #[test] @@ -145,8 +154,8 @@ fn opens_a_collection_and_shows_its_requests() { step_until(&mut h, "the collection", |h| { h.state() .state - .collection - .as_ref() + .collections + .first() .is_some_and(|c| !c.envs.names().is_empty()) }); h.step(); diff --git a/crates/app/tests/watcher.rs b/crates/app/tests/watcher.rs index 1b8978f..733dadc 100644 --- a/crates/app/tests/watcher.rs +++ b/crates/app/tests/watcher.rs @@ -23,7 +23,7 @@ fn reports_changes_to_http_and_env_files() { let root = dir.path().canonicalize().unwrap(); std::fs::write(root.join("a.http"), "GET /a\n").unwrap(); let (runner, mut rx) = Runner::new(rt.handle().clone(), None, Arc::new(NoClient), None, 4); - runner.run(Effect::Watch(Some(root.clone()))); + runner.run(Effect::Watch(root.clone())); std::thread::sleep(Duration::from_millis(200)); std::fs::write(root.join("a.http"), "GET /changed\n").unwrap(); @@ -41,7 +41,7 @@ fn reports_changes_to_http_and_env_files() { Ok(Some(Action::FileChangedOnDisk { path, text })) => { seen.insert(path, text); } - Ok(Some(Action::Rescan)) => rescan = true, + Ok(Some(Action::Rescan(r))) if r == root => rescan = true, Ok(Some(_)) => {} _ => break, } @@ -69,10 +69,41 @@ fn reports_changes_to_http_and_env_files() { assert_eq!(deleted, None); // Stopping the watch stops the events. - runner.run(Effect::Watch(None)); + runner.run(Effect::Unwatch(root.clone())); std::thread::sleep(Duration::from_millis(100)); while rx.try_recv().is_ok() {} std::fs::write(root.join("b.http"), "GET /b\n").unwrap(); std::thread::sleep(Duration::from_millis(400)); assert!(rx.try_recv().is_err()); } + +#[test] +fn watches_several_collections_at_once() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let (a, b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let (a, b) = (a.path().canonicalize().unwrap(), b.path().canonicalize().unwrap()); + let (runner, mut rx) = Runner::new(rt.handle().clone(), None, Arc::new(NoClient), None, 4); + runner.run(Effect::Watch(a.clone())); + runner.run(Effect::Watch(b.clone())); + std::thread::sleep(Duration::from_millis(200)); + std::fs::write(a.join("a.http"), "GET /a\n").unwrap(); + std::fs::write(b.join("b.http"), "GET /b\n").unwrap(); + + let mut seen = std::collections::HashSet::new(); + rt.block_on(async { + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + while seen.len() < 2 { + match tokio::time::timeout_at(deadline, rx.recv()).await { + Ok(Some(Action::FileChangedOnDisk { path, .. })) => { + seen.insert(path); + } + Ok(Some(_)) => {} + _ => break, + } + } + }); + assert!( + seen.contains(&a.join("a.http")) && seen.contains(&b.join("b.http")), + "{seen:?}" + ); +}