branch_picker.rs

  1use anyhow::Context as _;
  2use fuzzy::StringMatchCandidate;
  3
  4use collections::HashSet;
  5use git::repository::Branch;
  6use gpui::{
  7    App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, InteractiveElement,
  8    IntoElement, Modifiers, ModifiersChangedEvent, ParentElement, Render, SharedString, Styled,
  9    Subscription, Task, Window, rems,
 10};
 11use picker::{Picker, PickerDelegate, PickerEditorPosition};
 12use project::git_store::Repository;
 13use std::sync::Arc;
 14use time::OffsetDateTime;
 15use time_format::format_local_timestamp;
 16use ui::{HighlightedLabel, ListItem, ListItemSpacing, Tooltip, prelude::*};
 17use util::ResultExt;
 18use workspace::notifications::DetachAndPromptErr;
 19use workspace::{ModalView, Workspace};
 20
 21pub fn register(workspace: &mut Workspace) {
 22    workspace.register_action(open);
 23    workspace.register_action(switch);
 24    workspace.register_action(checkout_branch);
 25}
 26
 27pub fn checkout_branch(
 28    workspace: &mut Workspace,
 29    _: &zed_actions::git::CheckoutBranch,
 30    window: &mut Window,
 31    cx: &mut Context<Workspace>,
 32) {
 33    open(workspace, &zed_actions::git::Branch, window, cx);
 34}
 35
 36pub fn switch(
 37    workspace: &mut Workspace,
 38    _: &zed_actions::git::Switch,
 39    window: &mut Window,
 40    cx: &mut Context<Workspace>,
 41) {
 42    open(workspace, &zed_actions::git::Branch, window, cx);
 43}
 44
 45pub fn open(
 46    workspace: &mut Workspace,
 47    _: &zed_actions::git::Branch,
 48    window: &mut Window,
 49    cx: &mut Context<Workspace>,
 50) {
 51    let repository = workspace.project().read(cx).active_repository(cx);
 52    let style = BranchListStyle::Modal;
 53    workspace.toggle_modal(window, cx, |window, cx| {
 54        BranchList::new(repository, style, rems(34.), window, cx)
 55    })
 56}
 57
 58pub fn popover(
 59    repository: Option<Entity<Repository>>,
 60    window: &mut Window,
 61    cx: &mut App,
 62) -> Entity<BranchList> {
 63    cx.new(|cx| {
 64        let list = BranchList::new(repository, BranchListStyle::Popover, rems(20.), window, cx);
 65        list.focus_handle(cx).focus(window);
 66        list
 67    })
 68}
 69
 70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 71enum BranchListStyle {
 72    Modal,
 73    Popover,
 74}
 75
 76pub struct BranchList {
 77    width: Rems,
 78    pub picker: Entity<Picker<BranchListDelegate>>,
 79    _subscription: Subscription,
 80}
 81
 82impl BranchList {
 83    fn new(
 84        repository: Option<Entity<Repository>>,
 85        style: BranchListStyle,
 86        width: Rems,
 87        window: &mut Window,
 88        cx: &mut Context<Self>,
 89    ) -> Self {
 90        let all_branches_request = repository
 91            .clone()
 92            .map(|repository| repository.update(cx, |repository, _| repository.branches()));
 93        let default_branch_request = repository
 94            .clone()
 95            .map(|repository| repository.update(cx, |repository, _| repository.default_branch()));
 96
 97        cx.spawn_in(window, async move |this, cx| {
 98            let mut all_branches = all_branches_request
 99                .context("No active repository")?
100                .await??;
101            let default_branch = default_branch_request
102                .context("No active repository")?
103                .await
104                .map(Result::ok)
105                .ok()
106                .flatten()
107                .flatten();
108
109            let all_branches = cx
110                .background_spawn(async move {
111                    let remote_upstreams: HashSet<_> = all_branches
112                        .iter()
113                        .filter_map(|branch| {
114                            branch
115                                .upstream
116                                .as_ref()
117                                .filter(|upstream| upstream.is_remote())
118                                .map(|upstream| upstream.ref_name.clone())
119                        })
120                        .collect();
121
122                    all_branches.retain(|branch| !remote_upstreams.contains(&branch.ref_name));
123
124                    all_branches.sort_by_key(|branch| {
125                        branch
126                            .most_recent_commit
127                            .as_ref()
128                            .map(|commit| 0 - commit.commit_timestamp)
129                    });
130
131                    all_branches
132                })
133                .await;
134
135            this.update_in(cx, |this, window, cx| {
136                this.picker.update(cx, |picker, cx| {
137                    picker.delegate.default_branch = default_branch;
138                    picker.delegate.all_branches = Some(all_branches);
139                    picker.refresh(window, cx);
140                })
141            })?;
142
143            anyhow::Ok(())
144        })
145        .detach_and_log_err(cx);
146
147        let delegate = BranchListDelegate::new(repository, style);
148        let picker = cx.new(|cx| Picker::uniform_list(delegate, window, cx));
149
150        let _subscription = cx.subscribe(&picker, |_, _, _, cx| {
151            cx.emit(DismissEvent);
152        });
153
154        Self {
155            picker,
156            width,
157            _subscription,
158        }
159    }
160
161    fn handle_modifiers_changed(
162        &mut self,
163        ev: &ModifiersChangedEvent,
164        _: &mut Window,
165        cx: &mut Context<Self>,
166    ) {
167        self.picker
168            .update(cx, |picker, _| picker.delegate.modifiers = ev.modifiers)
169    }
170}
171impl ModalView for BranchList {}
172impl EventEmitter<DismissEvent> for BranchList {}
173
174impl Focusable for BranchList {
175    fn focus_handle(&self, cx: &App) -> FocusHandle {
176        self.picker.focus_handle(cx)
177    }
178}
179
180impl Render for BranchList {
181    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
182        v_flex()
183            .key_context("GitBranchSelector")
184            .w(self.width)
185            .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
186            .child(self.picker.clone())
187            .on_mouse_down_out({
188                cx.listener(move |this, _, window, cx| {
189                    this.picker.update(cx, |this, cx| {
190                        this.cancel(&Default::default(), window, cx);
191                    })
192                })
193            })
194    }
195}
196
197#[derive(Debug, Clone)]
198struct BranchEntry {
199    branch: Branch,
200    positions: Vec<usize>,
201    is_new: bool,
202}
203
204pub struct BranchListDelegate {
205    matches: Vec<BranchEntry>,
206    all_branches: Option<Vec<Branch>>,
207    default_branch: Option<SharedString>,
208    repo: Option<Entity<Repository>>,
209    style: BranchListStyle,
210    selected_index: usize,
211    last_query: String,
212    modifiers: Modifiers,
213}
214
215impl BranchListDelegate {
216    fn new(repo: Option<Entity<Repository>>, style: BranchListStyle) -> Self {
217        Self {
218            matches: vec![],
219            repo,
220            style,
221            all_branches: None,
222            default_branch: None,
223            selected_index: 0,
224            last_query: Default::default(),
225            modifiers: Default::default(),
226        }
227    }
228
229    fn create_branch(
230        &self,
231        from_branch: Option<SharedString>,
232        new_branch_name: SharedString,
233        window: &mut Window,
234        cx: &mut Context<Picker<Self>>,
235    ) {
236        let Some(repo) = self.repo.clone() else {
237            return;
238        };
239        let new_branch_name = new_branch_name.to_string().replace(' ', "-");
240        cx.spawn(async move |_, cx| {
241            if let Some(based_branch) = from_branch {
242                repo.update(cx, |repo, _| repo.change_branch(based_branch.to_string()))?
243                    .await??;
244            }
245
246            repo.update(cx, |repo, _| {
247                repo.create_branch(new_branch_name.to_string())
248            })?
249            .await??;
250            repo.update(cx, |repo, _| {
251                repo.change_branch(new_branch_name.to_string())
252            })?
253            .await??;
254
255            Ok(())
256        })
257        .detach_and_prompt_err("Failed to create branch", window, cx, |e, _, _| {
258            Some(e.to_string())
259        });
260        cx.emit(DismissEvent);
261    }
262}
263
264impl PickerDelegate for BranchListDelegate {
265    type ListItem = ListItem;
266
267    fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
268        "Select branch…".into()
269    }
270
271    fn editor_position(&self) -> PickerEditorPosition {
272        match self.style {
273            BranchListStyle::Modal => PickerEditorPosition::Start,
274            BranchListStyle::Popover => PickerEditorPosition::End,
275        }
276    }
277
278    fn match_count(&self) -> usize {
279        self.matches.len()
280    }
281
282    fn selected_index(&self) -> usize {
283        self.selected_index
284    }
285
286    fn set_selected_index(
287        &mut self,
288        ix: usize,
289        _window: &mut Window,
290        _: &mut Context<Picker<Self>>,
291    ) {
292        self.selected_index = ix;
293    }
294
295    fn update_matches(
296        &mut self,
297        query: String,
298        window: &mut Window,
299        cx: &mut Context<Picker<Self>>,
300    ) -> Task<()> {
301        let Some(all_branches) = self.all_branches.clone() else {
302            return Task::ready(());
303        };
304
305        const RECENT_BRANCHES_COUNT: usize = 10;
306        cx.spawn_in(window, async move |picker, cx| {
307            let mut matches: Vec<BranchEntry> = if query.is_empty() {
308                all_branches
309                    .into_iter()
310                    .filter(|branch| !branch.is_remote())
311                    .take(RECENT_BRANCHES_COUNT)
312                    .map(|branch| BranchEntry {
313                        branch,
314                        positions: Vec::new(),
315                        is_new: false,
316                    })
317                    .collect()
318            } else {
319                let candidates = all_branches
320                    .iter()
321                    .enumerate()
322                    .map(|(ix, branch)| StringMatchCandidate::new(ix, branch.name()))
323                    .collect::<Vec<StringMatchCandidate>>();
324                fuzzy::match_strings(
325                    &candidates,
326                    &query,
327                    true,
328                    true,
329                    10000,
330                    &Default::default(),
331                    cx.background_executor().clone(),
332                )
333                .await
334                .into_iter()
335                .map(|candidate| BranchEntry {
336                    branch: all_branches[candidate.candidate_id].clone(),
337                    positions: candidate.positions,
338                    is_new: false,
339                })
340                .collect()
341            };
342            picker
343                .update(cx, |picker, _| {
344                    #[allow(clippy::nonminimal_bool)]
345                    if !query.is_empty()
346                        && !matches
347                            .first()
348                            .is_some_and(|entry| entry.branch.name() == query)
349                    {
350                        let query = query.replace(' ', "-");
351                        matches.push(BranchEntry {
352                            branch: Branch {
353                                ref_name: format!("refs/heads/{query}").into(),
354                                is_head: false,
355                                upstream: None,
356                                most_recent_commit: None,
357                            },
358                            positions: Vec::new(),
359                            is_new: true,
360                        })
361                    }
362                    let delegate = &mut picker.delegate;
363                    delegate.matches = matches;
364                    if delegate.matches.is_empty() {
365                        delegate.selected_index = 0;
366                    } else {
367                        delegate.selected_index =
368                            core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
369                    }
370                    delegate.last_query = query;
371                })
372                .log_err();
373        })
374    }
375
376    fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
377        let Some(entry) = self.matches.get(self.selected_index()) else {
378            return;
379        };
380        if entry.is_new {
381            let from_branch = if secondary {
382                self.default_branch.clone()
383            } else {
384                None
385            };
386            self.create_branch(
387                from_branch,
388                entry.branch.name().to_owned().into(),
389                window,
390                cx,
391            );
392            return;
393        }
394
395        let current_branch = self.repo.as_ref().map(|repo| {
396            repo.read_with(cx, |repo, _| {
397                repo.branch.as_ref().map(|branch| branch.ref_name.clone())
398            })
399        });
400
401        if current_branch
402            .flatten()
403            .is_some_and(|current_branch| current_branch == entry.branch.ref_name)
404        {
405            cx.emit(DismissEvent);
406            return;
407        }
408
409        cx.spawn_in(window, {
410            let branch = entry.branch.clone();
411            async move |picker, cx| {
412                let branch_change_task = picker.update(cx, |this, cx| {
413                    let repo = this
414                        .delegate
415                        .repo
416                        .as_ref()
417                        .context("No active repository")?
418                        .clone();
419
420                    let mut cx = cx.to_async();
421
422                    anyhow::Ok(async move {
423                        repo.update(&mut cx, |repo, _| {
424                            repo.change_branch(branch.name().to_string())
425                        })?
426                        .await?
427                    })
428                })??;
429
430                branch_change_task.await?;
431
432                picker.update(cx, |_, cx| {
433                    cx.emit(DismissEvent);
434
435                    anyhow::Ok(())
436                })
437            }
438        })
439        .detach_and_prompt_err("Failed to change branch", window, cx, |_, _, _| None);
440    }
441
442    fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
443        cx.emit(DismissEvent);
444    }
445
446    fn render_match(
447        &self,
448        ix: usize,
449        selected: bool,
450        _window: &mut Window,
451        cx: &mut Context<Picker<Self>>,
452    ) -> Option<Self::ListItem> {
453        let entry = &self.matches[ix];
454
455        let (commit_time, subject) = entry
456            .branch
457            .most_recent_commit
458            .as_ref()
459            .map(|commit| {
460                let subject = commit.subject.clone();
461                let commit_time = OffsetDateTime::from_unix_timestamp(commit.commit_timestamp)
462                    .unwrap_or_else(|_| OffsetDateTime::now_utc());
463                let formatted_time = format_local_timestamp(
464                    commit_time,
465                    OffsetDateTime::now_utc(),
466                    time_format::TimestampFormat::Relative,
467                );
468                (Some(formatted_time), Some(subject))
469            })
470            .unwrap_or_else(|| (None, None));
471
472        let icon = if let Some(default_branch) = self.default_branch.clone()
473            && entry.is_new
474        {
475            Some(
476                IconButton::new("branch-from-default", IconName::GitBranchAlt)
477                    .on_click(cx.listener(move |this, _, window, cx| {
478                        this.delegate.set_selected_index(ix, window, cx);
479                        this.delegate.confirm(true, window, cx);
480                    }))
481                    .tooltip(move |window, cx| {
482                        Tooltip::for_action(
483                            format!("Create branch based off default: {default_branch}"),
484                            &menu::SecondaryConfirm,
485                            window,
486                            cx,
487                        )
488                    }),
489            )
490        } else {
491            None
492        };
493
494        let branch_name = if entry.is_new {
495            h_flex()
496                .gap_1()
497                .child(
498                    Icon::new(IconName::Plus)
499                        .size(IconSize::Small)
500                        .color(Color::Muted),
501                )
502                .child(
503                    Label::new(format!("Create branch \"{}\"", entry.branch.name()))
504                        .single_line()
505                        .truncate(),
506                )
507                .into_any_element()
508        } else {
509            HighlightedLabel::new(entry.branch.name().to_owned(), entry.positions.clone())
510                .truncate()
511                .into_any_element()
512        };
513
514        Some(
515            ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
516                .inset(true)
517                .spacing(ListItemSpacing::Sparse)
518                .toggle_state(selected)
519                .child(
520                    v_flex()
521                        .w_full()
522                        .overflow_hidden()
523                        .child(
524                            h_flex()
525                                .gap_6()
526                                .justify_between()
527                                .overflow_x_hidden()
528                                .child(branch_name)
529                                .when_some(commit_time, |label, commit_time| {
530                                    label.child(
531                                        Label::new(commit_time)
532                                            .size(LabelSize::Small)
533                                            .color(Color::Muted)
534                                            .into_element(),
535                                    )
536                                }),
537                        )
538                        .when(self.style == BranchListStyle::Modal, |el| {
539                            el.child(div().max_w_96().child({
540                                let message = if entry.is_new {
541                                    if let Some(current_branch) =
542                                        self.repo.as_ref().and_then(|repo| {
543                                            repo.read(cx).branch.as_ref().map(|b| b.name())
544                                        })
545                                    {
546                                        format!("based off {}", current_branch)
547                                    } else {
548                                        "based off the current branch".to_string()
549                                    }
550                                } else {
551                                    subject.unwrap_or("no commits found".into()).to_string()
552                                };
553                                Label::new(message)
554                                    .size(LabelSize::Small)
555                                    .truncate()
556                                    .color(Color::Muted)
557                            }))
558                        }),
559                )
560                .end_slot::<IconButton>(icon),
561        )
562    }
563
564    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
565        None
566    }
567}