BlueGit

ict rusty-teams

Files

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

link_preview.rs

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