Skip to main content

gitkraft_gui/features/commits/
view.rs

1//! Commit log view — scrollable list of commits with highlighted selection.
2//!
3//! Commit summaries are pre-truncated with "…" based on the actual available
4//! pixel width so that each row stays on exactly one line — matching
5//! GitKraken's behaviour.
6
7//
8// Renders only the rows currently visible in the viewport plus a small
9// overscan buffer.  Space widgets above and below maintain the correct
10// total scroll height so the scrollbar behaves naturally.
11
12use iced::widget::{button, column, container, mouse_area, row, scrollable, text, Row, Space};
13use iced::{Alignment, Color, Element, Length};
14
15use crate::icons;
16use crate::message::Message;
17use crate::state::{GitKraft, RepoTab};
18use crate::theme;
19use crate::theme::ThemeColors;
20use crate::view_utils;
21use crate::view_utils::truncate_to_fit;
22
23/// Estimated height of one commit row in pixels.  Used for virtual scrolling.
24/// A slight over- or under-estimate only affects scrollbar thumb precision,
25/// not correctness of the rendered content.
26const ROW_HEIGHT: f32 = 26.0;
27
28/// Rows rendered above and below the visible window (avoids pop-in during
29/// fast scrolling).
30const OVERSCAN: usize = 8;
31
32/// Assumed visible rows (covers a 1300 px tall viewport at ROW_HEIGHT).
33/// Making this generous costs almost nothing — we cap at `total` anyway.
34const VISIBLE_ROWS: usize = 50;
35
36/// Per-tab stable scroll id — Iced maintains a separate scroll position for
37/// each open tab so no programmatic `scroll_to` is needed on tab switches.
38pub fn commit_log_scroll_id(tab_index: usize) -> scrollable::Id {
39    scrollable::Id::new(format!("commit_log_{tab_index}"))
40}
41
42// ── graph_cell ────────────────────────────────────────────────────────────────
43
44/// Build a small `Row` of individually-coloured text elements representing one
45/// row of the commit graph.
46fn graph_cell<'a>(
47    graph_row: &gitkraft_core::GraphRow,
48    graph_colors: &[Color; 8],
49) -> Row<'a, Message> {
50    let width = graph_row.width;
51    let len = graph_colors.len();
52
53    if width == 0 {
54        return Row::new().push(
55            text("● ")
56                .font(iced::Font::MONOSPACE)
57                .size(12)
58                .color(graph_colors[graph_row.node_color % len]),
59        );
60    }
61
62    let mut column_passthrough: Vec<Option<usize>> = vec![None; width];
63    let mut has_left_cross = false;
64    let mut has_right_cross = false;
65    let mut left_cross_color: usize = 0;
66    let mut right_cross_color: usize = 0;
67    let mut cross_left_col: usize = graph_row.node_column;
68    let mut cross_right_col: usize = graph_row.node_column;
69
70    for edge in &graph_row.edges {
71        if edge.from_column == edge.to_column {
72            column_passthrough[edge.to_column] = Some(edge.color_index);
73        } else {
74            let target = edge.to_column;
75            if target < graph_row.node_column {
76                has_left_cross = true;
77                left_cross_color = edge.color_index;
78                if target < cross_left_col {
79                    cross_left_col = target;
80                }
81            } else if target > graph_row.node_column {
82                has_right_cross = true;
83                right_cross_color = edge.color_index;
84                if target > cross_right_col {
85                    cross_right_col = target;
86                }
87            }
88        }
89    }
90
91    let mut cells: Vec<Element<'a, Message>> = Vec::with_capacity(width);
92
93    for col in 0..width {
94        if col == graph_row.node_column {
95            let color = graph_colors[graph_row.node_color % len];
96            cells.push(
97                text("● ")
98                    .font(iced::Font::MONOSPACE)
99                    .size(12)
100                    .color(color)
101                    .into(),
102            );
103        } else if let Some(ci) = column_passthrough.get(col).copied().flatten() {
104            let in_left = has_left_cross && col >= cross_left_col && col < graph_row.node_column;
105            let in_right = has_right_cross && col > graph_row.node_column && col <= cross_right_col;
106
107            if in_left || in_right {
108                let cross_ci = if in_left {
109                    left_cross_color
110                } else {
111                    right_cross_color
112                };
113                cells.push(
114                    text("├─")
115                        .font(iced::Font::MONOSPACE)
116                        .size(12)
117                        .color(graph_colors[cross_ci % len])
118                        .into(),
119                );
120            } else {
121                cells.push(
122                    text("│ ")
123                        .font(iced::Font::MONOSPACE)
124                        .size(12)
125                        .color(graph_colors[ci % len])
126                        .into(),
127                );
128            }
129        } else {
130            let in_left = has_left_cross && col >= cross_left_col && col < graph_row.node_column;
131            let in_right = has_right_cross && col > graph_row.node_column && col <= cross_right_col;
132
133            if in_left {
134                let color = graph_colors[left_cross_color % len];
135                if col == cross_left_col {
136                    cells.push(
137                        text("╭─")
138                            .font(iced::Font::MONOSPACE)
139                            .size(12)
140                            .color(color)
141                            .into(),
142                    );
143                } else {
144                    cells.push(
145                        text("──")
146                            .font(iced::Font::MONOSPACE)
147                            .size(12)
148                            .color(color)
149                            .into(),
150                    );
151                }
152            } else if in_right {
153                let color = graph_colors[right_cross_color % len];
154                if col == cross_right_col {
155                    cells.push(
156                        text("─╮")
157                            .font(iced::Font::MONOSPACE)
158                            .size(12)
159                            .color(color)
160                            .into(),
161                    );
162                } else {
163                    cells.push(
164                        text("──")
165                            .font(iced::Font::MONOSPACE)
166                            .size(12)
167                            .color(color)
168                            .into(),
169                    );
170                }
171            } else {
172                cells.push(text("  ").font(iced::Font::MONOSPACE).size(12).into());
173            }
174        }
175    }
176
177    Row::with_children(cells).align_y(Alignment::Center)
178}
179
180// ── single row element ────────────────────────────────────────────────────────
181
182/// Build the widget for a single commit row.
183fn commit_row_element<'a>(
184    tab: &'a RepoTab,
185    idx: usize,
186    c: &ThemeColors,
187    available_summary_px: f32,
188) -> Element<'a, Message> {
189    let commit = &tab.commits[idx];
190    let is_selected = tab.selected_commit == Some(idx);
191
192    // Graph column
193    let graph_elem: Element<'_, Message> = if let Some(grow) = tab.graph_rows.get(idx) {
194        graph_cell(grow, &c.graph_colors).into()
195    } else {
196        text("").into()
197    };
198
199    let oid_label = text(commit.short_oid.as_str())
200        .size(12)
201        .color(c.accent)
202        .font(iced::Font::MONOSPACE);
203
204    // Use pre-computed display strings; fall back gracefully if out of sync.
205    let (summary_str, time_str, author_str) = tab
206        .commit_display
207        .get(idx)
208        .map(|(s, t, a)| (s.as_str(), t.as_str(), a.as_str()))
209        .unwrap_or((commit.summary.as_str(), "", commit.author_name.as_str()));
210
211    // Pre-truncate with "…" so the full row stays on one line.
212    let display_summary = truncate_to_fit(summary_str, available_summary_px, 7.0);
213    let summary_label = container(
214        text(display_summary)
215            .size(12)
216            .color(c.text_primary)
217            .wrapping(iced::widget::text::Wrapping::None),
218    )
219    .width(Length::Fill)
220    .clip(true);
221
222    // Fixed-width columns prevent author / time from being squeezed to zero
223    // and wrapping character-by-character.  Text is pre-truncated so it fits.
224    let author_label = container(
225        text(author_str)
226            .size(11)
227            .color(c.text_secondary)
228            .wrapping(iced::widget::text::Wrapping::None),
229    )
230    .width(90)
231    .clip(true);
232
233    let time_label = container(
234        text(time_str)
235            .size(11)
236            .color(c.muted)
237            .wrapping(iced::widget::text::Wrapping::None),
238    )
239    .width(72)
240    .clip(true);
241
242    let row_content = row![
243        graph_elem,
244        oid_label,
245        Space::with_width(6),
246        summary_label,
247        Space::with_width(8),
248        author_label,
249        Space::with_width(8),
250        time_label,
251    ]
252    .align_y(Alignment::Center)
253    .padding([3, 8]);
254
255    let style_fn = if is_selected {
256        theme::selected_row_style as fn(&iced::Theme) -> iced::widget::container::Style
257    } else {
258        theme::surface_style as fn(&iced::Theme) -> iced::widget::container::Style
259    };
260
261    mouse_area(
262        container(
263            button(row_content)
264                .padding(0)
265                .width(Length::Fill)
266                .on_press(Message::SelectCommit(idx))
267                .style(theme::ghost_button),
268        )
269        .width(Length::Fill)
270        .height(Length::Fixed(ROW_HEIGHT))
271        .clip(true)
272        .style(style_fn),
273    )
274    .on_right_press(Message::OpenCommitContextMenu(idx))
275    .into()
276}
277
278// ── view ─────────────────────────────────────────────────────────────────────
279
280/// Render the commit log panel.
281pub fn view(state: &GitKraft) -> Element<'_, Message> {
282    let tab = state.active_tab();
283    let c = state.colors();
284
285    let header_icon = icon!(icons::CLOCK, 14, c.accent);
286
287    let header_text = text("Commit Log").size(14).color(c.text_primary);
288
289    let commit_count = text(format!("({})", tab.commits.len()))
290        .size(12)
291        .color(c.muted);
292
293    let header_row = row![
294        header_icon,
295        Space::with_width(6),
296        header_text,
297        Space::with_width(6),
298        commit_count,
299    ]
300    .align_y(Alignment::Center)
301    .padding([8, 10]);
302
303    if tab.commits.is_empty() {
304        let empty_msg = text("No commits yet.").size(14).color(c.muted);
305
306        let content = column![
307            header_row,
308            container(empty_msg)
309                .width(Length::Fill)
310                .padding(20)
311                .center_x(Length::Fill),
312        ]
313        .width(Length::Fill)
314        .height(Length::Fill);
315
316        return view_utils::surface_panel(content, Length::Fill);
317    }
318
319    // ── Virtual scroll window ─────────────────────────────────────────────
320    //
321    // Only the rows visible in the viewport (plus OVERSCAN above/below) are
322    // constructed as widgets.  The remaining space is filled with two Space
323    // widgets so the scrollable keeps the correct total height and the
324    // scrollbar thumb stays proportional.
325
326    let total = tab.commits.len();
327    let scroll_y = tab.commit_scroll_offset;
328
329    let first = ((scroll_y / ROW_HEIGHT) as usize).saturating_sub(OVERSCAN);
330    let last = (first + VISIBLE_ROWS + 2 * OVERSCAN).min(total);
331
332    let top_space = first as f32 * ROW_HEIGHT;
333    let bottom_space = (total - last) as f32 * ROW_HEIGHT;
334
335    let mut list_col = column![].width(Length::Fill);
336
337    if top_space > 0.0 {
338        list_col = list_col.push(Space::with_height(top_space));
339    }
340
341    // Available px for the summary column:
342    // commit_log_width minus graph (~30) + oid (~56) + spaces + author (90)
343    // + time (72) + row padding (16) ≈ 280 px fixed overhead.
344    let available_summary_px = (state.commit_log_width - 280.0).max(40.0);
345
346    for idx in first..last {
347        list_col = list_col.push(commit_row_element(tab, idx, &c, available_summary_px));
348    }
349
350    if bottom_space > 0.0 {
351        list_col = list_col.push(Space::with_height(bottom_space));
352    }
353
354    // Loading spinner shown while a background fetch is in progress.
355    if tab.is_loading_more_commits {
356        list_col = list_col.push(
357            container(text("Loading more commits…").size(12).color(c.muted))
358                .width(Length::Fill)
359                .center_x(Length::Fill)
360                .padding([10, 0]),
361        );
362    }
363    // End-of-history marker once all commits are loaded.
364    if !tab.has_more_commits {
365        list_col = list_col.push(
366            container(text("— end of history —").size(11).color(c.muted))
367                .width(Length::Fill)
368                .center_x(Length::Fill)
369                .padding([10, 0]),
370        );
371    }
372
373    let commit_scroll = scrollable(list_col)
374        .height(Length::Fill)
375        .id(commit_log_scroll_id(state.active_tab))
376        .on_scroll(|vp| Message::CommitLogScrolled(vp.absolute_offset().y, vp.relative_offset().y))
377        .direction(view_utils::thin_scrollbar())
378        .style(crate::theme::overlay_scrollbar);
379
380    let content = column![header_row, commit_scroll]
381        .width(Length::Fill)
382        .height(Length::Fill);
383
384    view_utils::surface_panel(content, Length::Fill)
385}