project_diff.rs

  1use std::any::{Any, TypeId};
  2
  3use ::git::UnstageAndNext;
  4use anyhow::Result;
  5use buffer_diff::{BufferDiff, DiffHunkSecondaryStatus};
  6use collections::HashSet;
  7use editor::{
  8    actions::{GoToHunk, GoToPrevHunk},
  9    scroll::Autoscroll,
 10    Editor, EditorEvent, ToPoint,
 11};
 12use feature_flags::FeatureFlagViewExt;
 13use futures::StreamExt;
 14use git::{Commit, StageAll, StageAndNext, ToggleStaged, UnstageAll};
 15use gpui::{
 16    actions, Action, AnyElement, AnyView, App, AppContext as _, AsyncWindowContext, Entity,
 17    EventEmitter, FocusHandle, Focusable, Render, Subscription, Task, WeakEntity,
 18};
 19use language::{Anchor, Buffer, Capability, OffsetRangeExt, Point};
 20use multi_buffer::{MultiBuffer, PathKey};
 21use project::{git::GitStore, Project, ProjectPath};
 22use theme::ActiveTheme;
 23use ui::{prelude::*, vertical_divider, Tooltip};
 24use util::ResultExt as _;
 25use workspace::{
 26    item::{BreadcrumbText, Item, ItemEvent, ItemHandle, TabContentParams},
 27    searchable::SearchableItemHandle,
 28    ItemNavHistory, SerializableItem, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
 29    Workspace,
 30};
 31
 32use crate::git_panel::{GitPanel, GitPanelAddon, GitStatusEntry};
 33
 34actions!(git, [Diff]);
 35
 36pub(crate) struct ProjectDiff {
 37    multibuffer: Entity<MultiBuffer>,
 38    editor: Entity<Editor>,
 39    project: Entity<Project>,
 40    git_store: Entity<GitStore>,
 41    workspace: WeakEntity<Workspace>,
 42    focus_handle: FocusHandle,
 43    update_needed: postage::watch::Sender<()>,
 44    pending_scroll: Option<PathKey>,
 45
 46    _task: Task<Result<()>>,
 47    _subscription: Subscription,
 48}
 49
 50struct DiffBuffer {
 51    path_key: PathKey,
 52    buffer: Entity<Buffer>,
 53    diff: Entity<BufferDiff>,
 54}
 55
 56const CONFLICT_NAMESPACE: &'static str = "0";
 57const TRACKED_NAMESPACE: &'static str = "1";
 58const NEW_NAMESPACE: &'static str = "2";
 59
 60impl ProjectDiff {
 61    pub(crate) fn register(
 62        _: &mut Workspace,
 63        window: Option<&mut Window>,
 64        cx: &mut Context<Workspace>,
 65    ) {
 66        let Some(window) = window else { return };
 67        cx.when_flag_enabled::<feature_flags::GitUiFeatureFlag>(window, |workspace, _, _cx| {
 68            workspace.register_action(Self::deploy);
 69        });
 70
 71        workspace::register_serializable_item::<ProjectDiff>(cx);
 72    }
 73
 74    fn deploy(
 75        workspace: &mut Workspace,
 76        _: &Diff,
 77        window: &mut Window,
 78        cx: &mut Context<Workspace>,
 79    ) {
 80        workspace.open_panel::<GitPanel>(window, cx);
 81        Self::deploy_at(workspace, None, window, cx)
 82    }
 83
 84    pub fn deploy_at(
 85        workspace: &mut Workspace,
 86        entry: Option<GitStatusEntry>,
 87        window: &mut Window,
 88        cx: &mut Context<Workspace>,
 89    ) {
 90        let project_diff = if let Some(existing) = workspace.item_of_type::<Self>(cx) {
 91            workspace.activate_item(&existing, true, true, window, cx);
 92            existing
 93        } else {
 94            let workspace_handle = cx.entity();
 95            let project_diff =
 96                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx));
 97            workspace.add_item_to_active_pane(
 98                Box::new(project_diff.clone()),
 99                None,
100                true,
101                window,
102                cx,
103            );
104            project_diff
105        };
106        if let Some(entry) = entry {
107            project_diff.update(cx, |project_diff, cx| {
108                project_diff.scroll_to(entry, window, cx);
109            })
110        }
111    }
112
113    fn new(
114        project: Entity<Project>,
115        workspace: Entity<Workspace>,
116        window: &mut Window,
117        cx: &mut Context<Self>,
118    ) -> Self {
119        let focus_handle = cx.focus_handle();
120        let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
121
122        let editor = cx.new(|cx| {
123            let mut diff_display_editor = Editor::for_multibuffer(
124                multibuffer.clone(),
125                Some(project.clone()),
126                true,
127                window,
128                cx,
129            );
130            diff_display_editor.set_expand_all_diff_hunks(cx);
131            diff_display_editor.register_addon(GitPanelAddon {
132                workspace: workspace.downgrade(),
133            });
134            diff_display_editor
135        });
136        cx.subscribe_in(&editor, window, Self::handle_editor_event)
137            .detach();
138
139        let git_store = project.read(cx).git_store().clone();
140        let git_store_subscription = cx.subscribe_in(
141            &git_store,
142            window,
143            move |this, _git_store, _event, _window, _cx| {
144                *this.update_needed.borrow_mut() = ();
145            },
146        );
147
148        let (mut send, recv) = postage::watch::channel::<()>();
149        let worker = window.spawn(cx, {
150            let this = cx.weak_entity();
151            |cx| Self::handle_status_updates(this, recv, cx)
152        });
153        // Kick of a refresh immediately
154        *send.borrow_mut() = ();
155
156        Self {
157            project,
158            git_store: git_store.clone(),
159            workspace: workspace.downgrade(),
160            focus_handle,
161            editor,
162            multibuffer,
163            pending_scroll: None,
164            update_needed: send,
165            _task: worker,
166            _subscription: git_store_subscription,
167        }
168    }
169
170    pub fn scroll_to(
171        &mut self,
172        entry: GitStatusEntry,
173        window: &mut Window,
174        cx: &mut Context<Self>,
175    ) {
176        let Some(git_repo) = self.git_store.read(cx).active_repository() else {
177            return;
178        };
179        let repo = git_repo.read(cx);
180
181        let namespace = if repo.has_conflict(&entry.repo_path) {
182            CONFLICT_NAMESPACE
183        } else if entry.status.is_created() {
184            NEW_NAMESPACE
185        } else {
186            TRACKED_NAMESPACE
187        };
188
189        let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
190
191        self.scroll_to_path(path_key, window, cx)
192    }
193
194    fn scroll_to_path(&mut self, path_key: PathKey, window: &mut Window, cx: &mut Context<Self>) {
195        if let Some(position) = self.multibuffer.read(cx).location_for_path(&path_key, cx) {
196            self.editor.update(cx, |editor, cx| {
197                editor.change_selections(Some(Autoscroll::focused()), window, cx, |s| {
198                    s.select_ranges([position..position]);
199                })
200            })
201        } else {
202            self.pending_scroll = Some(path_key);
203        }
204    }
205
206    fn button_states(&self, cx: &App) -> ButtonStates {
207        let editor = self.editor.read(cx);
208        let snapshot = self.multibuffer.read(cx).snapshot(cx);
209        let prev_next = snapshot.diff_hunks().skip(1).next().is_some();
210        let mut selection = true;
211
212        let mut ranges = editor
213            .selections
214            .disjoint_anchor_ranges()
215            .collect::<Vec<_>>();
216        if !ranges.iter().any(|range| range.start != range.end) {
217            selection = false;
218            if let Some((excerpt_id, buffer, range)) = self.editor.read(cx).active_excerpt(cx) {
219                ranges = vec![multi_buffer::Anchor::range_in_buffer(
220                    excerpt_id,
221                    buffer.read(cx).remote_id(),
222                    range,
223                )];
224            } else {
225                ranges = Vec::default();
226            }
227        }
228        let mut has_staged_hunks = false;
229        let mut has_unstaged_hunks = false;
230        for hunk in editor.diff_hunks_in_ranges(&ranges, &snapshot) {
231            match hunk.secondary_status {
232                DiffHunkSecondaryStatus::HasSecondaryHunk => {
233                    has_unstaged_hunks = true;
234                }
235                DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk => {
236                    has_staged_hunks = true;
237                    has_unstaged_hunks = true;
238                }
239                DiffHunkSecondaryStatus::None => {
240                    has_staged_hunks = true;
241                }
242            }
243        }
244        let mut commit = false;
245        let mut stage_all = false;
246        let mut unstage_all = false;
247        self.workspace
248            .read_with(cx, |workspace, cx| {
249                if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
250                    let git_panel = git_panel.read(cx);
251                    commit = git_panel.can_commit();
252                    stage_all = git_panel.can_stage_all();
253                    unstage_all = git_panel.can_unstage_all();
254                }
255            })
256            .ok();
257
258        return ButtonStates {
259            stage: has_unstaged_hunks,
260            unstage: has_staged_hunks,
261            prev_next,
262            selection,
263            commit,
264            stage_all,
265            unstage_all,
266        };
267    }
268
269    fn handle_editor_event(
270        &mut self,
271        editor: &Entity<Editor>,
272        event: &EditorEvent,
273        window: &mut Window,
274        cx: &mut Context<Self>,
275    ) {
276        match event {
277            EditorEvent::ScrollPositionChanged { .. } => editor.update(cx, |editor, cx| {
278                let anchor = editor.scroll_manager.anchor().anchor;
279                let multibuffer = self.multibuffer.read(cx);
280                let snapshot = multibuffer.snapshot(cx);
281                let mut point = anchor.to_point(&snapshot);
282                point.row = (point.row + 1).min(snapshot.max_row().0);
283
284                let Some((_, buffer, _)) = self.multibuffer.read(cx).excerpt_containing(point, cx)
285                else {
286                    return;
287                };
288                let Some(project_path) = buffer
289                    .read(cx)
290                    .file()
291                    .map(|file| (file.worktree_id(cx), file.path().clone()))
292                else {
293                    return;
294                };
295                self.workspace
296                    .update(cx, |workspace, cx| {
297                        if let Some(git_panel) = workspace.panel::<GitPanel>(cx) {
298                            git_panel.update(cx, |git_panel, cx| {
299                                git_panel.select_entry_by_path(project_path.into(), window, cx)
300                            })
301                        }
302                    })
303                    .ok();
304            }),
305            _ => {}
306        }
307    }
308
309    fn load_buffers(&mut self, cx: &mut Context<Self>) -> Vec<Task<Result<DiffBuffer>>> {
310        let Some(repo) = self.git_store.read(cx).active_repository() else {
311            self.multibuffer.update(cx, |multibuffer, cx| {
312                multibuffer.clear(cx);
313            });
314            return vec![];
315        };
316
317        let mut previous_paths = self.multibuffer.read(cx).paths().collect::<HashSet<_>>();
318
319        let mut result = vec![];
320        repo.update(cx, |repo, cx| {
321            for entry in repo.status() {
322                if !entry.status.has_changes() {
323                    continue;
324                }
325                let Some(project_path) = repo.repo_path_to_project_path(&entry.repo_path) else {
326                    continue;
327                };
328                let namespace = if repo.has_conflict(&entry.repo_path) {
329                    CONFLICT_NAMESPACE
330                } else if entry.status.is_created() {
331                    NEW_NAMESPACE
332                } else {
333                    TRACKED_NAMESPACE
334                };
335                let path_key = PathKey::namespaced(namespace, entry.repo_path.0.clone());
336
337                previous_paths.remove(&path_key);
338                let load_buffer = self
339                    .project
340                    .update(cx, |project, cx| project.open_buffer(project_path, cx));
341
342                let project = self.project.clone();
343                result.push(cx.spawn(|_, mut cx| async move {
344                    let buffer = load_buffer.await?;
345                    let changes = project
346                        .update(&mut cx, |project, cx| {
347                            project.open_uncommitted_diff(buffer.clone(), cx)
348                        })?
349                        .await?;
350                    Ok(DiffBuffer {
351                        path_key,
352                        buffer,
353                        diff: changes,
354                    })
355                }));
356            }
357        });
358        self.multibuffer.update(cx, |multibuffer, cx| {
359            for path in previous_paths {
360                multibuffer.remove_excerpts_for_path(path, cx);
361            }
362        });
363        result
364    }
365
366    fn register_buffer(
367        &mut self,
368        diff_buffer: DiffBuffer,
369        window: &mut Window,
370        cx: &mut Context<Self>,
371    ) {
372        let path_key = diff_buffer.path_key;
373        let buffer = diff_buffer.buffer;
374        let diff = diff_buffer.diff;
375
376        let snapshot = buffer.read(cx).snapshot();
377        let diff = diff.read(cx);
378        let diff_hunk_ranges = if diff.base_text().is_none() {
379            vec![Point::zero()..snapshot.max_point()]
380        } else {
381            diff.hunks_intersecting_range(Anchor::MIN..Anchor::MAX, &snapshot, cx)
382                .map(|diff_hunk| diff_hunk.buffer_range.to_point(&snapshot))
383                .collect::<Vec<_>>()
384        };
385
386        self.multibuffer.update(cx, |multibuffer, cx| {
387            multibuffer.set_excerpts_for_path(
388                path_key.clone(),
389                buffer,
390                diff_hunk_ranges,
391                editor::DEFAULT_MULTIBUFFER_CONTEXT,
392                cx,
393            );
394        });
395        if self.multibuffer.read(cx).is_empty()
396            && self
397                .editor
398                .read(cx)
399                .focus_handle(cx)
400                .contains_focused(window, cx)
401        {
402            self.focus_handle.focus(window);
403        } else if self.focus_handle.is_focused(window) && !self.multibuffer.read(cx).is_empty() {
404            self.editor.update(cx, |editor, cx| {
405                editor.focus_handle(cx).focus(window);
406            });
407        }
408        if self.pending_scroll.as_ref() == Some(&path_key) {
409            self.scroll_to_path(path_key, window, cx);
410        }
411    }
412
413    pub async fn handle_status_updates(
414        this: WeakEntity<Self>,
415        mut recv: postage::watch::Receiver<()>,
416        mut cx: AsyncWindowContext,
417    ) -> Result<()> {
418        while let Some(_) = recv.next().await {
419            let buffers_to_load = this.update(&mut cx, |this, cx| this.load_buffers(cx))?;
420            for buffer_to_load in buffers_to_load {
421                if let Some(buffer) = buffer_to_load.await.log_err() {
422                    cx.update(|window, cx| {
423                        this.update(cx, |this, cx| this.register_buffer(buffer, window, cx))
424                            .ok();
425                    })?;
426                }
427            }
428            this.update(&mut cx, |this, _| this.pending_scroll.take())?;
429        }
430
431        Ok(())
432    }
433}
434
435impl EventEmitter<EditorEvent> for ProjectDiff {}
436
437impl Focusable for ProjectDiff {
438    fn focus_handle(&self, cx: &App) -> FocusHandle {
439        if self.multibuffer.read(cx).is_empty() {
440            self.focus_handle.clone()
441        } else {
442            self.editor.focus_handle(cx)
443        }
444    }
445}
446
447impl Item for ProjectDiff {
448    type Event = EditorEvent;
449
450    fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
451        Some(Icon::new(IconName::GitBranch).color(Color::Muted))
452    }
453
454    fn to_item_events(event: &EditorEvent, f: impl FnMut(ItemEvent)) {
455        Editor::to_item_events(event, f)
456    }
457
458    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
459        self.editor
460            .update(cx, |editor, cx| editor.deactivated(window, cx));
461    }
462
463    fn navigate(
464        &mut self,
465        data: Box<dyn Any>,
466        window: &mut Window,
467        cx: &mut Context<Self>,
468    ) -> bool {
469        self.editor
470            .update(cx, |editor, cx| editor.navigate(data, window, cx))
471    }
472
473    fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
474        Some("Project Diff".into())
475    }
476
477    fn tab_content(&self, params: TabContentParams, _window: &Window, _: &App) -> AnyElement {
478        Label::new("Uncommitted Changes")
479            .color(if params.selected {
480                Color::Default
481            } else {
482                Color::Muted
483            })
484            .into_any_element()
485    }
486
487    fn telemetry_event_text(&self) -> Option<&'static str> {
488        Some("Project Diff Opened")
489    }
490
491    fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
492        Some(Box::new(self.editor.clone()))
493    }
494
495    fn for_each_project_item(
496        &self,
497        cx: &App,
498        f: &mut dyn FnMut(gpui::EntityId, &dyn project::ProjectItem),
499    ) {
500        self.editor.for_each_project_item(cx, f)
501    }
502
503    fn is_singleton(&self, _: &App) -> bool {
504        false
505    }
506
507    fn set_nav_history(
508        &mut self,
509        nav_history: ItemNavHistory,
510        _: &mut Window,
511        cx: &mut Context<Self>,
512    ) {
513        self.editor.update(cx, |editor, _| {
514            editor.set_nav_history(Some(nav_history));
515        });
516    }
517
518    fn clone_on_split(
519        &self,
520        _workspace_id: Option<workspace::WorkspaceId>,
521        window: &mut Window,
522        cx: &mut Context<Self>,
523    ) -> Option<Entity<Self>>
524    where
525        Self: Sized,
526    {
527        let workspace = self.workspace.upgrade()?;
528        Some(cx.new(|cx| ProjectDiff::new(self.project.clone(), workspace, window, cx)))
529    }
530
531    fn is_dirty(&self, cx: &App) -> bool {
532        self.multibuffer.read(cx).is_dirty(cx)
533    }
534
535    fn has_conflict(&self, cx: &App) -> bool {
536        self.multibuffer.read(cx).has_conflict(cx)
537    }
538
539    fn can_save(&self, _: &App) -> bool {
540        true
541    }
542
543    fn save(
544        &mut self,
545        format: bool,
546        project: Entity<Project>,
547        window: &mut Window,
548        cx: &mut Context<Self>,
549    ) -> Task<Result<()>> {
550        self.editor.save(format, project, window, cx)
551    }
552
553    fn save_as(
554        &mut self,
555        _: Entity<Project>,
556        _: ProjectPath,
557        _window: &mut Window,
558        _: &mut Context<Self>,
559    ) -> Task<Result<()>> {
560        unreachable!()
561    }
562
563    fn reload(
564        &mut self,
565        project: Entity<Project>,
566        window: &mut Window,
567        cx: &mut Context<Self>,
568    ) -> Task<Result<()>> {
569        self.editor.reload(project, window, cx)
570    }
571
572    fn act_as_type<'a>(
573        &'a self,
574        type_id: TypeId,
575        self_handle: &'a Entity<Self>,
576        _: &'a App,
577    ) -> Option<AnyView> {
578        if type_id == TypeId::of::<Self>() {
579            Some(self_handle.to_any())
580        } else if type_id == TypeId::of::<Editor>() {
581            Some(self.editor.to_any())
582        } else {
583            None
584        }
585    }
586
587    fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
588        ToolbarItemLocation::PrimaryLeft
589    }
590
591    fn breadcrumbs(&self, theme: &theme::Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
592        self.editor.breadcrumbs(theme, cx)
593    }
594
595    fn added_to_workspace(
596        &mut self,
597        workspace: &mut Workspace,
598        window: &mut Window,
599        cx: &mut Context<Self>,
600    ) {
601        self.editor.update(cx, |editor, cx| {
602            editor.added_to_workspace(workspace, window, cx)
603        });
604    }
605}
606
607impl Render for ProjectDiff {
608    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
609        let is_empty = self.multibuffer.read(cx).is_empty();
610
611        div()
612            .track_focus(&self.focus_handle)
613            .bg(cx.theme().colors().editor_background)
614            .flex()
615            .items_center()
616            .justify_center()
617            .size_full()
618            .when(is_empty, |el| {
619                el.child(Label::new("No uncommitted changes"))
620            })
621            .when(!is_empty, |el| el.child(self.editor.clone()))
622    }
623}
624
625impl SerializableItem for ProjectDiff {
626    fn serialized_item_kind() -> &'static str {
627        "ProjectDiff"
628    }
629
630    fn cleanup(
631        _: workspace::WorkspaceId,
632        _: Vec<workspace::ItemId>,
633        _: &mut Window,
634        _: &mut App,
635    ) -> Task<Result<()>> {
636        Task::ready(Ok(()))
637    }
638
639    fn deserialize(
640        _project: Entity<Project>,
641        workspace: WeakEntity<Workspace>,
642        _workspace_id: workspace::WorkspaceId,
643        _item_id: workspace::ItemId,
644        window: &mut Window,
645        cx: &mut App,
646    ) -> Task<Result<Entity<Self>>> {
647        window.spawn(cx, |mut cx| async move {
648            workspace.update_in(&mut cx, |workspace, window, cx| {
649                let workspace_handle = cx.entity();
650                cx.new(|cx| Self::new(workspace.project().clone(), workspace_handle, window, cx))
651            })
652        })
653    }
654
655    fn serialize(
656        &mut self,
657        _workspace: &mut Workspace,
658        _item_id: workspace::ItemId,
659        _closing: bool,
660        _window: &mut Window,
661        _cx: &mut Context<Self>,
662    ) -> Option<Task<Result<()>>> {
663        None
664    }
665
666    fn should_serialize(&self, _: &Self::Event) -> bool {
667        false
668    }
669}
670
671pub struct ProjectDiffToolbar {
672    project_diff: Option<WeakEntity<ProjectDiff>>,
673    workspace: WeakEntity<Workspace>,
674}
675
676impl ProjectDiffToolbar {
677    pub fn new(workspace: &Workspace, _: &mut Context<Self>) -> Self {
678        Self {
679            project_diff: None,
680            workspace: workspace.weak_handle(),
681        }
682    }
683
684    fn project_diff(&self, _: &App) -> Option<Entity<ProjectDiff>> {
685        self.project_diff.as_ref()?.upgrade()
686    }
687    fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut Context<Self>) {
688        if let Some(project_diff) = self.project_diff(cx) {
689            project_diff.focus_handle(cx).focus(window);
690        }
691        let action = action.boxed_clone();
692        cx.defer(move |cx| {
693            cx.dispatch_action(action.as_ref());
694        })
695    }
696    fn dispatch_panel_action(
697        &self,
698        action: &dyn Action,
699        window: &mut Window,
700        cx: &mut Context<Self>,
701    ) {
702        self.workspace
703            .read_with(cx, |workspace, cx| {
704                if let Some(panel) = workspace.panel::<GitPanel>(cx) {
705                    panel.focus_handle(cx).focus(window)
706                }
707            })
708            .ok();
709        let action = action.boxed_clone();
710        cx.defer(move |cx| {
711            cx.dispatch_action(action.as_ref());
712        })
713    }
714}
715
716impl EventEmitter<ToolbarItemEvent> for ProjectDiffToolbar {}
717
718impl ToolbarItemView for ProjectDiffToolbar {
719    fn set_active_pane_item(
720        &mut self,
721        active_pane_item: Option<&dyn ItemHandle>,
722        _: &mut Window,
723        cx: &mut Context<Self>,
724    ) -> ToolbarItemLocation {
725        self.project_diff = active_pane_item
726            .and_then(|item| item.act_as::<ProjectDiff>(cx))
727            .map(|entity| entity.downgrade());
728        if self.project_diff.is_some() {
729            ToolbarItemLocation::PrimaryRight
730        } else {
731            ToolbarItemLocation::Hidden
732        }
733    }
734
735    fn pane_focus_update(
736        &mut self,
737        _pane_focused: bool,
738        _window: &mut Window,
739        _cx: &mut Context<Self>,
740    ) {
741    }
742}
743
744struct ButtonStates {
745    stage: bool,
746    unstage: bool,
747    prev_next: bool,
748    selection: bool,
749    stage_all: bool,
750    unstage_all: bool,
751    commit: bool,
752}
753
754impl Render for ProjectDiffToolbar {
755    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
756        let Some(project_diff) = self.project_diff(cx) else {
757            return div();
758        };
759        let focus_handle = project_diff.focus_handle(cx);
760        let button_states = project_diff.read(cx).button_states(cx);
761
762        h_group_xl()
763            .my_neg_1()
764            .items_center()
765            .py_1()
766            .pl_2()
767            .pr_1()
768            .flex_wrap()
769            .justify_between()
770            .child(
771                h_group_sm()
772                    .when(button_states.selection, |el| {
773                        el.child(
774                            Button::new("stage", "Toggle Staged")
775                                .tooltip(Tooltip::for_action_title_in(
776                                    "Toggle Staged",
777                                    &ToggleStaged,
778                                    &focus_handle,
779                                ))
780                                .disabled(!button_states.stage && !button_states.unstage)
781                                .on_click(cx.listener(|this, _, window, cx| {
782                                    this.dispatch_action(&ToggleStaged, window, cx)
783                                })),
784                        )
785                    })
786                    .when(!button_states.selection, |el| {
787                        el.child(
788                            Button::new("stage", "Stage")
789                                .tooltip(Tooltip::for_action_title_in(
790                                    "Stage",
791                                    &StageAndNext,
792                                    &focus_handle,
793                                ))
794                                // don't actually disable the button so it's mashable
795                                .color(if button_states.stage {
796                                    Color::Default
797                                } else {
798                                    Color::Disabled
799                                })
800                                .on_click(cx.listener(|this, _, window, cx| {
801                                    this.dispatch_action(&StageAndNext, window, cx)
802                                })),
803                        )
804                        .child(
805                            Button::new("unstage", "Unstage")
806                                .tooltip(Tooltip::for_action_title_in(
807                                    "Unstage",
808                                    &UnstageAndNext,
809                                    &focus_handle,
810                                ))
811                                .color(if button_states.unstage {
812                                    Color::Default
813                                } else {
814                                    Color::Disabled
815                                })
816                                .on_click(cx.listener(|this, _, window, cx| {
817                                    this.dispatch_action(&UnstageAndNext, window, cx)
818                                })),
819                        )
820                    }),
821            )
822            // n.b. the only reason these arrows are here is because we don't
823            // support "undo" for staging so we need a way to go back.
824            .child(
825                h_group_sm()
826                    .child(
827                        IconButton::new("up", IconName::ArrowUp)
828                            .shape(ui::IconButtonShape::Square)
829                            .tooltip(Tooltip::for_action_title_in(
830                                "Go to previous hunk",
831                                &GoToPrevHunk,
832                                &focus_handle,
833                            ))
834                            .disabled(!button_states.prev_next)
835                            .on_click(cx.listener(|this, _, window, cx| {
836                                this.dispatch_action(&GoToPrevHunk, window, cx)
837                            })),
838                    )
839                    .child(
840                        IconButton::new("down", IconName::ArrowDown)
841                            .shape(ui::IconButtonShape::Square)
842                            .tooltip(Tooltip::for_action_title_in(
843                                "Go to next hunk",
844                                &GoToHunk,
845                                &focus_handle,
846                            ))
847                            .disabled(!button_states.prev_next)
848                            .on_click(cx.listener(|this, _, window, cx| {
849                                this.dispatch_action(&GoToHunk, window, cx)
850                            })),
851                    ),
852            )
853            .child(vertical_divider())
854            .child(
855                h_group_sm()
856                    .when(
857                        button_states.unstage_all && !button_states.stage_all,
858                        |el| {
859                            el.child(Button::new("unstage-all", "Unstage All").on_click(
860                                cx.listener(|this, _, window, cx| {
861                                    this.dispatch_panel_action(&UnstageAll, window, cx)
862                                }),
863                            ))
864                        },
865                    )
866                    .when(
867                        !button_states.unstage_all || button_states.stage_all,
868                        |el| {
869                            el.child(
870                                // todo make it so that changing to say "Unstaged"
871                                // doesn't change the position.
872                                div().child(
873                                    Button::new("stage-all", "Stage All")
874                                        .disabled(!button_states.stage_all)
875                                        .on_click(cx.listener(|this, _, window, cx| {
876                                            this.dispatch_panel_action(&StageAll, window, cx)
877                                        })),
878                                ),
879                            )
880                        },
881                    )
882                    .child(
883                        Button::new("commit", "Commit")
884                            .disabled(!button_states.commit)
885                            .on_click(cx.listener(|this, _, window, cx| {
886                                // todo this should open modal, not focus panel.
887                                this.dispatch_action(&Commit, window, cx);
888                            })),
889                    ),
890            )
891    }
892}