commit_modal.rs

  1// #![allow(unused, dead_code)]
  2
  3use crate::branch_picker::{self, BranchList};
  4use crate::git_panel::{commit_message_editor, GitPanel};
  5use git::{Commit, GenerateCommitMessage};
  6use panel::{panel_button, panel_editor_style, panel_filled_button};
  7use ui::{prelude::*, KeybindingHint, PopoverMenu, Tooltip};
  8
  9use editor::{Editor, EditorElement};
 10use gpui::*;
 11use util::ResultExt;
 12use workspace::{
 13    dock::{Dock, PanelHandle},
 14    ModalView, Workspace,
 15};
 16
 17// nate: It is a pain to get editors to size correctly and not overflow.
 18//
 19// this can get replaced with a simple flex layout with more time/a more thoughtful approach.
 20#[derive(Debug, Clone, Copy)]
 21pub struct ModalContainerProperties {
 22    pub modal_width: f32,
 23    pub editor_height: f32,
 24    pub footer_height: f32,
 25    pub container_padding: f32,
 26    pub modal_border_radius: f32,
 27}
 28
 29impl ModalContainerProperties {
 30    pub fn new(window: &Window, preferred_char_width: usize) -> Self {
 31        let container_padding = 5.0;
 32
 33        // Calculate width based on character width
 34        let mut modal_width = 460.0;
 35        let style = window.text_style().clone();
 36        let font_id = window.text_system().resolve_font(&style.font());
 37        let font_size = style.font_size.to_pixels(window.rem_size());
 38
 39        if let Ok(em_width) = window.text_system().em_width(font_id, font_size) {
 40            modal_width = preferred_char_width as f32 * em_width.0 + (container_padding * 2.0);
 41        }
 42
 43        Self {
 44            modal_width,
 45            editor_height: 300.0,
 46            footer_height: 24.0,
 47            container_padding,
 48            modal_border_radius: 12.0,
 49        }
 50    }
 51
 52    pub fn editor_border_radius(&self) -> Pixels {
 53        px(self.modal_border_radius - self.container_padding / 2.0)
 54    }
 55}
 56
 57pub fn init(cx: &mut App) {
 58    cx.observe_new(|workspace: &mut Workspace, window, cx| {
 59        let Some(window) = window else {
 60            return;
 61        };
 62        CommitModal::register(workspace, window, cx)
 63    })
 64    .detach();
 65}
 66
 67pub struct CommitModal {
 68    branch_list: Entity<BranchList>,
 69    git_panel: Entity<GitPanel>,
 70    commit_editor: Entity<Editor>,
 71    restore_dock: RestoreDock,
 72    properties: ModalContainerProperties,
 73}
 74
 75impl Focusable for CommitModal {
 76    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
 77        self.commit_editor.focus_handle(cx)
 78    }
 79}
 80
 81impl EventEmitter<DismissEvent> for CommitModal {}
 82impl ModalView for CommitModal {
 83    fn on_before_dismiss(
 84        &mut self,
 85        window: &mut Window,
 86        cx: &mut Context<Self>,
 87    ) -> workspace::DismissDecision {
 88        self.git_panel.update(cx, |git_panel, cx| {
 89            git_panel.set_modal_open(false, cx);
 90        });
 91        self.restore_dock
 92            .dock
 93            .update(cx, |dock, cx| {
 94                if let Some(active_index) = self.restore_dock.active_index {
 95                    dock.activate_panel(active_index, window, cx)
 96                }
 97                dock.set_open(self.restore_dock.is_open, window, cx)
 98            })
 99            .log_err();
100        workspace::DismissDecision::Dismiss(true)
101    }
102}
103
104struct RestoreDock {
105    dock: WeakEntity<Dock>,
106    is_open: bool,
107    active_index: Option<usize>,
108}
109
110impl CommitModal {
111    pub fn register(workspace: &mut Workspace, _: &mut Window, _cx: &mut Context<Workspace>) {
112        workspace.register_action(|workspace, _: &Commit, window, cx| {
113            CommitModal::toggle(workspace, window, cx);
114        });
115    }
116
117    pub fn toggle(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<'_, Workspace>) {
118        let Some(git_panel) = workspace.panel::<GitPanel>(cx) else {
119            return;
120        };
121
122        git_panel.update(cx, |git_panel, cx| {
123            git_panel.set_modal_open(true, cx);
124        });
125
126        let dock = workspace.dock_at_position(git_panel.position(window, cx));
127        let is_open = dock.read(cx).is_open();
128        let active_index = dock.read(cx).active_panel_index();
129        let dock = dock.downgrade();
130        let restore_dock_position = RestoreDock {
131            dock,
132            is_open,
133            active_index,
134        };
135
136        workspace.open_panel::<GitPanel>(window, cx);
137        workspace.toggle_modal(window, cx, move |window, cx| {
138            CommitModal::new(git_panel, restore_dock_position, window, cx)
139        })
140    }
141
142    fn new(
143        git_panel: Entity<GitPanel>,
144        restore_dock: RestoreDock,
145        window: &mut Window,
146        cx: &mut Context<Self>,
147    ) -> Self {
148        let panel = git_panel.read(cx);
149        let active_repository = panel.active_repository.clone();
150        let suggested_commit_message = panel.suggest_commit_message();
151
152        let commit_editor = git_panel.update(cx, |git_panel, cx| {
153            git_panel.set_modal_open(true, cx);
154            let buffer = git_panel.commit_message_buffer(cx).clone();
155            let panel_editor = git_panel.commit_editor.clone();
156            let project = git_panel.project.clone();
157
158            cx.new(|cx| {
159                let mut editor =
160                    commit_message_editor(buffer, None, project.clone(), false, window, cx);
161                editor.sync_selections(panel_editor, cx).detach();
162
163                editor
164            })
165        });
166
167        let commit_message = commit_editor.read(cx).text(cx);
168
169        if let Some(suggested_commit_message) = suggested_commit_message {
170            if commit_message.is_empty() {
171                commit_editor.update(cx, |editor, cx| {
172                    editor.set_placeholder_text(suggested_commit_message, cx);
173                });
174            }
175        }
176
177        let focus_handle = commit_editor.focus_handle(cx);
178
179        cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
180            if !this
181                .branch_list
182                .focus_handle(cx)
183                .contains_focused(window, cx)
184            {
185                cx.emit(DismissEvent);
186            }
187        })
188        .detach();
189
190        let properties = ModalContainerProperties::new(window, 50);
191
192        Self {
193            branch_list: branch_picker::popover(active_repository.clone(), window, cx),
194            git_panel,
195            commit_editor,
196            restore_dock,
197            properties,
198        }
199    }
200
201    fn commit_editor_element(&self, window: &mut Window, cx: &mut Context<Self>) -> EditorElement {
202        let editor_style = panel_editor_style(true, window, cx);
203        EditorElement::new(&self.commit_editor, editor_style)
204    }
205
206    pub fn render_commit_editor(
207        &self,
208        window: &mut Window,
209        cx: &mut Context<Self>,
210    ) -> impl IntoElement {
211        let properties = self.properties;
212        let padding_t = 3.0;
213        let padding_b = 6.0;
214        // magic number for editor not to overflow the container??
215        let extra_space_hack = 1.5 * window.line_height();
216
217        v_flex()
218            .h(px(properties.editor_height + padding_b + padding_t) + extra_space_hack)
219            .w_full()
220            .flex_none()
221            .rounded(properties.editor_border_radius())
222            .overflow_hidden()
223            .px_1p5()
224            .pt(px(padding_t))
225            .pb(px(padding_b))
226            .child(
227                div()
228                    .h(px(properties.editor_height))
229                    .w_full()
230                    .child(self.commit_editor_element(window, cx)),
231            )
232    }
233
234    pub fn render_footer(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
235        let (branch, can_commit, tooltip, commit_label, co_authors, generate_commit_message) =
236            self.git_panel.update(cx, |git_panel, cx| {
237                let branch = git_panel
238                    .active_repository
239                    .as_ref()
240                    .and_then(|repo| {
241                        repo.read(cx)
242                            .repository_entry
243                            .branch()
244                            .map(|b| b.name.clone())
245                    })
246                    .unwrap_or_else(|| "<no branch>".into());
247                let (can_commit, tooltip) = git_panel.configure_commit_button(cx);
248                let title = git_panel.commit_button_title();
249                let co_authors = git_panel.render_co_authors(cx);
250                let generate_commit_message = git_panel.render_generate_commit_message_button(cx);
251                (
252                    branch,
253                    can_commit,
254                    tooltip,
255                    title,
256                    co_authors,
257                    generate_commit_message,
258                )
259            });
260
261        let branch_picker_button = panel_button(branch)
262            .icon(IconName::GitBranch)
263            .icon_size(IconSize::Small)
264            .icon_color(Color::Placeholder)
265            .color(Color::Muted)
266            .icon_position(IconPosition::Start)
267            .tooltip(Tooltip::for_action_title(
268                "Switch Branch",
269                &zed_actions::git::Branch,
270            ))
271            .on_click(cx.listener(|_, _, window, cx| {
272                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
273            }))
274            .style(ButtonStyle::Transparent);
275
276        let branch_picker = PopoverMenu::new("popover-button")
277            .menu({
278                let branch_list = self.branch_list.clone();
279                move |_window, _cx| Some(branch_list.clone())
280            })
281            .trigger_with_tooltip(
282                branch_picker_button,
283                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
284            )
285            .anchor(Corner::BottomLeft)
286            .offset(gpui::Point {
287                x: px(0.0),
288                y: px(-2.0),
289            });
290        let focus_handle = self.focus_handle(cx);
291
292        let close_kb_hint =
293            if let Some(close_kb) = ui::KeyBinding::for_action(&menu::Cancel, window, cx) {
294                Some(
295                    KeybindingHint::new(close_kb, cx.theme().colors().editor_background)
296                        .suffix("Cancel"),
297                )
298            } else {
299                None
300            };
301
302        let commit_button = panel_filled_button(commit_label)
303            .tooltip({
304                let panel_editor_focus_handle = focus_handle.clone();
305                move |window, cx| {
306                    Tooltip::for_action_in(tooltip, &Commit, &panel_editor_focus_handle, window, cx)
307                }
308            })
309            .disabled(!can_commit)
310            .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
311                telemetry::event!("Git Committed", source = "Git Modal");
312                this.git_panel
313                    .update(cx, |git_panel, cx| git_panel.commit_changes(window, cx));
314                cx.emit(DismissEvent);
315            }));
316
317        h_flex()
318            .group("commit_editor_footer")
319            .flex_none()
320            .w_full()
321            .items_center()
322            .justify_between()
323            .w_full()
324            .h(px(self.properties.footer_height))
325            .gap_1()
326            .child(
327                h_flex()
328                    .gap_1()
329                    .child(branch_picker)
330                    .children(generate_commit_message)
331                    .children(co_authors),
332            )
333            .child(div().flex_1())
334            .child(
335                h_flex()
336                    .items_center()
337                    .justify_end()
338                    .flex_none()
339                    .px_1()
340                    .gap_4()
341                    .children(close_kb_hint)
342                    .child(commit_button),
343            )
344    }
345
346    fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
347        cx.emit(DismissEvent);
348    }
349
350    fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
351        telemetry::event!("Git Committed", source = "Git Modal");
352        self.git_panel
353            .update(cx, |git_panel, cx| git_panel.commit_changes(window, cx));
354        cx.emit(DismissEvent);
355    }
356}
357
358impl Render for CommitModal {
359    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
360        let properties = self.properties;
361        let width = px(properties.modal_width);
362        let container_padding = px(properties.container_padding);
363        let border_radius = properties.modal_border_radius;
364        let editor_focus_handle = self.commit_editor.focus_handle(cx);
365
366        v_flex()
367            .id("commit-modal")
368            .key_context("GitCommit")
369            .on_action(cx.listener(Self::dismiss))
370            .on_action(cx.listener(Self::commit))
371            .on_action(cx.listener(|this, _: &GenerateCommitMessage, _, cx| {
372                this.git_panel.update(cx, |panel, cx| {
373                    panel.generate_commit_message(cx);
374                })
375            }))
376            .on_action(
377                cx.listener(|this, _: &zed_actions::git::Branch, window, cx| {
378                    toggle_branch_picker(this, window, cx);
379                }),
380            )
381            .on_action(
382                cx.listener(|this, _: &zed_actions::git::CheckoutBranch, window, cx| {
383                    toggle_branch_picker(this, window, cx);
384                }),
385            )
386            .on_action(
387                cx.listener(|this, _: &zed_actions::git::Switch, window, cx| {
388                    toggle_branch_picker(this, window, cx);
389                }),
390            )
391            .elevation_3(cx)
392            .overflow_hidden()
393            .flex_none()
394            .relative()
395            .bg(cx.theme().colors().elevated_surface_background)
396            .rounded(px(border_radius))
397            .border_1()
398            .border_color(cx.theme().colors().border)
399            .w(width)
400            .p(container_padding)
401            .child(
402                v_flex()
403                    .id("editor-container")
404                    .justify_between()
405                    .p_2()
406                    .size_full()
407                    .gap_2()
408                    .rounded(properties.editor_border_radius())
409                    .overflow_hidden()
410                    .cursor_text()
411                    .bg(cx.theme().colors().editor_background)
412                    .border_1()
413                    .border_color(cx.theme().colors().border_variant)
414                    .on_click(cx.listener(move |_, _: &ClickEvent, window, _cx| {
415                        window.focus(&editor_focus_handle);
416                    }))
417                    .child(
418                        div()
419                            .flex_1()
420                            .size_full()
421                            .child(self.render_commit_editor(window, cx)),
422                    )
423                    .child(self.render_footer(window, cx)),
424            )
425    }
426}
427
428fn toggle_branch_picker(
429    this: &mut CommitModal,
430    window: &mut Window,
431    cx: &mut Context<'_, CommitModal>,
432) {
433    this.branch_list.update(cx, |branch_list, cx| {
434        branch_list.popover_handle.toggle(window, cx);
435    })
436}