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, ShowCommitEditor};
  6use panel::{panel_button, panel_editor_style, panel_filled_button};
  7use project::Project;
  8use ui::{prelude::*, KeybindingHint, PopoverButton, Tooltip, TriggerablePopover};
  9
 10use editor::{Editor, EditorElement};
 11use gpui::*;
 12use util::ResultExt;
 13use workspace::{
 14    dock::{Dock, PanelHandle},
 15    ModalView, Workspace,
 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 fn init(cx: &mut App) {
 59    cx.observe_new(|workspace: &mut Workspace, window, cx| {
 60        let Some(window) = window else {
 61            return;
 62        };
 63        CommitModal::register(workspace, window, cx)
 64    })
 65    .detach();
 66}
 67
 68pub struct CommitModal {
 69    branch_list: Entity<BranchList>,
 70    git_panel: Entity<GitPanel>,
 71    commit_editor: Entity<Editor>,
 72    restore_dock: RestoreDock,
 73    properties: ModalContainerProperties,
 74}
 75
 76impl Focusable for CommitModal {
 77    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
 78        self.commit_editor.focus_handle(cx)
 79    }
 80}
 81
 82impl EventEmitter<DismissEvent> for CommitModal {}
 83impl ModalView for CommitModal {
 84    fn on_before_dismiss(
 85        &mut self,
 86        window: &mut Window,
 87        cx: &mut Context<Self>,
 88    ) -> workspace::DismissDecision {
 89        self.git_panel.update(cx, |git_panel, cx| {
 90            git_panel.set_modal_open(false, cx);
 91        });
 92        self.restore_dock
 93            .dock
 94            .update(cx, |dock, cx| {
 95                if let Some(active_index) = self.restore_dock.active_index {
 96                    dock.activate_panel(active_index, window, cx)
 97                }
 98                dock.set_open(self.restore_dock.is_open, window, cx)
 99            })
100            .log_err();
101        workspace::DismissDecision::Dismiss(true)
102    }
103}
104
105struct RestoreDock {
106    dock: WeakEntity<Dock>,
107    is_open: bool,
108    active_index: Option<usize>,
109}
110
111impl CommitModal {
112    pub fn register(workspace: &mut Workspace, _: &mut Window, _cx: &mut Context<Workspace>) {
113        workspace.register_action(|workspace, _: &ShowCommitEditor, window, cx| {
114            let Some(git_panel) = workspace.panel::<GitPanel>(cx) else {
115                return;
116            };
117
118            let (can_open_commit_editor, conflict) = git_panel.update(cx, |git_panel, cx| {
119                let can_open_commit_editor = git_panel.can_open_commit_editor();
120                let conflict = git_panel.has_unstaged_conflicts();
121                if can_open_commit_editor {
122                    git_panel.set_modal_open(true, cx);
123                }
124                (can_open_commit_editor, conflict)
125            });
126            if !can_open_commit_editor {
127                let message = if conflict {
128                    "There are still conflicts. You must stage these before committing."
129                } else {
130                    "No changes to commit."
131                };
132                let prompt = window.prompt(PromptLevel::Warning, message, None, &["Ok"], cx);
133                cx.spawn(|_, _| async move {
134                    prompt.await.ok();
135                })
136                .detach();
137                return;
138            }
139
140            let dock = workspace.dock_at_position(git_panel.position(window, cx));
141            let is_open = dock.read(cx).is_open();
142            let active_index = dock.read(cx).active_panel_index();
143            let dock = dock.downgrade();
144            let restore_dock_position = RestoreDock {
145                dock,
146                is_open,
147                active_index,
148            };
149
150            let project = workspace.project().clone();
151            workspace.open_panel::<GitPanel>(window, cx);
152            workspace.toggle_modal(window, cx, move |window, cx| {
153                CommitModal::new(git_panel, restore_dock_position, project, window, cx)
154            })
155        });
156    }
157
158    fn new(
159        git_panel: Entity<GitPanel>,
160        restore_dock: RestoreDock,
161        project: Entity<Project>,
162        window: &mut Window,
163        cx: &mut Context<Self>,
164    ) -> Self {
165        let panel = git_panel.read(cx);
166        let suggested_commit_message = panel.suggest_commit_message();
167
168        let commit_editor = git_panel.update(cx, |git_panel, cx| {
169            git_panel.set_modal_open(true, cx);
170            let buffer = git_panel.commit_message_buffer(cx).clone();
171            let project = git_panel.project.clone();
172            cx.new(|cx| commit_message_editor(buffer, None, project.clone(), false, window, cx))
173        });
174
175        let commit_message = commit_editor.read(cx).text(cx);
176
177        if let Some(suggested_commit_message) = suggested_commit_message {
178            if commit_message.is_empty() {
179                commit_editor.update(cx, |editor, cx| {
180                    editor.set_placeholder_text(suggested_commit_message, cx);
181                });
182            }
183        }
184
185        let focus_handle = commit_editor.focus_handle(cx);
186
187        cx.on_focus_out(&focus_handle, window, |this, _, window, cx| {
188            if !this
189                .branch_list
190                .focus_handle(cx)
191                .contains_focused(window, cx)
192            {
193                cx.emit(DismissEvent);
194            }
195        })
196        .detach();
197
198        let properties = ModalContainerProperties::new(window, 50);
199
200        Self {
201            branch_list: branch_picker::popover(project.clone(), window, cx),
202            git_panel,
203            commit_editor,
204            restore_dock,
205            properties,
206        }
207    }
208
209    fn commit_editor_element(&self, window: &mut Window, cx: &mut Context<Self>) -> EditorElement {
210        let editor_style = panel_editor_style(true, window, cx);
211        EditorElement::new(&self.commit_editor, editor_style)
212    }
213
214    pub fn render_commit_editor(
215        &self,
216        window: &mut Window,
217        cx: &mut Context<Self>,
218    ) -> impl IntoElement {
219        let properties = self.properties;
220        let padding_t = 3.0;
221        let padding_b = 6.0;
222        // magic number for editor not to overflow the container??
223        let extra_space_hack = 1.5 * window.line_height();
224
225        v_flex()
226            .h(px(properties.editor_height + padding_b + padding_t) + extra_space_hack)
227            .w_full()
228            .flex_none()
229            .rounded(properties.editor_border_radius())
230            .overflow_hidden()
231            .px_1p5()
232            .pt(px(padding_t))
233            .pb(px(padding_b))
234            .child(
235                div()
236                    .h(px(properties.editor_height))
237                    .w_full()
238                    .child(self.commit_editor_element(window, cx)),
239            )
240    }
241
242    pub fn render_footer(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
243        let git_panel = self.git_panel.clone();
244
245        let (branch, can_commit, tooltip, commit_label, co_authors) =
246            self.git_panel.update(cx, |git_panel, cx| {
247                let branch = git_panel
248                    .active_repository
249                    .as_ref()
250                    .and_then(|repo| {
251                        repo.read(cx)
252                            .repository_entry
253                            .branch()
254                            .map(|b| b.name.clone())
255                    })
256                    .unwrap_or_else(|| "<no branch>".into());
257                let (can_commit, tooltip) = git_panel.configure_commit_button(cx);
258                let title = git_panel.commit_button_title();
259                let co_authors = git_panel.render_co_authors(cx);
260                (branch, can_commit, tooltip, title, co_authors)
261            });
262
263        let branch_picker_button = panel_button(branch)
264            .icon(IconName::GitBranch)
265            .icon_size(IconSize::Small)
266            .icon_color(Color::Placeholder)
267            .color(Color::Muted)
268            .icon_position(IconPosition::Start)
269            .tooltip(Tooltip::for_action_title(
270                "Switch Branch",
271                &zed_actions::git::Branch,
272            ))
273            .on_click(cx.listener(|_, _, window, cx| {
274                window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
275            }))
276            .style(ButtonStyle::Transparent);
277
278        let branch_picker = PopoverButton::new(
279            self.branch_list.clone(),
280            Corner::BottomLeft,
281            branch_picker_button,
282            Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
283        );
284
285        let close_kb_hint =
286            if let Some(close_kb) = ui::KeyBinding::for_action(&menu::Cancel, window, cx) {
287                Some(
288                    KeybindingHint::new(close_kb, cx.theme().colors().editor_background)
289                        .suffix("Cancel"),
290                )
291            } else {
292                None
293            };
294
295        let panel_editor_focus_handle =
296            git_panel.update(cx, |git_panel, cx| git_panel.editor_focus_handle(cx));
297
298        let commit_button = panel_filled_button(commit_label)
299            .tooltip(move |window, cx| {
300                Tooltip::for_action_in(tooltip, &Commit, &panel_editor_focus_handle, window, cx)
301            })
302            .disabled(!can_commit)
303            .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
304                this.git_panel
305                    .update(cx, |git_panel, cx| git_panel.commit_changes(window, cx));
306                cx.emit(DismissEvent);
307            }));
308
309        h_flex()
310            .group("commit_editor_footer")
311            .flex_none()
312            .w_full()
313            .items_center()
314            .justify_between()
315            .w_full()
316            .h(px(self.properties.footer_height))
317            .gap_1()
318            .child(
319                h_flex()
320                    .gap_1()
321                    .child(branch_picker.render(window, cx))
322                    .children(co_authors),
323            )
324            .child(div().flex_1())
325            .child(
326                h_flex()
327                    .items_center()
328                    .justify_end()
329                    .flex_none()
330                    .px_1()
331                    .gap_4()
332                    .children(close_kb_hint)
333                    .child(commit_button),
334            )
335    }
336
337    fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
338        cx.emit(DismissEvent);
339    }
340
341    fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
342        self.git_panel
343            .update(cx, |git_panel, cx| git_panel.commit_changes(window, cx));
344        cx.emit(DismissEvent);
345    }
346}
347
348impl Render for CommitModal {
349    fn render(&mut self, window: &mut Window, cx: &mut Context<'_, Self>) -> impl IntoElement {
350        let properties = self.properties;
351        let width = px(properties.modal_width);
352        let container_padding = px(properties.container_padding);
353        let border_radius = properties.modal_border_radius;
354        let editor_focus_handle = self.commit_editor.focus_handle(cx);
355
356        v_flex()
357            .id("commit-modal")
358            .key_context("GitCommit")
359            .on_action(cx.listener(Self::dismiss))
360            .on_action(cx.listener(Self::commit))
361            .on_action(
362                cx.listener(|this, _: &zed_actions::git::Branch, window, cx| {
363                    this.branch_list.update(cx, |branch_list, cx| {
364                        branch_list.menu_handle(window, cx).toggle(window, cx);
365                    })
366                }),
367            )
368            .elevation_3(cx)
369            .overflow_hidden()
370            .flex_none()
371            .relative()
372            .bg(cx.theme().colors().elevated_surface_background)
373            .rounded(px(border_radius))
374            .border_1()
375            .border_color(cx.theme().colors().border)
376            .w(width)
377            .p(container_padding)
378            .child(
379                v_flex()
380                    .id("editor-container")
381                    .justify_between()
382                    .p_2()
383                    .size_full()
384                    .gap_2()
385                    .rounded(properties.editor_border_radius())
386                    .overflow_hidden()
387                    .cursor_text()
388                    .bg(cx.theme().colors().editor_background)
389                    .border_1()
390                    .border_color(cx.theme().colors().border_variant)
391                    .on_click(cx.listener(move |_, _: &ClickEvent, window, _cx| {
392                        window.focus(&editor_focus_handle);
393                    }))
394                    .child(
395                        div()
396                            .flex_1()
397                            .size_full()
398                            .child(self.render_commit_editor(window, cx)),
399                    )
400                    .child(self.render_footer(window, cx)),
401            )
402    }
403}