commit_modal.rs

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