BlueGit

ict rusty-teams

Files

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

link_preview.rs

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