Merge remote-tracking branch 'origin/main' into feat/channel-post-card
@@ -107,6 +107,7 @@ mod tests {
107
107
r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:c@thread.v2/messages/1728/hostedContents/aWQ9/$value" alt="a chart" width="300" height="120"></p>"#,
108
108
r#"<p><img src="https://media0.giphy.com/media/abc/giphy.gif"></p>"#,
109
109
r#"<attachment id="F1"></attachment>"#,
110
r#"<p><a href="https://news.example.com/story">https://news.example.com/story</a></p>"#,
110
111
)
111
112
.to_owned(),
112
113
attachments_json: r#"[
@@ -107,6 +107,7 @@ mod tests {107
r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:c@thread.v2/messages/1728/hostedContents/aWQ9/$value" alt="a chart" width="300" height="120"></p>"#,107
r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:c@thread.v2/messages/1728/hostedContents/aWQ9/$value" alt="a chart" width="300" height="120"></p>"#,108
r#"<p><img src="https://media0.giphy.com/media/abc/giphy.gif"></p>"#,108
r#"<p><img src="https://media0.giphy.com/media/abc/giphy.gif"></p>"#,109
r#"<attachment id="F1"></attachment>"#,109
r#"<attachment id="F1"></attachment>"#,110
r#"<p><a href="https://news.example.com/story">https://news.example.com/story</a></p>"#,110
)111
)111
.to_owned(),112
.to_owned(),112
attachments_json: r#"[113
attachments_json: r#"[@@ -1794,7 +1794,7 @@ fn release_messages() -> Vec<MessageRecord> {
1794
1794
LinkPreview {
1795
1795
url: "https://example.com/notes".to_owned(),
1796
1796
title: Some("Release notes 0.2".to_owned()),
1797
description: None,
1797
description: Some("What changed since 0.1".to_owned()),
1798
1798
image_url: None,
1799
1799
image_width: None,
1800
1800
image_height: None,
@@ -1794,7 +1794,7 @@ fn release_messages() -> Vec<MessageRecord> {1794
LinkPreview {1794
LinkPreview {1795
url: "https://example.com/notes".to_owned(),1795
url: "https://example.com/notes".to_owned(),1796
title: Some("Release notes 0.2".to_owned()),1796
title: Some("Release notes 0.2".to_owned()),1797
description: None,1797
description: Some("What changed since 0.1".to_owned()),1798
image_url: None,1798
image_url: None,1799
image_width: None,1799
image_width: None,1800
image_height: None,1800
image_height: None,@@ -32,12 +32,60 @@ pub fn edge_divider(tag: &'static str) -> Div {
32
32
.bg(theme::border())
33
33
}
34
34
35
pub fn settled_offset(offset: Point<Pixels>, max_offset: Point<Pixels>) -> Point<Pixels> {
36
let settle = |value: Pixels, max: Pixels| value.max(-max.max(px(0.))).min(px(0.));
37
point(
38
settle(offset.x, max_offset.x),
39
settle(offset.y, max_offset.y),
40
)
41
}
42
43
pub fn scroll_offset(handle: &ScrollHandle) -> Point<Pixels> {
44
settled_offset(handle.offset(), handle.max_offset())
45
}
46
47
pub fn pushes_past_edge(offset_y: Pixels, max_offset_y: Pixels, delta: Point<Pixels>) -> bool {
48
let vertical = if delta.y.is_zero() { delta.x } else { delta.y };
49
if vertical > px(0.) {
50
!content_hidden_above(offset_y)
51
} else if vertical < px(0.) {
52
f32::from(offset_y + max_offset_y) <= SCROLLED_THRESHOLD
53
} else {
54
false
55
}
56
}
57
58
pub fn edge_scroll_guard(handle: &ScrollHandle) -> impl IntoElement {
59
let handle = handle.clone();
60
canvas(
61
|bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),
62
move |_, hitbox, window, _| {
63
window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {
64
if phase == DispatchPhase::Capture
65
&& hitbox.should_handle_scroll(window)
66
&& pushes_past_edge(
67
handle.offset().y,
68
handle.max_offset().y,
69
event.delta.pixel_delta(window.line_height()),
70
)
71
{
72
cx.stop_propagation();
73
}
74
});
75
},
76
)
77
.absolute()
78
.top_0()
79
.left_0()
80
.size_full()
81
}
82
35
83
pub fn with_top_edge(
36
84
scroll_area: impl IntoElement,
37
85
handle: &ScrollHandle,
38
86
tag: &'static str,
39
87
) -> Div {
40
let visible = edge_visible(EdgeRule::WhenScrolled, handle.offset().y);
88
let visible = edge_visible(EdgeRule::WhenScrolled, scroll_offset(handle).y);
41
89
div()
42
90
.relative()
43
91
.flex()
@@ -45,6 +93,7 @@ pub fn with_top_edge(
45
93
.flex_1()
46
94
.min_h_0()
47
95
.w_full()
96
.child(edge_scroll_guard(handle))
48
97
.child(scroll_area)
49
98
.when(visible, |area| {
50
99
area.child(edge_divider(tag).absolute().top_0().left_0().right_0())
@@ -53,9 +102,196 @@ pub fn with_top_edge(
53
102
54
103
#[cfg(test)]
55
104
mod tests {
56
use gpui_kit::px;
105
use std::cell::{Cell, RefCell};
106
use std::rc::Rc;
107
108
use gpui_kit::{
109
Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,
110
ScrollDelta, ScrollHandle, ScrollWheelEvent, StatefulInteractiveElement as _, Styled as _,
111
TestAppContext, TouchPhase, VisualTestContext, Window, div, point, px,
112
};
113
114
use super::{
115
EdgeRule, content_hidden_above, edge_visible, pushes_past_edge, scroll_offset,
116
settled_offset, with_top_edge,
117
};
118
119
const EDGE_TAG: &str = "test-edge-line";
120
const ROW_HEIGHT: f32 = 40.;
121
const ROW_COUNT: usize = 60;
122
123
struct EdgeList {
124
handle: ScrollHandle,
125
rendered_offsets: Rc<RefCell<Vec<f32>>>,
126
}
127
128
impl Render for EdgeList {
129
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
130
self.rendered_offsets
131
.borrow_mut()
132
.push(f32::from(scroll_offset(&self.handle).y));
133
let rows =
134
(0..ROW_COUNT).map(|row_index| div().id(row_index).h(px(ROW_HEIGHT)).flex_none());
135
let scroll_area = div()
136
.id("edge-list")
137
.flex_1()
138
.min_h_0()
139
.overflow_y_scroll()
140
.track_scroll(&self.handle)
141
.children(rows);
142
div().size_full().flex().flex_col().child(with_top_edge(
143
scroll_area,
144
&self.handle,
145
EDGE_TAG,
146
))
147
}
148
}
149
150
struct Harness<'a> {
151
window_cx: &'a mut VisualTestContext,
152
handle: ScrollHandle,
153
notifications: Rc<Cell<usize>>,
154
rendered_offsets: Rc<RefCell<Vec<f32>>>,
155
}
156
157
impl Harness<'_> {
158
fn draw(&mut self) {
159
self.window_cx
160
.update(|window, cx| window.draw(cx).clear(cx));
161
}
162
163
fn wheel(&mut self, delta_y: f32, touch_phase: TouchPhase) {
164
self.window_cx.simulate_event(ScrollWheelEvent {
165
position: point(px(100.), px(200.)),
166
delta: ScrollDelta::Pixels(point(px(0.), px(delta_y))),
167
touch_phase,
168
..Default::default()
169
});
170
self.draw();
171
}
57
172
58
use super::{EdgeRule, content_hidden_above, edge_visible};
173
fn touchpad_swipe(&mut self, delta_y: f32, steps: usize) {
174
self.wheel(delta_y, TouchPhase::Started);
175
for _ in 0..steps {
176
self.wheel(delta_y, TouchPhase::Moved);
177
}
178
self.wheel(0., TouchPhase::Ended);
179
}
180
181
fn offset_y(&self) -> f32 {
182
f32::from(self.handle.offset().y)
183
}
184
185
fn shows_line(&mut self) -> bool {
186
self.window_cx.debug_bounds(EDGE_TAG).is_some()
187
}
188
}
189
190
fn open(cx: &mut TestAppContext) -> Harness<'_> {
191
cx.update(gpui_kit::init);
192
let handle = ScrollHandle::new();
193
let rendered_offsets = Rc::new(RefCell::new(Vec::new()));
194
let (view, window_cx): (Entity<EdgeList>, _) = cx.add_window_view({
195
let handle = handle.clone();
196
let rendered_offsets = rendered_offsets.clone();
197
move |_, _| EdgeList {
198
handle,
199
rendered_offsets,
200
}
201
});
202
let notifications = Rc::new(Cell::new(0));
203
window_cx.update({
204
let notifications = notifications.clone();
205
move |_, cx| {
206
cx.observe(&view, move |_, _| {
207
notifications.set(notifications.get() + 1)
208
})
209
.detach()
210
}
211
});
212
let mut harness = Harness {
213
window_cx,
214
handle,
215
notifications,
216
rendered_offsets,
217
};
218
harness.draw();
219
harness
220
}
221
222
#[gpui_kit::test]
223
fn touchpad_overscroll_at_the_top_changes_nothing(cx: &mut TestAppContext) {
224
let mut harness = open(cx);
225
harness.notifications.set(0);
226
harness.touchpad_swipe(35., 12);
227
assert_eq!(harness.offset_y(), 0.);
228
assert_eq!(harness.notifications.get(), 0, "no re-render at the edge");
229
assert!(!harness.shows_line());
230
}
231
232
#[gpui_kit::test]
233
fn touchpad_overscroll_at_the_bottom_changes_nothing(cx: &mut TestAppContext) {
234
let mut harness = open(cx);
235
harness.wheel(-100_000., TouchPhase::Moved);
236
let bottom = harness.offset_y();
237
assert!(bottom < -1000.);
238
harness.notifications.set(0);
239
harness.touchpad_swipe(-35., 12);
240
assert_eq!(harness.offset_y(), bottom);
241
assert_eq!(harness.notifications.get(), 0);
242
assert!(harness.shows_line());
243
}
244
245
#[gpui_kit::test]
246
fn overshoot_past_the_top_is_never_rendered(cx: &mut TestAppContext) {
247
let mut harness = open(cx);
248
harness.wheel(-10., TouchPhase::Moved);
249
assert_eq!(harness.offset_y(), -10.);
250
harness.rendered_offsets.borrow_mut().clear();
251
harness.touchpad_swipe(400., 2);
252
assert_eq!(harness.offset_y(), 0.);
253
let rendered = harness.rendered_offsets.borrow().clone();
254
assert!(
255
rendered.iter().all(|offset| *offset <= 0.),
256
"render saw an offset past the top: {rendered:?}"
257
);
258
assert!(!harness.shows_line());
259
}
260
261
#[gpui_kit::test]
262
fn scrolling_down_from_the_top_still_scrolls(cx: &mut TestAppContext) {
263
let mut harness = open(cx);
264
harness.touchpad_swipe(-30., 4);
265
assert_eq!(harness.offset_y(), -150.);
266
assert!(harness.shows_line());
267
harness.touchpad_swipe(30., 4);
268
assert_eq!(harness.offset_y(), 0.);
269
assert!(!harness.shows_line());
270
}
271
272
#[test]
273
fn settled_offset_stays_inside_the_scroll_range() {
274
let max = point(px(0.), px(500.));
275
assert_eq!(settled_offset(point(px(0.), px(120.)), max).y, px(0.));
276
assert_eq!(settled_offset(point(px(0.), px(-900.)), max).y, px(-500.));
277
assert_eq!(settled_offset(point(px(0.), px(-200.)), max).y, px(-200.));
278
assert_eq!(
279
settled_offset(point(px(0.), px(-40.)), point(px(0.), px(0.))).y,
280
px(0.)
281
);
282
}
283
284
#[test]
285
fn only_deltas_beyond_an_edge_are_held_back() {
286
let max = px(500.);
287
assert!(pushes_past_edge(px(0.), max, point(px(0.), px(30.))));
288
assert!(pushes_past_edge(px(0.), max, point(px(12.), px(0.))));
289
assert!(!pushes_past_edge(px(0.), max, point(px(0.), px(-30.))));
290
assert!(!pushes_past_edge(px(-10.), max, point(px(0.), px(30.))));
291
assert!(pushes_past_edge(px(-500.), max, point(px(0.), px(-30.))));
292
assert!(!pushes_past_edge(px(-500.), max, point(px(0.), px(30.))));
293
assert!(!pushes_past_edge(px(0.), max, point(px(0.), px(0.))));
294
}
59
295
60
296
#[test]
61
297
fn the_list_at_its_top_shows_no_line() {
@@ -32,12 +32,60 @@ pub fn edge_divider(tag: &'static str) -> Div {32
.bg(theme::border())32
.bg(theme::border())33
}33
}34
34
35
pub fn settled_offset(offset: Point<Pixels>, max_offset: Point<Pixels>) -> Point<Pixels> {36
let settle = |value: Pixels, max: Pixels| value.max(-max.max(px(0.))).min(px(0.));37
point(38
settle(offset.x, max_offset.x),39
settle(offset.y, max_offset.y),40
)41
}42
43
pub fn scroll_offset(handle: &ScrollHandle) -> Point<Pixels> {44
settled_offset(handle.offset(), handle.max_offset())45
}46
47
pub fn pushes_past_edge(offset_y: Pixels, max_offset_y: Pixels, delta: Point<Pixels>) -> bool {48
let vertical = if delta.y.is_zero() { delta.x } else { delta.y };49
if vertical > px(0.) {50
!content_hidden_above(offset_y)51
} else if vertical < px(0.) {52
f32::from(offset_y + max_offset_y) <= SCROLLED_THRESHOLD53
} else {54
false55
}56
}57
58
pub fn edge_scroll_guard(handle: &ScrollHandle) -> impl IntoElement {59
let handle = handle.clone();60
canvas(61
|bounds, window, _| window.insert_hitbox(bounds, HitboxBehavior::Normal),62
move |_, hitbox, window, _| {63
window.on_mouse_event(move |event: &ScrollWheelEvent, phase, window, cx| {64
if phase == DispatchPhase::Capture65
&& hitbox.should_handle_scroll(window)66
&& pushes_past_edge(67
handle.offset().y,68
handle.max_offset().y,69
event.delta.pixel_delta(window.line_height()),70
)71
{72
cx.stop_propagation();73
}74
});75
},76
)77
.absolute()78
.top_0()79
.left_0()80
.size_full()81
}82
35
pub fn with_top_edge(83
pub fn with_top_edge(36
scroll_area: impl IntoElement,84
scroll_area: impl IntoElement,37
handle: &ScrollHandle,85
handle: &ScrollHandle,38
tag: &'static str,86
tag: &'static str,39
) -> Div {87
) -> Div {40
let visible = edge_visible(EdgeRule::WhenScrolled, handle.offset().y);88
let visible = edge_visible(EdgeRule::WhenScrolled, scroll_offset(handle).y);41
div()89
div()42
.relative()90
.relative()43
.flex()91
.flex()@@ -45,6 +93,7 @@ pub fn with_top_edge(45
.flex_1()93
.flex_1()46
.min_h_0()94
.min_h_0()47
.w_full()95
.w_full()96
.child(edge_scroll_guard(handle))48
.child(scroll_area)97
.child(scroll_area)49
.when(visible, |area| {98
.when(visible, |area| {50
area.child(edge_divider(tag).absolute().top_0().left_0().right_0())99
area.child(edge_divider(tag).absolute().top_0().left_0().right_0())@@ -53,9 +102,196 @@ pub fn with_top_edge(53
102
54
#[cfg(test)]103
#[cfg(test)]55
mod tests {104
mod tests {56
use gpui_kit::px;105
use std::cell::{Cell, RefCell};106
use std::rc::Rc;107
108
use gpui_kit::{109
Context, Entity, InteractiveElement as _, IntoElement, ParentElement as _, Render,110
ScrollDelta, ScrollHandle, ScrollWheelEvent, StatefulInteractiveElement as _, Styled as _,111
TestAppContext, TouchPhase, VisualTestContext, Window, div, point, px,112
};113
114
use super::{115
EdgeRule, content_hidden_above, edge_visible, pushes_past_edge, scroll_offset,116
settled_offset, with_top_edge,117
};118
119
const EDGE_TAG: &str = "test-edge-line";120
const ROW_HEIGHT: f32 = 40.;121
const ROW_COUNT: usize = 60;122
123
struct EdgeList {124
handle: ScrollHandle,125
rendered_offsets: Rc<RefCell<Vec<f32>>>,126
}127
128
impl Render for EdgeList {129
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {130
self.rendered_offsets131
.borrow_mut()132
.push(f32::from(scroll_offset(&self.handle).y));133
let rows =134
(0..ROW_COUNT).map(|row_index| div().id(row_index).h(px(ROW_HEIGHT)).flex_none());135
let scroll_area = div()136
.id("edge-list")137
.flex_1()138
.min_h_0()139
.overflow_y_scroll()140
.track_scroll(&self.handle)141
.children(rows);142
div().size_full().flex().flex_col().child(with_top_edge(143
scroll_area,144
&self.handle,145
EDGE_TAG,146
))147
}148
}149
150
struct Harness<'a> {151
window_cx: &'a mut VisualTestContext,152
handle: ScrollHandle,153
notifications: Rc<Cell<usize>>,154
rendered_offsets: Rc<RefCell<Vec<f32>>>,155
}156
157
impl Harness<'_> {158
fn draw(&mut self) {159
self.window_cx160
.update(|window, cx| window.draw(cx).clear(cx));161
}162
163
fn wheel(&mut self, delta_y: f32, touch_phase: TouchPhase) {164
self.window_cx.simulate_event(ScrollWheelEvent {165
position: point(px(100.), px(200.)),166
delta: ScrollDelta::Pixels(point(px(0.), px(delta_y))),167
touch_phase,168
..Default::default()169
});170
self.draw();171
}57
172
58
use super::{EdgeRule, content_hidden_above, edge_visible};173
fn touchpad_swipe(&mut self, delta_y: f32, steps: usize) {174
self.wheel(delta_y, TouchPhase::Started);175
for _ in 0..steps {176
self.wheel(delta_y, TouchPhase::Moved);177
}178
self.wheel(0., TouchPhase::Ended);179
}180
181
fn offset_y(&self) -> f32 {182
f32::from(self.handle.offset().y)183
}184
185
fn shows_line(&mut self) -> bool {186
self.window_cx.debug_bounds(EDGE_TAG).is_some()187
}188
}189
190
fn open(cx: &mut TestAppContext) -> Harness<'_> {191
cx.update(gpui_kit::init);192
let handle = ScrollHandle::new();193
let rendered_offsets = Rc::new(RefCell::new(Vec::new()));194
let (view, window_cx): (Entity<EdgeList>, _) = cx.add_window_view({195
let handle = handle.clone();196
let rendered_offsets = rendered_offsets.clone();197
move |_, _| EdgeList {198
handle,199
rendered_offsets,200
}201
});202
let notifications = Rc::new(Cell::new(0));203
window_cx.update({204
let notifications = notifications.clone();205
move |_, cx| {206
cx.observe(&view, move |_, _| {207
notifications.set(notifications.get() + 1)208
})209
.detach()210
}211
});212
let mut harness = Harness {213
window_cx,214
handle,215
notifications,216
rendered_offsets,217
};218
harness.draw();219
harness220
}221
222
#[gpui_kit::test]223
fn touchpad_overscroll_at_the_top_changes_nothing(cx: &mut TestAppContext) {224
let mut harness = open(cx);225
harness.notifications.set(0);226
harness.touchpad_swipe(35., 12);227
assert_eq!(harness.offset_y(), 0.);228
assert_eq!(harness.notifications.get(), 0, "no re-render at the edge");229
assert!(!harness.shows_line());230
}231
232
#[gpui_kit::test]233
fn touchpad_overscroll_at_the_bottom_changes_nothing(cx: &mut TestAppContext) {234
let mut harness = open(cx);235
harness.wheel(-100_000., TouchPhase::Moved);236
let bottom = harness.offset_y();237
assert!(bottom < -1000.);238
harness.notifications.set(0);239
harness.touchpad_swipe(-35., 12);240
assert_eq!(harness.offset_y(), bottom);241
assert_eq!(harness.notifications.get(), 0);242
assert!(harness.shows_line());243
}244
245
#[gpui_kit::test]246
fn overshoot_past_the_top_is_never_rendered(cx: &mut TestAppContext) {247
let mut harness = open(cx);248
harness.wheel(-10., TouchPhase::Moved);249
assert_eq!(harness.offset_y(), -10.);250
harness.rendered_offsets.borrow_mut().clear();251
harness.touchpad_swipe(400., 2);252
assert_eq!(harness.offset_y(), 0.);253
let rendered = harness.rendered_offsets.borrow().clone();254
assert!(255
rendered.iter().all(|offset| *offset <= 0.),256
"render saw an offset past the top: {rendered:?}"257
);258
assert!(!harness.shows_line());259
}260
261
#[gpui_kit::test]262
fn scrolling_down_from_the_top_still_scrolls(cx: &mut TestAppContext) {263
let mut harness = open(cx);264
harness.touchpad_swipe(-30., 4);265
assert_eq!(harness.offset_y(), -150.);266
assert!(harness.shows_line());267
harness.touchpad_swipe(30., 4);268
assert_eq!(harness.offset_y(), 0.);269
assert!(!harness.shows_line());270
}271
272
#[test]273
fn settled_offset_stays_inside_the_scroll_range() {274
let max = point(px(0.), px(500.));275
assert_eq!(settled_offset(point(px(0.), px(120.)), max).y, px(0.));276
assert_eq!(settled_offset(point(px(0.), px(-900.)), max).y, px(-500.));277
assert_eq!(settled_offset(point(px(0.), px(-200.)), max).y, px(-200.));278
assert_eq!(279
settled_offset(point(px(0.), px(-40.)), point(px(0.), px(0.))).y,280
px(0.)281
);282
}283
284
#[test]285
fn only_deltas_beyond_an_edge_are_held_back() {286
let max = px(500.);287
assert!(pushes_past_edge(px(0.), max, point(px(0.), px(30.))));288
assert!(pushes_past_edge(px(0.), max, point(px(12.), px(0.))));289
assert!(!pushes_past_edge(px(0.), max, point(px(0.), px(-30.))));290
assert!(!pushes_past_edge(px(-10.), max, point(px(0.), px(30.))));291
assert!(pushes_past_edge(px(-500.), max, point(px(0.), px(-30.))));292
assert!(!pushes_past_edge(px(-500.), max, point(px(0.), px(30.))));293
assert!(!pushes_past_edge(px(0.), max, point(px(0.), px(0.))));294
}59
295
60
#[test]296
#[test]61
fn the_list_at_its_top_shows_no_line() {297
fn the_list_at_its_top_shows_no_line() {@@ -11,7 +11,7 @@ use gpui_kit::*;
11
11
use super::avatar::person_avatar;
12
12
use super::join_dialog::open_join_with_id;
13
13
use super::new_meeting_dialog::open_new_meeting;
14
use super::scroll_edge::with_top_edge;
14
use super::scroll_edge::{scroll_offset, with_top_edge};
15
15
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
16
16
use super::widgets::{icon, menu_icon};
17
17
use crate::app_state::AppState;
@@ -411,7 +411,7 @@ pub fn calls_body(
411
411
let rebuild_state = state.clone();
412
412
cx.defer(move |cx| rebuild_state.update(cx, |state, cx| state.rebuild_calls_list(cx)));
413
413
}
414
let top = -f32::from(scroll.offset().y);
414
let top = -f32::from(scroll_offset(scroll).y);
415
415
let measured = f32::from(scroll.bounds().size.height);
416
416
let height = if measured > 1. {
417
417
measured
@@ -11,7 +11,7 @@ use gpui_kit::*;11
use super::avatar::person_avatar;11
use super::avatar::person_avatar;12
use super::join_dialog::open_join_with_id;12
use super::join_dialog::open_join_with_id;13
use super::new_meeting_dialog::open_new_meeting;13
use super::new_meeting_dialog::open_new_meeting;14
use super::scroll_edge::with_top_edge;14
use super::scroll_edge::{scroll_offset, with_top_edge};15
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;15
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;16
use super::widgets::{icon, menu_icon};16
use super::widgets::{icon, menu_icon};17
use crate::app_state::AppState;17
use crate::app_state::AppState;@@ -411,7 +411,7 @@ pub fn calls_body(411
let rebuild_state = state.clone();411
let rebuild_state = state.clone();412
cx.defer(move |cx| rebuild_state.update(cx, |state, cx| state.rebuild_calls_list(cx)));412
cx.defer(move |cx| rebuild_state.update(cx, |state, cx| state.rebuild_calls_list(cx)));413
}413
}414
let top = -f32::from(scroll.offset().y);414
let top = -f32::from(scroll_offset(scroll).y);415
let measured = f32::from(scroll.bounds().size.height);415
let measured = f32::from(scroll.bounds().size.height);416
let height = if measured > 1. {416
let height = if measured > 1. {417
measured417
measured@@ -2,7 +2,7 @@ use gpui_kit::assets::IconName;
2
2
use gpui_kit::component::tooltip::Tooltip;
3
3
use gpui_kit::prelude::FluentBuilder as _;
4
4
use gpui_kit::*;
5
use teams_core::CardMedia;
5
use teams_core::{CardMedia, fallback_poster_url};
6
6
7
7
use super::widgets::icon;
8
8
use crate::theme;
@@ -19,13 +19,17 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
19
19
let source_url = media.source_url.clone();
20
20
let alt_text = media.alt_text.clone();
21
21
let poster = match &media.poster_url {
22
Some(url) => img(url.clone())
23
.size_full()
24
.rounded(px(MEDIA_RADIUS))
25
.object_fit(ObjectFit::Cover)
26
.with_loading(placeholder)
27
.with_fallback(placeholder)
28
.into_any_element(),
22
Some(url) => {
23
let fallback_url = fallback_poster_url(url);
24
poster_image(url.clone())
25
.with_fallback(move || match fallback_url.clone() {
26
Some(fallback_url) => poster_image(fallback_url)
27
.with_fallback(placeholder)
28
.into_any_element(),
29
None => placeholder(),
30
})
31
.into_any_element()
32
}
29
33
None => placeholder(),
30
34
};
31
35
div()
@@ -71,6 +75,14 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
71
75
.into_any_element()
72
76
}
73
77
78
fn poster_image(url: String) -> Img {
79
img(url)
80
.size_full()
81
.rounded(px(MEDIA_RADIUS))
82
.object_fit(ObjectFit::Cover)
83
.with_loading(placeholder)
84
}
85
74
86
fn placeholder() -> AnyElement {
75
87
div()
76
88
.size_full()
@@ -2,7 +2,7 @@ use gpui_kit::assets::IconName;2
use gpui_kit::component::tooltip::Tooltip;2
use gpui_kit::component::tooltip::Tooltip;3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;4
use gpui_kit::*;5
use teams_core::CardMedia;5
use teams_core::{CardMedia, fallback_poster_url};6
6
7
use super::widgets::icon;7
use super::widgets::icon;8
use crate::theme;8
use crate::theme;@@ -19,13 +19,17 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {19
let source_url = media.source_url.clone();19
let source_url = media.source_url.clone();20
let alt_text = media.alt_text.clone();20
let alt_text = media.alt_text.clone();21
let poster = match &media.poster_url {21
let poster = match &media.poster_url {22
Some(url) => img(url.clone())22
Some(url) => {23
.size_full()23
let fallback_url = fallback_poster_url(url);24
.rounded(px(MEDIA_RADIUS))24
poster_image(url.clone())25
.object_fit(ObjectFit::Cover)25
.with_fallback(move || match fallback_url.clone() {26
.with_loading(placeholder)26
Some(fallback_url) => poster_image(fallback_url)27
.with_fallback(placeholder)27
.with_fallback(placeholder)28
.into_any_element(),28
.into_any_element(),29
None => placeholder(),30
})31
.into_any_element()32
}29
None => placeholder(),33
None => placeholder(),30
};34
};31
div()35
div()@@ -71,6 +75,14 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {71
.into_any_element()75
.into_any_element()72
}76
}73
77
78
fn poster_image(url: String) -> Img {79
img(url)80
.size_full()81
.rounded(px(MEDIA_RADIUS))82
.object_fit(ObjectFit::Cover)83
.with_loading(placeholder)84
}85
74
fn placeholder() -> AnyElement {86
fn placeholder() -> AnyElement {75
div()87
div()76
.size_full()88
.size_full()@@ -20,7 +20,7 @@ use super::activity_panel::ActivityPanel;
20
20
use super::avatar::{spec_avatar, square_avatar, with_presence};
21
21
use super::calls_tab::calls_body;
22
22
use super::saved_panel::SavedPanel;
23
use super::scroll_edge::with_top_edge;
23
use super::scroll_edge::{scroll_offset, with_top_edge};
24
24
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
25
25
use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
26
26
use crate::agents::AgentsPanel;
@@ -1267,7 +1267,7 @@ impl SidebarView {
1267
1267
(sections, section_menus, menu, state.local_previews.clone())
1268
1268
};
1269
1269
1270
let top = -f32::from(self.chats_scroll.offset().y);
1270
let top = -f32::from(scroll_offset(&self.chats_scroll).y);
1271
1271
let measured: f32 = f32::from(self.chats_scroll.bounds().size.height);
1272
1272
let height = if measured > 1. {
1273
1273
measured
@@ -20,7 +20,7 @@ use super::activity_panel::ActivityPanel;20
use super::avatar::{spec_avatar, square_avatar, with_presence};20
use super::avatar::{spec_avatar, square_avatar, with_presence};21
use super::calls_tab::calls_body;21
use super::calls_tab::calls_body;22
use super::saved_panel::SavedPanel;22
use super::saved_panel::SavedPanel;23
use super::scroll_edge::with_top_edge;23
use super::scroll_edge::{scroll_offset, with_top_edge};24
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};24
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};25
use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};25
use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};26
use crate::agents::AgentsPanel;26
use crate::agents::AgentsPanel;@@ -1267,7 +1267,7 @@ impl SidebarView {1267
(sections, section_menus, menu, state.local_previews.clone())1267
(sections, section_menus, menu, state.local_previews.clone())1268
};1268
};1269
1269
1270
let top = -f32::from(self.chats_scroll.offset().y);1270
let top = -f32::from(scroll_offset(&self.chats_scroll).y);1271
let measured: f32 = f32::from(self.chats_scroll.bounds().size.height);1271
let measured: f32 = f32::from(self.chats_scroll.bounds().size.height);1272
let height = if measured > 1. {1272
let height = if measured > 1. {1273
measured1273
measured@@ -1025,7 +1025,8 @@ fn parse_media(value: &Value) -> Option<CardMedia> {
1025
1025
Some(CardMedia {
1026
1026
poster_url: string_field(value, "poster")
1027
1027
.filter(|url| url.starts_with(IMAGE_URL_SCHEME))
1028
.map(str::to_owned),
1028
.map(str::to_owned)
1029
.or_else(|| crate::youtube::poster_url(source_url)),
1029
1030
source_url: source_url.to_owned(),
1030
1031
alt_text: string_field(value, "altText")
1031
1032
.filter(|text| !text.trim().is_empty())
@@ -1025,7 +1025,8 @@ fn parse_media(value: &Value) -> Option<CardMedia> {1025
Some(CardMedia {1025
Some(CardMedia {1026
poster_url: string_field(value, "poster")1026
poster_url: string_field(value, "poster")1027
.filter(|url| url.starts_with(IMAGE_URL_SCHEME))1027
.filter(|url| url.starts_with(IMAGE_URL_SCHEME))1028
.map(str::to_owned),1028
.map(str::to_owned)1029
.or_else(|| crate::youtube::poster_url(source_url)),1029
source_url: source_url.to_owned(),1030
source_url: source_url.to_owned(),1030
alt_text: string_field(value, "altText")1031
alt_text: string_field(value, "altText")1031
.filter(|text| !text.trim().is_empty())1032
.filter(|text| !text.trim().is_empty())@@ -65,6 +65,7 @@ mod teams_quote;
65
65
mod time_zone;
66
66
mod translate_sync;
67
67
mod translation;
68
mod youtube;
68
69
69
70
pub use adaptive_card::{
70
71
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,
@@ -146,6 +147,7 @@ pub use graph::{
146
147
pub use images::StoredImage;
147
148
pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};
148
149
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};
150
pub use youtube::fallback_poster_url;
149
151
pub use mapping::{chat_record, message_record};
150
152
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
151
153
pub use meeting_join::{
@@ -65,6 +65,7 @@ mod teams_quote;65
mod time_zone;65
mod time_zone;66
mod translate_sync;66
mod translate_sync;67
mod translation;67
mod translation;68
mod youtube;68
69
69
pub use adaptive_card::{70
pub use adaptive_card::{70
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,71
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,@@ -146,6 +147,7 @@ pub use graph::{146
pub use images::StoredImage;147
pub use images::StoredImage;147
pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};148
pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};148
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};149
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};150
pub use youtube::fallback_poster_url;149
pub use mapping::{chat_record, message_record};151
pub use mapping::{chat_record, message_record};150
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};152
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};151
pub use meeting_join::{153
pub use meeting_join::{@@ -5,7 +5,7 @@ use scraper::{Html, Selector};
5
5
use serde_json::{Value, json};
6
6
use store::MessageRecord;
7
7
8
use crate::stored::ImageRef;
8
use crate::stored::{AttachmentInfo, ImageRef, attachments};
9
9
10
10
pub const EMPTY_LINKS: &str = "[]";
11
11
@@ -90,7 +90,12 @@ impl LinkPreview {
90
90
}
91
91
92
92
fn is_showable(&self) -> bool {
93
self.title.is_some() || self.image_url.is_some()
93
let parts = [
94
self.image_url.is_some(),
95
self.title.is_some(),
96
self.description.is_some(),
97
];
98
parts.into_iter().filter(|present| *present).count() >= 2
94
99
}
95
100
}
96
101
@@ -103,10 +108,11 @@ pub fn has_stored_links(links_json: &str) -> bool {
103
108
}
104
109
105
110
pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {
106
if record.deleted {
111
if record.deleted || has_link_unfurl_card(record) {
107
112
return None;
108
113
}
109
select_preview(&record.links_json)
114
let first_link = first_link(&record.body_html)?;
115
select_preview(&record.links_json).filter(|preview| same_link(&preview.url, &first_link))
110
116
}
111
117
112
118
pub fn select_preview(links_json: &str) -> Option<LinkPreview> {
@@ -114,8 +120,27 @@ pub fn select_preview(links_json: &str) -> Option<LinkPreview> {
114
120
entries.iter().find_map(entry_preview)
115
121
}
116
122
123
fn has_link_unfurl_card(record: &MessageRecord) -> bool {
124
attachments(record)
125
.iter()
126
.any(AttachmentInfo::is_link_unfurl_card)
127
}
128
129
fn first_link(html: &str) -> Option<String> {
130
let selector = Selector::parse("a[href]").ok()?;
131
Html::parse_fragment(html)
132
.select(&selector)
133
.find_map(|anchor| anchor.value().attr("href"))
134
.map(str::to_owned)
135
}
136
137
fn same_link(first: &str, second: &str) -> bool {
138
let normalize = |url: &str| url.trim().trim_end_matches('/').to_ascii_lowercase();
139
normalize(first) == normalize(second)
140
}
141
117
142
fn entry_preview(entry: &Value) -> Option<LinkPreview> {
118
if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) {
143
if entry.get("previewenabled").and_then(Value::as_bool) != Some(true) {
119
144
return None;
120
145
}
121
146
let url = entry.get("url")?.as_str()?;
@@ -269,12 +294,13 @@ mod tests {
269
294
}
270
295
271
296
#[test]
272
fn picks_the_first_public_link_with_a_title() {
297
fn picks_the_first_enabled_public_link_with_two_parts() {
273
298
let preview = select_preview(&links(json!([
274
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true},
299
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File", "description": "F"}, "previewenabled": true},
275
300
{"url": "https://a.example/x", "preview": {}, "previewenabled": true},
276
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}},
277
{"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true},
301
{"url": "https://n.example/x", "preview": {"title": "N", "description": "No flag"}},
302
{"url": "https://t.example/x", "preview": {"title": "Title only"}, "previewenabled": true},
303
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}, "previewenabled": true},
278
304
])))
279
305
.unwrap();
280
306
assert_eq!(preview.url, "https://b.example/y");
@@ -284,9 +310,15 @@ mod tests {
284
310
}
285
311
286
312
#[test]
287
fn an_image_alone_is_enough() {
313
fn an_image_needs_a_title_or_description() {
314
assert_eq!(
315
select_preview(&links(json!([
316
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL}, "previewenabled": true},
317
]))),
318
None
319
);
288
320
let preview = select_preview(&links(json!([
289
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null},
321
{"url": "https://a.example", "preview": {"description": "D", "previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": true},
290
322
])))
291
323
.unwrap();
292
324
assert_eq!(preview.title, None);
@@ -300,8 +332,7 @@ mod tests {
300
332
#[test]
301
333
fn reads_the_camel_case_meta_and_null_meta() {
302
334
let preview = select_preview(&links(json!([
303
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}},
304
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
335
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}, "previewenabled": true},
305
336
])))
306
337
.unwrap();
307
338
assert_eq!(
@@ -309,12 +340,99 @@ mod tests {
309
340
(Some(20), Some(10))
310
341
);
311
342
let second = select_preview(&links(json!([
312
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
343
{"url": "https://b.example", "preview": {"title": "B", "description": "D", "previewmeta": null}, "previewenabled": true},
313
344
])))
314
345
.unwrap();
315
346
assert_eq!(second.image_width, None);
316
347
}
317
348
349
fn linked_record(body_html: &str, links_json: Value, attachments_json: Value) -> MessageRecord {
350
MessageRecord {
351
body_html: body_html.to_owned(),
352
links_json: links(links_json),
353
attachments_json: attachments_json.to_string(),
354
..demo_record()
355
}
356
}
357
358
fn video_link_entry(previewenabled: Value) -> Value {
359
json!([{
360
"@type": HYPERLINK_TYPE,
361
"itemid": "0",
362
"url": "https://www.youtube.com/watch?v=video_id_01",
363
"preview": {"title": "Sample video", "description": "1K views", "previewurl": THUMBNAIL},
364
"previewenabled": previewenabled,
365
}])
366
}
367
368
fn unfurl_card(id: &str, teams_app_id: Option<&str>) -> Value {
369
let content = json!({
370
"type": "AdaptiveCard",
371
"version": "1.5",
372
"body": [
373
{"type": "Media", "sources": [{"mimeType": "video/mp4", "url": "https://www.youtube.com/watch?v=video_id_01"}]},
374
{"type": "TextBlock", "text": "Sample video"},
375
{"type": "TextBlock", "text": "Sample channel"},
376
],
377
"actions": [{"type": "Action.OpenUrl", "title": "Open", "url": "https://www.youtube.com/watch?v=video_id_01"}],
378
});
379
json!([{
380
"content_type": "application/vnd.microsoft.card.adaptive",
381
"name": null,
382
"url": null,
383
"text": null,
384
"id": id,
385
"content": content.to_string(),
386
"teams_app_id": teams_app_id,
387
}])
388
}
389
390
const VIDEO_BODY: &str = "<p><a href=\"https://www.youtube.com/watch?v=video_id_01\">https://www.youtube.com/watch?v=video_id_01</a></p>";
391
392
#[test]
393
fn a_video_link_with_its_unfurl_card_shows_only_the_card() {
394
let teams_sent = linked_record(
395
VIDEO_BODY,
396
video_link_entry(json!(false)),
397
unfurl_card("app-preview-card-1", None),
398
);
399
assert_eq!(link_preview(&teams_sent), None);
400
let flagged_on = linked_record(
401
VIDEO_BODY,
402
video_link_entry(json!(true)),
403
unfurl_card(
404
"74d20c7f34aa4a7f",
405
Some("4623dd0c-d55c-4c95-9290-ad31619b577a"),
406
),
407
);
408
assert_eq!(link_preview(&flagged_on), None);
409
let by_card_id = linked_record(
410
VIDEO_BODY,
411
video_link_entry(json!(true)),
412
unfurl_card("app-preview-card-2", None),
413
);
414
assert_eq!(link_preview(&by_card_id), None);
415
let cards = crate::stored::adaptive_cards(&flagged_on);
416
assert_eq!(cards.len(), 1);
417
}
418
419
#[test]
420
fn a_video_link_without_a_card_keeps_its_preview() {
421
let record = linked_record(VIDEO_BODY, video_link_entry(json!(true)), json!([]));
422
let preview = link_preview(&record).unwrap();
423
assert_eq!(preview.domain(), "youtube.com");
424
let missing_flag = linked_record(VIDEO_BODY, video_link_entry(Value::Null), json!([]));
425
assert_eq!(link_preview(&missing_flag), None);
426
}
427
428
#[test]
429
fn only_the_first_link_of_the_message_gets_a_preview() {
430
let body = "<p><a href=\"https://other.example/\">other</a> <a href=\"https://www.youtube.com/watch?v=video_id_01\">video</a></p>";
431
let record = linked_record(body, video_link_entry(json!(true)), json!([]));
432
assert_eq!(link_preview(&record), None);
433
assert!(same_link("https://A.example/x/", "https://a.example/x"));
434
}
435
318
436
#[test]
319
437
fn a_removed_preview_is_not_shown() {
320
438
assert_eq!(
@@ -418,7 +536,10 @@ mod tests {
418
536
fn deleted_messages_show_no_preview() {
419
537
let record = MessageRecord {
420
538
deleted: true,
421
links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])),
539
body_html: "<p><a href=\"https://a.example\">a</a></p>".to_owned(),
540
links_json: links(
541
json!([{"url": "https://a.example", "preview": {"title": "A", "description": "D"}, "previewenabled": true}]),
542
),
422
543
..MessageRecord::default()
423
544
};
424
545
assert_eq!(link_preview(&record), None);
@@ -5,7 +5,7 @@ use scraper::{Html, Selector};5
use serde_json::{Value, json};5
use serde_json::{Value, json};6
use store::MessageRecord;6
use store::MessageRecord;7
7
8
use crate::stored::ImageRef;8
use crate::stored::{AttachmentInfo, ImageRef, attachments};9
9
10
pub const EMPTY_LINKS: &str = "[]";10
pub const EMPTY_LINKS: &str = "[]";11
11
@@ -90,7 +90,12 @@ impl LinkPreview {90
}90
}91
91
92
fn is_showable(&self) -> bool {92
fn is_showable(&self) -> bool {93
self.title.is_some() || self.image_url.is_some()93
let parts = [94
self.image_url.is_some(),95
self.title.is_some(),96
self.description.is_some(),97
];98
parts.into_iter().filter(|present| *present).count() >= 294
}99
}95
}100
}96
101
@@ -103,10 +108,11 @@ pub fn has_stored_links(links_json: &str) -> bool {103
}108
}104
109
105
pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {110
pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {106
if record.deleted {111
if record.deleted || has_link_unfurl_card(record) {107
return None;112
return None;108
}113
}109
select_preview(&record.links_json)114
let first_link = first_link(&record.body_html)?;115
select_preview(&record.links_json).filter(|preview| same_link(&preview.url, &first_link))110
}116
}111
117
112
pub fn select_preview(links_json: &str) -> Option<LinkPreview> {118
pub fn select_preview(links_json: &str) -> Option<LinkPreview> {@@ -114,8 +120,27 @@ pub fn select_preview(links_json: &str) -> Option<LinkPreview> {114
entries.iter().find_map(entry_preview)120
entries.iter().find_map(entry_preview)115
}121
}116
122
123
fn has_link_unfurl_card(record: &MessageRecord) -> bool {124
attachments(record)125
.iter()126
.any(AttachmentInfo::is_link_unfurl_card)127
}128
129
fn first_link(html: &str) -> Option<String> {130
let selector = Selector::parse("a[href]").ok()?;131
Html::parse_fragment(html)132
.select(&selector)133
.find_map(|anchor| anchor.value().attr("href"))134
.map(str::to_owned)135
}136
137
fn same_link(first: &str, second: &str) -> bool {138
let normalize = |url: &str| url.trim().trim_end_matches('/').to_ascii_lowercase();139
normalize(first) == normalize(second)140
}141
117
fn entry_preview(entry: &Value) -> Option<LinkPreview> {142
fn entry_preview(entry: &Value) -> Option<LinkPreview> {118
if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) {143
if entry.get("previewenabled").and_then(Value::as_bool) != Some(true) {119
return None;144
return None;120
}145
}121
let url = entry.get("url")?.as_str()?;146
let url = entry.get("url")?.as_str()?;@@ -269,12 +294,13 @@ mod tests {269
}294
}270
295
271
#[test]296
#[test]272
fn picks_the_first_public_link_with_a_title() {297
fn picks_the_first_enabled_public_link_with_two_parts() {273
let preview = select_preview(&links(json!([298
let preview = select_preview(&links(json!([274
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true},299
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File", "description": "F"}, "previewenabled": true},275
{"url": "https://a.example/x", "preview": {}, "previewenabled": true},300
{"url": "https://a.example/x", "preview": {}, "previewenabled": true},276
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}},301
{"url": "https://n.example/x", "preview": {"title": "N", "description": "No flag"}},277
{"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true},302
{"url": "https://t.example/x", "preview": {"title": "Title only"}, "previewenabled": true},303
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}, "previewenabled": true},278
])))304
])))279
.unwrap();305
.unwrap();280
assert_eq!(preview.url, "https://b.example/y");306
assert_eq!(preview.url, "https://b.example/y");@@ -284,9 +310,15 @@ mod tests {284
}310
}285
311
286
#[test]312
#[test]287
fn an_image_alone_is_enough() {313
fn an_image_needs_a_title_or_description() {314
assert_eq!(315
select_preview(&links(json!([316
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL}, "previewenabled": true},317
]))),318
None319
);288
let preview = select_preview(&links(json!([320
let preview = select_preview(&links(json!([289
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null},321
{"url": "https://a.example", "preview": {"description": "D", "previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": true},290
])))322
])))291
.unwrap();323
.unwrap();292
assert_eq!(preview.title, None);324
assert_eq!(preview.title, None);@@ -300,8 +332,7 @@ mod tests {300
#[test]332
#[test]301
fn reads_the_camel_case_meta_and_null_meta() {333
fn reads_the_camel_case_meta_and_null_meta() {302
let preview = select_preview(&links(json!([334
let preview = select_preview(&links(json!([303
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}},335
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}, "previewenabled": true},304
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},305
])))336
])))306
.unwrap();337
.unwrap();307
assert_eq!(338
assert_eq!(@@ -309,12 +340,99 @@ mod tests {309
(Some(20), Some(10))340
(Some(20), Some(10))310
);341
);311
let second = select_preview(&links(json!([342
let second = select_preview(&links(json!([312
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},343
{"url": "https://b.example", "preview": {"title": "B", "description": "D", "previewmeta": null}, "previewenabled": true},313
])))344
])))314
.unwrap();345
.unwrap();315
assert_eq!(second.image_width, None);346
assert_eq!(second.image_width, None);316
}347
}317
348
349
fn linked_record(body_html: &str, links_json: Value, attachments_json: Value) -> MessageRecord {350
MessageRecord {351
body_html: body_html.to_owned(),352
links_json: links(links_json),353
attachments_json: attachments_json.to_string(),354
..demo_record()355
}356
}357
358
fn video_link_entry(previewenabled: Value) -> Value {359
json!([{360
"@type": HYPERLINK_TYPE,361
"itemid": "0",362
"url": "https://www.youtube.com/watch?v=video_id_01",363
"preview": {"title": "Sample video", "description": "1K views", "previewurl": THUMBNAIL},364
"previewenabled": previewenabled,365
}])366
}367
368
fn unfurl_card(id: &str, teams_app_id: Option<&str>) -> Value {369
let content = json!({370
"type": "AdaptiveCard",371
"version": "1.5",372
"body": [373
{"type": "Media", "sources": [{"mimeType": "video/mp4", "url": "https://www.youtube.com/watch?v=video_id_01"}]},374
{"type": "TextBlock", "text": "Sample video"},375
{"type": "TextBlock", "text": "Sample channel"},376
],377
"actions": [{"type": "Action.OpenUrl", "title": "Open", "url": "https://www.youtube.com/watch?v=video_id_01"}],378
});379
json!([{380
"content_type": "application/vnd.microsoft.card.adaptive",381
"name": null,382
"url": null,383
"text": null,384
"id": id,385
"content": content.to_string(),386
"teams_app_id": teams_app_id,387
}])388
}389
390
const VIDEO_BODY: &str = "<p><a href=\"https://www.youtube.com/watch?v=video_id_01\">https://www.youtube.com/watch?v=video_id_01</a></p>";391
392
#[test]393
fn a_video_link_with_its_unfurl_card_shows_only_the_card() {394
let teams_sent = linked_record(395
VIDEO_BODY,396
video_link_entry(json!(false)),397
unfurl_card("app-preview-card-1", None),398
);399
assert_eq!(link_preview(&teams_sent), None);400
let flagged_on = linked_record(401
VIDEO_BODY,402
video_link_entry(json!(true)),403
unfurl_card(404
"74d20c7f34aa4a7f",405
Some("4623dd0c-d55c-4c95-9290-ad31619b577a"),406
),407
);408
assert_eq!(link_preview(&flagged_on), None);409
let by_card_id = linked_record(410
VIDEO_BODY,411
video_link_entry(json!(true)),412
unfurl_card("app-preview-card-2", None),413
);414
assert_eq!(link_preview(&by_card_id), None);415
let cards = crate::stored::adaptive_cards(&flagged_on);416
assert_eq!(cards.len(), 1);417
}418
419
#[test]420
fn a_video_link_without_a_card_keeps_its_preview() {421
let record = linked_record(VIDEO_BODY, video_link_entry(json!(true)), json!([]));422
let preview = link_preview(&record).unwrap();423
assert_eq!(preview.domain(), "youtube.com");424
let missing_flag = linked_record(VIDEO_BODY, video_link_entry(Value::Null), json!([]));425
assert_eq!(link_preview(&missing_flag), None);426
}427
428
#[test]429
fn only_the_first_link_of_the_message_gets_a_preview() {430
let body = "<p><a href=\"https://other.example/\">other</a> <a href=\"https://www.youtube.com/watch?v=video_id_01\">video</a></p>";431
let record = linked_record(body, video_link_entry(json!(true)), json!([]));432
assert_eq!(link_preview(&record), None);433
assert!(same_link("https://A.example/x/", "https://a.example/x"));434
}435
318
#[test]436
#[test]319
fn a_removed_preview_is_not_shown() {437
fn a_removed_preview_is_not_shown() {320
assert_eq!(438
assert_eq!(@@ -418,7 +536,10 @@ mod tests {418
fn deleted_messages_show_no_preview() {536
fn deleted_messages_show_no_preview() {419
let record = MessageRecord {537
let record = MessageRecord {420
deleted: true,538
deleted: true,421
links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])),539
body_html: "<p><a href=\"https://a.example\">a</a></p>".to_owned(),540
links_json: links(541
json!([{"url": "https://a.example", "preview": {"title": "A", "description": "D"}, "previewenabled": true}]),542
),422
..MessageRecord::default()543
..MessageRecord::default()423
};544
};424
assert_eq!(link_preview(&record), None);545
assert_eq!(link_preview(&record), None);@@ -245,6 +245,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
245
245
)
246
246
}),
247
247
unavailable: false,
248
teams_app_id: attachment.teams_app_id.clone(),
248
249
}
249
250
}
250
251
@@ -245,6 +245,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {245
)245
)246
}),246
}),247
unavailable: false,247
unavailable: false,248
teams_app_id: attachment.teams_app_id.clone(),248
}249
}249
}250
}250
251
@@ -12,6 +12,8 @@ use crate::spans::{Span, html_to_spans};
12
12
13
13
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
14
14
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
15
const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";
16
const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";
15
17
16
18
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17
19
pub struct AttachmentInfo {
@@ -31,6 +33,8 @@ pub struct AttachmentInfo {
31
33
/// A forward whose original Graph did not return; it is not fetched again.
32
34
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
33
35
pub unavailable: bool,
36
#[serde(default, skip_serializing_if = "Option::is_none")]
37
pub teams_app_id: Option<String>,
34
38
}
35
39
36
40
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -108,6 +112,18 @@ impl AttachmentInfo {
108
112
.is_some_and(|content_type| content_type.contains("card"))
109
113
}
110
114
115
pub fn is_link_unfurl_card(&self) -> bool {
116
self.is_card()
117
&& (self
118
.teams_app_id
119
.as_deref()
120
.is_some_and(|app_id| app_id.eq_ignore_ascii_case(LINK_UNFURL_APP_ID))
121
|| self
122
.id
123
.as_deref()
124
.is_some_and(|id| id.starts_with(LINK_UNFURL_CARD_PREFIX)))
125
}
126
111
127
pub fn adaptive_card(&self) -> Option<AdaptiveCard> {
112
128
self.content
113
129
.as_deref()
@@ -1053,6 +1069,7 @@ mod tests {
1053
1069
id: None,
1054
1070
content: None,
1055
1071
unavailable: false,
1072
teams_app_id: None,
1056
1073
}
1057
1074
.file_kind()
1058
1075
};
@@ -1107,6 +1124,7 @@ mod tests {
1107
1124
content_type: Some("messageReference".to_owned()),
1108
1125
content_url: None,
1109
1126
name: None,
1127
teams_app_id: None,
1110
1128
content: Some(
1111
1129
r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),
1112
1130
),
@@ -12,6 +12,8 @@ use crate::spans::{Span, html_to_spans};12
12
13
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";13
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";14
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";14
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";15
const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";16
const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";15
17
16
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]18
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]17
pub struct AttachmentInfo {19
pub struct AttachmentInfo {@@ -31,6 +33,8 @@ pub struct AttachmentInfo {31
/// A forward whose original Graph did not return; it is not fetched again.33
/// A forward whose original Graph did not return; it is not fetched again.32
#[serde(default, skip_serializing_if = "std::ops::Not::not")]34
#[serde(default, skip_serializing_if = "std::ops::Not::not")]33
pub unavailable: bool,35
pub unavailable: bool,36
#[serde(default, skip_serializing_if = "Option::is_none")]37
pub teams_app_id: Option<String>,34
}38
}35
39
36
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]40
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]@@ -108,6 +112,18 @@ impl AttachmentInfo {108
.is_some_and(|content_type| content_type.contains("card"))112
.is_some_and(|content_type| content_type.contains("card"))109
}113
}110
114
115
pub fn is_link_unfurl_card(&self) -> bool {116
self.is_card()117
&& (self118
.teams_app_id119
.as_deref()120
.is_some_and(|app_id| app_id.eq_ignore_ascii_case(LINK_UNFURL_APP_ID))121
|| self122
.id123
.as_deref()124
.is_some_and(|id| id.starts_with(LINK_UNFURL_CARD_PREFIX)))125
}126
111
pub fn adaptive_card(&self) -> Option<AdaptiveCard> {127
pub fn adaptive_card(&self) -> Option<AdaptiveCard> {112
self.content128
self.content113
.as_deref()129
.as_deref()@@ -1053,6 +1069,7 @@ mod tests {1053
id: None,1069
id: None,1054
content: None,1070
content: None,1055
unavailable: false,1071
unavailable: false,1072
teams_app_id: None,1056
}1073
}1057
.file_kind()1074
.file_kind()1058
};1075
};@@ -1107,6 +1124,7 @@ mod tests {1107
content_type: Some("messageReference".to_owned()),1124
content_type: Some("messageReference".to_owned()),1108
content_url: None,1125
content_url: None,1109
name: None,1126
name: None,1127
teams_app_id: None,1110
content: Some(1128
content: Some(1111
r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),1129
r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),1112
),1130
),@@ -0,0 +1,87 @@
1
use url::Url;
2
3
const POSTER_FILE: &str = "maxresdefault.jpg";
4
const FALLBACK_POSTER_FILE: &str = "hqdefault.jpg";
5
6
pub fn video_id(link: &str) -> Option<String> {
7
let parsed = Url::parse(link).ok()?;
8
let host = parsed.host_str()?.to_ascii_lowercase();
9
let host = host
10
.strip_prefix("www.")
11
.or_else(|| host.strip_prefix("m."))
12
.unwrap_or(&host);
13
let mut segments = parsed.path_segments()?;
14
let candidate = match host {
15
"youtu.be" => segments.next().map(str::to_owned),
16
"youtube.com" | "youtube-nocookie.com" => match segments.next()? {
17
"watch" => parsed
18
.query_pairs()
19
.find(|(key, _)| key == "v")
20
.map(|(_, value)| value.into_owned()),
21
"shorts" | "embed" | "live" | "v" => segments.next().map(str::to_owned),
22
_ => None,
23
},
24
_ => None,
25
}?;
26
let valid = !candidate.is_empty()
27
&& candidate
28
.chars()
29
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'));
30
valid.then_some(candidate)
31
}
32
33
pub fn poster_url(link: &str) -> Option<String> {
34
video_id(link).map(|id| format!("https://img.youtube.com/vi/{id}/{POSTER_FILE}"))
35
}
36
37
pub fn fallback_poster_url(poster: &str) -> Option<String> {
38
poster
39
.strip_suffix(POSTER_FILE)
40
.filter(|base| base.starts_with("https://img.youtube.com/vi/"))
41
.map(|base| format!("{base}{FALLBACK_POSTER_FILE}"))
42
}
43
44
#[cfg(test)]
45
mod tests {
46
use super::*;
47
48
#[test]
49
fn reads_the_video_id_from_every_link_form() {
50
for link in [
51
"https://www.youtube.com/watch?v=abc_DEF-123&t=42",
52
"https://youtube.com/watch?feature=share&v=abc_DEF-123",
53
"https://m.youtube.com/watch?v=abc_DEF-123",
54
"https://youtu.be/abc_DEF-123?t=7",
55
"https://www.youtube.com/shorts/abc_DEF-123",
56
"https://www.youtube.com/embed/abc_DEF-123",
57
] {
58
assert_eq!(video_id(link).as_deref(), Some("abc_DEF-123"), "{link}");
59
}
60
}
61
62
#[test]
63
fn other_links_have_no_video() {
64
for link in [
65
"https://example.com/watch?v=abc",
66
"https://www.youtube.com/channel/xyz",
67
"https://www.youtube.com/watch?v=bad%20id",
68
"not a url",
69
] {
70
assert_eq!(video_id(link), None, "{link}");
71
}
72
}
73
74
#[test]
75
fn the_poster_falls_back_to_the_smaller_still() {
76
let poster = poster_url("https://youtu.be/abc").unwrap();
77
assert_eq!(poster, "https://img.youtube.com/vi/abc/maxresdefault.jpg");
78
assert_eq!(
79
fallback_poster_url(&poster).as_deref(),
80
Some("https://img.youtube.com/vi/abc/hqdefault.jpg")
81
);
82
assert_eq!(
83
fallback_poster_url("https://example.com/maxresdefault.jpg"),
84
None
85
);
86
}
87
}
@@ -0,0 +1,87 @@1
use url::Url;2
3
const POSTER_FILE: &str = "maxresdefault.jpg";4
const FALLBACK_POSTER_FILE: &str = "hqdefault.jpg";5
6
pub fn video_id(link: &str) -> Option<String> {7
let parsed = Url::parse(link).ok()?;8
let host = parsed.host_str()?.to_ascii_lowercase();9
let host = host10
.strip_prefix("www.")11
.or_else(|| host.strip_prefix("m."))12
.unwrap_or(&host);13
let mut segments = parsed.path_segments()?;14
let candidate = match host {15
"youtu.be" => segments.next().map(str::to_owned),16
"youtube.com" | "youtube-nocookie.com" => match segments.next()? {17
"watch" => parsed18
.query_pairs()19
.find(|(key, _)| key == "v")20
.map(|(_, value)| value.into_owned()),21
"shorts" | "embed" | "live" | "v" => segments.next().map(str::to_owned),22
_ => None,23
},24
_ => None,25
}?;26
let valid = !candidate.is_empty()27
&& candidate28
.chars()29
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'));30
valid.then_some(candidate)31
}32
33
pub fn poster_url(link: &str) -> Option<String> {34
video_id(link).map(|id| format!("https://img.youtube.com/vi/{id}/{POSTER_FILE}"))35
}36
37
pub fn fallback_poster_url(poster: &str) -> Option<String> {38
poster39
.strip_suffix(POSTER_FILE)40
.filter(|base| base.starts_with("https://img.youtube.com/vi/"))41
.map(|base| format!("{base}{FALLBACK_POSTER_FILE}"))42
}43
44
#[cfg(test)]45
mod tests {46
use super::*;47
48
#[test]49
fn reads_the_video_id_from_every_link_form() {50
for link in [51
"https://www.youtube.com/watch?v=abc_DEF-123&t=42",52
"https://youtube.com/watch?feature=share&v=abc_DEF-123",53
"https://m.youtube.com/watch?v=abc_DEF-123",54
"https://youtu.be/abc_DEF-123?t=7",55
"https://www.youtube.com/shorts/abc_DEF-123",56
"https://www.youtube.com/embed/abc_DEF-123",57
] {58
assert_eq!(video_id(link).as_deref(), Some("abc_DEF-123"), "{link}");59
}60
}61
62
#[test]63
fn other_links_have_no_video() {64
for link in [65
"https://example.com/watch?v=abc",66
"https://www.youtube.com/channel/xyz",67
"https://www.youtube.com/watch?v=bad%20id",68
"not a url",69
] {70
assert_eq!(video_id(link), None, "{link}");71
}72
}73
74
#[test]75
fn the_poster_falls_back_to_the_smaller_still() {76
let poster = poster_url("https://youtu.be/abc").unwrap();77
assert_eq!(poster, "https://img.youtube.com/vi/abc/maxresdefault.jpg");78
assert_eq!(79
fallback_poster_url(&poster).as_deref(),80
Some("https://img.youtube.com/vi/abc/hqdefault.jpg")81
);82
assert_eq!(83
fallback_poster_url("https://example.com/maxresdefault.jpg"),84
None85
);86
}87
}@@ -1041,6 +1041,7 @@ impl Remote for Handle {
1041
1041
Ok(chatsvc::LinkInfo {
1042
1042
url: url.to_owned(),
1043
1043
title: Some("Example".into()),
1044
description: Some("Example page".into()),
1044
1045
..chatsvc::LinkInfo::default()
1045
1046
})
1046
1047
}
@@ -1041,6 +1041,7 @@ impl Remote for Handle {1041
Ok(chatsvc::LinkInfo {1041
Ok(chatsvc::LinkInfo {1042
url: url.to_owned(),1042
url: url.to_owned(),1043
title: Some("Example".into()),1043
title: Some("Example".into()),1044
description: Some("Example page".into()),1044
..chatsvc::LinkInfo::default()1045
..chatsvc::LinkInfo::default()1045
})1046
})1046
}1047
}@@ -95,6 +95,7 @@ pub struct Attachment {
95
95
pub content_url: Option<String>,
96
96
pub name: Option<String>,
97
97
pub content: Option<String>,
98
pub teams_app_id: Option<String>,
98
99
}
99
100
100
101
#[derive(Debug, Clone, Deserialize, PartialEq)]
@@ -95,6 +95,7 @@ pub struct Attachment {95
pub content_url: Option<String>,95
pub content_url: Option<String>,96
pub name: Option<String>,96
pub name: Option<String>,97
pub content: Option<String>,97
pub content: Option<String>,98
pub teams_app_id: Option<String>,98
}99
}99
100
100
#[derive(Debug, Clone, Deserialize, PartialEq)]101
#[derive(Debug, Clone, Deserialize, PartialEq)]