BlueGit

ict rusty-teams

Files

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

link_preview.rs

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