gitkraft 0.7.3

GitKraft — Git IDE desktop application (Iced GUI)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! Main view entry point — builds the top-level layout shell and delegates to
//! feature views for each region of the UI.
//!
//! Layout (when a repo is open):
//! ```text
//! ┌──────────────────────────────────────────┐
//! │  header toolbar                          │
//! ├────────┬─────────────────┬───────────────┤
//! │        │                 │               │
//! │ side-  │  commit log     │  diff viewer  │
//! │ bar    │                 │               │
//! │        │                 │               │
//! ├────────┴─────────────────┴───────────────┤
//! │  staging area (unstaged | staged | msg)  │
//! ├──────────────────────────────────────────┤
//! │  status bar                              │
//! └──────────────────────────────────────────┘
//! ```
//!
//! All vertical and horizontal dividers between panes are **draggable** — the
//! user can resize the sidebar, commit-log, diff-viewer, and staging area by
//! grabbing the thin divider lines and dragging.
//!
//! The outer-most widget is a `mouse_area` that captures `on_release` events
//! unconditionally, and `on_move` events **only while a drag is in progress**.
//! This avoids firing `PaneDragMove → update() → view()` on every cursor
//! movement when no resize drag is active.

use iced::widget::{column, container, mouse_area, row, text, Space};
use iced::{Alignment, Element, Length};

use crate::features;
use crate::icons;
use crate::message::Message;
use crate::state::{DragTarget, DragTargetH, GitKraft};
use crate::theme;
use crate::theme::ThemeColors;
use crate::view_utils;
use crate::widgets;

impl GitKraft {
    /// Top-level view — called by the Iced runtime on every frame.
    pub fn view(&self) -> Element<'_, Message> {
        let c = self.colors();

        // ── Tab bar (always visible) ──────────────────────────────────────
        let tab_bar = widgets::tab_bar::view(self);

        if !self.has_repo() {
            // Show the tab bar above the welcome screen so users can
            // switch between tabs even when the active one has no repo.
            let welcome = features::repo::view::welcome_view(self);
            let outer = column![tab_bar, welcome]
                .width(Length::Fill)
                .height(Length::Fill);
            return container(outer)
                .width(Length::Fill)
                .height(Length::Fill)
                .style(theme::bg_style)
                .into();
        }

        let tab = self.active_tab();

        // ── Header toolbar ────────────────────────────────────────────────
        let header = widgets::header::view(self);

        // ── Sidebar (branches + stash + remotes) ──────────────────────────
        let sidebar: Element<'_, Message> = if self.sidebar_expanded {
            let branches = features::branches::view::view(self);
            let stash = features::stash::view::view(self);
            let remotes = features::remotes::view::view(self);

            let sidebar_content = container(
                column![
                    branches,
                    iced::widget::rule::horizontal(1),
                    stash,
                    iced::widget::rule::horizontal(1),
                    remotes
                ]
                .width(Length::Fill)
                .height(Length::Fill),
            )
            .width(Length::Fixed(self.sidebar_width))
            .height(Length::Fill)
            .style(theme::sidebar_style);

            let divider = widgets::divider::vertical_divider(DragTarget::SidebarRight, &c);

            row![sidebar_content, divider].height(Length::Fill).into()
        } else {
            Space::new().into()
        };

        // ── Commit log ────────────────────────────────────────────────────
        let commit_log_content = container(features::commits::view::view(self))
            .width(Length::Fixed(self.commit_log_width))
            .height(Length::Fill);

        let commit_divider = widgets::divider::vertical_divider(DragTarget::CommitLogRight, &c);

        let commit_log: Element<'_, Message> = row![commit_log_content, commit_divider]
            .height(Length::Fill)
            .into();

        // ── Diff viewer (fills all remaining horizontal space) ────────────
        let diff_viewer = container(features::diff::view::view(self))
            .width(Length::Fill)
            .height(Length::Fill);

        // ── Middle row: sidebar | divider | commit log | divider | diff ───
        let middle = row![sidebar, commit_log, diff_viewer]
            .height(Length::Fill)
            .width(Length::Fill);

        // ── Horizontal divider between middle and staging ─────────────────
        let h_divider = widgets::divider::horizontal_divider(DragTargetH::StagingTop, &c);

        // ── Staging area ──────────────────────────────────────────────────
        let staging = container(features::staging::view::view(self))
            .width(Length::Fill)
            .height(Length::Fixed(self.staging_height));

        // ── Status bar ────────────────────────────────────────────────────
        let status_bar = status_bar_view(self);

        // ── Error banner (if any) ─────────────────────────────────────────
        let mut main_col = column![].width(Length::Fill).height(Length::Fill);

        main_col = main_col.push(tab_bar);

        if let Some(ref err) = tab.error_message {
            main_col = main_col.push(error_banner(err, &c));
        }

        main_col = main_col
            .push(header)
            .push(middle)
            .push(h_divider)
            .push(staging)
            .push(status_bar);

        let body = container(main_col)
            .width(Length::Fill)
            .height(Length::Fill)
            .style(theme::bg_style);

        // on_move is always active so cursor_pos stays current for context
        // menus.  Virtual scrolling keeps the per-frame rebuild cost low
        // (~66 commit rows instead of 500) so this is acceptable.
        let ma: Element<'_, Message> = mouse_area(body)
            .on_move(|p| Message::PaneDragMove(p.x, p.y))
            .on_release(Message::PaneDragEnd)
            .into();

        // ── Search overlay ────────────────────────────────────────────────
        let ma: Element<'_, Message> = if self.search_visible {
            let search_panel = search_overlay(self, &c);
            iced::widget::stack![ma, search_panel].into()
        } else {
            ma
        };

        // ── Context menu overlay ──────────────────────────────────────────
        if self.active_tab().context_menu.is_some() {
            // Transparent full-screen backdrop — clicking it dismisses the menu.
            let backdrop = mouse_area(
                container(Space::new().width(Length::Fill).height(Length::Fill))
                    .style(theme::backdrop_style),
            )
            .on_press(Message::CloseContextMenu)
            .on_right_press(Message::CloseContextMenu);

            let (menu_x, menu_y) = context_menu_position(self);
            let menu_panel = context_menu_panel(self, &c);

            let positioned = column![
                Space::new().height(menu_y),
                row![Space::new().width(menu_x), menu_panel,],
            ]
            .width(Length::Fill)
            .height(Length::Fill);

            iced::widget::stack![ma, backdrop, positioned].into()
        } else {
            ma
        }
    }
}

/// Render the status bar at the very bottom of the window.
fn status_bar_view(state: &GitKraft) -> Element<'_, Message> {
    let tab = state.active_tab();
    let c = state.colors();

    let status_text = if tab.is_loading {
        tab.status_message
            .as_deref()
            .unwrap_or("Loading…")
            .to_string()
    } else {
        tab.status_message.as_deref().unwrap_or("Ready").to_string()
    };

    let status_label = text(status_text).size(12).color(c.text_secondary);

    let branch_info: Element<'_, Message> = if let Some(ref branch) = tab.current_branch {
        let icon = icon!(icons::GIT_BRANCH, 12, c.accent);
        let label = text(branch.as_str()).size(12).color(c.text_primary);
        row![icon, Space::new().width(4), label]
            .align_y(Alignment::Center)
            .into()
    } else {
        Space::new().into()
    };

    let repo_state_info: Element<'_, Message> = if let Some(ref info) = tab.repo_info {
        let state_str = format!("{}", info.state);
        if state_str != "Clean" {
            text(state_str).size(12).color(c.yellow).into()
        } else {
            Space::new().into()
        }
    } else {
        Space::new().into()
    };

    let changes_summary = {
        let unstaged_count = tab.unstaged_changes.len();
        let staged_count = tab.staged_changes.len();
        if unstaged_count > 0 || staged_count > 0 {
            text(format!("{unstaged_count} unstaged, {staged_count} staged"))
                .size(12)
                .color(c.muted)
        } else {
            text("Working tree clean").size(12).color(c.muted)
        }
    };

    let zoom_label: Element<'_, Message> = if (state.ui_scale - 1.0).abs() > 0.01 {
        text(format!("{}%", (state.ui_scale * 100.0).round() as u32))
            .size(11)
            .color(c.muted)
            .into()
    } else {
        Space::new().into()
    };

    let bar = row![
        status_label,
        Space::new().width(Length::Fill),
        changes_summary,
        Space::new().width(16),
        zoom_label,
        Space::new().width(16),
        repo_state_info,
        Space::new().width(16),
        branch_info,
    ]
    .align_y(Alignment::Center)
    .padding([4, 10])
    .width(Length::Fill);

    container(bar)
        .width(Length::Fill)
        .style(theme::header_style)
        .into()
}

/// Render an error banner at the top of the window with a dismiss button.
fn error_banner<'a>(message: &str, c: &ThemeColors) -> Element<'a, Message> {
    let icon = icon!(icons::EXCLAMATION_TRIANGLE, 14, c.red);

    let msg = text(message.to_string()).size(13).color(c.text_primary);

    let dismiss = iced::widget::button(icon!(icons::X_CIRCLE, 14, c.text_secondary))
        .padding([2, 6])
        .on_press(Message::DismissError);

    let banner_row = row![
        icon,
        Space::new().width(8),
        msg,
        Space::new().width(Length::Fill),
        dismiss,
    ]
    .align_y(Alignment::Center)
    .padding([6, 12])
    .width(Length::Fill);

    container(banner_row)
        .width(Length::Fill)
        .style(theme::error_banner_style)
        .into()
}

/// Approximate pixel position of the context menu based on what was right-clicked.
fn context_menu_position(state: &GitKraft) -> (f32, f32) {
    // Use the position that was frozen when the menu opened, not the live
    // cursor_pos — otherwise the panel would follow the mouse.
    // Nudge right/down by 2 px so the pointer tip sits just inside the panel.
    let (x, y) = state.active_tab().context_menu_pos;
    ((x + 2.0).max(2.0), (y + 2.0).max(2.0))
}

/// Render the search overlay — a centered panel with an input and results list.
fn search_overlay<'a>(state: &'a GitKraft, c: &ThemeColors) -> Element<'a, Message> {
    use iced::widget::{
        button, column, container, mouse_area, row, scrollable, text, text_input, Space,
    };
    use iced::{Alignment, Length};

    let input = text_input("Search commits…", &state.search_query)
        .on_input(Message::SearchQueryChanged)
        .on_submit(Message::ConfirmSearchResult)
        .padding(10)
        .size(16);

    let mut results_col = column![].spacing(2).width(Length::Fill);

    if state.search_results.is_empty() && state.search_query.len() >= 2 {
        results_col = results_col.push(
            container(text("No results found").size(13).color(c.muted))
                .padding([12, 8])
                .width(Length::Fill)
                .center_x(Length::Fill),
        );
    }

    for (i, commit) in state.search_results.iter().take(50).enumerate() {
        let is_selected = state.search_selected == Some(i);
        let bg_style = if is_selected {
            theme::selected_row_style as fn(&iced::Theme) -> iced::widget::container::Style
        } else {
            theme::surface_style as fn(&iced::Theme) -> iced::widget::container::Style
        };

        let oid_label = text(&commit.short_oid)
            .size(12)
            .color(c.accent)
            .font(iced::Font::MONOSPACE);

        let summary_label = text(&commit.summary).size(13).color(c.text_primary);

        let author_label = text(&commit.author_name).size(11).color(c.text_secondary);

        let time_label = text(commit.relative_time()).size(11).color(c.muted);

        let row_content = row![
            oid_label,
            Space::new().width(8),
            summary_label,
            Space::new().width(Length::Fill),
            author_label,
            Space::new().width(8),
            time_label,
        ]
        .align_y(Alignment::Center)
        .padding([6, 10]);

        let result_btn = button(row_content)
            .padding(0)
            .width(Length::Fill)
            .style(theme::ghost_button)
            .on_press(Message::ConfirmSearchResult);

        let result_row: Element<'a, Message> =
            mouse_area(container(result_btn).width(Length::Fill).style(bg_style))
                .on_press(Message::SelectSearchResult(i))
                .on_right_press(Message::OpenSearchResultContextMenu(i))
                .into();

        results_col = results_col.push(result_row);
    }

    let result_count = if !state.search_results.is_empty() {
        text(format!("{} result(s)", state.search_results.len()))
            .size(11)
            .color(c.muted)
    } else {
        text("").size(1)
    };

    let close_btn = button(text("\u{2715}").size(14).color(c.text_secondary))
        .padding([4, 8])
        .style(theme::ghost_button)
        .on_press(Message::ToggleSearch);

    let header = row![
        icon!(icons::CLOCK_HISTORY, 16, c.accent),
        Space::new().width(8),
        text("Search Commits").size(16).color(c.text_primary),
        Space::new().width(Length::Fill),
        result_count,
        Space::new().width(8),
        close_btn,
    ]
    .align_y(Alignment::Center)
    .padding([8, 12]);

    let scrollable_results = scrollable(results_col)
        .height(Length::Fill)
        .direction(crate::view_utils::thin_scrollbar())
        .style(crate::theme::overlay_scrollbar);

    let panel = container(
        column![header, input, scrollable_results,]
            .width(Length::Fill)
            .height(Length::Fill)
            .spacing(4),
    )
    .width(700)
    .height(500)
    .style(theme::context_menu_style)
    .padding(8);

    // Center the panel on screen with a backdrop
    let backdrop = mouse_area(
        container(Space::new().width(Length::Fill).height(Length::Fill))
            .style(theme::backdrop_style),
    )
    .on_press(Message::ToggleSearch);

    let centered = container(panel)
        .width(Length::Fill)
        .height(Length::Fill)
        .center_x(Length::Fill)
        .center_y(Length::Fill);

    iced::widget::stack![backdrop, centered].into()
}

/// Build the context menu panel widget for the currently active menu.
fn context_menu_panel<'a>(state: &'a GitKraft, c: &ThemeColors) -> Element<'a, Message> {
    use iced::widget::{button, column, container, row, text, Space};
    use iced::{Alignment, Length};

    let text_primary = c.text_primary;
    let menu_item = move |label: &str, msg: Message| {
        button(
            row![
                Space::new().width(4),
                text(label.to_string()).size(13).color(text_primary),
            ]
            .align_y(Alignment::Center),
        )
        .padding([7, 12])
        .width(Length::Fill)
        .style(theme::context_menu_item)
        .on_press(msg)
    };

    let content: Element<'a, Message> = match &state.active_tab().context_menu {
        Some(crate::state::ContextMenu::Branch {
            name, is_current, ..
        }) => {
            let tab = state.active_tab();
            let remote = tab
                .remotes
                .first()
                .map(|r| r.name.clone())
                .unwrap_or_else(|| "origin".to_string());

            // Look up the branch tip OID for SHA copy and tag creation.
            let tip_oid: Option<String> = tab
                .branches
                .iter()
                .find(|b| &b.name == name)
                .and_then(|b| b.target_oid.clone());

            let header =
                view_utils::context_menu_header::<Message>(format!("Branch: {name}"), c.muted);

            let mut col = column![header];

            // Group 1: Checkout (when not on this branch)
            if !is_current {
                col = col.push(menu_item("Checkout", Message::CheckoutBranch(name.clone())));
            }

            // Group 2: Remote sync
            let push_label = format!("Push to {remote}");
            let pull_label = format!("Pull from {remote} (rebase)");
            col = col
                .push(menu_item(&push_label, Message::PushBranch(name.clone())))
                .push(menu_item(&pull_label, Message::PullBranch(name.clone())));

            // Group 3: Rebase / merge
            col = col.push(view_utils::context_menu_separator::<Message>());
            let rebase_label = format!("Rebase current onto '{name}'");
            col = col.push(menu_item(&rebase_label, Message::RebaseOnto(name.clone())));
            if !is_current {
                col = col.push(menu_item(
                    "Merge into current branch",
                    Message::MergeBranch(name.clone()),
                ));
            }

            // Group 4: Branch management
            col = col.push(view_utils::context_menu_separator::<Message>());
            col = col
                .push(menu_item(
                    "Rename\u{2026}",
                    Message::BeginRenameBranch(name.clone()),
                ))
                .push(menu_item("Delete", Message::DeleteBranch(name.clone())));

            // Group 5: Copy info
            col = col.push(view_utils::context_menu_separator::<Message>());
            col = col.push(menu_item(
                "Copy branch name",
                Message::CopyText(name.clone()),
            ));
            if let Some(ref oid) = tip_oid {
                col = col.push(menu_item(
                    "Copy tip commit SHA",
                    Message::CopyText(oid.clone()),
                ));
            }

            // Group 6: Tag creation
            if tip_oid.is_some() {
                col = col.push(view_utils::context_menu_separator::<Message>());
                let oid = tip_oid.clone().unwrap();
                col = col
                    .push(menu_item(
                        "Create tag here",
                        Message::BeginCreateTag(oid.clone(), false),
                    ))
                    .push(menu_item(
                        "Create annotated tag here\u{2026}",
                        Message::BeginCreateTag(oid, true),
                    ));
            }

            col.into()
        }

        Some(crate::state::ContextMenu::RemoteBranch { name }) => {
            // Extract remote and branch parts for display
            let (remote, short_name) = name.split_once('/').unwrap_or(("", name.as_str()));

            let header =
                view_utils::context_menu_header::<Message>(format!("Remote: {name}"), c.muted);

            // Check if a local branch with the same short name already exists
            let local_exists =
                state.active_tab().branches.iter().any(|b| {
                    b.branch_type == gitkraft_core::BranchType::Local && b.name == short_name
                });

            let mut col = column![header];

            // Checkout (only if no local branch with same name exists)
            if !local_exists {
                col = col.push(menu_item(
                    &format!("Checkout as '{short_name}'"),
                    Message::CheckoutRemoteBranch(name.clone()),
                ));
            }

            // Delete from remote
            col = col.push(view_utils::context_menu_separator::<Message>());
            col = col.push(menu_item(
                &format!("Delete from {remote}"),
                Message::DeleteRemoteBranch(name.clone()),
            ));

            // Copy info
            col = col.push(view_utils::context_menu_separator::<Message>());
            col = col.push(menu_item(
                "Copy branch name",
                Message::CopyText(name.clone()),
            ));
            col = col.push(menu_item(
                &format!("Copy short name '{short_name}'"),
                Message::CopyText(short_name.to_string()),
            ));

            // Look up tip OID
            let tip_oid: Option<String> = state
                .active_tab()
                .branches
                .iter()
                .find(|b| &b.name == name)
                .and_then(|b| b.target_oid.clone());

            if let Some(ref oid) = tip_oid {
                col = col.push(menu_item(
                    "Copy tip commit SHA",
                    Message::CopyText(oid.clone()),
                ));
            }

            col.into()
        }

        Some(crate::state::ContextMenu::Commit { index, oid }) => {
            let tab = state.active_tab();
            let short = gitkraft_core::utils::short_oid_str(oid);
            let msg_text = tab
                .commits
                .get(*index)
                .map(|c| c.message.clone())
                .unwrap_or_default();

            let header =
                view_utils::context_menu_header::<Message>(format!("Commit: {short}"), c.muted);

            column![
                header,
                menu_item(
                    "Checkout (detached HEAD)",
                    Message::CheckoutCommitDetached(oid.clone()),
                ),
                menu_item(
                    "Rebase current branch onto this",
                    Message::RebaseOntoCommit(oid.clone()),
                ),
                menu_item("Revert commit", Message::RevertCommit(oid.clone())),
                menu_item(
                    "Reset here — soft (keep staged)",
                    Message::ResetSoft(oid.clone())
                ),
                menu_item(
                    "Reset here — mixed (keep files)",
                    Message::ResetMixed(oid.clone())
                ),
                menu_item(
                    "Reset here — hard (discard all)",
                    Message::ResetHard(oid.clone())
                ),
                menu_item("Copy commit SHA", Message::CopyText(oid.clone())),
                menu_item("Copy commit message", Message::CopyText(msg_text)),
            ]
            .into()
        }

        Some(crate::state::ContextMenu::Stash { index }) => {
            let index = *index;
            let header =
                view_utils::context_menu_header::<Message>(format!("stash@{{{index}}}"), c.muted);

            column![
                header,
                menu_item("View diff", Message::ViewStashDiff(index)),
                menu_item("Apply (keep stash)", Message::StashApply(index)),
                menu_item("Pop (apply + remove)", Message::StashPop(index)),
                view_utils::context_menu_separator::<Message>(),
                menu_item("Drop (delete)", Message::StashDrop(index)),
            ]
            .into()
        }

        Some(crate::state::ContextMenu::UnstagedFile { path }) => {
            let selected_count = state.active_tab().selected_unstaged.len();
            let is_multi = selected_count > 1;

            let header_text = if is_multi {
                format!("{} files selected", selected_count)
            } else {
                format!("Unstaged: {}", path.rsplit('/').next().unwrap_or(path))
            };
            let header = view_utils::context_menu_header::<Message>(header_text, c.muted);

            let mut col = column![header];

            if is_multi {
                // Batch operations for multi-select
                col = col.push(menu_item(
                    &format!("Stage {} file(s)", selected_count),
                    Message::StageSelected,
                ));
                col = col.push(view_utils::context_menu_separator::<Message>());
                col = col.push(menu_item(
                    &format!("Discard {} file(s)", selected_count),
                    Message::DiscardSelected,
                ));
            } else {
                // Single file operations
                let diff = state
                    .active_tab()
                    .unstaged_changes
                    .iter()
                    .find(|d| d.display_path() == path.as_str())
                    .cloned()
                    .unwrap_or_else(|| gitkraft_core::DiffInfo {
                        old_file: String::new(),
                        new_file: path.clone(),
                        status: gitkraft_core::FileStatus::Modified,
                        hunks: Vec::new(),
                    });

                col = col.push(menu_item("View diff", Message::SelectDiff(diff)));
                col = col.push(menu_item("Stage file", Message::StageFile(path.clone())));
                col = col.push(view_utils::context_menu_separator::<Message>());
                col = col.push(menu_item(
                    "Discard changes",
                    Message::DiscardFile(path.clone()),
                ));
            }

            col = col.push(view_utils::context_menu_separator::<Message>());
            col = col.push(menu_item("Copy file path", Message::CopyText(path.clone())));
            col = col.push(menu_item(
                "Open in editor",
                Message::OpenInEditor(path.clone()),
            ));
            col = col.push(menu_item(
                "Open in default program",
                Message::OpenInDefaultProgram(path.clone()),
            ));
            col = col.push(menu_item(
                "Show in folder",
                Message::ShowInFolder(path.clone()),
            ));

            col.into()
        }

        Some(crate::state::ContextMenu::StagedFile { path }) => {
            let selected_count = state.active_tab().selected_staged.len();
            let is_multi = selected_count > 1;

            let header_text = if is_multi {
                format!("{} files selected", selected_count)
            } else {
                format!("Staged: {}", path.rsplit('/').next().unwrap_or(path))
            };
            let header = view_utils::context_menu_header::<Message>(header_text, c.muted);

            let mut col = column![header];

            if is_multi {
                col = col.push(menu_item(
                    &format!("Unstage {} file(s)", selected_count),
                    Message::UnstageSelected,
                ));
                col = col.push(view_utils::context_menu_separator::<Message>());
                col = col.push(menu_item(
                    &format!("Discard {} file(s)", selected_count),
                    Message::DiscardSelected,
                ));
            } else {
                let diff = state
                    .active_tab()
                    .staged_changes
                    .iter()
                    .find(|d| d.display_path() == path.as_str())
                    .cloned()
                    .unwrap_or_else(|| gitkraft_core::DiffInfo {
                        old_file: String::new(),
                        new_file: path.clone(),
                        status: gitkraft_core::FileStatus::Modified,
                        hunks: Vec::new(),
                    });

                col = col.push(menu_item("View diff", Message::SelectDiff(diff)));
                col = col.push(menu_item(
                    "Unstage file",
                    Message::UnstageFile(path.clone()),
                ));
                col = col.push(view_utils::context_menu_separator::<Message>());
                col = col.push(menu_item(
                    "Discard changes",
                    Message::DiscardStagedFile(path.clone()),
                ));
            }

            col = col.push(view_utils::context_menu_separator::<Message>());
            col = col.push(menu_item("Copy file path", Message::CopyText(path.clone())));
            col = col.push(menu_item(
                "Open in editor",
                Message::OpenInEditor(path.clone()),
            ));
            col = col.push(menu_item(
                "Open in default program",
                Message::OpenInDefaultProgram(path.clone()),
            ));
            col = col.push(menu_item(
                "Show in folder",
                Message::ShowInFolder(path.clone()),
            ));

            col.into()
        }

        Some(crate::state::ContextMenu::CommitFile { oid, file_path }) => {
            let file_name = file_path.rsplit('/').next().unwrap_or(file_path);
            let header =
                view_utils::context_menu_header::<Message>(format!("File: {}", file_name), c.muted);

            column![
                header,
                menu_item(
                    "Diff with working tree",
                    Message::DiffFileWithWorkingTree(oid.clone(), file_path.clone()),
                ),
                view_utils::context_menu_separator::<Message>(),
                menu_item("Copy file path", Message::CopyText(file_path.clone()),),
                menu_item("Copy commit SHA", Message::CopyText(oid.clone()),),
                menu_item("Open in editor", Message::OpenInEditor(file_path.clone()),),
                menu_item("Show in folder", Message::ShowInFolder(file_path.clone()),),
            ]
            .into()
        }

        None => Space::new().into(),
    };

    container(content)
        .width(280)
        .style(theme::context_menu_style)
        .into()
}