1use fuzzy::StringMatchCandidate;
2
3use git::stash::StashEntry;
4use gpui::{
5 Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable,
6 InteractiveElement, IntoElement, Modifiers, ModifiersChangedEvent, ParentElement, Render,
7 SharedString, Styled, Subscription, Task, WeakEntity, Window, actions, rems,
8};
9use picker::{Picker, PickerDelegate};
10use project::git_store::{Repository, RepositoryEvent};
11use std::sync::Arc;
12use time::{OffsetDateTime, UtcOffset};
13use time_format;
14use ui::{HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, Tooltip, prelude::*};
15use util::ResultExt;
16use workspace::notifications::DetachAndPromptErr;
17use workspace::{ModalView, Workspace};
18
19use crate::commit_view::CommitView;
20use crate::stash_picker;
21
22actions!(
23 stash_picker,
24 [
25 /// Drop the selected stash entry.
26 DropStashItem,
27 /// Show the diff view of the selected stash entry.
28 ShowStashItem,
29 ]
30);
31
32pub fn open(
33 workspace: &mut Workspace,
34 _: &zed_actions::git::ViewStash,
35 window: &mut Window,
36 cx: &mut Context<Workspace>,
37) {
38 let repository = workspace.project().read(cx).active_repository(cx);
39 let weak_workspace = workspace.weak_handle();
40 workspace.toggle_modal(window, cx, |window, cx| {
41 StashList::new(repository, weak_workspace, rems(34.), window, cx)
42 })
43}
44
45pub fn create_embedded(
46 repository: Option<Entity<Repository>>,
47 workspace: WeakEntity<Workspace>,
48 width: Rems,
49 window: &mut Window,
50 cx: &mut Context<StashList>,
51) -> StashList {
52 StashList::new_embedded(repository, workspace, width, window, cx)
53}
54
55pub struct StashList {
56 width: Rems,
57 pub picker: Entity<Picker<StashListDelegate>>,
58 picker_focus_handle: FocusHandle,
59 _subscriptions: Vec<Subscription>,
60}
61
62impl StashList {
63 fn new(
64 repository: Option<Entity<Repository>>,
65 workspace: WeakEntity<Workspace>,
66 width: Rems,
67 window: &mut Window,
68 cx: &mut Context<Self>,
69 ) -> Self {
70 let mut this = Self::new_inner(repository, workspace, width, false, window, cx);
71 this._subscriptions
72 .push(cx.subscribe(&this.picker, |_, _, _, cx| {
73 cx.emit(DismissEvent);
74 }));
75 this
76 }
77
78 fn new_inner(
79 repository: Option<Entity<Repository>>,
80 workspace: WeakEntity<Workspace>,
81 width: Rems,
82 embedded: bool,
83 window: &mut Window,
84 cx: &mut Context<Self>,
85 ) -> Self {
86 let mut _subscriptions = Vec::new();
87 let stash_request = repository
88 .clone()
89 .map(|repository| repository.read_with(cx, |repo, _| repo.cached_stash()));
90
91 if let Some(repo) = repository.clone() {
92 _subscriptions.push(
93 cx.subscribe_in(&repo, window, |this, _, event, window, cx| {
94 if matches!(event, RepositoryEvent::StashEntriesChanged) {
95 let stash_entries = this.picker.read_with(cx, |picker, cx| {
96 picker
97 .delegate
98 .repo
99 .clone()
100 .map(|repo| repo.read(cx).cached_stash().entries.to_vec())
101 });
102 this.picker.update(cx, |this, cx| {
103 this.delegate.all_stash_entries = stash_entries;
104 this.refresh(window, cx);
105 });
106 }
107 }),
108 )
109 }
110
111 cx.spawn_in(window, async move |this, cx| {
112 let stash_entries = stash_request
113 .map(|git_stash| git_stash.entries.to_vec())
114 .unwrap_or_default();
115
116 this.update_in(cx, |this, window, cx| {
117 this.picker.update(cx, |picker, cx| {
118 picker.delegate.all_stash_entries = Some(stash_entries);
119 picker.refresh(window, cx);
120 })
121 })?;
122
123 anyhow::Ok(())
124 })
125 .detach_and_log_err(cx);
126
127 let delegate = StashListDelegate::new(repository, workspace, window, cx);
128 let picker = cx.new(|cx| {
129 Picker::uniform_list(delegate, window, cx)
130 .show_scrollbar(true)
131 .modal(!embedded)
132 });
133 let picker_focus_handle = picker.focus_handle(cx);
134 picker.update(cx, |picker, _| {
135 picker.delegate.focus_handle = picker_focus_handle.clone();
136 });
137
138 Self {
139 picker,
140 picker_focus_handle,
141 width,
142 _subscriptions,
143 }
144 }
145
146 fn new_embedded(
147 repository: Option<Entity<Repository>>,
148 workspace: WeakEntity<Workspace>,
149 width: Rems,
150 window: &mut Window,
151 cx: &mut Context<Self>,
152 ) -> Self {
153 let mut this = Self::new_inner(repository, workspace, width, true, window, cx);
154 this._subscriptions
155 .push(cx.subscribe(&this.picker, |_, _, _, cx| {
156 cx.emit(DismissEvent);
157 }));
158 this
159 }
160
161 pub fn handle_drop_stash(
162 &mut self,
163 _: &DropStashItem,
164 window: &mut Window,
165 cx: &mut Context<Self>,
166 ) {
167 self.picker.update(cx, |picker, cx| {
168 picker
169 .delegate
170 .drop_stash_at(picker.delegate.selected_index(), window, cx);
171 });
172 cx.notify();
173 }
174
175 pub fn handle_show_stash(
176 &mut self,
177 _: &ShowStashItem,
178 window: &mut Window,
179 cx: &mut Context<Self>,
180 ) {
181 self.picker.update(cx, |picker, cx| {
182 picker
183 .delegate
184 .show_stash_at(picker.delegate.selected_index(), window, cx);
185 });
186
187 cx.emit(DismissEvent);
188 }
189
190 pub fn handle_modifiers_changed(
191 &mut self,
192 ev: &ModifiersChangedEvent,
193 _: &mut Window,
194 cx: &mut Context<Self>,
195 ) {
196 self.picker
197 .update(cx, |picker, _| picker.delegate.modifiers = ev.modifiers)
198 }
199}
200
201impl ModalView for StashList {}
202impl EventEmitter<DismissEvent> for StashList {}
203impl Focusable for StashList {
204 fn focus_handle(&self, _: &App) -> FocusHandle {
205 self.picker_focus_handle.clone()
206 }
207}
208
209impl Render for StashList {
210 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
211 v_flex()
212 .key_context("StashList")
213 .w(self.width)
214 .on_modifiers_changed(cx.listener(Self::handle_modifiers_changed))
215 .on_action(cx.listener(Self::handle_drop_stash))
216 .on_action(cx.listener(Self::handle_show_stash))
217 .child(self.picker.clone())
218 }
219}
220
221#[derive(Debug, Clone)]
222struct StashEntryMatch {
223 entry: StashEntry,
224 positions: Vec<usize>,
225 formatted_timestamp: String,
226}
227
228pub struct StashListDelegate {
229 matches: Vec<StashEntryMatch>,
230 all_stash_entries: Option<Vec<StashEntry>>,
231 repo: Option<Entity<Repository>>,
232 workspace: WeakEntity<Workspace>,
233 selected_index: usize,
234 last_query: String,
235 modifiers: Modifiers,
236 focus_handle: FocusHandle,
237 timezone: UtcOffset,
238}
239
240impl StashListDelegate {
241 fn new(
242 repo: Option<Entity<Repository>>,
243 workspace: WeakEntity<Workspace>,
244 _window: &mut Window,
245 cx: &mut Context<StashList>,
246 ) -> Self {
247 let timezone = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC);
248
249 Self {
250 matches: vec![],
251 repo,
252 workspace,
253 all_stash_entries: None,
254 selected_index: 0,
255 last_query: Default::default(),
256 modifiers: Default::default(),
257 focus_handle: cx.focus_handle(),
258 timezone,
259 }
260 }
261
262 fn format_message(ix: usize, message: &String) -> String {
263 format!("#{}: {}", ix, message)
264 }
265
266 fn format_timestamp(timestamp: i64, timezone: UtcOffset) -> String {
267 let timestamp =
268 OffsetDateTime::from_unix_timestamp(timestamp).unwrap_or(OffsetDateTime::now_utc());
269 time_format::format_localized_timestamp(
270 timestamp,
271 OffsetDateTime::now_utc(),
272 timezone,
273 time_format::TimestampFormat::EnhancedAbsolute,
274 )
275 }
276
277 fn drop_stash_at(&self, ix: usize, window: &mut Window, cx: &mut Context<Picker<Self>>) {
278 let Some(entry_match) = self.matches.get(ix) else {
279 return;
280 };
281 let stash_index = entry_match.entry.index;
282 let Some(repo) = self.repo.clone() else {
283 return;
284 };
285
286 cx.spawn(async move |_, cx| {
287 repo.update(cx, |repo, cx| repo.stash_drop(Some(stash_index), cx))
288 .await??;
289 Ok(())
290 })
291 .detach_and_prompt_err("Failed to drop stash", window, cx, |e, _, _| {
292 Some(e.to_string())
293 });
294 }
295
296 fn show_stash_at(&self, ix: usize, window: &mut Window, cx: &mut Context<Picker<Self>>) {
297 let Some(entry_match) = self.matches.get(ix) else {
298 return;
299 };
300 let stash_sha = entry_match.entry.oid.to_string();
301 let stash_index = entry_match.entry.index;
302 let Some(repo) = self.repo.clone() else {
303 return;
304 };
305 CommitView::open(
306 stash_sha,
307 repo.downgrade(),
308 self.workspace.clone(),
309 Some(stash_index),
310 None,
311 window,
312 cx,
313 );
314 }
315
316 fn pop_stash(&self, stash_index: usize, window: &mut Window, cx: &mut Context<Picker<Self>>) {
317 let Some(repo) = self.repo.clone() else {
318 return;
319 };
320
321 cx.spawn(async move |_, cx| {
322 repo.update(cx, |repo, cx| repo.stash_pop(Some(stash_index), cx))
323 .await?;
324 Ok(())
325 })
326 .detach_and_prompt_err("Failed to pop stash", window, cx, |e, _, _| {
327 Some(e.to_string())
328 });
329 cx.emit(DismissEvent);
330 }
331
332 fn apply_stash(&self, stash_index: usize, window: &mut Window, cx: &mut Context<Picker<Self>>) {
333 let Some(repo) = self.repo.clone() else {
334 return;
335 };
336
337 cx.spawn(async move |_, cx| {
338 repo.update(cx, |repo, cx| repo.stash_apply(Some(stash_index), cx))
339 .await?;
340 Ok(())
341 })
342 .detach_and_prompt_err("Failed to apply stash", window, cx, |e, _, _| {
343 Some(e.to_string())
344 });
345 cx.emit(DismissEvent);
346 }
347}
348
349impl PickerDelegate for StashListDelegate {
350 type ListItem = ListItem;
351
352 fn placeholder_text(&self, _window: &mut Window, _cx: &mut App) -> Arc<str> {
353 "Select a stash…".into()
354 }
355
356 fn match_count(&self) -> usize {
357 self.matches.len()
358 }
359
360 fn selected_index(&self) -> usize {
361 self.selected_index
362 }
363
364 fn set_selected_index(
365 &mut self,
366 ix: usize,
367 _window: &mut Window,
368 _: &mut Context<Picker<Self>>,
369 ) {
370 self.selected_index = ix;
371 }
372
373 fn update_matches(
374 &mut self,
375 query: String,
376 window: &mut Window,
377 cx: &mut Context<Picker<Self>>,
378 ) -> Task<()> {
379 let Some(all_stash_entries) = self.all_stash_entries.clone() else {
380 return Task::ready(());
381 };
382
383 let timezone = self.timezone;
384
385 cx.spawn_in(window, async move |picker, cx| {
386 let matches: Vec<StashEntryMatch> = if query.is_empty() {
387 all_stash_entries
388 .into_iter()
389 .map(|entry| {
390 let formatted_timestamp = Self::format_timestamp(entry.timestamp, timezone);
391
392 StashEntryMatch {
393 entry,
394 positions: Vec::new(),
395 formatted_timestamp,
396 }
397 })
398 .collect()
399 } else {
400 let candidates = all_stash_entries
401 .iter()
402 .enumerate()
403 .map(|(ix, entry)| {
404 StringMatchCandidate::new(
405 ix,
406 &Self::format_message(entry.index, &entry.message),
407 )
408 })
409 .collect::<Vec<StringMatchCandidate>>();
410 fuzzy::match_strings(
411 &candidates,
412 &query,
413 false,
414 true,
415 10000,
416 &Default::default(),
417 cx.background_executor().clone(),
418 )
419 .await
420 .into_iter()
421 .map(|candidate| {
422 let entry = all_stash_entries[candidate.candidate_id].clone();
423 let formatted_timestamp = Self::format_timestamp(entry.timestamp, timezone);
424
425 StashEntryMatch {
426 entry,
427 positions: candidate.positions,
428 formatted_timestamp,
429 }
430 })
431 .collect()
432 };
433
434 picker
435 .update(cx, |picker, _| {
436 let delegate = &mut picker.delegate;
437 delegate.matches = matches;
438 if delegate.matches.is_empty() {
439 delegate.selected_index = 0;
440 } else {
441 delegate.selected_index =
442 core::cmp::min(delegate.selected_index, delegate.matches.len() - 1);
443 }
444 delegate.last_query = query;
445 })
446 .log_err();
447 })
448 }
449
450 fn confirm(&mut self, secondary: bool, window: &mut Window, cx: &mut Context<Picker<Self>>) {
451 let Some(entry_match) = self.matches.get(self.selected_index()) else {
452 return;
453 };
454 let stash_index = entry_match.entry.index;
455 if secondary {
456 self.pop_stash(stash_index, window, cx);
457 } else {
458 self.apply_stash(stash_index, window, cx);
459 }
460 }
461
462 fn dismissed(&mut self, _: &mut Window, cx: &mut Context<Picker<Self>>) {
463 cx.emit(DismissEvent);
464 }
465
466 fn render_match(
467 &self,
468 ix: usize,
469 selected: bool,
470 _window: &mut Window,
471 cx: &mut Context<Picker<Self>>,
472 ) -> Option<Self::ListItem> {
473 let entry_match = &self.matches[ix];
474
475 let stash_message =
476 Self::format_message(entry_match.entry.index, &entry_match.entry.message);
477 let positions = entry_match.positions.clone();
478 let stash_label = HighlightedLabel::new(stash_message, positions)
479 .truncate()
480 .into_any_element();
481
482 let branch_name = entry_match.entry.branch.clone().unwrap_or_default();
483 let branch_info = h_flex()
484 .gap_1p5()
485 .w_full()
486 .child(
487 Label::new(branch_name)
488 .truncate()
489 .color(Color::Muted)
490 .size(LabelSize::Small),
491 )
492 .child(
493 Label::new("•")
494 .alpha(0.5)
495 .color(Color::Muted)
496 .size(LabelSize::Small),
497 )
498 .child(
499 Label::new(entry_match.formatted_timestamp.clone())
500 .color(Color::Muted)
501 .size(LabelSize::Small),
502 );
503
504 let focus_handle = self.focus_handle.clone();
505
506 let drop_button = |entry_ix: usize| {
507 IconButton::new(("drop-stash", entry_ix), IconName::Trash)
508 .icon_size(IconSize::Small)
509 .tooltip(move |_, cx| {
510 Tooltip::for_action_in("Drop Stash", &DropStashItem, &focus_handle, cx)
511 })
512 .on_click(cx.listener(move |this, _, window, cx| {
513 this.delegate.drop_stash_at(entry_ix, window, cx);
514 }))
515 };
516
517 Some(
518 ListItem::new(format!("stash-{ix}"))
519 .inset(true)
520 .spacing(ListItemSpacing::Sparse)
521 .toggle_state(selected)
522 .child(
523 h_flex()
524 .w_full()
525 .gap_2p5()
526 .child(
527 Icon::new(IconName::BoxOpen)
528 .size(IconSize::Small)
529 .color(Color::Muted),
530 )
531 .child(div().w_full().child(stash_label).child(branch_info)),
532 )
533 .tooltip(Tooltip::text(format!(
534 "stash@{{{}}}",
535 entry_match.entry.index
536 )))
537 .map(|this| {
538 if selected {
539 this.end_slot(drop_button(ix))
540 } else {
541 this.end_hover_slot(drop_button(ix))
542 }
543 }),
544 )
545 }
546
547 fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
548 Some("No stashes found".into())
549 }
550
551 fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
552 let focus_handle = self.focus_handle.clone();
553
554 Some(
555 h_flex()
556 .w_full()
557 .p_1p5()
558 .gap_0p5()
559 .justify_end()
560 .flex_wrap()
561 .border_t_1()
562 .border_color(cx.theme().colors().border_variant)
563 .child(
564 Button::new("drop-stash", "Drop")
565 .key_binding(
566 KeyBinding::for_action_in(
567 &stash_picker::DropStashItem,
568 &focus_handle,
569 cx,
570 )
571 .map(|kb| kb.size(rems_from_px(12.))),
572 )
573 .on_click(|_, window, cx| {
574 window.dispatch_action(stash_picker::DropStashItem.boxed_clone(), cx)
575 }),
576 )
577 .child(
578 Button::new("view-stash", "View")
579 .key_binding(
580 KeyBinding::for_action_in(
581 &stash_picker::ShowStashItem,
582 &focus_handle,
583 cx,
584 )
585 .map(|kb| kb.size(rems_from_px(12.))),
586 )
587 .on_click(cx.listener(move |picker, _, window, cx| {
588 cx.stop_propagation();
589 let selected_ix = picker.delegate.selected_index();
590 picker.delegate.show_stash_at(selected_ix, window, cx);
591 })),
592 )
593 .child(
594 Button::new("pop-stash", "Pop")
595 .key_binding(
596 KeyBinding::for_action_in(&menu::SecondaryConfirm, &focus_handle, cx)
597 .map(|kb| kb.size(rems_from_px(12.))),
598 )
599 .on_click(|_, window, cx| {
600 window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx)
601 }),
602 )
603 .child(
604 Button::new("apply-stash", "Apply")
605 .key_binding(
606 KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
607 .map(|kb| kb.size(rems_from_px(12.))),
608 )
609 .on_click(|_, window, cx| {
610 window.dispatch_action(menu::Confirm.boxed_clone(), cx)
611 }),
612 )
613 .into_any(),
614 )
615 }
616}
617
618#[cfg(test)]
619mod tests {
620 use std::str::FromStr;
621
622 use super::*;
623 use git::{Oid, stash::StashEntry};
624 use gpui::{TestAppContext, VisualTestContext, rems};
625 use picker::PickerDelegate;
626 use project::{FakeFs, Project};
627 use settings::SettingsStore;
628 use workspace::MultiWorkspace;
629
630 fn init_test(cx: &mut TestAppContext) {
631 cx.update(|cx| {
632 let settings_store = SettingsStore::test(cx);
633 cx.set_global(settings_store);
634
635 theme::init(theme::LoadThemes::JustBase, cx);
636 editor::init(cx);
637 })
638 }
639
640 /// Convenience function for creating `StashEntry` instances during tests.
641 /// Feel free to update in case you need to provide extra fields.
642 fn stash_entry(index: usize, message: &str, branch: Option<&str>) -> StashEntry {
643 let oid = Oid::from_str(&format!("{:0>40x}", index)).unwrap();
644
645 StashEntry {
646 index,
647 oid,
648 message: message.to_string(),
649 branch: branch.map(Into::into),
650 timestamp: 1000 - index as i64,
651 }
652 }
653
654 #[gpui::test]
655 async fn test_show_stash_dismisses(cx: &mut TestAppContext) {
656 init_test(cx);
657
658 let fs = FakeFs::new(cx.executor());
659 let project = Project::test(fs, [], cx).await;
660 let multi_workspace =
661 cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
662 let cx = &mut VisualTestContext::from_window(*multi_workspace, cx);
663 let workspace = multi_workspace
664 .update(cx, |workspace, _, _| workspace.workspace().clone())
665 .unwrap();
666 let stash_entries = vec![
667 stash_entry(0, "stash #0", Some("main")),
668 stash_entry(1, "stash #1", Some("develop")),
669 ];
670
671 let stash_list = workspace.update_in(cx, |workspace, window, cx| {
672 let weak_workspace = workspace.weak_handle();
673
674 workspace.toggle_modal(window, cx, move |window, cx| {
675 StashList::new(None, weak_workspace, rems(34.), window, cx)
676 });
677
678 assert!(workspace.active_modal::<StashList>(cx).is_some());
679 workspace.active_modal::<StashList>(cx).unwrap()
680 });
681
682 cx.run_until_parked();
683 stash_list.update(cx, |stash_list, cx| {
684 stash_list.picker.update(cx, |picker, _| {
685 picker.delegate.all_stash_entries = Some(stash_entries);
686 });
687 });
688
689 stash_list
690 .update_in(cx, |stash_list, window, cx| {
691 stash_list.picker.update(cx, |picker, cx| {
692 picker.delegate.update_matches(String::new(), window, cx)
693 })
694 })
695 .await;
696
697 cx.run_until_parked();
698 stash_list.update_in(cx, |stash_list, window, cx| {
699 assert_eq!(stash_list.picker.read(cx).delegate.matches.len(), 2);
700 stash_list.handle_show_stash(&Default::default(), window, cx);
701 });
702
703 workspace.update(cx, |workspace, cx| {
704 assert!(workspace.active_modal::<StashList>(cx).is_none());
705 });
706 }
707}