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