1use anyhow::{anyhow, Context, Result};
2use fuzzy::{StringMatch, StringMatchCandidate};
3use git::repository::Branch;
4use gpui::{
5 rems, AnyElement, AppContext, AsyncAppContext, DismissEvent, EventEmitter, FocusHandle,
6 FocusableView, InteractiveElement, IntoElement, ParentElement, Render, SharedString, Styled,
7 Subscription, Task, View, ViewContext, VisualContext, WeakView, WindowContext,
8};
9use picker::{Picker, PickerDelegate};
10use project::ProjectPath;
11use std::{ops::Not, sync::Arc};
12use ui::{prelude::*, HighlightedLabel, ListItem, ListItemSpacing};
13use util::ResultExt;
14use workspace::notifications::DetachAndPromptErr;
15use workspace::{ModalView, Workspace};
16use zed_actions::branches::OpenRecent;
17
18pub fn init(cx: &mut AppContext) {
19 cx.observe_new_views(|workspace: &mut Workspace, _| {
20 workspace.register_action(BranchList::open);
21 })
22 .detach();
23}
24
25pub struct BranchList {
26 pub picker: View<Picker<BranchListDelegate>>,
27 rem_width: f32,
28 _subscription: Subscription,
29}
30
31impl BranchList {
32 pub fn open(_: &mut Workspace, _: &OpenRecent, cx: &mut ViewContext<Workspace>) {
33 let this = cx.view().clone();
34 cx.spawn(|_, mut cx| async move {
35 // Modal branch picker has a longer trailoff than a popover one.
36 let delegate = BranchListDelegate::new(this.clone(), 70, &cx).await?;
37
38 this.update(&mut cx, |workspace, cx| {
39 workspace.toggle_modal(cx, |cx| BranchList::new(delegate, 34., cx))
40 })?;
41
42 Ok(())
43 })
44 .detach_and_prompt_err("Failed to read branches", cx, |_, _| None)
45 }
46
47 fn new(delegate: BranchListDelegate, rem_width: f32, cx: &mut ViewContext<Self>) -> Self {
48 let picker = cx.new_view(|cx| Picker::uniform_list(delegate, cx));
49 let _subscription = cx.subscribe(&picker, |_, _, _, cx| cx.emit(DismissEvent));
50 Self {
51 picker,
52 rem_width,
53 _subscription,
54 }
55 }
56}
57impl ModalView for BranchList {}
58impl EventEmitter<DismissEvent> for BranchList {}
59
60impl FocusableView for BranchList {
61 fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
62 self.picker.focus_handle(cx)
63 }
64}
65
66impl Render for BranchList {
67 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
68 v_flex()
69 .w(rems(self.rem_width))
70 .child(self.picker.clone())
71 .on_mouse_down_out(cx.listener(|this, _, cx| {
72 this.picker.update(cx, |this, cx| {
73 this.cancel(&Default::default(), cx);
74 })
75 }))
76 }
77}
78
79#[derive(Debug, Clone)]
80enum BranchEntry {
81 Branch(StringMatch),
82 NewBranch { name: String },
83}
84
85impl BranchEntry {
86 fn name(&self) -> &str {
87 match self {
88 Self::Branch(branch) => &branch.string,
89 Self::NewBranch { name } => &name,
90 }
91 }
92}
93
94pub struct BranchListDelegate {
95 matches: Vec<BranchEntry>,
96 all_branches: Vec<Branch>,
97 workspace: WeakView<Workspace>,
98 selected_index: usize,
99 last_query: String,
100 /// Max length of branch name before we truncate it and add a trailing `...`.
101 branch_name_trailoff_after: usize,
102}
103
104impl BranchListDelegate {
105 async fn new(
106 workspace: View<Workspace>,
107 branch_name_trailoff_after: usize,
108 cx: &AsyncAppContext,
109 ) -> Result<Self> {
110 let all_branches_request = cx.update(|cx| {
111 let project = workspace.read(cx).project().read(cx);
112 let first_worktree = project
113 .visible_worktrees(cx)
114 .next()
115 .context("No worktrees found")?;
116 let project_path = ProjectPath::root_path(first_worktree.read(cx).id());
117 anyhow::Ok(project.branches(project_path, cx))
118 })??;
119
120 let all_branches = all_branches_request.await?;
121
122 Ok(Self {
123 matches: vec![],
124 workspace: workspace.downgrade(),
125 all_branches,
126 selected_index: 0,
127 last_query: Default::default(),
128 branch_name_trailoff_after,
129 })
130 }
131}
132
133impl PickerDelegate for BranchListDelegate {
134 type ListItem = ListItem;
135
136 fn placeholder_text(&self, _cx: &mut WindowContext) -> Arc<str> {
137 "Select branch...".into()
138 }
139
140 fn match_count(&self) -> usize {
141 self.matches.len()
142 }
143
144 fn selected_index(&self) -> usize {
145 self.selected_index
146 }
147
148 fn set_selected_index(&mut self, ix: usize, _: &mut ViewContext<Picker<Self>>) {
149 self.selected_index = ix;
150 }
151
152 fn update_matches(&mut self, query: String, cx: &mut ViewContext<Picker<Self>>) -> Task<()> {
153 cx.spawn(move |picker, mut cx| async move {
154 let candidates = picker.update(&mut cx, |view, _| {
155 const RECENT_BRANCHES_COUNT: usize = 10;
156 let mut branches = view.delegate.all_branches.clone();
157 if query.is_empty() {
158 if branches.len() > RECENT_BRANCHES_COUNT {
159 // Truncate list of recent branches
160 // Do a partial sort to show recent-ish branches first.
161 branches.select_nth_unstable_by(RECENT_BRANCHES_COUNT - 1, |lhs, rhs| {
162 rhs.is_head
163 .cmp(&lhs.is_head)
164 .then(rhs.unix_timestamp.cmp(&lhs.unix_timestamp))
165 });
166 branches.truncate(RECENT_BRANCHES_COUNT);
167 }
168 branches.sort_unstable_by(|lhs, rhs| {
169 rhs.is_head.cmp(&lhs.is_head).then(lhs.name.cmp(&rhs.name))
170 });
171 }
172 branches
173 .into_iter()
174 .enumerate()
175 .map(|(ix, command)| StringMatchCandidate::new(ix, &command.name))
176 .collect::<Vec<StringMatchCandidate>>()
177 });
178 let Some(candidates) = candidates.log_err() else {
179 return;
180 };
181 let matches = if query.is_empty() {
182 candidates
183 .into_iter()
184 .enumerate()
185 .map(|(index, candidate)| StringMatch {
186 candidate_id: index,
187 string: candidate.string,
188 positions: Vec::new(),
189 score: 0.0,
190 })
191 .collect()
192 } else {
193 fuzzy::match_strings(
194 &candidates,
195 &query,
196 true,
197 10000,
198 &Default::default(),
199 cx.background_executor().clone(),
200 )
201 .await
202 };
203 picker
204 .update(&mut cx, |picker, _| {
205 let delegate = &mut picker.delegate;
206 delegate.matches = matches.into_iter().map(BranchEntry::Branch).collect();
207 if delegate.matches.is_empty() {
208 if !query.is_empty() {
209 delegate.matches.push(BranchEntry::NewBranch {
210 name: query.trim().replace(' ', "-"),
211 });
212 }
213
214 delegate.selected_index = 0;
215 } else {
216 delegate.selected_index =
217 core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
218 }
219 delegate.last_query = query;
220 })
221 .log_err();
222 })
223 }
224
225 fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
226 let Some(branch) = self.matches.get(self.selected_index()) else {
227 return;
228 };
229 cx.spawn({
230 let branch = branch.clone();
231 |picker, mut cx| async move {
232 let branch_change_task = picker.update(&mut cx, |this, cx| {
233 let workspace = this
234 .delegate
235 .workspace
236 .upgrade()
237 .ok_or_else(|| anyhow!("workspace was dropped"))?;
238
239 let project = workspace.read(cx).project().read(cx);
240 let branch_to_checkout = match branch {
241 BranchEntry::Branch(branch) => branch.string,
242 BranchEntry::NewBranch { name: branch_name } => branch_name,
243 };
244 let worktree = project
245 .visible_worktrees(cx)
246 .next()
247 .context("worktree disappeared")?;
248 let repository = ProjectPath::root_path(worktree.read(cx).id());
249
250 anyhow::Ok(project.update_or_create_branch(repository, branch_to_checkout, cx))
251 })??;
252
253 branch_change_task.await?;
254
255 picker.update(&mut cx, |_, cx| {
256 cx.emit(DismissEvent);
257
258 Ok::<(), anyhow::Error>(())
259 })
260 }
261 })
262 .detach_and_prompt_err("Failed to change branch", cx, |_, _| None);
263 }
264
265 fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
266 cx.emit(DismissEvent);
267 }
268
269 fn render_match(
270 &self,
271 ix: usize,
272 selected: bool,
273 _cx: &mut ViewContext<Picker<Self>>,
274 ) -> Option<Self::ListItem> {
275 let hit = &self.matches[ix];
276 let shortened_branch_name =
277 util::truncate_and_trailoff(&hit.name(), self.branch_name_trailoff_after);
278
279 Some(
280 ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
281 .inset(true)
282 .spacing(ListItemSpacing::Sparse)
283 .toggle_state(selected)
284 .map(|parent| match hit {
285 BranchEntry::Branch(branch) => {
286 let highlights: Vec<_> = branch
287 .positions
288 .iter()
289 .filter(|index| index < &&self.branch_name_trailoff_after)
290 .copied()
291 .collect();
292
293 parent.child(HighlightedLabel::new(shortened_branch_name, highlights))
294 }
295 BranchEntry::NewBranch { name } => {
296 parent.child(Label::new(format!("Create branch '{name}'")))
297 }
298 }),
299 )
300 }
301
302 fn render_header(&self, _: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
303 let label = if self.last_query.is_empty() {
304 Label::new("Recent Branches")
305 .size(LabelSize::Small)
306 .mt_1()
307 .ml_3()
308 .into_any_element()
309 } else {
310 let match_label = self.matches.is_empty().not().then(|| {
311 let suffix = if self.matches.len() == 1 { "" } else { "es" };
312 Label::new(format!("{} match{}", self.matches.len(), suffix))
313 .color(Color::Muted)
314 .size(LabelSize::Small)
315 });
316 h_flex()
317 .px_3()
318 .justify_between()
319 .child(Label::new("Branches").size(LabelSize::Small))
320 .children(match_label)
321 .into_any_element()
322 };
323 Some(v_flex().mt_1().child(label).into_any_element())
324 }
325}