Multiple collections, tab close-all and rename, tab scroll bar fix

- Keep several collections open at once. Each has its own environments,
  selected environment, cookie jar and file watcher, and they are reopened
  on start. The environment picker acts on the current collection (the
  active tab's, or the one last chosen). Overlapping folders are refused.
- Close all / close others for tabs (Ctrl+Shift+W, tab menu, File menu),
  asking once about tabs with unsaved changes.
- Rename a request from its tab (double-click, tab menu, or the … menu).
- Give the tab strip's scroll bar its own row so it no longer covers the
  tab names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Torbjörn MolinandClaude Opus 5.5 committed 2026-10-19 10:55:20 +02:00
1 parent 4b729c5d32
commit d5e7b484fc
13 files changed
+935 -175

No files matched your search

+12
View File
@@ -43,6 +43,14 @@ Authorization: Bearer {{token}}
{ "name": "Ada" } { "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 Environments come from `http-client.env.json` (committed) and
`http-client.private.env.json` (secrets, git-ignored) next to the `.http` files. `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 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 - **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. 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`. 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 - The **Source** tab shows the request as `.http` text; edits there and in the
form stay in sync. form stay in sync.
- The **Auth** tab is a helper that writes the `Authorization` header. Basic - The **Auth** tab is a helper that writes the `Authorization` header. Basic
@@ -79,6 +90,7 @@ Other things worth knowing:
| Ctrl+S | Save | | Ctrl+S | Save |
| Ctrl+T | New tab | | Ctrl+T | New tab |
| Ctrl+W | Close tab | | Ctrl+W | Close tab |
| Ctrl+Shift+W | Close all tabs |
| Ctrl+L | Focus the URL bar | | Ctrl+L | Focus the URL bar |
| Ctrl+P | Quick-open a request | | Ctrl+P | Quick-open a request |
| Ctrl+F | Find in the response | | Ctrl+F | Find in the response |
+213 -84
View File
@@ -26,6 +26,15 @@ pub enum Action {
CloseTab(TabId), CloseTab(TabId),
/// Close even with unsaved changes. /// Close even with unsaved changes.
DiscardAndCloseTab(TabId), DiscardAndCloseTab(TabId),
/// Close several tabs; asks once about the ones with unsaved changes.
CloseTabs(Vec<TabId>),
DiscardAndCloseTabs(Vec<TabId>),
/// 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), SelectTab(TabId),
OpenRequest { OpenRequest {
file: PathBuf, file: PathBuf,
@@ -73,14 +82,20 @@ pub enum Action {
// Collections. // Collections.
PickCollection, PickCollection,
OpenCollection(PathBuf), OpenCollection(PathBuf),
CloseCollection(PathBuf),
/// Makes a collection the current one (environment picker, untitled tabs).
SetActiveCollection(PathBuf),
CollectionLoaded(Result<Collection, String>), CollectionLoaded(Result<Collection, String>),
/// The environments, and whether the private file exists without being git-ignored. /// 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 { FileChangedOnDisk {
path: PathBuf, path: PathBuf,
text: Option<String>, text: Option<String>,
}, },
Rescan, Rescan(PathBuf),
Save(TabId), Save(TabId),
/// `existing` is the current content of `path`, if it exists. /// `existing` is the current content of `path`, if it exists.
SaveAs { SaveAs {
@@ -130,8 +145,8 @@ pub enum Action {
EnvEditorChanged(EnvEditor), EnvEditorChanged(EnvEditor),
EnvEditorSave, EnvEditorSave,
EnvEditorClose, EnvEditorClose,
AddPrivateFileToGitignore, AddPrivateFileToGitignore(PathBuf),
DismissGitignoreOffer, DismissGitignoreOffer(PathBuf),
// Import / export. // Import / export.
CopyAsCurl(TabId), CopyAsCurl(TabId),
@@ -187,9 +202,55 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
state.dialog = None; state.dialog = None;
close_tab(state, id); 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) => { 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); state.active = Some(id);
if root.is_some() {
state.active_collection = root;
}
} }
} }
Action::OpenRequest { file, index } => open_request(state, &file, index), Action::OpenRequest { file, index } => open_request(state, &file, index),
@@ -357,23 +418,78 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
// ---------------------------------------------------- collections // ---------------------------------------------------- collections
Action::PickCollection => fx.push(Effect::PickCollectionFolder), Action::PickCollection => fx.push(Effect::PickCollectionFolder),
Action::OpenCollection(root) => { 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()); 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::SaveSettings(state.settings.clone()));
fx.push(Effect::LoadCollection(root)); 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(Err(e)) => state.set_error(format!("Could not open the collection: {e}")),
Action::CollectionLoaded(Ok(c)) => collection_loaded(state, c, &mut fx), Action::CollectionLoaded(Ok(c)) => collection_loaded(state, c, &mut fx),
Action::EnvironmentsLoaded(res) => { Action::EnvironmentsLoaded { root, result } => {
if let Some(c) = &mut state.collection { if let Some(c) = state.collection_mut(&root) {
match res { match result {
Ok((envs, private_not_ignored)) => { Ok((envs, private_not_ignored)) => {
c.envs = envs; c.envs = envs;
c.env_error = None; c.env_error = None;
c.private_not_ignored = private_not_ignored; c.private_not_ignored = private_not_ignored;
if let Some(sel) = &state.selected_env { if c.selected_env.as_ref().is_some_and(|sel| !c.envs.names().contains(sel)) {
if !c.envs.names().contains(sel) { c.selected_env = None;
state.selected_env = None;
}
} }
} }
Err(e) => c.env_error = Some(e), Err(e) => c.env_error = Some(e),
@@ -381,9 +497,9 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
} }
} }
Action::FileChangedOnDisk { path, text } => file_changed(state, path, text, &mut fx), Action::FileChangedOnDisk { path, text } => file_changed(state, path, text, &mut fx),
Action::Rescan => { Action::Rescan(root) => {
if let Some(c) = &state.collection { if state.collection(&root).is_some() {
fx.push(Effect::LoadCollection(c.root.clone())); fx.push(Effect::LoadCollection(root));
} }
} }
Action::Save(id) => save(state, id, &mut fx), Action::Save(id) => save(state, id, &mut fx),
@@ -410,7 +526,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
format!("{name}.http") format!("{name}.http")
}; };
let path = dir.join(name); 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())); state.set_error(format!("{} already exists", path.display()));
return fx; return fx;
} }
@@ -568,7 +684,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
} }
} }
} }
if let Some(c) = &mut state.collection { if let Some(c) = state.collection_of_mut(&path) {
if let Some(f) = c.files.remove(&path) { if let Some(f) = c.files.remove(&path) {
c.files.insert(to, f); c.files.insert(to, f);
} }
@@ -586,7 +702,7 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
.map(|e| e.to_string_lossy().into_owned()) .map(|e| e.to_string_lossy().into_owned())
.unwrap_or("http".into()); .unwrap_or("http".into());
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default(); 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}"))) let copy = std::iter::once(dir.join(format!("{stem} copy.{ext}")))
.chain((2..).map(|n| dir.join(format!("{stem} copy {n}.{ext}")))) .chain((2..).map(|n| dir.join(format!("{stem} copy {n}.{ext}"))))
.find(|p| !taken(p)) .find(|p| !taken(p))
@@ -598,21 +714,30 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
state.dialog = None; state.dialog = None;
fx.push(file_ops(state, vec![FileOp::Delete(path.clone())], true)); fx.push(file_ops(state, vec![FileOp::Delete(path.clone())], true));
orphan_tabs(state, &path, None); 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); c.files.remove(&path);
} }
} }
// ---------------------------------------------------- environments // ---------------------------------------------------- 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 => { Action::OpenEnvEditor => {
if let Some(c) = &state.collection { if let Some(c) = state.current_collection() {
let selected = state let selected = c
.selected_env .selected_env
.clone() .clone()
.or_else(|| c.envs.names().first().cloned()) .or_else(|| c.envs.names().first().cloned())
.unwrap_or_else(|| "dev".into()); .unwrap_or_else(|| "dev".into());
state.env_editor = Some(EnvEditor { state.env_editor = Some(EnvEditor {
root: c.root.clone(),
envs: c.envs.clone(), envs: c.envs.clone(),
selected, selected,
revealed: Vec::new(), revealed: Vec::new(),
@@ -625,7 +750,8 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
Action::EnvEditorChanged(e) => state.env_editor = Some(e), Action::EnvEditorChanged(e) => state.env_editor = Some(e),
Action::EnvEditorClose => state.env_editor = None, Action::EnvEditorClose => state.env_editor = None,
Action::EnvEditorSave => { 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; return fx;
}; };
let mut ops = Vec::new(); let mut ops = Vec::new();
@@ -643,14 +769,14 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
fx.push(Effect::LoadEnvironments(c.root.clone())); fx.push(Effect::LoadEnvironments(c.root.clone()));
} }
} }
Action::AddPrivateFileToGitignore => { Action::AddPrivateFileToGitignore(root) => {
if let Some(c) = &mut state.collection { if let Some(c) = state.collection_mut(&root) {
fx.push(Effect::AppendGitignore(c.root.clone())); fx.push(Effect::AppendGitignore(root));
c.private_not_ignored = false; c.private_not_ignored = false;
} }
} }
Action::DismissGitignoreOffer => { Action::DismissGitignoreOffer(root) => {
if let Some(c) = &mut state.collection { if let Some(c) = state.collection_mut(&root) {
c.gitignore_offer_dismissed = true; c.gitignore_offer_dismissed = true;
} }
} }
@@ -697,13 +823,14 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
Action::RestoreHistory(i) => { Action::RestoreHistory(i) => {
if let Some(e) = state.history.get(i) { if let Some(e) = state.history.get(i) {
let text = e.http.clone(); let text = e.http.clone();
if e.env.is_some() let env = e.env.clone();
&& state let root = state.current_collection().map(|c| c.root.clone());
.collection if let (Some(env), Some(root)) = (env, root) {
.as_ref() if let Some(c) = state.collection_mut(&root) {
.is_some_and(|c| c.envs.names().contains(e.env.as_ref().unwrap())) if c.envs.names().contains(&env) {
{ c.selected_env = Some(env);
state.selected_env = e.env.clone(); }
}
} }
return update(state, Action::NewTabFromHttp(text)); return update(state, Action::NewTabFromHttp(text));
} }
@@ -713,11 +840,11 @@ pub fn update(state: &mut AppState, action: Action) -> Vec<Effect> {
fx.push(Effect::RewriteHistory(Vec::new())); fx.push(Effect::RewriteHistory(Vec::new()));
} }
Action::ClearCookies => { 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(); state.cookie_jars.entry(key).or_default().clear();
} }
Action::DeleteCookie(i) => { 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); state.cookie_jars.entry(key).or_default().remove(i);
} }
Action::SettingsLoaded(s) => { 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> { 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) { 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)); 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<FileOp>, rescan: bool) -> Effect { fn file_ops(state: &AppState, ops: Vec<FileOp>, rescan: bool) -> Effect {
let first = ops.first().map(|op| match op {
FileOp::Write(p, _) | FileOp::Delete(p) | FileOp::Rename(p, _) => p.clone(),
});
Effect::FileOps { Effect::FileOps {
rescan: first
.filter(|_| rescan)
.and_then(|p| state.collection_of(&p))
.map(|c| c.root.clone()),
ops, 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; return;
}; };
let (req, src) = (req.clone(), src.to_string()); let (req, src) = (req.clone(), src.to_string());
state.active_collection = state.collection_of(file).map(|c| c.root.clone());
new_tab( new_tab(
state, state,
req, req,
@@ -894,7 +1026,9 @@ fn send(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
} }
}; };
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 { if let Some(key) = &jar_key {
let has_cookie = resolved.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("cookie")); let has_cookie = resolved.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("cookie"));
if let Some(c) = state if let Some(c) = state
@@ -917,7 +1051,7 @@ fn send(state: &mut AppState, id: TabId, fx: &mut Vec<Effect>) {
url: resolved.url.clone(), url: resolved.url.clone(),
status: None, status: None,
duration_ms: 0, duration_ms: 0,
env: state.selected_env.clone(), env,
http: if t.source.trim().is_empty() { http: if t.source.trim().is_empty() {
render_request(&t.request, "\n") render_request(&t.request, "\n")
} else { } else {
@@ -1068,37 +1202,17 @@ fn recompute_search(t: &mut Tab) {
} }
fn collection_loaded(state: &mut AppState, c: Collection, fx: &mut Vec<Effect>) { fn collection_loaded(state: &mut AppState, c: Collection, fx: &mut Vec<Effect>) {
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(); let root = c.root.clone();
state.collection = Some(CollectionState { match state.collection_mut(&root) {
root: c.root, Some(existing) => {
tree: c.tree, // A rescan: keep environments and choices, take the new tree.
files: c.files, existing.tree = c.tree;
envs, existing.files = c.files;
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 let ids: Vec<(TabId, PathBuf)> = state
.tabs .tabs
.iter() .iter()
.filter_map(|t| t.origin.as_ref().map(|o| (t.id, o.file.clone()))) .filter_map(|t| t.origin.as_ref().map(|o| (t.id, o.file.clone())))
.filter(|(_, f)| f.starts_with(&root))
.collect(); .collect();
for (id, file) in ids { for (id, file) in ids {
if file_of(state, &file).is_none() { if file_of(state, &file).is_none() {
@@ -1108,14 +1222,35 @@ fn collection_loaded(state: &mut AppState, c: Collection, fx: &mut Vec<Effect>)
} }
} }
} }
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)); fx.push(Effect::LoadEnvironments(root));
} }
fn file_changed(state: &mut AppState, path: PathBuf, text: Option<String>, fx: &mut Vec<Effect>) { fn file_changed(state: &mut AppState, path: PathBuf, text: Option<String>, fx: &mut Vec<Effect>) {
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(""); let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if name == env::PUBLIC_FILE || name == env::PRIVATE_FILE { 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; return;
} }
if !collection::is_http_file(&path) { if !collection::is_http_file(&path) {
@@ -1125,7 +1260,7 @@ fn file_changed(state: &mut AppState, path: PathBuf, text: Option<String>, fx: &
None => { None => {
if c.files.remove(&path).is_some() { if c.files.remove(&path).is_some() {
orphan_tabs(state, &path, None); orphan_tabs(state, &path, None);
fx.push(Effect::LoadCollection(state.collection.as_ref().unwrap().root.clone())); fx.push(Effect::LoadCollection(root));
} }
} }
Some(text) => { Some(text) => {
@@ -1135,7 +1270,7 @@ fn file_changed(state: &mut AppState, path: PathBuf, text: Option<String>, fx: &
let is_new = !c.files.contains_key(&path); let is_new = !c.files.contains_key(&path);
c.files.insert(path.clone(), HttpFile::parse(text)); c.files.insert(path.clone(), HttpFile::parse(text));
if is_new { if is_new {
fx.push(Effect::LoadCollection(c.root.clone())); fx.push(Effect::LoadCollection(root));
} }
let ids: Vec<TabId> = state let ids: Vec<TabId> = state
.tabs .tabs
@@ -1295,11 +1430,7 @@ fn save_as(state: &mut AppState, id: TabId, path: PathBuf, existing: Option<Stri
let text = file.insert_request_text(None, &block); let text = file.insert_request_text(None, &block);
fx.push(Effect::FileOps { fx.push(Effect::FileOps {
ops: vec![FileOp::Write(path.clone(), text.clone())], ops: vec![FileOp::Write(path.clone(), text.clone())],
rescan: state rescan: state.collection_of(&path).map(|c| c.root.clone()),
.collection
.as_ref()
.filter(|c| path.starts_with(&c.root))
.map(|c| c.root.clone()),
}); });
let parsed = HttpFile::parse(text); let parsed = HttpFile::parse(text);
let fresh = (|| { let fresh = (|| {
@@ -1309,11 +1440,9 @@ fn save_as(state: &mut AppState, id: TabId, path: PathBuf, existing: Option<Stri
parsed.key_of(index)?, parsed.key_of(index)?,
)) ))
})(); })();
if let Some(c) = &mut state.collection { if let Some(c) = state.collection_of_mut(&path) {
if path.starts_with(&c.root) {
c.files.insert(path.clone(), parsed); c.files.insert(path.clone(), parsed);
} }
}
let t = state.tab_mut(id).unwrap(); let t = state.tab_mut(id).unwrap();
if let Some((req, src, key)) = fresh { if let Some((req, src, key)) = fresh {
t.request = req.clone(); t.request = req.clone();
+332 -6
View File
@@ -36,7 +36,12 @@ fn response(status: u16, body: &str, headers: &[(&str, &str)]) -> Response {
/// A loaded collection at `/c` with the given files. /// A loaded collection at `/c` with the given files.
fn with_collection(s: &mut AppState, files: &[(&str, &str)]) -> PathBuf { 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 { let c = Collection {
root: root.clone(), root: root.clone(),
tree: Node::Folder { tree: Node::Folder {
@@ -56,7 +61,7 @@ fn with_collection(s: &mut AppState, files: &[(&str, &str)]) -> PathBuf {
.collect(), .collect(),
}; };
let fx = update(s, Action::CollectionLoaded(Ok(c))); 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(_)))); assert!(fx.iter().any(|e| matches!(e, Effect::LoadEnvironments(_))));
root root
} }
@@ -239,7 +244,13 @@ fn environments_resolve_and_switch() {
.unwrap(), .unwrap(),
private: EnvFile::parse(r#"{"dev": {"token": "t-dev"}, "prod": {"token": "t-prod"}}"#, &root).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( update(
&mut s, &mut s,
Action::OpenRequest { Action::OpenRequest {
@@ -260,7 +271,7 @@ fn environments_resolve_and_switch() {
}; };
assert_eq!(request.url, url); assert_eq!(request.url, url);
assert_eq!(request.headers[0].1, auth); 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; let seq = *seq;
update( update(
&mut s, &mut s,
@@ -607,7 +618,7 @@ fn create_rename_duplicate_move_delete() {
}, },
); );
assert!(s.tab(copy_tab).unwrap().orphaned); 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] #[test]
@@ -710,7 +721,7 @@ fn env_editor_writes_both_files() {
assert!(w assert!(w
.iter() .iter()
.any(|(p, t)| p == &root.join(env::PRIVATE_FILE) && t.contains("\"token\": \"secret\""))); .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] #[test]
@@ -759,3 +770,318 @@ fn concurrency_setting_reaches_the_runner() {
let fx = update(&mut s, Action::SettingsChanged(changed)); let fx = update(&mut s, Action::SettingsChanged(changed));
assert!(fx.iter().any(|e| matches!(e, Effect::SetConcurrency(5)))); 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<TabId> = 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"));
}
+32 -16
View File
@@ -2,6 +2,7 @@
//! watching). Each effect runs as a Tokio task and reports back by sending an //! watching). Each effect runs as a Tokio task and reports back by sending an
//! [`Action`] over a channel and waking the UI. //! [`Action`] over a channel and waking the UI.
use std::collections::HashMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
@@ -42,8 +43,10 @@ pub enum Effect {
}, },
LoadCollection(PathBuf), LoadCollection(PathBuf),
LoadEnvironments(PathBuf), LoadEnvironments(PathBuf),
/// Watch a collection folder (or stop watching). /// Start watching a collection folder.
Watch(Option<PathBuf>), Watch(PathBuf),
/// Stop watching a collection folder.
Unwatch(PathBuf),
/// Run file operations in order, then rescan the collection if given. /// Run file operations in order, then rescan the collection if given.
FileOps { FileOps {
ops: Vec<FileOp>, ops: Vec<FileOp>,
@@ -118,7 +121,8 @@ pub struct Runner {
outbox: Outbox, outbox: Outbox,
client: Arc<dyn DynHttpClient>, client: Arc<dyn DynHttpClient>,
semaphore: Mutex<Arc<Semaphore>>, semaphore: Mutex<Arc<Semaphore>>,
watcher: Arc<Mutex<Option<notify::RecommendedWatcher>>>, /// One watcher per open collection, by root.
watchers: Mutex<HashMap<PathBuf, notify::RecommendedWatcher>>,
paths: Option<Paths>, paths: Option<Paths>,
/// Serializes history writes. /// Serializes history writes.
history_lock: Arc<tokio::sync::Mutex<()>>, history_lock: Arc<tokio::sync::Mutex<()>>,
@@ -142,7 +146,7 @@ impl Runner {
outbox: Outbox { tx, ctx }, outbox: Outbox { tx, ctx },
client, client,
semaphore: Mutex::new(Arc::new(Semaphore::new(max_concurrent.max(1)))), semaphore: Mutex::new(Arc::new(Semaphore::new(max_concurrent.max(1)))),
watcher: Arc::new(Mutex::new(None)), watchers: Mutex::new(HashMap::new()),
paths, paths,
history_lock: Arc::new(tokio::sync::Mutex::new(())), history_lock: Arc::new(tokio::sync::Mutex::new(())),
}, },
@@ -167,10 +171,15 @@ impl Runner {
Err(_) => Settings::default(), Err(_) => Settings::default(),
}; };
let limit = settings.history_limit; let limit = settings.history_limit;
if let Some(last) = settings.recent_collections.first().cloned() { // Reopen what was open last time (older settings only know the
if last.is_dir() { // most recent collection).
out.send(Action::OpenCollection(last)); 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)); out.send(Action::SettingsLoaded(settings));
if let Ok(text) = tokio::fs::read_to_string(paths.history_file()).await { if let Ok(text) = tokio::fs::read_to_string(paths.history_file()).await {
@@ -230,17 +239,23 @@ impl Runner {
} }
Effect::LoadEnvironments(root) => { Effect::LoadEnvironments(root) => {
self.handle.spawn(async move { 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 envs = Environments::load(&root).map_err(|e| e.to_string())?;
let not_ignored = root.join(env::PRIVATE_FILE).exists() && !env::private_file_ignored(&root); let not_ignored = root.join(env::PRIVATE_FILE).exists() && !env::private_file_ignored(&root);
Ok((envs, not_ignored)) Ok((envs, not_ignored))
}) })
.await .await
.unwrap_or_else(|e| Err(e.to_string())); .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::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 } => { Effect::FileOps { ops, rescan } => {
self.handle.spawn(async move { self.handle.spawn(async move {
for op in ops { for op in ops {
@@ -412,10 +427,11 @@ impl Runner {
/// Watches a collection with `notify`; changes are debounced and turned /// Watches a collection with `notify`; changes are debounced and turned
/// into `FileChangedOnDisk` actions (and a rescan when files come or go). /// into `FileChangedOnDisk` actions (and a rescan when files come or go).
fn watch(&self, root: Option<PathBuf>) { fn watch(&self, root: PathBuf) {
let mut slot = self.watcher.lock().unwrap(); let mut watchers = self.watchers.lock().unwrap();
*slot = None; // drops (stops) the old watcher if watchers.contains_key(&root) {
let Some(root) = root else { return }; return;
}
let (tx, mut rx) = mpsc::unbounded_channel::<notify::Event>(); let (tx, mut rx) = mpsc::unbounded_channel::<notify::Event>();
let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| { let watcher = notify::recommended_watcher(move |res: notify::Result<notify::Event>| {
if let Ok(ev) = res { if let Ok(ev) = res {
@@ -435,7 +451,7 @@ impl Runner {
.send(Action::Error(format!("Cannot watch {}: {e}", root.display()))); .send(Action::Error(format!("Cannot watch {}: {e}", root.display())));
return; return;
} }
*slot = Some(watcher); watchers.insert(root.clone(), watcher);
let out = self.outbox(); let out = self.outbox();
self.handle.spawn(async move { self.handle.spawn(async move {
while let Some(first) = rx.recv().await { while let Some(first) = rx.recv().await {
@@ -474,7 +490,7 @@ impl Runner {
out.send(Action::FileChangedOnDisk { path: p, text }); out.send(Action::FileChangedOnDisk { path: p, text });
} }
if rescan { if rescan {
out.send(Action::Rescan); out.send(Action::Rescan(root.clone()));
} }
} }
}); });
+3
View File
@@ -39,6 +39,8 @@ pub struct Settings {
pub max_concurrent_requests: usize, pub max_concurrent_requests: usize,
pub history_limit: usize, pub history_limit: usize,
pub recent_collections: Vec<PathBuf>, pub recent_collections: Vec<PathBuf>,
/// Collections that were open when the app last ran.
pub open_collections: Vec<PathBuf>,
} }
impl Default for Settings { impl Default for Settings {
@@ -54,6 +56,7 @@ impl Default for Settings {
max_concurrent_requests: 8, max_concurrent_requests: 8,
history_limit: 500, history_limit: 500,
recent_collections: Vec::new(), recent_collections: Vec::new(),
open_collections: Vec::new(),
} }
} }
} }
+71 -13
View File
@@ -25,8 +25,11 @@ pub struct AppState {
pub tabs: Vec<Tab>, pub tabs: Vec<Tab>,
pub active: Option<TabId>, pub active: Option<TabId>,
pub next_tab_id: TabId, pub next_tab_id: TabId,
pub collection: Option<CollectionState>, /// Open collections, in the order they were opened.
pub selected_env: Option<String>, pub collections: Vec<CollectionState>,
/// 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<PathBuf>,
pub settings: Settings, pub settings: Settings,
/// Oldest first. /// Oldest first.
pub history: Vec<HistoryEntry>, pub history: Vec<HistoryEntry>,
@@ -61,6 +64,8 @@ pub struct Windows {
pub enum Dialog { pub enum Dialog {
/// Closing a tab with unsaved changes. /// Closing a tab with unsaved changes.
ConfirmCloseTab(TabId), ConfirmCloseTab(TabId),
/// Closing several tabs, these of which have unsaved changes.
ConfirmCloseTabs(Vec<TabId>),
/// Quitting with unsaved changes. /// Quitting with unsaved changes.
ConfirmQuit, ConfirmQuit,
/// The file of a tab with unsaved changes changed on disk. /// The file of a tab with unsaved changes changed on disk.
@@ -95,6 +100,7 @@ pub enum PromptKind {
NewFile { dir: PathBuf }, NewFile { dir: PathBuf },
RenameFile { path: PathBuf }, RenameFile { path: PathBuf },
RenameRequest { file: PathBuf, index: usize }, RenameRequest { file: PathBuf, index: usize },
RenameTab { tab: TabId },
NewEnvironment, NewEnvironment,
} }
@@ -107,6 +113,8 @@ pub struct QuickOpen {
/// The environment editor works on a copy that is written on Save. /// The environment editor works on a copy that is written on Save.
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvEditor { pub struct EnvEditor {
/// The collection whose env files are being edited.
pub root: PathBuf,
pub envs: Environments, pub envs: Environments,
pub selected: String, pub selected: String,
/// Private values whose text is shown instead of `••••`. /// Private values whose text is shown instead of `••••`.
@@ -119,6 +127,7 @@ pub struct CollectionState {
pub tree: Node, pub tree: Node,
pub files: BTreeMap<PathBuf, HttpFile>, pub files: BTreeMap<PathBuf, HttpFile>,
pub envs: Environments, pub envs: Environments,
pub selected_env: Option<String>,
pub env_error: Option<String>, pub env_error: Option<String>,
/// The private env file exists but is not git-ignored. /// The private env file exists but is not git-ignored.
pub private_not_ignored: bool, pub private_not_ignored: bool,
@@ -136,6 +145,14 @@ impl CollectionState {
pub fn relative<'a>(&self, p: &'a Path) -> &'a Path { pub fn relative<'a>(&self, p: &'a Path) -> &'a Path {
p.strip_prefix(&self.root).unwrap_or(p) 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)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -356,27 +373,68 @@ impl AppState {
self.tabs.iter().any(Tab::is_dirty) 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 { pub fn resolver_for(&self, tab: &Tab) -> Resolver {
let file_vars = tab let file_vars = tab
.origin .origin
.as_ref() .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()) .map(|f| f.variables())
.unwrap_or_default(); .unwrap_or_default();
match &self.collection { match self.collection_for_tab(tab) {
Some(c) => c.envs.resolver(self.selected_env.as_deref(), &file_vars), Some(c) => c.envs.resolver(c.selected_env.as_deref(), &file_vars),
None => Environments::default().resolver(None, &file_vars), None => Environments::default().resolver(None, &file_vars),
} }
} }
/// Whether `name` comes from the private env file (shown masked). /// Whether `name` comes from the private env file (shown masked).
pub fn is_private_var(&self, name: &str) -> bool { pub fn is_private_var(&self, tab: &Tab, name: &str) -> bool {
match (&self.collection, &self.selected_env) { self.collection_for_tab(tab).is_some_and(|c| {
(Some(c), Some(env)) => c.envs.is_private(env, name), let env = c.selected_env.as_deref().unwrap_or(reqlite_core::env::SHARED_ENV);
(Some(c), None) => c.envs.is_private(reqlite_core::env::SHARED_ENV, name), c.envs.is_private(env, name)
_ => false, })
}
} }
/// Directory that relative file references in the tab resolve against. /// Directory that relative file references in the tab resolve against.
@@ -386,7 +444,7 @@ impl AppState {
return p.to_path_buf(); return p.to_path_buf();
} }
} }
if let Some(c) = &self.collection { if let Some(c) = self.current_collection() {
return c.root.clone(); return c.root.clone();
} }
std::env::current_dir().unwrap_or_default() std::env::current_dir().unwrap_or_default()
+53 -8
View File
@@ -26,7 +26,7 @@ pub fn draw(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
match state.active_tab() { match state.active_tab() {
Some(tab) => { Some(tab) => {
let resolver = state.resolver_for(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 { let vars = VarCtx {
resolver: &resolver, resolver: &resolver,
is_private: &is_private, is_private: &is_private,
@@ -76,6 +76,10 @@ fn shortcuts(ctx: &Context, state: &AppState, acts: &mut Vec<Action>) {
if i.consume_shortcut(&cmd(Key::T)) { if i.consume_shortcut(&cmd(Key::T)) {
acts.push(Action::NewTab); 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 i.consume_shortcut(&cmd(Key::W)) {
if let Some(id) = active { if let Some(id) = active {
acts.push(Action::CloseTab(id)); acts.push(Action::CloseTab(id));
@@ -126,6 +130,13 @@ fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
acts.push(Action::Save(state.active.unwrap())); acts.push(Action::Save(state.active.unwrap()));
ui.close(); 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(); ui.separator();
if ui.button("Import Postman collection…").clicked() { if ui.button("Import Postman collection…").clicked() {
acts.push(Action::ImportPostman); acts.push(Action::ImportPostman);
@@ -173,38 +184,45 @@ fn menu_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
// Environment picker on the right. // Environment picker on the right.
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { 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() { if ui.button("Edit…").on_hover_text("Edit environments").clicked() {
acts.push(Action::OpenEnvEditor); acts.push(Action::OpenEnvEditor);
} }
let names = c.envs.names(); 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") egui::ComboBox::from_id_salt("env-picker")
.selected_text(label) .selected_text(label)
.width(150.0) .width(150.0)
.show_ui(ui, |ui| { .show_ui(ui, |ui| {
if ui if ui
.selectable_label(state.selected_env.is_none(), "No environment") .selectable_label(c.selected_env.is_none(), "No environment")
.clicked() .clicked()
{ {
acts.push(Action::SelectEnv(None)); acts.push(Action::SelectEnv(None));
} }
for n in names { for n in names {
if ui if ui.selectable_label(c.selected_env.as_ref() == Some(&n), &n).clicked() {
.selectable_label(state.selected_env.as_ref() == Some(&n), &n)
.clicked()
{
acts.push(Action::SelectEnv(Some(n.clone()))); acts.push(Action::SelectEnv(Some(n.clone())));
} }
} }
}); });
// 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:"); ui.label("Environment:");
} }
}
}); });
}); });
} }
fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) { fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
// 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| { egui::ScrollArea::horizontal().id_salt("tabs").show(ui, |ui| {
ui.horizontal(|ui| { ui.horizontal(|ui| {
for t in &state.tabs { for t in &state.tabs {
@@ -227,11 +245,28 @@ fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
if resp.middle_clicked() { if resp.middle_clicked() {
acts.push(Action::CloseTab(t.id)); acts.push(Action::CloseTab(t.id));
} }
if resp.double_clicked() {
acts.push(rename_tab_prompt(t));
}
resp.context_menu(|ui| { resp.context_menu(|ui| {
if ui.button("Rename…").clicked() {
acts.push(rename_tab_prompt(t));
ui.close();
}
ui.separator();
if ui.button("Close").clicked() { if ui.button("Close").clicked() {
acts.push(Action::CloseTab(t.id)); acts.push(Action::CloseTab(t.id));
ui.close(); 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() { if ui.small_button("×").on_hover_text("Close (Ctrl+W)").clicked() {
acts.push(Action::CloseTab(t.id)); acts.push(Action::CloseTab(t.id));
@@ -243,6 +278,7 @@ fn tab_bar(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
} }
}); });
}); });
});
ui.separator(); ui.separator();
} }
@@ -290,3 +326,12 @@ fn welcome(ui: &mut Ui, acts: &mut Vec<Action>) {
ui.label(RichText::new("Tip: paste a curl command into the URL bar to import it.").weak()); 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(),
})))
}
+4
View File
@@ -84,6 +84,10 @@ pub fn url_bar(ui: &mut Ui, state: &AppState, tab: &Tab, vars: &VarCtx, acts: &m
acts.push(Action::CopyAsHttp(id)); acts.push(Action::CopyAsHttp(id));
ui.close(); ui.close();
} }
if ui.button("Rename…").clicked() {
acts.push(super::rename_tab_prompt(tab));
ui.close();
}
ui.separator(); ui.separator();
let mut follow = !tab.request.directives.no_redirect; let mut follow = !tab.request.directives.no_redirect;
if ui.checkbox(&mut follow, "Follow redirects").changed() { if ui.checkbox(&mut follow, "Follow redirects").changed() {
+92 -27
View File
@@ -10,7 +10,20 @@ use crate::action::Action;
use crate::state::{AppState, CollectionState, DeleteTarget, Dialog, Prompt, PromptKind}; use crate::state::{AppState, CollectionState, DeleteTarget, Dialog, Prompt, PromptKind};
pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) { pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
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.add_space(8.0);
ui.label("No collection open."); ui.label("No collection open.");
ui.label(RichText::new("A collection is a folder of .http files.").weak()); ui.label(RichText::new("A collection is a folder of .http files.").weak());
@@ -32,33 +45,88 @@ pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
} }
} }
return; return;
}; }
ui.separator();
ui.horizontal(|ui| { let current = state.current_collection().map(|c| c.root.clone());
ui.label(RichText::new(c.tree.name()).strong()) egui::ScrollArea::vertical()
.on_hover_text(c.root.display().to_string()); .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<Action>) {
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| { 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() { if ui.small_button("⟳").on_hover_text("Reload from disk").clicked() {
acts.push(Action::Rescan); acts.push(Action::Rescan(c.root.clone()));
} }
if ui.small_button("+").on_hover_text("New .http file").clicked() { if ui.small_button("+").on_hover_text("New .http file").clicked() {
acts.push(new_file_prompt(&c.root)); acts.push(new_file_prompt(&c.root));
} }
}); });
}); })
.body(|ui| {
if c.private_not_ignored && !c.gitignore_offer_dismissed { if c.private_not_ignored && !c.gitignore_offer_dismissed {
egui::Frame::group(ui.style()).show(ui, |ui| { egui::Frame::group(ui.style()).show(ui, |ui| {
ui.label( ui.label(
RichText::new("http-client.private.env.json is not in .gitignore, so secrets could be committed.") RichText::new(
"http-client.private.env.json is not in .gitignore, so secrets could be committed.",
)
.color(ui.visuals().warn_fg_color), .color(ui.visuals().warn_fg_color),
); );
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.button("Add to .gitignore").clicked() { if ui.button("Add to .gitignore").clicked() {
acts.push(Action::AddPrivateFileToGitignore); acts.push(Action::AddPrivateFileToGitignore(c.root.clone()));
} }
if ui.button("Dismiss").clicked() { if ui.button("Dismiss").clicked() {
acts.push(Action::DismissGitignoreOffer); acts.push(Action::DismissGitignoreOffer(c.root.clone()));
} }
}); });
}); });
@@ -66,12 +134,6 @@ pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
if let Some(e) = &c.env_error { if let Some(e) = &c.env_error {
ui.colored_label(ui.visuals().error_fg_color, format!("Environments: {e}")); ui.colored_label(ui.visuals().error_fg_color, format!("Environments: {e}"));
} }
ui.separator();
egui::ScrollArea::vertical()
.id_salt("tree")
.auto_shrink(false)
.show(ui, |ui| {
if let Node::Folder { children, .. } = &c.tree { if let Node::Folder { children, .. } = &c.tree {
if children.is_empty() { if children.is_empty() {
ui.label(RichText::new("No .http files yet.").weak()); ui.label(RichText::new("No .http files yet.").weak());
@@ -83,14 +145,6 @@ pub fn show(ui: &mut Ui, state: &AppState, acts: &mut Vec<Action>) {
node(ui, state, c, child, acts); 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.close();
} }
ui.menu_button("Move to", |ui| { ui.menu_button("Move to", |ui| {
for other in c.files.keys().filter(|p| *p != path) { let many = state.collections.len() > 1;
if ui.button(c.relative(other).display().to_string()).clicked() { 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 { acts.push(Action::MoveRequest {
from: path.clone(), from: path.clone(),
index: i, index: i,
+47 -15
View File
@@ -62,6 +62,24 @@ fn dialog(ctx: &Context, state: &AppState, d: &Dialog, acts: &mut Vec<Action>) {
} }
}); });
} }
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 => { Dialog::ConfirmQuit => {
let n = state.tabs.iter().filter(|t| t.is_dirty()).count(); let n = state.tabs.iter().filter(|t| t.is_dirty()).count();
ui.heading("Quit reqlite?"); ui.heading("Quit reqlite?");
@@ -192,6 +210,10 @@ fn prompt(ui: &mut egui::Ui, state: &AppState, p: &Prompt, acts: &mut Vec<Action
index: *index, index: *index,
title: value.clone(), title: value.clone(),
}, },
PromptKind::RenameTab { tab } => Action::RenameTab {
tab: *tab,
title: value.clone(),
},
PromptKind::NewEnvironment => { PromptKind::NewEnvironment => {
if let Some(ed) = &state.env_editor { if let Some(ed) = &state.env_editor {
let mut ed = ed.clone(); 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<Action>) { fn cookies(ctx: &Context, state: &AppState, open: &mut bool, acts: &mut Vec<Action>) {
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); let jar = state.cookie_jars.get(&key);
egui::Window::new("Cookies") egui::Window::new("Cookies")
.open(open) .open(open)
@@ -415,6 +437,7 @@ fn about(ctx: &Context, open: &mut bool) {
("Ctrl+S", "Save"), ("Ctrl+S", "Save"),
("Ctrl+T", "New tab"), ("Ctrl+T", "New tab"),
("Ctrl+W", "Close tab"), ("Ctrl+W", "Close tab"),
("Ctrl+Shift+W", "Close all tabs"),
("Ctrl+L", "Focus the URL bar"), ("Ctrl+L", "Focus the URL bar"),
("Ctrl+P", "Quick-open a request"), ("Ctrl+P", "Quick-open a request"),
("Ctrl+F", "Find in the response"), ("Ctrl+F", "Find in the response"),
@@ -431,7 +454,14 @@ fn env_editor(ctx: &Context, ed: &EnvEditor, acts: &mut Vec<Action>) {
let mut e = ed.clone(); let mut e = ed.clone();
let mut open = true; let mut open = true;
let mut save = false; 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) .open(&mut open)
.default_size([640.0, 380.0]) .default_size([640.0, 380.0])
.show(ctx, |ui| { .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<Action>) { fn quick_open(ctx: &Context, state: &AppState, q: &QuickOpen, acts: &mut Vec<Action>) {
let Some(c) = &state.collection else { if state.collections.is_empty() {
acts.push(Action::QuickOpen(None)); acts.push(Action::QuickOpen(None));
acts.push(Action::Error("Open a collection to quick-open its requests".into())); acts.push(Action::Error("Open a collection to quick-open its requests".into()));
return; return;
}; }
let query = q.query.to_lowercase(); let query = q.query.to_lowercase();
let mut items: Vec<(i32, std::path::PathBuf, usize, String, String)> = c let many = state.collections.len() > 1;
.all_requests() let mut items: Vec<(i32, std::path::PathBuf, usize, String, String)> = state
.filter_map(|(path, i, r)| { .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 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)?; let score = fuzzy_score(&hay.to_lowercase(), &query)?;
Some(( Some((score, path.clone(), i, name, format!("{} {rel}", r.method)))
score,
path.clone(),
i,
name,
format!("{} {}", r.method, c.relative(path).display()),
))
}) })
.collect(); .collect();
items.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.3.cmp(&b.3))); items.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.3.cmp(&b.3)));
+31 -1
View File
@@ -105,7 +105,7 @@ fn screenshots() {
h.state_mut().dispatch(Action::OpenCollection(root.clone())); h.state_mut().dispatch(Action::OpenCollection(root.clone()));
wait(&mut h, |a| { 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::SelectEnv(Some("dev".into())));
h.state_mut().dispatch(Action::OpenRequest { 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::SetResponseTab(id, ResponseTab::Body));
h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Params)); h.state_mut().dispatch(Action::SetRequestTab(id, RequestTab::Params));
shoot(&mut h, "07-light-theme"); 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");
} }
+11 -2
View File
@@ -123,6 +123,15 @@ fn keyboard_shortcuts_open_and_close_tabs() {
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::W); h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::W);
h.step(); h.step();
assert_eq!(h.state().state.tabs.len(), 1); 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] #[test]
@@ -145,8 +154,8 @@ fn opens_a_collection_and_shows_its_requests() {
step_until(&mut h, "the collection", |h| { step_until(&mut h, "the collection", |h| {
h.state() h.state()
.state .state
.collection .collections
.as_ref() .first()
.is_some_and(|c| !c.envs.names().is_empty()) .is_some_and(|c| !c.envs.names().is_empty())
}); });
h.step(); h.step();
+34 -3
View File
@@ -23,7 +23,7 @@ fn reports_changes_to_http_and_env_files() {
let root = dir.path().canonicalize().unwrap(); let root = dir.path().canonicalize().unwrap();
std::fs::write(root.join("a.http"), "GET /a\n").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); 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::thread::sleep(Duration::from_millis(200));
std::fs::write(root.join("a.http"), "GET /changed\n").unwrap(); 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 })) => { Ok(Some(Action::FileChangedOnDisk { path, text })) => {
seen.insert(path, text); seen.insert(path, text);
} }
Ok(Some(Action::Rescan)) => rescan = true, Ok(Some(Action::Rescan(r))) if r == root => rescan = true,
Ok(Some(_)) => {} Ok(Some(_)) => {}
_ => break, _ => break,
} }
@@ -69,10 +69,41 @@ fn reports_changes_to_http_and_env_files() {
assert_eq!(deleted, None); assert_eq!(deleted, None);
// Stopping the watch stops the events. // Stopping the watch stops the events.
runner.run(Effect::Watch(None)); runner.run(Effect::Unwatch(root.clone()));
std::thread::sleep(Duration::from_millis(100)); std::thread::sleep(Duration::from_millis(100));
while rx.try_recv().is_ok() {} while rx.try_recv().is_ok() {}
std::fs::write(root.join("b.http"), "GET /b\n").unwrap(); std::fs::write(root.join("b.http"), "GET /b\n").unwrap();
std::thread::sleep(Duration::from_millis(400)); std::thread::sleep(Duration::from_millis(400));
assert!(rx.try_recv().is_err()); 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:?}"
);
}