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 project::DisableAiSettings;
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::ChevronDown).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.downgrade();
299 move |_, cx| {
300 git_panel
301 .update(cx, |git_panel, cx| {
302 git_panel.toggle_amend_pending(cx);
303 })
304 .ok();
305 }
306 },
307 )
308 })
309 .toggleable_entry(
310 "Signoff",
311 signoff_enabled,
312 IconPosition::Start,
313 Some(Box::new(Signoff)),
314 {
315 let git_panel = git_panel_entity.clone();
316 move |window, cx| {
317 git_panel.update(cx, |git_panel, cx| {
318 git_panel.toggle_signoff_enabled(&Signoff, window, cx);
319 })
320 }
321 },
322 )
323 }))
324 }
325 })
326 .with_handle(self.commit_menu_handle.clone())
327 .anchor(Corner::TopRight)
328 }
329
330 pub fn render_footer(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
331 let (
332 can_commit,
333 tooltip,
334 commit_label,
335 co_authors,
336 generate_commit_message,
337 active_repo,
338 is_amend_pending,
339 is_signoff_enabled,
340 ) = self.git_panel.update(cx, |git_panel, cx| {
341 let (can_commit, tooltip) = git_panel.configure_commit_button(cx);
342 let title = git_panel.commit_button_title();
343 let co_authors = git_panel.render_co_authors(cx);
344 let generate_commit_message = git_panel.render_generate_commit_message_button(cx);
345 let active_repo = git_panel.active_repository.clone();
346 let is_amend_pending = git_panel.amend_pending();
347 let is_signoff_enabled = git_panel.signoff_enabled();
348 (
349 can_commit,
350 tooltip,
351 title,
352 co_authors,
353 generate_commit_message,
354 active_repo,
355 is_amend_pending,
356 is_signoff_enabled,
357 )
358 });
359
360 let branch = active_repo
361 .as_ref()
362 .and_then(|repo| repo.read(cx).branch.as_ref())
363 .map(|b| b.name().to_owned())
364 .unwrap_or_else(|| "<no branch>".to_owned());
365
366 let branch_picker_button = panel_button(branch)
367 .icon(IconName::GitBranch)
368 .icon_size(IconSize::Small)
369 .icon_color(Color::Placeholder)
370 .color(Color::Muted)
371 .icon_position(IconPosition::Start)
372 .tooltip(Tooltip::for_action_title(
373 "Switch Branch",
374 &zed_actions::git::Branch,
375 ))
376 .on_click(cx.listener(|_, _, window, cx| {
377 window.dispatch_action(zed_actions::git::Branch.boxed_clone(), cx);
378 }))
379 .style(ButtonStyle::Transparent);
380
381 let branch_picker = PopoverMenu::new("popover-button")
382 .menu(move |window, cx| Some(branch_picker::popover(active_repo.clone(), window, cx)))
383 .with_handle(self.branch_list_handle.clone())
384 .trigger_with_tooltip(
385 branch_picker_button,
386 Tooltip::for_action_title("Switch Branch", &zed_actions::git::Branch),
387 )
388 .anchor(Corner::BottomLeft)
389 .offset(gpui::Point {
390 x: px(0.0),
391 y: px(-2.0),
392 });
393 let focus_handle = self.focus_handle(cx);
394
395 let close_kb_hint =
396 if let Some(close_kb) = ui::KeyBinding::for_action(&menu::Cancel, window, cx) {
397 Some(
398 KeybindingHint::new(close_kb, cx.theme().colors().editor_background)
399 .suffix("Cancel"),
400 )
401 } else {
402 None
403 };
404
405 h_flex()
406 .group("commit_editor_footer")
407 .flex_none()
408 .w_full()
409 .items_center()
410 .justify_between()
411 .w_full()
412 .h(px(self.properties.footer_height))
413 .gap_1()
414 .child(
415 h_flex()
416 .gap_1()
417 .flex_shrink()
418 .overflow_x_hidden()
419 .child(
420 h_flex()
421 .flex_shrink()
422 .overflow_x_hidden()
423 .child(branch_picker),
424 )
425 .children(generate_commit_message)
426 .children(co_authors),
427 )
428 .child(div().flex_1())
429 .child(
430 h_flex()
431 .items_center()
432 .justify_end()
433 .flex_none()
434 .px_1()
435 .gap_4()
436 .children(close_kb_hint)
437 .child(SplitButton::new(
438 ui::ButtonLike::new_rounded_left(ElementId::Name(
439 format!("split-button-left-{}", commit_label).into(),
440 ))
441 .layer(ui::ElevationIndex::ModalSurface)
442 .size(ui::ButtonSize::Compact)
443 .child(
444 div()
445 .child(Label::new(commit_label).size(LabelSize::Small))
446 .mr_0p5(),
447 )
448 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
449 telemetry::event!("Git Committed", source = "Git Modal");
450 this.git_panel.update(cx, |git_panel, cx| {
451 git_panel.commit_changes(
452 CommitOptions {
453 amend: is_amend_pending,
454 signoff: is_signoff_enabled,
455 },
456 window,
457 cx,
458 )
459 });
460 cx.emit(DismissEvent);
461 }))
462 .disabled(!can_commit)
463 .tooltip({
464 let focus_handle = focus_handle.clone();
465 move |window, cx| {
466 if can_commit {
467 Tooltip::with_meta_in(
468 tooltip,
469 Some(&git::Commit),
470 format!(
471 "git commit{}{}",
472 if is_amend_pending { " --amend" } else { "" },
473 if is_signoff_enabled { " --signoff" } else { "" }
474 ),
475 &focus_handle.clone(),
476 window,
477 cx,
478 )
479 } else {
480 Tooltip::simple(tooltip, cx)
481 }
482 }
483 }),
484 self.render_git_commit_menu(
485 ElementId::Name(format!("split-button-right-{}", commit_label).into()),
486 Some(focus_handle.clone()),
487 )
488 .into_any_element(),
489 )),
490 )
491 }
492
493 fn dismiss(&mut self, _: &menu::Cancel, _: &mut Window, cx: &mut Context<Self>) {
494 if self.git_panel.read(cx).amend_pending() {
495 self.git_panel
496 .update(cx, |git_panel, cx| git_panel.set_amend_pending(false, cx));
497 } else {
498 cx.emit(DismissEvent);
499 }
500 }
501
502 fn commit(&mut self, _: &git::Commit, window: &mut Window, cx: &mut Context<Self>) {
503 if self.git_panel.read(cx).amend_pending() {
504 return;
505 }
506 telemetry::event!("Git Committed", source = "Git Modal");
507 self.git_panel.update(cx, |git_panel, cx| {
508 git_panel.commit_changes(
509 CommitOptions {
510 amend: false,
511 signoff: git_panel.signoff_enabled(),
512 },
513 window,
514 cx,
515 )
516 });
517 cx.emit(DismissEvent);
518 }
519
520 fn amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
521 if self
522 .git_panel
523 .read(cx)
524 .active_repository
525 .as_ref()
526 .and_then(|repo| repo.read(cx).head_commit.as_ref())
527 .is_none()
528 {
529 return;
530 }
531 if !self.git_panel.read(cx).amend_pending() {
532 self.git_panel.update(cx, |git_panel, cx| {
533 git_panel.set_amend_pending(true, cx);
534 git_panel.load_last_commit_message_if_empty(cx);
535 });
536 } else {
537 telemetry::event!("Git Amended", source = "Git Modal");
538 self.git_panel.update(cx, |git_panel, cx| {
539 git_panel.set_amend_pending(false, cx);
540 git_panel.commit_changes(
541 CommitOptions {
542 amend: true,
543 signoff: git_panel.signoff_enabled(),
544 },
545 window,
546 cx,
547 );
548 });
549 cx.emit(DismissEvent);
550 }
551 }
552
553 fn toggle_branch_selector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
554 if self.branch_list_handle.is_focused(window, cx) {
555 self.focus_handle(cx).focus(window)
556 } else {
557 self.branch_list_handle.toggle(window, cx);
558 }
559 }
560}
561
562impl Render for CommitModal {
563 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
564 let properties = self.properties;
565 let width = px(properties.modal_width);
566 let container_padding = px(properties.container_padding);
567 let border_radius = properties.modal_border_radius;
568 let editor_focus_handle = self.commit_editor.focus_handle(cx);
569
570 v_flex()
571 .id("commit-modal")
572 .key_context("GitCommit")
573 .on_action(cx.listener(Self::dismiss))
574 .on_action(cx.listener(Self::commit))
575 .on_action(cx.listener(Self::amend))
576 .when(!DisableAiSettings::get_global(cx).disable_ai, |this| {
577 this.on_action(cx.listener(|this, _: &GenerateCommitMessage, _, cx| {
578 this.git_panel.update(cx, |panel, cx| {
579 panel.generate_commit_message(cx);
580 })
581 }))
582 })
583 .on_action(
584 cx.listener(|this, _: &zed_actions::git::Branch, window, cx| {
585 this.toggle_branch_selector(window, cx);
586 }),
587 )
588 .on_action(
589 cx.listener(|this, _: &zed_actions::git::CheckoutBranch, window, cx| {
590 this.toggle_branch_selector(window, cx);
591 }),
592 )
593 .on_action(
594 cx.listener(|this, _: &zed_actions::git::Switch, window, cx| {
595 this.toggle_branch_selector(window, cx);
596 }),
597 )
598 .elevation_3(cx)
599 .overflow_hidden()
600 .flex_none()
601 .relative()
602 .bg(cx.theme().colors().elevated_surface_background)
603 .rounded(px(border_radius))
604 .border_1()
605 .border_color(cx.theme().colors().border)
606 .w(width)
607 .p(container_padding)
608 .child(
609 v_flex()
610 .id("editor-container")
611 .justify_between()
612 .p_2()
613 .size_full()
614 .gap_2()
615 .rounded(properties.editor_border_radius())
616 .overflow_hidden()
617 .cursor_text()
618 .bg(cx.theme().colors().editor_background)
619 .border_1()
620 .border_color(cx.theme().colors().border_variant)
621 .on_click(cx.listener(move |_, _: &ClickEvent, window, _cx| {
622 window.focus(&editor_focus_handle);
623 }))
624 .child(
625 div()
626 .flex_1()
627 .size_full()
628 .child(self.render_commit_editor(window, cx)),
629 )
630 .child(self.render_footer(window, cx)),
631 )
632 }
633}