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_MIN_HEIGHT: f32 = 48.;
18const THUMB_MAX_HEIGHT: f32 = 112.;
19const THUMB_RADIUS: f32 = 6.;
20const CLOSE_SIZE: f32 = 22.;
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(4.))
101 .right(px(4.))
102 .size(px(CLOSE_SIZE))
103 .flex()
104 .items_center()
105 .justify_center()
106 .rounded(px(6.))
107 .cursor_pointer()
108 .hover(|button| button.bg(theme::row_hover()))
109 .child(icon(IconName::Close, 12., 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(10.))
123 .p(px(8.))
124 .items_start()
125 .rounded(px(9.))
126 .bg(theme::surface())
127 .border_1()
128 .border_color(theme::border_strong())
129 .cursor_pointer()
130 .hover(|card| card.bg(theme::row_hover()).border_color(theme::accent()))
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)
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)
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| cx.open_url(&url))
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(10.))
173 .gap(px(5.))
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}