feat: browse the files of a commit
This commit is contained in:
@@ -5,6 +5,7 @@
|
|||||||
### Added
|
### Added
|
||||||
|
|
||||||
- Add a confirmation dialog before deleting a repository
|
- Add a confirmation dialog before deleting a repository
|
||||||
|
- Browse the files of a commit as of that commit from the Commits list, the short id on a row shows the commit's files in place of the worktree and the branch selector shows the commit until a branch or tag is picked again
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
@@ -14,6 +15,7 @@
|
|||||||
- Reuse the rendered file tree, commit diffs, README previews and split pane instead of rebuilding them on every repaint
|
- Reuse the rendered file tree, commit diffs, README previews and split pane instead of rebuilding them on every repaint
|
||||||
- Truncate long tab and file tree labels with an ellipsis instead of letting them widen their row
|
- Truncate long tab and file tree labels with an ellipsis instead of letting them widen their row
|
||||||
- Open the New issue form in a split panel instead of a dialog, it now stays open until the issue is published and shows a failed publish in the form
|
- Open the New issue form in a split panel instead of a dialog, it now stays open until the issue is published and shows a failed publish in the form
|
||||||
|
- Show each commit of the Commits list on one row with its author avatar and name, short id and summary
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,20 @@ enum FileContent {
|
|||||||
Failed(String),
|
Failed(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl FileContent {
|
||||||
|
/// Classifies raw bytes, refusing files too large to preview.
|
||||||
|
fn from_bytes(bytes: Vec<u8>) -> Self {
|
||||||
|
if bytes.len() > MAX_PREVIEW_BYTES {
|
||||||
|
return Self::TooLarge;
|
||||||
|
}
|
||||||
|
|
||||||
|
match String::from_utf8(bytes) {
|
||||||
|
Ok(text) => Self::Text(text),
|
||||||
|
Err(_) => Self::Binary,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
struct MarkdownView {
|
struct MarkdownView {
|
||||||
/// `None` means the repository README.
|
/// `None` means the repository README.
|
||||||
path: Option<SharedString>,
|
path: Option<SharedString>,
|
||||||
@@ -72,6 +86,8 @@ pub struct RepoFilesView {
|
|||||||
commits: HashMap<String, FileCommit>,
|
commits: HashMap<String, FileCommit>,
|
||||||
pending_commits: Vec<String>,
|
pending_commits: Vec<String>,
|
||||||
loading_commits: bool,
|
loading_commits: bool,
|
||||||
|
/// The commit whose tree is browsed instead of the worktree.
|
||||||
|
commit: Option<FileCommit>,
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
/// Bumped when the previews are cleared, so loads started before it are dropped.
|
/// Bumped when the previews are cleared, so loads started before it are dropped.
|
||||||
generation: u64,
|
generation: u64,
|
||||||
@@ -99,6 +115,7 @@ impl RepoFilesView {
|
|||||||
commits: HashMap::new(),
|
commits: HashMap::new(),
|
||||||
pending_commits: Vec::new(),
|
pending_commits: Vec::new(),
|
||||||
loading_commits: false,
|
loading_commits: false,
|
||||||
|
commit: None,
|
||||||
tasks: Vec::new(),
|
tasks: Vec::new(),
|
||||||
generation: 0,
|
generation: 0,
|
||||||
}
|
}
|
||||||
@@ -108,6 +125,11 @@ impl RepoFilesView {
|
|||||||
self.worktree = Some(path);
|
self.worktree = Some(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Browses the files of `commit` instead of the worktree, or the worktree when `None`.
|
||||||
|
pub fn pin_commit(&mut self, commit: Option<FileCommit>) {
|
||||||
|
self.commit = commit;
|
||||||
|
}
|
||||||
|
|
||||||
pub fn apply_entries(
|
pub fn apply_entries(
|
||||||
&mut self,
|
&mut self,
|
||||||
tree: Vec<TreeItemSeed>,
|
tree: Vec<TreeItemSeed>,
|
||||||
@@ -544,6 +566,7 @@ impl RepoFilesView {
|
|||||||
|
|
||||||
self.loading_files.insert(path.to_string());
|
self.loading_files.insert(path.to_string());
|
||||||
let path = path.to_string();
|
let path = path.to_string();
|
||||||
|
let commit = self.commit.as_ref().map(|commit| commit.id.clone());
|
||||||
|
|
||||||
self.load_commit(&path, cx);
|
self.load_commit(&path, cx);
|
||||||
|
|
||||||
@@ -553,25 +576,34 @@ impl RepoFilesView {
|
|||||||
let path_for_read = path.clone();
|
let path_for_read = path.clone();
|
||||||
let content = cx
|
let content = cx
|
||||||
.background_spawn(async move {
|
.background_spawn(async move {
|
||||||
let full = worktree.join(&path_for_read);
|
match commit {
|
||||||
|
Some(commit) => Repo::open_cached(&worktree)
|
||||||
|
.and_then(|repo| repo.read_at(&commit, Path::new(&path_for_read)))
|
||||||
|
.map(|bytes| {
|
||||||
|
bytes.map_or_else(
|
||||||
|
|| FileContent::Failed("File is not in this commit".into()),
|
||||||
|
FileContent::from_bytes,
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
None => {
|
||||||
|
let full = worktree.join(&path_for_read);
|
||||||
|
|
||||||
let metadata = match std::fs::metadata(&full) {
|
let metadata = match std::fs::metadata(&full) {
|
||||||
Ok(metadata) => metadata,
|
Ok(metadata) => metadata,
|
||||||
Err(error) => return Err(anyhow::anyhow!("{}", error)),
|
Err(error) => return Err(anyhow::anyhow!("{}", error)),
|
||||||
};
|
};
|
||||||
|
|
||||||
if metadata.len() > MAX_PREVIEW_BYTES as u64 {
|
if metadata.len() > MAX_PREVIEW_BYTES as u64 {
|
||||||
return Ok(FileContent::TooLarge);
|
return Ok(FileContent::TooLarge);
|
||||||
}
|
}
|
||||||
|
|
||||||
let bytes = match std::fs::read(&full) {
|
let bytes = match std::fs::read(&full) {
|
||||||
Ok(bytes) => bytes,
|
Ok(bytes) => bytes,
|
||||||
Err(error) => return Err(anyhow::anyhow!("{}", error)),
|
Err(error) => return Err(anyhow::anyhow!("{}", error)),
|
||||||
};
|
};
|
||||||
|
|
||||||
match String::from_utf8(bytes) {
|
Ok(FileContent::from_bytes(bytes))
|
||||||
Ok(text) => Ok(FileContent::Text(text)),
|
}
|
||||||
Err(_) => Ok(FileContent::Binary),
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
@@ -668,6 +700,12 @@ impl RepoFilesView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn load_commit(&mut self, path: &str, cx: &mut Context<Self>) {
|
fn load_commit(&mut self, path: &str, cx: &mut Context<Self>) {
|
||||||
|
// A pinned tree labels every file with the commit being browsed.
|
||||||
|
if let Some(commit) = &self.commit {
|
||||||
|
self.commits.insert(path.to_string(), commit.clone());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if self.commits.contains_key(path) || self.pending_commits.iter().any(|p| p == path) {
|
if self.commits.contains_key(path) || self.pending_commits.iter().any(|p| p == path) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -85,6 +85,14 @@ pub(super) struct RepoData {
|
|||||||
pub(super) head_commit: Option<FileCommit>,
|
pub(super) head_commit: Option<FileCommit>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A commit's tree and README, as the file explorer shows them.
|
||||||
|
pub(super) struct CommitTree {
|
||||||
|
pub(super) tree: Vec<TreeItemSeed>,
|
||||||
|
pub(super) paths: Vec<String>,
|
||||||
|
pub(super) readme_path: Option<PathBuf>,
|
||||||
|
pub(super) readme: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
/// Sorted relative paths of a worktree snapshot.
|
/// Sorted relative paths of a worktree snapshot.
|
||||||
pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
|
pub(crate) fn sorted_worktree_paths(entries: &[PathBuf]) -> Vec<String> {
|
||||||
let mut paths: Vec<String> = entries
|
let mut paths: Vec<String> = entries
|
||||||
@@ -142,6 +150,24 @@ pub(super) fn snapshot_worktree(
|
|||||||
Ok((snapshot, tree, paths))
|
Ok((snapshot, tree, paths))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Lists the tree and README of `commit` in the repository at `worktree`.
|
||||||
|
pub(super) fn snapshot_commit(worktree: &Path, commit: &str) -> Result<CommitTree, Error> {
|
||||||
|
let repo = Repo::open_cached(worktree)?;
|
||||||
|
let entries = repo.entries_at(commit)?;
|
||||||
|
let readme_path = Repo::pick_readme(&entries);
|
||||||
|
let readme = match &readme_path {
|
||||||
|
Some(path) => repo.read_at(commit, path)?,
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(CommitTree {
|
||||||
|
tree: TreeItemSeed::from_paths(&entries),
|
||||||
|
paths: sorted_worktree_paths(&entries),
|
||||||
|
readme_path,
|
||||||
|
readme,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> AnyElement {
|
pub(super) fn clone_group(label: &str, id: SharedString, command: &SharedString) -> AnyElement {
|
||||||
v_flex()
|
v_flex()
|
||||||
.gap_1()
|
.gap_1()
|
||||||
|
|||||||
@@ -4,14 +4,15 @@ use std::sync::Arc;
|
|||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use gpui::prelude::FluentBuilder as _;
|
use gpui::prelude::FluentBuilder as _;
|
||||||
use gpui::{
|
use gpui::{
|
||||||
AppContext as _, Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _,
|
App, AppContext as _, Context, Entity, InteractiveElement as _, IntoElement,
|
||||||
Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task,
|
ParentElement as _, Render, SharedString, StatefulInteractiveElement as _, Styled as _, Task,
|
||||||
UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
|
UniformListScrollHandle, WeakEntity, Window, div, uniform_list,
|
||||||
};
|
};
|
||||||
use signed_git::{CommitList, FileCommit, Repo};
|
use signed_git::{CommitList, FileCommit, Repo};
|
||||||
use signed_state::{Backend, RepoStore, SyncStatusDirectory};
|
use signed_state::{Backend, RepoStore, SyncStatusDirectory};
|
||||||
use ui::alert::{Alert, AlertSeverity, AlertStyle};
|
use ui::alert::{Alert, AlertSeverity, AlertStyle};
|
||||||
use ui::button::{Button, ButtonVariant};
|
use ui::avatar::IdentityRow;
|
||||||
|
use ui::button::{Button, ButtonSide, ButtonVariant};
|
||||||
use ui::common::{Sizable as _, h_flex, v_flex};
|
use ui::common::{Sizable as _, h_flex, v_flex};
|
||||||
use ui::empty_state::EmptyState;
|
use ui::empty_state::EmptyState;
|
||||||
use ui::icons::{Icon, IconRole};
|
use ui::icons::{Icon, IconRole};
|
||||||
@@ -124,6 +125,14 @@ impl RepoHistoryView {
|
|||||||
self.load_task = Some(task);
|
self.load_task = Some(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The panel id of `commit_id` in this repository's worktree, namespaced by `kind`.
|
||||||
|
fn panel_id(&self, kind: &str, commit_id: &str, worktree: &Path, cx: &App) -> SharedString {
|
||||||
|
match self.store.read(cx).addr() {
|
||||||
|
Some(addr) => SharedString::from(format!("{kind}:{addr}:{commit_id}")),
|
||||||
|
None => SharedString::from(format!("{kind}:{}:{commit_id}", worktree.display())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn open_commit_diff(
|
pub fn open_commit_diff(
|
||||||
&mut self,
|
&mut self,
|
||||||
commit_id: &str,
|
commit_id: &str,
|
||||||
@@ -134,12 +143,8 @@ impl RepoHistoryView {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let store = self.store.clone();
|
|
||||||
let commit_id = commit_id.to_owned();
|
let commit_id = commit_id.to_owned();
|
||||||
let id = match store.read(cx).addr() {
|
let id = self.panel_id("commit", &commit_id, &worktree, cx);
|
||||||
Some(addr) => SharedString::from(format!("commit:{addr}:{commit_id}")),
|
|
||||||
None => SharedString::from(format!("commit:{}:{}", worktree.display(), commit_id)),
|
|
||||||
};
|
|
||||||
let workspace = self.workspace.clone();
|
let workspace = self.workspace.clone();
|
||||||
|
|
||||||
log_dropped(workspace.update(cx, |root, cx| {
|
log_dropped(workspace.update(cx, |root, cx| {
|
||||||
@@ -164,6 +169,27 @@ impl RepoHistoryView {
|
|||||||
})
|
})
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shows the files of the listed commit `commit_id` in the repository panel.
|
||||||
|
fn browse_commit(&mut self, commit_id: &str, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
|
// The list comes from this worktree, which may be another checkout than the panel shows.
|
||||||
|
let Some(source) = self.worktree.clone() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(commit) = self
|
||||||
|
.commits
|
||||||
|
.iter()
|
||||||
|
.find(|commit| commit.id == commit_id)
|
||||||
|
.cloned()
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
log_dropped(self.detail.update(cx, |detail, cx| {
|
||||||
|
detail.browse_commit(commit, source, window, cx);
|
||||||
|
}));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Render for RepoHistoryView {
|
impl Render for RepoHistoryView {
|
||||||
@@ -250,7 +276,10 @@ impl Render for RepoHistoryView {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let row_id = commit.id.clone();
|
let row_id = commit.id.clone();
|
||||||
|
let browse_id = commit.id.clone();
|
||||||
let view = view.clone();
|
let view = view.clone();
|
||||||
|
let browse_view = view.clone();
|
||||||
|
|
||||||
let ahead = ahead
|
let ahead = ahead
|
||||||
.iter()
|
.iter()
|
||||||
.find(|(id, _)| id.starts_with(commit.id.as_str()));
|
.find(|(id, _)| id.starts_with(commit.id.as_str()));
|
||||||
@@ -258,51 +287,64 @@ impl Render for RepoHistoryView {
|
|||||||
h_flex()
|
h_flex()
|
||||||
.id(commit.id.clone())
|
.id(commit.id.clone())
|
||||||
.px_4()
|
.px_4()
|
||||||
.h_16()
|
.h_12()
|
||||||
.w_full()
|
.w_full()
|
||||||
.gap_3()
|
.gap_2()
|
||||||
|
.text_sm()
|
||||||
.border_b_1()
|
.border_b_1()
|
||||||
.border_color(cx.theme().colors.border)
|
.border_color(cx.theme().colors.border)
|
||||||
.hover(|this| this.bg(cx.theme().colors.muted_hover))
|
.hover(|this| this.bg(cx.theme().colors.muted))
|
||||||
.child(
|
.child(
|
||||||
v_flex()
|
IdentityRow::new(
|
||||||
|
commit.author.clone(),
|
||||||
|
commit.author.clone(),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.small()
|
||||||
|
.truncate()
|
||||||
|
.gap_2()
|
||||||
|
.flex_none()
|
||||||
|
.w_32()
|
||||||
|
.text_color(cx.theme().colors.muted_foreground),
|
||||||
|
)
|
||||||
|
.child(
|
||||||
|
h_flex().w_24().child(
|
||||||
|
Button::new(format!("browse-commit:{}", commit.id))
|
||||||
|
.label(short_id(&commit.id))
|
||||||
|
.variant(ButtonVariant::Ghost)
|
||||||
|
.side(ButtonSide::Left)
|
||||||
|
.small()
|
||||||
|
.tooltip(Tooltip::text(
|
||||||
|
"Browse files at commit",
|
||||||
|
))
|
||||||
|
.on_click(move |_, window, cx| {
|
||||||
|
cx.stop_propagation();
|
||||||
|
log_dropped(browse_view.update(
|
||||||
|
cx,
|
||||||
|
|this, cx| {
|
||||||
|
this.browse_commit(
|
||||||
|
&browse_id, window, cx,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.child(
|
||||||
|
div()
|
||||||
.flex_1()
|
.flex_1()
|
||||||
.min_w_0()
|
.min_w_0()
|
||||||
.justify_center()
|
.text_ellipsis()
|
||||||
.child(
|
.whitespace_nowrap()
|
||||||
h_flex()
|
.child(commit.summary.clone()),
|
||||||
.gap_2()
|
)
|
||||||
.overflow_hidden()
|
.child(
|
||||||
.child(
|
div()
|
||||||
div()
|
.flex_none()
|
||||||
.text_sm()
|
.text_xs()
|
||||||
.text_color(
|
.text_color(cx.theme().colors.muted_foreground)
|
||||||
cx.theme()
|
.whitespace_nowrap()
|
||||||
.colors
|
.child(relative_time_secs(commit.time)),
|
||||||
.muted_foreground,
|
|
||||||
)
|
|
||||||
.child(short_id(&commit.id)),
|
|
||||||
)
|
|
||||||
.child(
|
|
||||||
div()
|
|
||||||
.flex_1()
|
|
||||||
.min_w_0()
|
|
||||||
.text_sm()
|
|
||||||
.text_ellipsis()
|
|
||||||
.whitespace_nowrap()
|
|
||||||
.child(commit.summary.clone()),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.child(
|
|
||||||
h_flex()
|
|
||||||
.gap_2()
|
|
||||||
.text_xs()
|
|
||||||
.text_color(
|
|
||||||
cx.theme().colors.muted_foreground,
|
|
||||||
)
|
|
||||||
.child(commit.author.clone())
|
|
||||||
.child(relative_time_secs(commit.time)),
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
.when_some(ahead, |row, (ahead_id, path)| {
|
.when_some(ahead, |row, (ahead_id, path)| {
|
||||||
let detail = detail.clone();
|
let detail = detail.clone();
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ pub mod refs;
|
|||||||
use files::RepoFilesView;
|
use files::RepoFilesView;
|
||||||
use helpers::{
|
use helpers::{
|
||||||
RepoData, announcement_display_name, bound_repo_label, clone_group, fork_row, load_repo_data,
|
RepoData, announcement_display_name, bound_repo_label, clone_group, fork_row, load_repo_data,
|
||||||
nostr_clone_url, repo_display_name, snapshot_worktree,
|
nostr_clone_url, repo_display_name, snapshot_commit, snapshot_worktree,
|
||||||
};
|
};
|
||||||
use history::RepoHistoryView;
|
use history::RepoHistoryView;
|
||||||
use refs::RefSwitcher;
|
use refs::RefSwitcher;
|
||||||
@@ -117,6 +117,8 @@ pub struct RepoDetailView {
|
|||||||
loading: bool,
|
loading: bool,
|
||||||
error: Option<SharedString>,
|
error: Option<SharedString>,
|
||||||
head_commit: Option<FileCommit>,
|
head_commit: Option<FileCommit>,
|
||||||
|
/// The commit whose files are shown in place of the worktree.
|
||||||
|
browsed_commit: Option<FileCommit>,
|
||||||
refs: RefSwitcher,
|
refs: RefSwitcher,
|
||||||
tasks: Vec<Task<Result<(), Error>>>,
|
tasks: Vec<Task<Result<(), Error>>>,
|
||||||
/// Profiles rendered by the header and maintainers.
|
/// Profiles rendered by the header and maintainers.
|
||||||
@@ -244,6 +246,7 @@ impl RepoDetailView {
|
|||||||
loading: true,
|
loading: true,
|
||||||
error: None,
|
error: None,
|
||||||
head_commit: None,
|
head_commit: None,
|
||||||
|
browsed_commit: None,
|
||||||
refs,
|
refs,
|
||||||
tasks: Vec::new(),
|
tasks: Vec::new(),
|
||||||
directory: ProfileDirectory::new(cx),
|
directory: ProfileDirectory::new(cx),
|
||||||
@@ -561,9 +564,12 @@ impl RepoDetailView {
|
|||||||
|
|
||||||
self.worktree = Some(worktree.clone());
|
self.worktree = Some(worktree.clone());
|
||||||
self.head_commit = head_commit;
|
self.head_commit = head_commit;
|
||||||
|
self.browsed_commit = None;
|
||||||
|
self.refs.commit_label = None;
|
||||||
|
|
||||||
self.files.update(cx, |files, cx| {
|
self.files.update(cx, |files, cx| {
|
||||||
files.set_worktree(worktree.clone());
|
files.set_worktree(worktree.clone());
|
||||||
|
files.pin_commit(None);
|
||||||
files.apply_entries(tree, sorted_worktree_paths(&entries), cx);
|
files.apply_entries(tree, sorted_worktree_paths(&entries), cx);
|
||||||
files.set_readme(readme_path, readme, cx);
|
files.set_readme(readme_path, readme, cx);
|
||||||
});
|
});
|
||||||
@@ -583,6 +589,59 @@ impl RepoDetailView {
|
|||||||
self.refs.set_tags(tags, window, cx);
|
self.refs.set_tags(tags, window, cx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shows the files of `commit`, read from the repository at `source`, in place of the worktree.
|
||||||
|
fn browse_commit(
|
||||||
|
&mut self,
|
||||||
|
commit: FileCommit,
|
||||||
|
source: PathBuf,
|
||||||
|
window: &mut Window,
|
||||||
|
cx: &mut Context<Self>,
|
||||||
|
) {
|
||||||
|
self.active_section = RepoSection::Files;
|
||||||
|
self.browsed_commit = Some(commit.clone());
|
||||||
|
self.refs.show_commit(short_id(&commit.id), window, cx);
|
||||||
|
cx.notify();
|
||||||
|
|
||||||
|
let loaded_id = commit.id.clone();
|
||||||
|
let shown = source.clone();
|
||||||
|
|
||||||
|
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
|
let result = cx
|
||||||
|
.background_spawn(async move { snapshot_commit(&source, &loaded_id) })
|
||||||
|
.await;
|
||||||
|
|
||||||
|
this.update_in(cx, |this, window, cx| {
|
||||||
|
// A later pick replaced this one while it loaded.
|
||||||
|
let current = this
|
||||||
|
.browsed_commit
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|current| current.id == commit.id);
|
||||||
|
if !current {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(tree) => this.files.update(cx, |files, cx| {
|
||||||
|
files.set_worktree(shown);
|
||||||
|
files.clear_previews();
|
||||||
|
files.apply_entries(tree.tree, tree.paths, cx);
|
||||||
|
files.pin_commit(Some(commit));
|
||||||
|
files.set_readme(tree.readme_path, tree.readme, cx);
|
||||||
|
}),
|
||||||
|
Err(error) => {
|
||||||
|
this.error = Some(error.to_string().into());
|
||||||
|
this.reload_worktree(window, cx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cx.notify();
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
|
||||||
|
self.push_task(task);
|
||||||
|
}
|
||||||
|
|
||||||
fn clone_to_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn clone_to_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let store = self.store.clone();
|
let store = self.store.clone();
|
||||||
|
|
||||||
@@ -653,6 +712,8 @@ impl RepoDetailView {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let name = name.into();
|
let name = name.into();
|
||||||
|
let browsing = self.browsed_commit.is_some();
|
||||||
|
self.refs.commit_label = None;
|
||||||
|
|
||||||
// Restored if the checkout fails while HEAD stays detached.
|
// Restored if the checkout fails while HEAD stays detached.
|
||||||
let previous_tag = match kind {
|
let previous_tag = match kind {
|
||||||
@@ -684,6 +745,13 @@ impl RepoDetailView {
|
|||||||
// A failed checkout leaves HEAD alone; report the branch it is still on.
|
// A failed checkout leaves HEAD alone; report the branch it is still on.
|
||||||
let current = repo.as_ref().ok().and_then(|repo| repo.current_branch());
|
let current = repo.as_ref().ok().and_then(|repo| repo.current_branch());
|
||||||
let checkout = match kind {
|
let checkout = match kind {
|
||||||
|
// Browsing a commit leaves HEAD alone, so picking its branch again only
|
||||||
|
// returns to the worktree.
|
||||||
|
RefKind::Branch
|
||||||
|
if browsing && current.as_deref() == Some(checkout_name.as_ref()) =>
|
||||||
|
{
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
RefKind::Branch => {
|
RefKind::Branch => {
|
||||||
repo.and_then(|repo| repo.checkout_branch(&checkout_name))
|
repo.and_then(|repo| repo.checkout_branch(&checkout_name))
|
||||||
}
|
}
|
||||||
@@ -698,7 +766,7 @@ impl RepoDetailView {
|
|||||||
|
|
||||||
this.update_in(cx, |this, window, cx| {
|
this.update_in(cx, |this, window, cx| {
|
||||||
match outcome {
|
match outcome {
|
||||||
Ok(_) => this.reload_worktree(cx),
|
Ok(_) => this.reload_worktree(window, cx),
|
||||||
Err((error, current)) => {
|
Err((error, current)) => {
|
||||||
this.error = Some(format!("Failed to check out {name}: {error}").into());
|
this.error = Some(format!("Failed to check out {name}: {error}").into());
|
||||||
this.refs.switching_ref = false;
|
this.refs.switching_ref = false;
|
||||||
@@ -714,6 +782,10 @@ impl RepoDetailView {
|
|||||||
let tag = if detached { previous_tag } else { None };
|
let tag = if detached { previous_tag } else { None };
|
||||||
this.refs
|
this.refs
|
||||||
.restore_selection(&this.refs.tag_select, &tag, window, cx);
|
.restore_selection(&this.refs.tag_select, &tag, window, cx);
|
||||||
|
|
||||||
|
if browsing {
|
||||||
|
this.reload_worktree(window, cx);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
cx.notify();
|
cx.notify();
|
||||||
@@ -725,29 +797,43 @@ impl RepoDetailView {
|
|||||||
self.push_task(task);
|
self.push_task(task);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn reload_worktree(&mut self, cx: &mut Context<Self>) {
|
/// Reloads the worktree, ending a browsed commit.
|
||||||
|
fn reload_worktree(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let Some(worktree) = self.worktree.clone() else {
|
let Some(worktree) = self.worktree.clone() else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let task: Task<Result<(), Error>> = cx.spawn(async move |this, cx| {
|
let displayed = worktree.clone();
|
||||||
|
|
||||||
|
let task: Task<Result<(), Error>> = cx.spawn_in(window, async move |this, cx| {
|
||||||
let result = cx
|
let result = cx
|
||||||
.background_spawn(async move { snapshot_worktree(worktree) })
|
.background_spawn(async move { snapshot_worktree(worktree) })
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
this.update(cx, |this, cx| {
|
this.update_in(cx, |this, window, cx| {
|
||||||
this.refs.switching_ref = false;
|
this.refs.switching_ref = false;
|
||||||
|
this.browsed_commit = None;
|
||||||
|
this.refs.commit_label = None;
|
||||||
|
this.files.update(cx, |files, _| files.pin_commit(None));
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok((snapshot, tree, paths)) => {
|
Ok((snapshot, tree, paths)) => {
|
||||||
this.head_commit = snapshot.head_commit.clone();
|
this.head_commit = snapshot.head_commit.clone();
|
||||||
|
let current_branch = snapshot.current_branch.map(Into::into);
|
||||||
let readme_path = snapshot.readme_path;
|
let readme_path = snapshot.readme_path;
|
||||||
let readme = snapshot.readme;
|
let readme = snapshot.readme;
|
||||||
this.files.update(cx, |files, cx| {
|
this.files.update(cx, |files, cx| {
|
||||||
|
files.set_worktree(displayed);
|
||||||
files.clear_previews();
|
files.clear_previews();
|
||||||
files.apply_entries(tree, paths, cx);
|
files.apply_entries(tree, paths, cx);
|
||||||
files.set_readme(readme_path, readme, cx);
|
files.set_readme(readme_path, readme, cx);
|
||||||
});
|
});
|
||||||
|
this.refs.restore_selection(
|
||||||
|
&this.refs.branch_select,
|
||||||
|
¤t_branch,
|
||||||
|
window,
|
||||||
|
cx,
|
||||||
|
);
|
||||||
this.history.update(cx, |history, cx| history.reload(cx));
|
this.history.update(cx, |history, cx| history.reload(cx));
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -782,9 +868,12 @@ impl RepoDetailView {
|
|||||||
this.update(cx, |this, cx| match result {
|
this.update(cx, |this, cx| match result {
|
||||||
Ok((snapshot, tree, paths)) => {
|
Ok((snapshot, tree, paths)) => {
|
||||||
this.head_commit = snapshot.head_commit.clone();
|
this.head_commit = snapshot.head_commit.clone();
|
||||||
this.files.update(cx, |files, cx| {
|
// A browsed commit's tree does not follow the worktree.
|
||||||
files.catch_up(&snapshot, tree, paths, cx);
|
if this.browsed_commit.is_none() {
|
||||||
});
|
this.files.update(cx, |files, cx| {
|
||||||
|
files.catch_up(&snapshot, tree, paths, cx);
|
||||||
|
});
|
||||||
|
}
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
@@ -1434,16 +1523,20 @@ impl RepoDetailView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
|
fn render_last_commit(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
|
||||||
let commit = self.head_commit.as_ref()?;
|
let commit = self.browsed_commit.as_ref().or(self.head_commit.as_ref())?;
|
||||||
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
|
let short = commit.id.get(..8).unwrap_or(&commit.id).to_owned();
|
||||||
let history = self.history.clone();
|
let history = self.history.clone();
|
||||||
let commit_id = commit.id.clone();
|
let commit_id = commit.id.clone();
|
||||||
|
let tooltip = match self.browsed_commit {
|
||||||
|
Some(_) => "View commit",
|
||||||
|
None => "View latest commit",
|
||||||
|
};
|
||||||
|
|
||||||
Some(
|
Some(
|
||||||
Button::new("last-commit")
|
Button::new("last-commit")
|
||||||
.variant(ButtonVariant::Ghost)
|
.variant(ButtonVariant::Ghost)
|
||||||
.fully_rounded(true)
|
.fully_rounded(true)
|
||||||
.tooltip(Tooltip::text("View latest commit"))
|
.tooltip(Tooltip::text(tooltip))
|
||||||
.on_click(move |_, window, cx| {
|
.on_click(move |_, window, cx| {
|
||||||
history.update(cx, |history, cx| {
|
history.update(cx, |history, cx| {
|
||||||
history.open_commit_diff(&commit_id, window, cx);
|
history.open_commit_diff(&commit_id, window, cx);
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ pub(super) struct RefSwitcher {
|
|||||||
ref_branches: Vec<SharedString>,
|
ref_branches: Vec<SharedString>,
|
||||||
ref_tags: Vec<SharedString>,
|
ref_tags: Vec<SharedString>,
|
||||||
pub(super) switching_ref: bool,
|
pub(super) switching_ref: bool,
|
||||||
|
/// The commit shown in place of the branch while the panel browses one.
|
||||||
|
pub(super) commit_label: Option<SharedString>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RefSwitcher {
|
impl RefSwitcher {
|
||||||
@@ -60,6 +62,7 @@ impl RefSwitcher {
|
|||||||
ref_branches: Vec::new(),
|
ref_branches: Vec::new(),
|
||||||
ref_tags: Vec::new(),
|
ref_tags: Vec::new(),
|
||||||
switching_ref: false,
|
switching_ref: false,
|
||||||
|
commit_label: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,6 +73,13 @@ impl RefSwitcher {
|
|||||||
window: &mut Window,
|
window: &mut Window,
|
||||||
cx: &mut App,
|
cx: &mut App,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
|
// A shown commit keeps its label until a ref is picked.
|
||||||
|
let selected = if self.commit_label.is_some() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
selected
|
||||||
|
};
|
||||||
|
|
||||||
sync_selector(
|
sync_selector(
|
||||||
&self.branch_select,
|
&self.branch_select,
|
||||||
&mut self.ref_branches,
|
&mut self.ref_branches,
|
||||||
@@ -89,6 +99,13 @@ impl RefSwitcher {
|
|||||||
sync_selector(&self.tag_select, &mut self.ref_tags, tags, None, window, cx)
|
sync_selector(&self.tag_select, &mut self.ref_tags, tags, None, window, cx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Shows `label` in the branch selector until a ref is picked.
|
||||||
|
pub(super) fn show_commit(&mut self, label: SharedString, window: &mut Window, cx: &mut App) {
|
||||||
|
self.commit_label = Some(label.clone());
|
||||||
|
self.branch_select
|
||||||
|
.update(cx, |state, cx| state.set_display_label(label, window, cx));
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn restore_selection(
|
pub(super) fn restore_selection(
|
||||||
&self,
|
&self,
|
||||||
select: &Entity<ComboboxState<SharedString>>,
|
select: &Entity<ComboboxState<SharedString>>,
|
||||||
|
|||||||
@@ -1084,15 +1084,48 @@ impl Repo {
|
|||||||
/// Lists every worktree path relative to the root, directories first.
|
/// Lists every worktree path relative to the root, directories first.
|
||||||
pub fn entries(&self) -> Result<Vec<PathBuf>> {
|
pub fn entries(&self) -> Result<Vec<PathBuf>> {
|
||||||
let workdir = self.inner.workdir().context("repository has no worktree")?;
|
let workdir = self.inner.workdir().context("repository has no worktree")?;
|
||||||
|
|
||||||
let mut entries: Vec<(PathBuf, bool)> = Vec::new();
|
let mut entries: Vec<(PathBuf, bool)> = Vec::new();
|
||||||
Self::collect_entries(workdir, workdir, &mut entries)?;
|
|
||||||
|
|
||||||
|
Self::collect_entries(workdir, workdir, &mut entries)?;
|
||||||
|
Self::sort_entries(&mut entries);
|
||||||
|
|
||||||
|
Ok(entries.into_iter().map(|(path, _)| path).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sorts directories before files, each alphabetically.
|
||||||
|
fn sort_entries(entries: &mut [(PathBuf, bool)]) {
|
||||||
entries.sort_by(|(a, a_is_dir), (b, b_is_dir)| {
|
entries.sort_by(|(a, a_is_dir), (b, b_is_dir)| {
|
||||||
b_is_dir
|
b_is_dir
|
||||||
.cmp(a_is_dir)
|
.cmp(a_is_dir)
|
||||||
.then_with(|| a.as_os_str().cmp(b.as_os_str()))
|
.then_with(|| a.as_os_str().cmp(b.as_os_str()))
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lists every path in the tree of commit `id`, directories first like `entries`.
|
||||||
|
pub fn entries_at(&self, id: &str) -> Result<Vec<PathBuf>> {
|
||||||
|
let commit_id = self.inner.rev_parse_single(id.as_bytes())?;
|
||||||
|
let tree = commit_id.object()?.into_commit().tree()?;
|
||||||
|
|
||||||
|
let mut entries: Vec<(PathBuf, bool)> = Vec::new();
|
||||||
|
for entry in tree.traverse().breadthfirst.files()? {
|
||||||
|
if !entry.mode.is_blob() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let path = gix::path::from_bstring(entry.filepath);
|
||||||
|
for dir in path
|
||||||
|
.ancestors()
|
||||||
|
.skip(1)
|
||||||
|
.filter(|dir| !dir.as_os_str().is_empty())
|
||||||
|
{
|
||||||
|
entries.push((dir.to_path_buf(), true));
|
||||||
|
}
|
||||||
|
entries.push((path, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
Self::sort_entries(&mut entries);
|
||||||
|
entries.dedup_by(|a, b| a.0 == b.0);
|
||||||
|
|
||||||
Ok(entries.into_iter().map(|(path, _)| path).collect())
|
Ok(entries.into_iter().map(|(path, _)| path).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1109,22 +1142,48 @@ impl Repo {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reads a file from the tree of commit `id`, or `None` when it has no file at `rel`.
|
||||||
|
pub fn read_at(&self, id: &str, rel: &Path) -> Result<Option<Vec<u8>>> {
|
||||||
|
let commit_id = self.inner.rev_parse_single(id.as_bytes())?;
|
||||||
|
let tree = commit_id.object()?.into_commit().tree()?;
|
||||||
|
|
||||||
|
match tree.lookup_entry_by_path(rel)? {
|
||||||
|
Some(entry) if entry.mode().is_blob() => {
|
||||||
|
let mut blob = entry.object()?;
|
||||||
|
Ok(Some(std::mem::take(&mut blob.data)))
|
||||||
|
}
|
||||||
|
_ => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Finds the top-level README, preferring markdown extensions.
|
/// Finds the top-level README, preferring markdown extensions.
|
||||||
pub fn find_readme(&self) -> Result<Option<PathBuf>> {
|
pub fn find_readme(&self) -> Result<Option<PathBuf>> {
|
||||||
let Some(workdir) = self.inner.workdir() else {
|
let Some(workdir) = self.inner.workdir() else {
|
||||||
return Ok(None);
|
return Ok(None);
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut candidates: Vec<PathBuf> = Vec::new();
|
let mut names = Vec::new();
|
||||||
for entry in std::fs::read_dir(workdir)? {
|
for entry in std::fs::read_dir(workdir)? {
|
||||||
let entry = entry?;
|
names.push(PathBuf::from(entry?.file_name()));
|
||||||
let name = entry.file_name();
|
|
||||||
let Some(name) = name.to_str() else { continue };
|
|
||||||
if name.to_ascii_lowercase().starts_with("readme") {
|
|
||||||
candidates.push(entry.path());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Ok(Self::pick_readme(&names))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The top-level README among `entries`, preferring markdown extensions.
|
||||||
|
pub fn pick_readme(entries: &[PathBuf]) -> Option<PathBuf> {
|
||||||
|
let mut candidates: Vec<PathBuf> = entries
|
||||||
|
.iter()
|
||||||
|
.filter(|path| {
|
||||||
|
path.components().count() == 1
|
||||||
|
&& path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|name| name.to_str())
|
||||||
|
.is_some_and(|name| name.to_ascii_lowercase().starts_with("readme"))
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect();
|
||||||
|
|
||||||
candidates.sort_by_key(|path| {
|
candidates.sort_by_key(|path| {
|
||||||
let ext = path
|
let ext = path
|
||||||
.extension()
|
.extension()
|
||||||
@@ -1139,10 +1198,7 @@ impl Repo {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(candidates
|
candidates.into_iter().next()
|
||||||
.into_iter()
|
|
||||||
.next()
|
|
||||||
.and_then(|path| path.strip_prefix(workdir).ok().map(Path::to_path_buf)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Captures worktree entries, README, and ref state in one pass.
|
/// Captures worktree entries, README, and ref state in one pass.
|
||||||
|
|||||||
@@ -992,3 +992,72 @@ fn parses_real_format_patch_output() {
|
|||||||
assert_eq!(file.insertions, 0);
|
assert_eq!(file.insertions, 0);
|
||||||
assert_eq!(file.deletions, 0);
|
assert_eq!(file.deletions, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entries_at_lists_a_commits_files_directories_first() {
|
||||||
|
let (_dir, repo) = fixture(&[
|
||||||
|
("README", b"plain"),
|
||||||
|
("docs/README.md", b"# Docs"),
|
||||||
|
("notes.txt", b"one"),
|
||||||
|
("readme.md", b"# Title"),
|
||||||
|
("src/lib.rs", b"fn old() {}"),
|
||||||
|
]);
|
||||||
|
commit_all(&repo, "initial");
|
||||||
|
let first = repo.head_commit().expect("head").expect("commit").id;
|
||||||
|
|
||||||
|
let expected = vec![
|
||||||
|
PathBuf::from("docs"),
|
||||||
|
PathBuf::from("src"),
|
||||||
|
PathBuf::from("README"),
|
||||||
|
PathBuf::from("docs/README.md"),
|
||||||
|
PathBuf::from("notes.txt"),
|
||||||
|
PathBuf::from("readme.md"),
|
||||||
|
PathBuf::from("src/lib.rs"),
|
||||||
|
];
|
||||||
|
|
||||||
|
let entries = repo.entries_at(&first).expect("entries");
|
||||||
|
assert_eq!(entries, expected);
|
||||||
|
assert_eq!(repo.entries().expect("entries"), expected);
|
||||||
|
assert_eq!(
|
||||||
|
Repo::pick_readme(&entries).as_deref(),
|
||||||
|
Some(Path::new("readme.md"))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
repo.find_readme().expect("readme").as_deref(),
|
||||||
|
Some(Path::new("readme.md"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn read_at_reads_the_files_of_that_commit() {
|
||||||
|
let (dir, repo) = fixture(&[("notes.txt", b"one"), ("src/lib.rs", b"fn old() {}")]);
|
||||||
|
commit_all(&repo, "initial");
|
||||||
|
let first = repo.head_commit().expect("head").expect("commit").id;
|
||||||
|
|
||||||
|
std::fs::write(dir.path().join("src/lib.rs"), b"fn new() {}").expect("write");
|
||||||
|
std::fs::remove_file(dir.path().join("notes.txt")).expect("remove");
|
||||||
|
commit_all(&repo, "second");
|
||||||
|
let second = repo.head_commit().expect("head").expect("commit").id;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
repo.read_at(&first, Path::new("src/lib.rs"))
|
||||||
|
.expect("read")
|
||||||
|
.as_deref(),
|
||||||
|
Some(b"fn old() {}".as_slice())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
repo.read_at(&second, Path::new("src/lib.rs"))
|
||||||
|
.expect("read")
|
||||||
|
.as_deref(),
|
||||||
|
Some(b"fn new() {}".as_slice())
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
repo.read_at(&second, Path::new("notes.txt")).expect("read"),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
assert_eq!(repo.read_at(&second, Path::new("src")).expect("read"), None);
|
||||||
|
assert!(
|
||||||
|
repo.read_at("0000000000000000000000000000000000000000", Path::new("src"))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -180,6 +180,8 @@ where
|
|||||||
options: Vec<ComboboxOption<T>>,
|
options: Vec<ComboboxOption<T>>,
|
||||||
/// The chosen value. `None` while the text names nothing.
|
/// The chosen value. `None` while the text names nothing.
|
||||||
selected: Option<T>,
|
selected: Option<T>,
|
||||||
|
/// A label shown in the field in place of a chosen option.
|
||||||
|
display_label: Option<SharedString>,
|
||||||
query: Entity<InputState>,
|
query: Entity<InputState>,
|
||||||
/// Indices into `options` that survived the filter, in popup row order.
|
/// Indices into `options` that survived the filter, in popup row order.
|
||||||
visible: Vec<usize>,
|
visible: Vec<usize>,
|
||||||
@@ -241,6 +243,7 @@ where
|
|||||||
placeholder: combobox.placeholder,
|
placeholder: combobox.placeholder,
|
||||||
options: combobox.options,
|
options: combobox.options,
|
||||||
selected: combobox.selected,
|
selected: combobox.selected,
|
||||||
|
display_label: None,
|
||||||
query,
|
query,
|
||||||
visible,
|
visible,
|
||||||
highlight: None,
|
highlight: None,
|
||||||
@@ -262,6 +265,7 @@ where
|
|||||||
/// Replaces the value; reports it when it actually changed.
|
/// Replaces the value; reports it when it actually changed.
|
||||||
pub fn set_selected(&mut self, value: Option<T>, window: &mut Window, cx: &mut Context<Self>) {
|
pub fn set_selected(&mut self, value: Option<T>, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let changed = self.selected != value;
|
let changed = self.selected != value;
|
||||||
|
self.display_label = None;
|
||||||
self.set_value(value, window, cx);
|
self.set_value(value, window, cx);
|
||||||
if changed {
|
if changed {
|
||||||
let label = self.selected_label().unwrap_or_default();
|
let label = self.selected_label().unwrap_or_default();
|
||||||
@@ -279,13 +283,34 @@ where
|
|||||||
window: &mut Window,
|
window: &mut Window,
|
||||||
cx: &mut Context<Self>,
|
cx: &mut Context<Self>,
|
||||||
) {
|
) {
|
||||||
if self.selected == value {
|
if self.selected == value && self.display_label.is_none() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.display_label = None;
|
||||||
self.selected = value;
|
self.selected = value;
|
||||||
|
|
||||||
let label = self.selected_label().unwrap_or_default();
|
let label = self.selected_label().unwrap_or_default();
|
||||||
self.query
|
self.query.update(cx, |query, cx| {
|
||||||
.update(cx, |query, cx| query.set_value_silent(label, window, cx));
|
query.set_value_silent(label, window, cx);
|
||||||
|
});
|
||||||
|
self.refilter("");
|
||||||
|
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shows `label` in the field in place of the choice, reporting nothing; a choice replaces it.
|
||||||
|
pub fn set_display_label(
|
||||||
|
&mut self,
|
||||||
|
label: SharedString,
|
||||||
|
window: &mut Window,
|
||||||
|
cx: &mut Context<Self>,
|
||||||
|
) {
|
||||||
|
self.selected = None;
|
||||||
|
self.display_label = Some(label.clone());
|
||||||
|
self.query.update(cx, |query, cx| {
|
||||||
|
query.set_value_silent(label.to_string(), window, cx)
|
||||||
|
});
|
||||||
self.refilter("");
|
self.refilter("");
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
@@ -298,13 +323,16 @@ where
|
|||||||
cx.notify();
|
cx.notify();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The label of the chosen option, if there is one.
|
/// The label of the chosen option, or the display label's.
|
||||||
fn selected_label(&self) -> Option<SharedString> {
|
fn selected_label(&self) -> Option<SharedString> {
|
||||||
let selected = self.selected.as_ref()?;
|
if let Some(selected) = &self.selected {
|
||||||
self.options
|
return self
|
||||||
.iter()
|
.options
|
||||||
.find(|(value, _)| value == selected)
|
.iter()
|
||||||
.map(|(_, label)| label.clone())
|
.find(|(value, _)| value == selected)
|
||||||
|
.map(|(_, label)| label.clone());
|
||||||
|
}
|
||||||
|
self.display_label.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Recomputes `visible` for `query` and clamps the highlight onto it.
|
/// Recomputes `visible` for `query` and clamps the highlight onto it.
|
||||||
@@ -329,6 +357,7 @@ where
|
|||||||
if self.selected == value {
|
if self.selected == value {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
self.display_label = None;
|
||||||
self.selected = value.clone();
|
self.selected = value.clone();
|
||||||
if let Some(on_change) = self.on_change.clone() {
|
if let Some(on_change) = self.on_change.clone() {
|
||||||
let value = value.clone();
|
let value = value.clone();
|
||||||
@@ -526,7 +555,9 @@ where
|
|||||||
if state.highlight.is_some() {
|
if state.highlight.is_some() {
|
||||||
state.highlight = None;
|
state.highlight = None;
|
||||||
} else {
|
} else {
|
||||||
if state.selected.is_some() {
|
if state.selected.is_some()
|
||||||
|
|| state.display_label.is_some()
|
||||||
|
{
|
||||||
state.refilter("");
|
state.refilter("");
|
||||||
} else {
|
} else {
|
||||||
let query =
|
let query =
|
||||||
|
|||||||
Reference in New Issue
Block a user