Fix project diff focus (#24691)

Conrad Irwin created

Release Notes:

- N/A

Change summary

crates/git_ui/src/project_diff.rs | 53 +++++++++++++++++++++-----------
1 file changed, 34 insertions(+), 19 deletions(-)

Detailed changes

crates/git_ui/src/project_diff.rs 🔗

@@ -335,6 +335,22 @@ impl ProjectDiff {
                 cx,
             );
         });
+        if self.multibuffer.read(cx).is_empty()
+            && self
+                .editor
+                .read(cx)
+                .focus_handle(cx)
+                .contains_focused(window, cx)
+        {
+            self.focus_handle.focus(window);
+        } else if self.focus_handle.contains_focused(window, cx)
+            && !self.multibuffer.read(cx).is_empty()
+        {
+            self.editor.update(cx, |editor, cx| {
+                editor.focus_handle(cx).focus(window);
+                editor.move_to_beginning(&Default::default(), window, cx);
+            });
+        }
         if self.pending_scroll.as_ref() == Some(&path_key) {
             self.scroll_to_path(path_key, window, cx);
         }
@@ -365,8 +381,12 @@ impl ProjectDiff {
 impl EventEmitter<EditorEvent> for ProjectDiff {}
 
 impl Focusable for ProjectDiff {
-    fn focus_handle(&self, _: &App) -> FocusHandle {
-        self.focus_handle.clone()
+    fn focus_handle(&self, cx: &App) -> FocusHandle {
+        if self.multibuffer.read(cx).is_empty() {
+            self.focus_handle.clone()
+        } else {
+            self.editor.focus_handle(cx)
+        }
     }
 }
 
@@ -537,22 +557,17 @@ impl Item for ProjectDiff {
 impl Render for ProjectDiff {
     fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
         let is_empty = self.multibuffer.read(cx).is_empty();
-        if is_empty {
-            div()
-                .bg(cx.theme().colors().editor_background)
-                .flex()
-                .items_center()
-                .justify_center()
-                .size_full()
-                .child(Label::new("No uncommitted changes"))
-        } else {
-            div()
-                .bg(cx.theme().colors().editor_background)
-                .flex()
-                .items_center()
-                .justify_center()
-                .size_full()
-                .child(self.editor.clone())
-        }
+
+        div()
+            .track_focus(&self.focus_handle)
+            .bg(cx.theme().colors().editor_background)
+            .flex()
+            .items_center()
+            .justify_center()
+            .size_full()
+            .when(is_empty, |el| {
+                el.child(Label::new("No uncommitted changes"))
+            })
+            .when(!is_empty, |el| el.child(self.editor.clone()))
     }
 }