BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / link_preview.rs

link_preview.rs

3e88a0c9 History
link_preview.rs 12.2 KiB Download Raw
1use crate::views::image_memory::preview as scaled_preview;
2use std::rc::Rc;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8use teams_core::{LinkPreview, first_public_link};
9
10use super::widgets::icon;
11use crate::app_state::AppHandle;
12use crate::data::Directory;
13use crate::theme;
14
15const CARD_WIDTH: f32 = 360.;
16const THUMB_WIDTH: f32 = 112.;
17const THUMB_WIDTH_COMPACT: f32 = 72.;
18const THUMB_MAX_WIDTH_RATIO: f32 = 0.4;
19const THUMB_MIN_HEIGHT: f32 = 48.;
20const THUMB_MAX_HEIGHT: f32 = 112.;
21const THUMB_RADIUS: f32 = 6.;
22const CLOSE_SIZE: f32 = 28.;
23const JOIN_CHIP_HEIGHT: f32 = 24.;
24
25pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
26
27pub fn thumbnail_size(
28 declared: Option<(u32, u32)>,
29 loaded: Option<(u32, u32)>,
30 width: f32,
31) -> (f32, f32) {
32 let aspect = declared
33 .or(loaded)
34 .filter(|(width, height)| *width > 0 && *height > 0)
35 .map_or(0.6, |(image_width, image_height)| {
36 image_height as f32 / image_width as f32
37 });
38 (
39 width,
40 (width * aspect)
41 .clamp(THUMB_MIN_HEIGHT, THUMB_MAX_HEIGHT)
42 .round(),
43 )
44}
45
46fn thumbnail(
47 preview: &LinkPreview,
48 id: &str,
49 directory: &Directory,
50 width: f32,
51) -> Option<AnyElement> {
52 let image = preview.image()?;
53 let entry = directory.image(&image.url);
54 let (width, height) = thumbnail_size(
55 image.width.zip(image.height),
56 entry.and_then(|entry| entry.size),
57 width,
58 );
59 let frame = div()
60 .id(ElementId::Name(format!("{id}-thumbnail").into()))
61 .w(px(width))
62 .h(px(height))
63 .flex_none()
64 .max_w(relative(THUMB_MAX_WIDTH_RATIO))
65 .rounded(px(THUMB_RADIUS))
66 .overflow_hidden()
67 .bg(theme::background());
68 Some(match entry {
69 Some(entry) => frame
70 .child(
71 img(scaled_preview(entry.path.clone()))
72 .size_full()
73 .object_fit(ObjectFit::Cover),
74 )
75 .into_any_element(),
76 None => frame
77 .flex()
78 .items_center()
79 .justify_center()
80 .child(icon(IconName::Image, 18., theme::text_muted()))
81 .into_any_element(),
82 })
83}
84
85pub fn link_preview_card(
86 preview: &LinkPreview,
87 id: String,
88 directory: &Directory,
89 compact: bool,
90 close: Option<CloseHandler>,
91) -> AnyElement {
92 let thumb_width = if compact {
93 THUMB_WIDTH_COMPACT
94 } else {
95 THUMB_WIDTH
96 };
97 let url = preview.url.clone();
98 let title = preview.title.clone().unwrap_or_else(|| preview.domain());
99 let close_button = close.map(|close| {
100 div()
101 .id(ElementId::Name(format!("{id}-close").into()))
102 .absolute()
103 .top(px(8.))
104 .right(px(8.))
105 .size(px(CLOSE_SIZE))
106 .flex()
107 .items_center()
108 .justify_center()
109 .rounded(px(7.))
110 .cursor_pointer()
111 .hover(|button| button.bg(theme::popup_hover()))
112 .child(icon(IconName::Close, 14., theme::text_muted()))
113 .on_click(move |_, window, cx| {
114 cx.stop_propagation();
115 close(window, cx);
116 })
117 });
118 h_flex()
119 .id(ElementId::Name(id.clone().into()))
120 .relative()
121 .overflow_hidden()
122 .w_full()
123 .when(!compact, |card| card.max_w(px(CARD_WIDTH)))
124 .gap(px(12.))
125 .p(px(8.))
126 .items_start()
127 .rounded(px(10.))
128 .bg(theme::surface())
129 .cursor_pointer()
130 .hover(|card| card.bg(theme::row_hover()))
131 .children(thumbnail(preview, &id, directory, thumb_width))
132 .child(
133 v_flex()
134 .flex_1()
135 .min_w_0()
136 .gap(px(2.))
137 .when(close_button.is_some(), |column| column.pr(px(CLOSE_SIZE)))
138 .child(
139 div()
140 .line_clamp(2).text_ellipsis()
141 .text_size(px(13.))
142 .font_weight(FontWeight::SEMIBOLD)
143 .text_color(theme::text_strong())
144 .child(title),
145 )
146 .children(preview.description.clone().map(|description| {
147 div()
148 .line_clamp(2).text_ellipsis()
149 .text_size(px(12.))
150 .text_color(theme::text_muted())
151 .child(description)
152 }))
153 .child(
154 div()
155 .truncate()
156 .text_size(px(11.))
157 .text_color(theme::text_muted())
158 .child(preview.domain()),
159 ),
160 )
161 .children(close_button)
162 .on_click(move |_, _, cx| app_ui_kit::render::hooks::open_link(&url, cx))
163 .into_any_element()
164}
165
166pub fn meeting_join_chip(id: String, url: String) -> AnyElement {
167 h_flex()
168 .id(ElementId::Name(id.into()))
169 .flex_none()
170 .self_start()
171 .h(px(JOIN_CHIP_HEIGHT))
172 .px(px(12.))
173 .gap(px(4.))
174 .items_center()
175 .rounded_full()
176 .bg(theme::accent())
177 .text_size(px(12.))
178 .font_weight(FontWeight::SEMIBOLD)
179 .text_color(theme::on_accent())
180 .cursor_pointer()
181 .hover(|chip| chip.opacity(0.85))
182 .child(icon(IconName::Video, 13., theme::on_accent()))
183 .child("Join")
184 .on_click(move |_, _, cx| {
185 cx.stop_propagation();
186 let Some(handle) = cx.try_global::<AppHandle>() else {
187 return;
188 };
189 let app = handle.0.clone();
190 app.update(cx, |state, cx| state.join_meeting_link(&url, cx));
191 })
192 .into_any_element()
193}
194
195#[derive(Default)]
196pub struct ComposeLink {
197 url: Option<String>,
198 preview: Option<LinkPreview>,
199 dismissed: Option<String>,
200 pub meeting: Option<String>,
201 pub lookup: Option<Task<()>>,
202}
203
204impl ComposeLink {
205 pub fn shown(&self) -> Option<&LinkPreview> {
206 self.preview.as_ref()
207 }
208
209 /// The link to look up when the draft's link changed.
210 pub fn observe(&mut self, link: Option<String>, draft_blank: bool) -> Option<String> {
211 if draft_blank {
212 self.reset();
213 return None;
214 }
215 let Some(link) = link else {
216 self.url = None;
217 self.preview = None;
218 self.lookup = None;
219 return None;
220 };
221 if self.url.as_deref() == Some(link.as_str()) {
222 return None;
223 }
224 self.preview = None;
225 self.lookup = None;
226 self.url = Some(link.clone());
227 (self.dismissed.as_deref() != Some(link.as_str())).then_some(link)
228 }
229
230 pub fn apply(&mut self, url: &str, preview: Option<LinkPreview>) -> bool {
231 let current = self.url.as_deref() == Some(url) && self.dismissed.as_deref() != Some(url);
232 if current {
233 self.preview = preview;
234 }
235 current
236 }
237
238 pub fn dismiss(&mut self) {
239 self.dismissed = self.url.clone();
240 self.preview = None;
241 self.lookup = None;
242 }
243
244 pub fn restore(&mut self, preview: Option<LinkPreview>) {
245 self.dismissed = None;
246 self.lookup = None;
247 self.url = preview.as_ref().map(|preview| preview.url.clone());
248 self.preview = preview;
249 }
250
251 pub fn reset(&mut self) {
252 *self = ComposeLink::default();
253 }
254}
255
256pub fn draft_link(draft: &teams_core::Draft) -> Option<String> {
257 first_public_link(&draft.to_html()).or_else(|| {
258 draft
259 .plain_text()
260 .split_whitespace()
261 .map(|word| word.trim_end_matches(['.', ',', ';', ':', '!', '?', ')']))
262 .find(|word| {
263 let lower = word.to_ascii_lowercase();
264 (lower.starts_with("http://") || lower.starts_with("https://"))
265 && teams_core::is_public_link(word)
266 })
267 .map(str::to_owned)
268 })
269}
270
271#[cfg(test)]
272mod tests {
273 use teams_core::LinkPreview;
274
275 use super::{ComposeLink, THUMB_MAX_HEIGHT, THUMB_MIN_HEIGHT, draft_link, thumbnail_size};
276
277 fn preview(url: &str) -> LinkPreview {
278 LinkPreview {
279 url: url.to_owned(),
280 title: Some("Title".to_owned()),
281 description: None,
282 image_url: None,
283 image_width: None,
284 image_height: None,
285 }
286 }
287
288 #[test]
289 fn thumbnails_keep_the_aspect_within_bounds() {
290 assert_eq!(thumbnail_size(Some((320, 160)), None, 112.), (112., 56.));
291 assert_eq!(
292 thumbnail_size(Some((100, 400)), None, 112.),
293 (112., THUMB_MAX_HEIGHT)
294 );
295 assert_eq!(
296 thumbnail_size(Some((400, 20)), None, 112.),
297 (112., THUMB_MIN_HEIGHT)
298 );
299 assert_eq!(thumbnail_size(None, Some((200, 100)), 100.), (100., 50.));
300 assert_eq!(thumbnail_size(None, None, 100.), (100., 60.));
301 }
302
303 #[test]
304 fn a_new_link_is_looked_up_once() {
305 let mut link = ComposeLink::default();
306 assert_eq!(
307 link.observe(Some("https://a.example".into()), false),
308 Some("https://a.example".into())
309 );
310 assert_eq!(link.observe(Some("https://a.example".into()), false), None);
311 assert!(link.apply("https://a.example", Some(preview("https://a.example"))));
312 assert!(link.shown().is_some());
313 assert_eq!(
314 link.observe(Some("https://b.example".into()), false),
315 Some("https://b.example".into())
316 );
317 assert!(link.shown().is_none());
318 }
319
320 #[test]
321 fn a_late_answer_for_an_old_link_is_ignored() {
322 let mut link = ComposeLink::default();
323 link.observe(Some("https://a.example".into()), false);
324 link.observe(Some("https://b.example".into()), false);
325 assert!(!link.apply("https://a.example", Some(preview("https://a.example"))));
326 assert!(link.shown().is_none());
327 }
328
329 #[test]
330 fn a_dismissed_link_stays_hidden_until_the_link_changes_or_the_draft_clears() {
331 let mut link = ComposeLink::default();
332 link.observe(Some("https://a.example".into()), false);
333 link.apply("https://a.example", Some(preview("https://a.example")));
334 link.dismiss();
335 assert!(link.shown().is_none());
336 assert_eq!(link.observe(Some("https://a.example".into()), false), None);
337 assert_eq!(link.observe(None, false), None);
338 assert_eq!(link.observe(Some("https://a.example".into()), false), None);
339 assert!(!link.apply("https://a.example", Some(preview("https://a.example"))));
340 assert_eq!(
341 link.observe(Some("https://b.example".into()), false),
342 Some("https://b.example".into())
343 );
344 link.dismiss();
345 assert_eq!(link.observe(None, true), None);
346 assert_eq!(
347 link.observe(Some("https://b.example".into()), false),
348 Some("https://b.example".into())
349 );
350 }
351
352 #[test]
353 fn removing_the_link_removes_the_card() {
354 let mut link = ComposeLink::default();
355 link.observe(Some("https://a.example".into()), false);
356 link.apply("https://a.example", Some(preview("https://a.example")));
357 assert_eq!(link.observe(None, false), None);
358 assert!(link.shown().is_none());
359 }
360
361 #[test]
362 fn restoring_a_sent_preview_shows_it_without_a_new_lookup() {
363 let mut link = ComposeLink::default();
364 link.restore(Some(preview("https://a.example")));
365 assert!(link.shown().is_some());
366 assert_eq!(link.observe(Some("https://a.example".into()), false), None);
367 assert!(link.shown().is_some());
368 }
369
370 #[test]
371 fn finds_anchors_and_bare_urls_in_a_draft() {
372 let marked = teams_core::Draft::from_markdown("see [docs](https://docs.example/a) now");
373 assert_eq!(
374 draft_link(&marked).as_deref(),
375 Some("https://docs.example/a")
376 );
377 let bare = teams_core::Draft::plain("go to https://b.example/x, ok");
378 assert_eq!(draft_link(&bare).as_deref(), Some("https://b.example/x"));
379 let internal = teams_core::Draft::plain("https://contoso.sharepoint.com/x");
380 assert_eq!(draft_link(&internal), None);
381 }
382}