stash_picker.rs

  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        Some(
505            ListItem::new(format!("stash-{ix}"))
506                .inset(true)
507                .spacing(ListItemSpacing::Sparse)
508                .toggle_state(selected)
509                .child(v_flex().w_full().child(stash_label).child(branch_info))
510                .tooltip(Tooltip::text(format!(
511                    "stash@{{{}}}",
512                    entry_match.entry.index
513                ))),
514        )
515    }
516
517    fn no_matches_text(&self, _window: &mut Window, _cx: &mut App) -> Option<SharedString> {
518        Some("No stashes found".into())
519    }
520
521    fn render_footer(&self, _: &mut Window, cx: &mut Context<Picker<Self>>) -> Option<AnyElement> {
522        let focus_handle = self.focus_handle.clone();
523
524        Some(
525            h_flex()
526                .w_full()
527                .p_1p5()
528                .gap_0p5()
529                .justify_end()
530                .flex_wrap()
531                .border_t_1()
532                .border_color(cx.theme().colors().border_variant)
533                .child(
534                    Button::new("drop-stash", "Drop")
535                        .key_binding(
536                            KeyBinding::for_action_in(
537                                &stash_picker::DropStashItem,
538                                &focus_handle,
539                                cx,
540                            )
541                            .map(|kb| kb.size(rems_from_px(12.))),
542                        )
543                        .on_click(|_, window, cx| {
544                            window.dispatch_action(stash_picker::DropStashItem.boxed_clone(), cx)
545                        }),
546                )
547                .child(
548                    Button::new("view-stash", "View")
549                        .key_binding(
550                            KeyBinding::for_action_in(
551                                &stash_picker::ShowStashItem,
552                                &focus_handle,
553                                cx,
554                            )
555                            .map(|kb| kb.size(rems_from_px(12.))),
556                        )
557                        .on_click(cx.listener(move |picker, _, window, cx| {
558                            cx.stop_propagation();
559                            let selected_ix = picker.delegate.selected_index();
560                            picker.delegate.show_stash_at(selected_ix, window, cx);
561                        })),
562                )
563                .child(
564                    Button::new("pop-stash", "Pop")
565                        .key_binding(
566                            KeyBinding::for_action_in(&menu::SecondaryConfirm, &focus_handle, cx)
567                                .map(|kb| kb.size(rems_from_px(12.))),
568                        )
569                        .on_click(|_, window, cx| {
570                            window.dispatch_action(menu::SecondaryConfirm.boxed_clone(), cx)
571                        }),
572                )
573                .child(
574                    Button::new("apply-stash", "Apply")
575                        .key_binding(
576                            KeyBinding::for_action_in(&menu::Confirm, &focus_handle, cx)
577                                .map(|kb| kb.size(rems_from_px(12.))),
578                        )
579                        .on_click(|_, window, cx| {
580                            window.dispatch_action(menu::Confirm.boxed_clone(), cx)
581                        }),
582                )
583                .into_any(),
584        )
585    }
586}
587
588#[cfg(test)]
589mod tests {
590    use std::str::FromStr;
591
592    use super::*;
593    use git::{Oid, stash::StashEntry};
594    use gpui::{TestAppContext, VisualTestContext, rems};
595    use picker::PickerDelegate;
596    use project::{FakeFs, Project};
597    use settings::SettingsStore;
598    use workspace::MultiWorkspace;
599
600    fn init_test(cx: &mut TestAppContext) {
601        cx.update(|cx| {
602            let settings_store = SettingsStore::test(cx);
603            cx.set_global(settings_store);
604
605            theme::init(theme::LoadThemes::JustBase, cx);
606            editor::init(cx);
607        })
608    }
609
610    /// Convenience function for creating `StashEntry` instances during tests.
611    /// Feel free to update in case you need to provide extra fields.
612    fn stash_entry(index: usize, message: &str, branch: Option<&str>) -> StashEntry {
613        let oid = Oid::from_str(&format!("{:0>40x}", index)).unwrap();
614
615        StashEntry {
616            index,
617            oid,
618            message: message.to_string(),
619            branch: branch.map(Into::into),
620            timestamp: 1000 - index as i64,
621        }
622    }
623
624    #[gpui::test]
625    async fn test_show_stash_dismisses(cx: &mut TestAppContext) {
626        init_test(cx);
627
628        let fs = FakeFs::new(cx.executor());
629        let project = Project::test(fs, [], cx).await;
630        let multi_workspace =
631            cx.add_window(|window, cx| MultiWorkspace::test_new(project, window, cx));
632        let cx = &mut VisualTestContext::from_window(*multi_workspace, cx);
633        let workspace = multi_workspace
634            .update(cx, |workspace, _, _| workspace.workspace().clone())
635            .unwrap();
636        let stash_entries = vec![
637            stash_entry(0, "stash #0", Some("main")),
638            stash_entry(1, "stash #1", Some("develop")),
639        ];
640
641        let stash_list = workspace.update_in(cx, |workspace, window, cx| {
642            let weak_workspace = workspace.weak_handle();
643
644            workspace.toggle_modal(window, cx, move |window, cx| {
645                StashList::new(None, weak_workspace, rems(34.), window, cx)
646            });
647
648            assert!(workspace.active_modal::<StashList>(cx).is_some());
649            workspace.active_modal::<StashList>(cx).unwrap()
650        });
651
652        cx.run_until_parked();
653        stash_list.update(cx, |stash_list, cx| {
654            stash_list.picker.update(cx, |picker, _| {
655                picker.delegate.all_stash_entries = Some(stash_entries);
656            });
657        });
658
659        stash_list
660            .update_in(cx, |stash_list, window, cx| {
661                stash_list.picker.update(cx, |picker, cx| {
662                    picker.delegate.update_matches(String::new(), window, cx)
663                })
664            })
665            .await;
666
667        cx.run_until_parked();
668        stash_list.update_in(cx, |stash_list, window, cx| {
669            assert_eq!(stash_list.picker.read(cx).delegate.matches.len(), 2);
670            stash_list.handle_show_stash(&Default::default(), window, cx);
671        });
672
673        workspace.update(cx, |workspace, cx| {
674            assert!(workspace.active_modal::<StashList>(cx).is_none());
675        });
676    }
677}