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 {
176 id: ix,
177 char_bag: command.name.chars().collect(),
178 string: command.name.into(),
179 })
180 .collect::<Vec<StringMatchCandidate>>()
181 });
182 let Some(candidates) = candidates.log_err() else {
183 return;
184 };
185 let matches = if query.is_empty() {
186 candidates
187 .into_iter()
188 .enumerate()
189 .map(|(index, candidate)| StringMatch {
190 candidate_id: index,
191 string: candidate.string,
192 positions: Vec::new(),
193 score: 0.0,
194 })
195 .collect()
196 } else {
197 fuzzy::match_strings(
198 &candidates,
199 &query,
200 true,
201 10000,
202 &Default::default(),
203 cx.background_executor().clone(),
204 )
205 .await
206 };
207 picker
208 .update(&mut cx, |picker, _| {
209 let delegate = &mut picker.delegate;
210 delegate.matches = matches.into_iter().map(BranchEntry::Branch).collect();
211 if delegate.matches.is_empty() {
212 if !query.is_empty() {
213 delegate.matches.push(BranchEntry::NewBranch {
214 name: query.trim().replace(' ', "-"),
215 });
216 }
217
218 delegate.selected_index = 0;
219 } else {
220 delegate.selected_index =
221 core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
222 }
223 delegate.last_query = query;
224 })
225 .log_err();
226 })
227 }
228
229 fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<Self>>) {
230 let Some(branch) = self.matches.get(self.selected_index()) else {
231 return;
232 };
233 cx.spawn({
234 let branch = branch.clone();
235 |picker, mut cx| async move {
236 let branch_change_task = picker.update(&mut cx, |this, cx| {
237 let workspace = this
238 .delegate
239 .workspace
240 .upgrade()
241 .ok_or_else(|| anyhow!("workspace was dropped"))?;
242
243 let project = workspace.read(cx).project().read(cx);
244 let branch_to_checkout = match branch {
245 BranchEntry::Branch(branch) => branch.string,
246 BranchEntry::NewBranch { name: branch_name } => branch_name,
247 };
248 let worktree = project
249 .visible_worktrees(cx)
250 .next()
251 .context("worktree disappeared")?;
252 let repository = ProjectPath::root_path(worktree.read(cx).id());
253
254 anyhow::Ok(project.update_or_create_branch(repository, branch_to_checkout, cx))
255 })??;
256
257 branch_change_task.await?;
258
259 picker.update(&mut cx, |_, cx| {
260 cx.emit(DismissEvent);
261
262 Ok::<(), anyhow::Error>(())
263 })
264 }
265 })
266 .detach_and_prompt_err("Failed to change branch", cx, |_, _| None);
267 }
268
269 fn dismissed(&mut self, cx: &mut ViewContext<Picker<Self>>) {
270 cx.emit(DismissEvent);
271 }
272
273 fn render_match(
274 &self,
275 ix: usize,
276 selected: bool,
277 _cx: &mut ViewContext<Picker<Self>>,
278 ) -> Option<Self::ListItem> {
279 let hit = &self.matches[ix];
280 let shortened_branch_name =
281 util::truncate_and_trailoff(&hit.name(), self.branch_name_trailoff_after);
282
283 Some(
284 ListItem::new(SharedString::from(format!("vcs-menu-{ix}")))
285 .inset(true)
286 .spacing(ListItemSpacing::Sparse)
287 .selected(selected)
288 .map(|parent| match hit {
289 BranchEntry::Branch(branch) => {
290 let highlights: Vec<_> = branch
291 .positions
292 .iter()
293 .filter(|index| index < &&self.branch_name_trailoff_after)
294 .copied()
295 .collect();
296
297 parent.child(HighlightedLabel::new(shortened_branch_name, highlights))
298 }
299 BranchEntry::NewBranch { name } => {
300 parent.child(Label::new(format!("Create branch '{name}'")))
301 }
302 }),
303 )
304 }
305
306 fn render_header(&self, _: &mut ViewContext<Picker<Self>>) -> Option<AnyElement> {
307 let label = if self.last_query.is_empty() {
308 Label::new("Recent Branches")
309 .size(LabelSize::Small)
310 .mt_1()
311 .ml_3()
312 .into_any_element()
313 } else {
314 let match_label = self.matches.is_empty().not().then(|| {
315 let suffix = if self.matches.len() == 1 { "" } else { "es" };
316 Label::new(format!("{} match{}", self.matches.len(), suffix))
317 .color(Color::Muted)
318 .size(LabelSize::Small)
319 });
320 h_flex()
321 .px_3()
322 .justify_between()
323 .child(Label::new("Branches").size(LabelSize::Small))
324 .children(match_label)
325 .into_any_element()
326 };
327 Some(v_flex().mt_1().child(label).into_any_element())
328 }
329}