commit_tooltip.rs

  1use crate::commit_view::CommitView;
  2use editor::hover_markdown_style;
  3use futures::Future;
  4use git::blame::BlameEntry;
  5use git::repository::CommitSummary;
  6use git::{GitRemote, blame::ParsedCommitMessage};
  7use gpui::{
  8    App, Asset, ClipboardItem, Element, Entity, MouseButton, ParentElement, Render, ScrollHandle,
  9    StatefulInteractiveElement, WeakEntity, prelude::*,
 10};
 11use markdown::{Markdown, MarkdownElement};
 12use project::git_store::Repository;
 13use settings::Settings;
 14use std::hash::Hash;
 15use theme::ThemeSettings;
 16use time::{OffsetDateTime, UtcOffset};
 17use time_format::format_local_timestamp;
 18use ui::{Avatar, Divider, IconButtonShape, prelude::*, tooltip_container};
 19use workspace::Workspace;
 20
 21#[derive(Clone, Debug)]
 22pub struct CommitDetails {
 23    pub sha: SharedString,
 24    pub author_name: SharedString,
 25    pub author_email: SharedString,
 26    pub commit_time: OffsetDateTime,
 27    pub message: Option<ParsedCommitMessage>,
 28}
 29
 30pub struct CommitAvatar<'a> {
 31    commit: &'a CommitDetails,
 32}
 33
 34impl<'a> CommitAvatar<'a> {
 35    pub fn new(details: &'a CommitDetails) -> Self {
 36        Self { commit: details }
 37    }
 38}
 39
 40impl<'a> CommitAvatar<'a> {
 41    pub fn render(&'a self, window: &mut Window, cx: &mut App) -> Option<impl IntoElement + use<>> {
 42        let remote = self
 43            .commit
 44            .message
 45            .as_ref()
 46            .and_then(|details| details.remote.clone())
 47            .filter(|remote| remote.host_supports_avatars())?;
 48
 49        let avatar_url = CommitAvatarAsset::new(remote, self.commit.sha.clone());
 50
 51        let element = match window.use_asset::<CommitAvatarAsset>(&avatar_url, cx) {
 52            // Loading or no avatar found
 53            None | Some(None) => Icon::new(IconName::Person)
 54                .color(Color::Muted)
 55                .into_element()
 56                .into_any(),
 57            // Found
 58            Some(Some(url)) => Avatar::new(url.to_string()).into_element().into_any(),
 59        };
 60        Some(element)
 61    }
 62}
 63
 64#[derive(Clone, Debug)]
 65struct CommitAvatarAsset {
 66    sha: SharedString,
 67    remote: GitRemote,
 68}
 69
 70impl Hash for CommitAvatarAsset {
 71    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 72        self.sha.hash(state);
 73        self.remote.host.name().hash(state);
 74    }
 75}
 76
 77impl CommitAvatarAsset {
 78    fn new(remote: GitRemote, sha: SharedString) -> Self {
 79        Self { remote, sha }
 80    }
 81}
 82
 83impl Asset for CommitAvatarAsset {
 84    type Source = Self;
 85    type Output = Option<SharedString>;
 86
 87    fn load(
 88        source: Self::Source,
 89        cx: &mut App,
 90    ) -> impl Future<Output = Self::Output> + Send + 'static {
 91        let client = cx.http_client();
 92
 93        async move {
 94            source
 95                .remote
 96                .avatar_url(source.sha, client)
 97                .await
 98                .map(|url| SharedString::from(url.to_string()))
 99        }
100    }
101}
102
103pub struct CommitTooltip {
104    commit: CommitDetails,
105    scroll_handle: ScrollHandle,
106    markdown: Entity<Markdown>,
107    repository: Entity<Repository>,
108    workspace: WeakEntity<Workspace>,
109}
110
111impl CommitTooltip {
112    pub fn blame_entry(
113        blame: &BlameEntry,
114        details: Option<ParsedCommitMessage>,
115        repository: Entity<Repository>,
116        workspace: WeakEntity<Workspace>,
117        cx: &mut Context<Self>,
118    ) -> Self {
119        let commit_time = blame
120            .committer_time
121            .and_then(|t| OffsetDateTime::from_unix_timestamp(t).ok())
122            .unwrap_or(OffsetDateTime::now_utc());
123
124        Self::new(
125            CommitDetails {
126                sha: blame.sha.to_string().into(),
127                commit_time,
128                author_name: blame
129                    .author
130                    .clone()
131                    .unwrap_or("<no name>".to_string())
132                    .into(),
133                author_email: blame.author_mail.clone().unwrap_or("".to_string()).into(),
134                message: details,
135            },
136            repository,
137            workspace,
138            cx,
139        )
140    }
141
142    pub fn new(
143        commit: CommitDetails,
144        repository: Entity<Repository>,
145        workspace: WeakEntity<Workspace>,
146        cx: &mut Context<Self>,
147    ) -> Self {
148        let markdown = cx.new(|cx| {
149            Markdown::new(
150                commit
151                    .message
152                    .as_ref()
153                    .map(|message| message.message.clone())
154                    .unwrap_or_default(),
155                None,
156                None,
157                cx,
158            )
159        });
160        Self {
161            commit,
162            repository,
163            workspace,
164            scroll_handle: ScrollHandle::new(),
165            markdown,
166        }
167    }
168}
169
170impl Render for CommitTooltip {
171    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
172        let avatar = CommitAvatar::new(&self.commit).render(window, cx);
173
174        let author = self.commit.author_name.clone();
175
176        let author_email = self.commit.author_email.clone();
177
178        let short_commit_id = self
179            .commit
180            .sha
181            .get(0..8)
182            .map(|sha| sha.to_string().into())
183            .unwrap_or_else(|| self.commit.sha.clone());
184        let full_sha = self.commit.sha.to_string();
185        let absolute_timestamp = format_local_timestamp(
186            self.commit.commit_time,
187            OffsetDateTime::now_utc(),
188            time_format::TimestampFormat::MediumAbsolute,
189        );
190        let markdown_style = {
191            let mut style = hover_markdown_style(window, cx);
192            if let Some(code_block) = &style.code_block.text {
193                style.base_text_style.refine(code_block);
194            }
195            style
196        };
197
198        let message = self
199            .commit
200            .message
201            .as_ref()
202            .map(|_| MarkdownElement::new(self.markdown.clone(), markdown_style).into_any())
203            .unwrap_or("<no commit message>".into_any());
204
205        let pull_request = self
206            .commit
207            .message
208            .as_ref()
209            .and_then(|details| details.pull_request.clone());
210
211        let ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
212        let message_max_height = window.line_height() * 12 + (ui_font_size / 0.4);
213        let repo = self.repository.clone();
214        let workspace = self.workspace.clone();
215        let commit_summary = CommitSummary {
216            sha: self.commit.sha.clone(),
217            subject: self
218                .commit
219                .message
220                .as_ref()
221                .map_or(Default::default(), |message| {
222                    message
223                        .message
224                        .split('\n')
225                        .next()
226                        .unwrap()
227                        .trim_end()
228                        .to_string()
229                        .into()
230                }),
231            commit_timestamp: self.commit.commit_time.unix_timestamp(),
232            has_parent: false,
233        };
234
235        tooltip_container(window, cx, move |this, _, cx| {
236            this.occlude()
237                .on_mouse_move(|_, _, cx| cx.stop_propagation())
238                .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
239                .child(
240                    v_flex()
241                        .w(gpui::rems(30.))
242                        .gap_4()
243                        .child(
244                            h_flex()
245                                .pb_1p5()
246                                .gap_x_2()
247                                .overflow_x_hidden()
248                                .flex_wrap()
249                                .children(avatar)
250                                .child(author)
251                                .when(!author_email.is_empty(), |this| {
252                                    this.child(
253                                        div()
254                                            .text_color(cx.theme().colors().text_muted)
255                                            .child(author_email),
256                                    )
257                                })
258                                .border_b_1()
259                                .border_color(cx.theme().colors().border_variant),
260                        )
261                        .child(
262                            div()
263                                .id("inline-blame-commit-message")
264                                .child(message)
265                                .max_h(message_max_height)
266                                .overflow_y_scroll()
267                                .track_scroll(&self.scroll_handle),
268                        )
269                        .child(
270                            h_flex()
271                                .text_color(cx.theme().colors().text_muted)
272                                .w_full()
273                                .justify_between()
274                                .pt_1p5()
275                                .border_t_1()
276                                .border_color(cx.theme().colors().border_variant)
277                                .child(absolute_timestamp)
278                                .child(
279                                    h_flex()
280                                        .gap_1p5()
281                                        .when_some(pull_request, |this, pr| {
282                                            this.child(
283                                                Button::new(
284                                                    "pull-request-button",
285                                                    format!("#{}", pr.number),
286                                                )
287                                                .color(Color::Muted)
288                                                .icon(IconName::PullRequest)
289                                                .icon_color(Color::Muted)
290                                                .icon_position(IconPosition::Start)
291                                                .style(ButtonStyle::Subtle)
292                                                .on_click(move |_, _, cx| {
293                                                    cx.stop_propagation();
294                                                    cx.open_url(pr.url.as_str())
295                                                }),
296                                            )
297                                        })
298                                        .child(Divider::vertical())
299                                        .child(
300                                            Button::new(
301                                                "commit-sha-button",
302                                                short_commit_id.clone(),
303                                            )
304                                            .style(ButtonStyle::Subtle)
305                                            .color(Color::Muted)
306                                            .icon(IconName::FileGit)
307                                            .icon_color(Color::Muted)
308                                            .icon_position(IconPosition::Start)
309                                            .on_click(
310                                                move |_, window, cx| {
311                                                    CommitView::open(
312                                                        commit_summary.clone(),
313                                                        repo.downgrade(),
314                                                        workspace.clone(),
315                                                        window,
316                                                        cx,
317                                                    );
318                                                    cx.stop_propagation();
319                                                },
320                                            ),
321                                        )
322                                        .child(
323                                            IconButton::new("copy-sha-button", IconName::Copy)
324                                                .shape(IconButtonShape::Square)
325                                                .icon_size(IconSize::Small)
326                                                .icon_color(Color::Muted)
327                                                .on_click(move |_, _, cx| {
328                                                    cx.stop_propagation();
329                                                    cx.write_to_clipboard(
330                                                        ClipboardItem::new_string(full_sha.clone()),
331                                                    )
332                                                }),
333                                        ),
334                                ),
335                        ),
336                )
337        })
338    }
339}
340
341fn blame_entry_timestamp(blame_entry: &BlameEntry, format: time_format::TimestampFormat) -> String {
342    match blame_entry.author_offset_date_time() {
343        Ok(timestamp) => {
344            let local = chrono::Local::now().offset().local_minus_utc();
345            time_format::format_localized_timestamp(
346                timestamp,
347                time::OffsetDateTime::now_utc(),
348                UtcOffset::from_whole_seconds(local).unwrap(),
349                format,
350            )
351        }
352        Err(_) => "Error parsing date".to_string(),
353    }
354}
355
356pub fn blame_entry_relative_timestamp(blame_entry: &BlameEntry) -> String {
357    blame_entry_timestamp(blame_entry, time_format::TimestampFormat::Relative)
358}