commit_modal.rs

  1use crate::branch_picker::{self, BranchList};
  2use crate::git_panel::{GitPanel, commit_message_editor};
  3use client::DisableAiSettings;
  4use git::repository::CommitOptions;
  5use git::{Amend, Commit, GenerateCommitMessage, Signoff};
  6use panel::{panel_button, panel_editor_style};
  7use settings::Settings;
  8use ui::{
  9    ContextMenu, KeybindingHint, PopoverMenu, PopoverMenuHandle, SplitButton, Tooltip, prelude::*,
 10};
 11
 12use editor::{Editor, EditorElement};
 13use gpui::*;
 14use util::ResultExt;
 15use workspace::{
 16    ModalView, Workspace,
 17    dock::{Dock, PanelHandle},
 18};
 19
 20// nate: It is a pain to get editors to size correctly and not overflow.
 21//
 22// this can get replaced with a simple flex layout with more time/a more thoughtful approach.
 23#[derive(Debug, Clone, Copy)]
 24pub struct ModalContainerProperties {
 25    pub modal_width: f32,
 26    pub editor_height: f32,
 27    pub footer_height: f32,
 28    pub container_padding: f32,
 29    pub modal_border_radius: f32,
 30}
 31
 32impl ModalContainerProperties {
 33    pub fn new(window: &Window, preferred_char_width: usize) -> Self {
 34        let container_padding = 5.0;
 35
 36        // Calculate width based on character width
 37        let mut modal_width = 460.0;
 38        let style = window.text_style().clone();
 39        let font_id = window.text_system().resolve_font(&style.font());
 40        let font_size = style.font_size.to_pixels(window.rem_size());
 41
 42        if let Ok(em_width) = window.text_system().em_width(font_id, font_size) {
 43            modal_width = preferred_char_width as f32 * em_width.0 + (container_padding * 2.0);
 44        }
 45
 46        Self {
 47            modal_width,
 48            editor_height: 300.0,
 49            footer_height: 24.0,
 50            container_padding,
 51            modal_border_radius: 12.0,
 52        }
 53    }
 54
 55    pub fn editor_border_radius(&self) -> Pixels {
 56        px(self.modal_border_radius - self.container_padding / 2.0)
 57    }
 58}
 59
 60pub struct CommitModal {
 61    git_panel: Entity<GitPanel>,
 62    commit_editor: Entity<Editor>,
 63    restore_dock: RestoreDock,
 64    properties: ModalContainerProperties,
 65    branch_list_handle: PopoverMenuHandle<BranchList>,
 66    commit_menu_handle: PopoverMenuHandle<ContextMenu>,
 67}
 68
 69impl Focusable for CommitModal {
 70    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
 71        self.commit_editor.focus_handle(cx)
 72    }
 73}
 74
 75impl EventEmitter<DismissEvent> for CommitModal {}
 76impl ModalView for CommitModal {
 77    fn on_before_dismiss(
 78        &mut self,
 79        window: &mut Window,
 80        cx: &mut Context<Self>,
 81    ) -> workspace::DismissDecision {
 82        self.git_panel.update(cx, |git_panel, cx| {
 83            git_panel.set_modal_open(false, cx);
 84        });
 85        self.restore_dock
 86            .dock
 87            .update(cx, |dock, cx| {
 88                if let Some(active_index) = self.restore_dock.active_index {
 89                    dock.activate_panel(active_index, window, cx)
 90                }
 91                dock.set_open(self.restore_dock.is_open, window, cx)
 92            })
 93            .log_err();
 94        workspace::DismissDecision::Dismiss(true)
 95    }
 96}
 97
 98struct RestoreDock {
 99    dock: WeakEntity<Dock>,
100    is_open: bool,
101    active_index: Option<usize>,
102}
103
104pub enum ForceMode {
105    Amend,
106    Commit,
107}
108
109impl CommitModal {
110    pub fn register(workspace: &mut Workspace) {
111        workspace.register_action(|workspace, _: &Commit, window, cx| {
112            CommitModal::toggle(workspace, Some(ForceMode::Commit), window, cx);
113        });
114        workspace.register_action(|workspace, _: &Amend, window, cx| {
115            CommitModal::toggle(workspace, Some(ForceMode::Amend), window, cx);
116        });
117    }
118
119    pub fn toggle(
120        workspace: &mut Workspace,
121        force_mode: Option<ForceMode>,
122        window: &mut Window,
123        cx: &mut Context<Workspace>,
124    ) {
125        let Some(git_panel) = workspace.panel::<GitPanel>(cx) else {
126            return;
127        };
128
129        git_panel.update(cx, |git_panel, cx| {
130            if let Some(force_mode) = force_mode {
131                match force_mode {
132                    ForceMode::Amend => {
133                        if git_panel
134                            .active_repository
135                            .as_ref()
136                            .and_then(|repo| repo.read(cx).head_commit.as_ref())
137                            .is_some()
138                        {
139                            if !git_panel.amend_pending() {
140                                git_panel.set_amend_pending(true, cx);
141                                git_panel.load_last_commit_message_if_empty(cx);
142                            }
143                        }
144                    }
145                    ForceMode::Commit => {
146                        if git_panel.amend_pending() {
147                            git_panel.set_amend_pending(false, cx);
148                        }
149                    }
150                }
151            }
152            git_panel.set_modal_open(true, cx);
153            git_panel.load_local_committer(cx);
154        });
155
156        let dock = workspace.dock_at_position(git_panel.position(window, cx));
157        let is_open = dock.read(cx).is_open();
158        let active_index = dock.read(cx).active_panel_index();
159        let dock = dock.downgrade();
160        let restore_dock_position = RestoreDock {
161            dock,
162            is_open,
163            active_index,
164        };
165
166        workspace.open_panel::<GitPanel>(window, cx);
167        workspace.toggle_modal(window, cx, move |window, cx| {
168            CommitModal::new(git_panel, restore_dock_position, window, cx)
169        })
170    }
171
172    fn new(
173        git_panel: Entity<GitPanel>,
174        restore_dock: RestoreDock,
175        window: &mut Window,
176        cx: &mut Context<Self>,
177    ) -> Self {
178        let panel = git_panel.read(cx);
179        let suggested_commit_message = panel.suggest_commit_message(cx);
180
181        let commit_editor = git_panel.update(cx, |git_panel, cx| {
182            git_panel.set_modal_open(true, cx);
183            let buffer = git_panel.commit_message_buffer(cx).clone();
184            let panel_editor = git_panel.commit_editor.clone();
185            let project = git_panel.project.clone();
186
187            cx.new(|cx| {
188                let mut editor =
189                    commit_message_editor(buffer, None, project.clone(), false, window, cx);
190                editor.sync_selections(panel_editor, cx).detach();
191
192                editor
193            })
194        });
195
196        let commit_message = commit_editor.read(cx).text(cx);
197
198        if let Some(suggested_commit_message) = suggested_commit_message {
199            if commit_message.is_empty() {
200                commit_editor.update(cx, |editor, cx| {
201                    editor.set_placeholder_text(suggested_commit_message, cx);
202                });
203            }
204        }
205
206        let focus_handle = commit_editor.focus_handle(cx);
207
208        cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
209            if !this.branch_list_handle.is_focused(window, cx)
210                && !this.commit_menu_handle.is_focused(window, cx)
211            {
212                cx.emit(DismissEvent);
213            }
214        })
215        .detach();
216
217        let properties = ModalContainerProperties::new(window, 50);
218
219        Self {
220            git_panel,
221            commit_editor,
222            restore_dock,
223            properties,
224            branch_list_handle: PopoverMenuHandle::default(),
225            commit_menu_handle: PopoverMenuHandle::default(),
226        }
227    }
228
229    fn commit_editor_element(&self, window: &mut Window, cx: &mut Context<Self>) -> EditorElement {
230        let editor_style = panel_editor_style(true, window, cx);
231        EditorElement::new(&self.commit_editor, editor_style)
232    }
233
234    pub fn render_commit_editor(
235        &self,
236        window: &mut Window,
237        cx: &mut Context<Self>,
238    ) -> impl IntoElement {
239        let properties = self.properties;
240        let padding_t = 3.0;
241        let padding_b = 6.0;
242        // magic number for editor not to overflow the container??
243        let extra_space_hack = 1.5 * window.line_height();
244
245        v_flex()
246            .h(px(properties.editor_height + padding_b + padding_t) + extra_space_hack)
247            .w_full()
248            .flex_none()
249            .rounded(properties.editor_border_radius())
250            .overflow_hidden()
251            .px_1p5()
252            .pt(px(padding_t))
253            .pb(px(padding_b))
254            .child(
255                div()
256                    .h(px(properties.editor_height))
257                    .w_full()
258                    .child(self.commit_editor_element(window, cx)),
259            )
260    }
261
262    fn render_git_commit_menu(
263        &self,
264        id: impl Into<ElementId>,
265        keybinding_target: Option<FocusHandle>,
266    ) -> impl IntoElement {
267        PopoverMenu::new(id.into())
268            .trigger(
269                ui::ButtonLike::new_rounded_right("commit-split-button-right")
270                    .layer(ui::ElevationIndex::ModalSurface)
271                    .size(ui::ButtonSize::None)
272                    .child(
273                        div()
274                            .px_1()
275                            .child(Icon::new(IconName::ChevronDownSmall).size(IconSize::XSmall)),
276                    ),
277            )
278            .menu({
279                let git_panel_entity = self.git_panel.clone();
280                move |window, cx| {
281                    let git_panel = git_panel_entity.read(cx);
282                    let amend_enabled = git_panel.amend_pending();
283                    let signoff_enabled = git_panel.signoff_enabled();
284                    let has_previous_commit = git_panel.head_commit(cx).is_some();
285
286                    Some(ContextMenu::build(window, cx, |context_menu, _, _| {
287                        context_menu
288                            .when_some(keybinding_target.clone(), |el, keybinding_target| {
289                                el.context(keybinding_target.clone())
290                            })
291                            .when(has_previous_commit, |this| {
292                                this.toggleable_entry(
293                                    "Amend",
294                                    amend_enabled,
295                                    IconPosition::Start,
296                                    Some(Box::new(Amend)),
297                                    {
298                                        let git_panel = git_panel_entity.clone();
299                                        move |window, cx| {
300                                            git_panel.update(cx, |git_panel, cx| {
301                                                git_panel.toggle_amend_pending(&Amend, window, cx);
302                                            })
303                                        }
304                                    },
305                                )
306                            })
307                            .toggleable_entry(
308                                "Signoff",
309                                signoff_enabled,
310                                IconPosition::Start,
311                                Some(Box::new(Signoff)),
312                                {
313                                    let git_panel = git_panel_entity.clone();
314                                    move |window, cx| {
315                                        git_panel.update(cx, |git_panel, cx| {
316                                            git_panel.toggle_signoff_enabled(&Signoff, window, cx);
317                                        })
318                                    }
319                                },
320                            )
321                    }))
322                }
323            })
324            .with_handle(self.commit_menu_handle.clone())
325            .anchor(Corner::TopRight)
326    }
327
328    pub fn render_footer(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
329        let (
330            can_commit,
331            tooltip,
332            commit_label,
333            co_authors,
334            generate_commit_message,
335            active_repo,
336            is_amend_pending,
337            is_signoff_enabled,
338        ) = self.git_panel.update(cx, |git_panel, cx| {
339            let (can_commit, tooltip) = git_panel.configure_commit_button(cx);
340            let title = git_panel.commit_button_title();
341            let co_authors = git_panel.render_co_authors(cx);
342            let generate_commit_message = git_panel.render_generate_commit_message_button(cx);
343            let active_repo = git_panel.active_repository.clone();
344            let is_amend_pending = git_panel.amend_pending();
345            let is_signoff_enabled = git_panel.signoff_enabled();
346            (
347                can_commit,
348                tooltip,
349                title,
350                co_authors,
351                generate_commit_message,
352                active_repo,
353                is_amend_pending,
354                is_signoff_enabled,
355            )
356        });
357
358        let branch = active_repo
359            .as_ref()
360            .and_then(|repo| repo.read(cx).branch.as_ref())
361            .map(|b| b.name().to_owned())
362            .unwrap_or_else(|| "<no branch>".to_owned());
363
364        let branch_picker_button = panel_button(branch)
365            .icon(IconName::GitBranch)
366            .icon_size(IconSize::Small)
367            .icon_color(Color::Placeholder)
368            .color(Color::Muted)
369            .icon_position(IconPosition::Start)
370            .tooltip(Tooltip::for_action_title(
371                "Switch Branch",
372                &zed_actions::git::Branch,
373            ))
374            .on_click(cx.listener(|_, _, window, cx| {
375                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
376            }))
377            .style(ButtonStyle::Transparent);
378
379        let branch_picker = PopoverMenu::new("popover-button")
380            .menu(move |window, cx| Some(branch_picker::popover(active_repo.clone(), window, cx)))
381            .with_handle(self.branch_list_handle.clone())
382            .trigger_with_tooltip(
383                branch_picker_button,
384                Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
385            )
386            .anchor(Corner::BottomLeft)
387            .offset(gpui::Point {
388                x: px(0.0),
389                y: px(-2.0),
390            });
391        let focus_handle = self.focus_handle(cx);
392
393        let close_kb_hint =
394            if let Some(close_kb) = ui::KeyBinding::for_action(&menu::Cancel, window, cx) {
395                Some(
396                    KeybindingHint::new(close_kb, cx.theme().colors().editor_background)
397                        .suffix("Cancel"),
398                )
399            } else {
400                None
401            };
402
403        h_flex()
404            .group("commit_editor_footer")
405            .flex_none()
406            .w_full()
407            .items_center()
408            .justify_between()
409            .w_full()
410            .h(px(self.properties.footer_height))
411            .gap_1()
412            .child(
413                h_flex()
414                    .gap_1()
415                    .flex_shrink()
416                    .overflow_x_hidden()
417                    .child(
418                        h_flex()
419                            .flex_shrink()
420                            .overflow_x_hidden()
421                            .child(branch_picker),
422                    )
423                    .children(generate_commit_message)
424                    .children(co_authors),
425            )
426            .child(div().flex_1())
427            .child(
428                h_flex()
429                    .items_center()
430                    .justify_end()
431                    .flex_none()
432                    .px_1()
433                    .gap_4()
434                    .children(close_kb_hint)
435                    .child(SplitButton::new(
436                        ui::ButtonLike::new_rounded_left(ElementId::Name(
437                            format!("split-button-left-{}", commit_label).into(),
438                        ))
439                        .layer(ui::ElevationIndex::ModalSurface)
440                        .size(ui::ButtonSize::Compact)
441                        .child(
442                            div()
443                                .child(Label::new(commit_label).size(LabelSize::Small))
444                                .mr_0p5(),
445                        )
446                        .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
447                            telemetry::event!("Git Committed", source = "Git Modal");
448                            this.git_panel.update(cx, |git_panel, cx| {
449                                git_panel.commit_changes(
450                                    CommitOptions {
451                                        amend: is_amend_pending,
452                                        signoff: is_signoff_enabled,
453                                    },
454                                    window,
455                                    cx,
456                                )
457                            });
458                            cx.emit(DismissEvent);
459                        }))
460                        .disabled(!can_commit)
461                        .tooltip({
462                            let focus_handle = focus_handle.clone();
463                            move |window, cx| {
464                                if can_commit {
465                                    Tooltip::with_meta_in(
466                                        tooltip,
467                                        Some(&git::Commit),
468                                        format!(
469                                            "git commit{}{}",
470                                            if is_amend_pending { " --amend" } else { "" },
471                                            if is_signoff_enabled { " --signoff" } else { "" }
472                                        ),
473                                        &focus_handle.clone(),
474                                        window,
475                                        cx,
476                                    )
477                                } else {
478                                    Tooltip::simple(tooltip, cx)
479                                }
480                            }
481                        }),
482                        self.render_git_commit_menu(
483                            ElementId::Name(format!("split-button-right-{}", commit_label).into()),
484                            Some(focus_handle.clone()),
485                        )
486                        .into_any_element(),
487                    )),
488            )
489    }
490
491    fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
492        if self.git_panel.read(cx).amend_pending() {
493            self.git_panel
494                .update(cx, |git_panel, cx| git_panel.set_amend_pending(false, cx));
495        } else {
496            cx.emit(DismissEvent);
497        }
498    }
499
500    fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
501        if self.git_panel.read(cx).amend_pending() {
502            return;
503        }
504        telemetry::event!("Git Committed", source = "Git Modal");
505        self.git_panel.update(cx, |git_panel, cx| {
506            git_panel.commit_changes(
507                CommitOptions {
508                    amend: false,
509                    signoff: git_panel.signoff_enabled(),
510                },
511                window,
512                cx,
513            )
514        });
515        cx.emit(DismissEvent);
516    }
517
518    fn amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
519        if self
520            .git_panel
521            .read(cx)
522            .active_repository
523            .as_ref()
524            .and_then(|repo| repo.read(cx).head_commit.as_ref())
525            .is_none()
526        {
527            return;
528        }
529        if !self.git_panel.read(cx).amend_pending() {
530            self.git_panel.update(cx, |git_panel, cx| {
531                git_panel.set_amend_pending(true, cx);
532                git_panel.load_last_commit_message_if_empty(cx);
533            });
534        } else {
535            telemetry::event!("Git Amended", source = "Git Modal");
536            self.git_panel.update(cx, |git_panel, cx| {
537                git_panel.set_amend_pending(false, cx);
538                git_panel.commit_changes(
539                    CommitOptions {
540                        amend: true,
541                        signoff: git_panel.signoff_enabled(),
542                    },
543                    window,
544                    cx,
545                );
546            });
547            cx.emit(DismissEvent);
548        }
549    }
550
551    fn toggle_branch_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
552        if self.branch_list_handle.is_focused(window, cx) {
553            self.focus_handle(cx).focus(window)
554        } else {
555            self.branch_list_handle.toggle(window, cx);
556        }
557    }
558}
559
560impl Render for CommitModal {
561    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
562        let properties = self.properties;
563        let width = px(properties.modal_width);
564        let container_padding = px(properties.container_padding);
565        let border_radius = properties.modal_border_radius;
566        let editor_focus_handle = self.commit_editor.focus_handle(cx);
567
568        v_flex()
569            .id("commit-modal")
570            .key_context("GitCommit")
571            .on_action(cx.listener(Self::dismiss))
572            .on_action(cx.listener(Self::commit))
573            .on_action(cx.listener(Self::amend))
574            .when(!DisableAiSettings::get_global(cx).disable_ai, |this| {
575                this.on_action(cx.listener(|this, _: &GenerateCommitMessage, _, cx| {
576                    this.git_panel.update(cx, |panel, cx| {
577                        panel.generate_commit_message(cx);
578                    })
579                }))
580            })
581            .on_action(
582                cx.listener(|this, _: &zed_actions::git::Branch, window, cx| {
583                    this.toggle_branch_selector(window, cx);
584                }),
585            )
586            .on_action(
587                cx.listener(|this, _: &zed_actions::git::CheckoutBranch, window, cx| {
588                    this.toggle_branch_selector(window, cx);
589                }),
590            )
591            .on_action(
592                cx.listener(|this, _: &zed_actions::git::Switch, window, cx| {
593                    this.toggle_branch_selector(window, cx);
594                }),
595            )
596            .elevation_3(cx)
597            .overflow_hidden()
598            .flex_none()
599            .relative()
600            .bg(cx.theme().colors().elevated_surface_background)
601            .rounded(px(border_radius))
602            .border_1()
603            .border_color(cx.theme().colors().border)
604            .w(width)
605            .p(container_padding)
606            .child(
607                v_flex()
608                    .id("editor-container")
609                    .justify_between()
610                    .p_2()
611                    .size_full()
612                    .gap_2()
613                    .rounded(properties.editor_border_radius())
614                    .overflow_hidden()
615                    .cursor_text()
616                    .bg(cx.theme().colors().editor_background)
617                    .border_1()
618                    .border_color(cx.theme().colors().border_variant)
619                    .on_click(cx.listener(move |_, _: &ClickEvent, window, _cx| {
620                        window.focus(&editor_focus_handle);
621                    }))
622                    .child(
623                        div()
624                            .flex_1()
625                            .size_full()
626                            .child(self.render_commit_editor(window, cx)),
627                    )
628                    .child(self.render_footer(window, cx)),
629            )
630    }
631}