1use cosmic::Element;
21use cosmic::iced::widget::svg;
22use cosmic::iced::widget::text::{Shaping, Wrapping};
23use cosmic::iced::{Alignment, Background, Color, Length, mouse};
24use cosmic::widget::{self, container, icon, text};
25
26use crate::fl;
27use crate::helpers::relative_time;
28use crate::messages::Message;
29use crate::nostr::engagement::Reaction;
30use crate::nostr::models::display_name;
31use crate::nostr::notifications::{Notification, What};
32use crate::nostr::outbox::Whereabouts;
33use crate::views::components::note_row::{
34 NOTE_ACTION_DIM, NOTE_AVATAR_GAP, NOTE_AVATAR_SIZE, NOTE_DIVIDER_HEIGHT, NOTE_PADDING_TOP, RowContext, RowSizes,
35 estimated_note_height, line_height, note_row, opening_profile, opening_thread,
36};
37use crate::views::components::{avatar, like_icon, reply_icon, repost_icon, zap_icon};
38
39const REASON_PADDING_TOP: f32 = 6.0;
41
42const GLYPH_WIDTH: f32 = 22.0;
45
46const LINE_GAP: f32 = 2.0;
49const SHORT_PADDING_BOTTOM: f32 = 8.0;
50
51const NEW_TINT: f32 = 0.10;
53
54fn reason_height(sizes: RowSizes) -> f32 {
57 REASON_PADDING_TOP + line_height(sizes.time())
58}
59
60fn lines_under(notification: &Notification) -> (Option<&str>, Option<&str>) {
64 let comment = match ¬ification.what {
65 What::Zap { comment, .. } if !comment.is_empty() => Some(comment.as_str()),
66 _ => None,
67 };
68 (comment, notification.preview.as_deref().filter(|preview| !preview.is_empty()))
69}
70
71fn short_height(notification: &Notification, sizes: RowSizes) -> f32 {
74 let (comment, preview) = lines_under(notification);
75 let mut lines = line_height(sizes.name());
76 if comment.is_some() {
77 lines += LINE_GAP + line_height(sizes.text());
78 }
79 if preview.is_some() {
80 lines += LINE_GAP + line_height(sizes.time());
81 }
82 f32::from(NOTE_PADDING_TOP) + NOTE_AVATAR_SIZE.max(lines) + SHORT_PADDING_BOTTOM + NOTE_DIVIDER_HEIGHT
83}
84
85pub fn estimated_notification_height(notification: &Notification, sizes: RowSizes, width: f32, in_full: bool) -> f32 {
89 match ¬ification.note {
90 Some(note) => reason_height(sizes) + estimated_note_height(note, sizes, width, in_full),
91 None => short_height(notification, sizes),
92 }
93}
94
95fn reason(what: &What) -> String {
97 match what {
98 What::Reply => fl!("notification-reply"),
99 What::ThreadReply => fl!("notification-thread-reply"),
100 What::Quote => fl!("notification-quote"),
101 _ => fl!("notification-mention"),
102 }
103}
104
105fn deed(what: &What) -> String {
107 match what {
108 What::Reaction(_) => fl!("notification-reaction"),
109 What::Repost => fl!("notification-repost"),
110 What::Zap { sats, .. } => fl!("notification-zap", sats = sats.to_string()),
111 _ => String::new(),
112 }
113}
114
115fn one_line<'a>(said: impl Into<String>, size: u16, color: Color) -> Element<'a, Message> {
118 let said = text(said.into()).size(size).wrapping(Wrapping::None).shaping(Shaping::Advanced);
119 container(said.class(cosmic::theme::Text::Color(color)))
120 .width(Length::Fill)
121 .height(Length::Fixed(line_height(size)))
122 .align_y(Alignment::Center)
123 .clip(true)
124 .into()
125}
126
127fn glyph<'a>(what: &What, accent: Color) -> Element<'a, Message> {
130 let picture = |handle: icon::Handle| -> Element<'a, Message> {
131 icon::icon(handle).size(18).class(cosmic::theme::Svg::custom(move |_theme| svg::Style { color: Some(accent) })).into()
132 };
133 let shown = match what {
134 What::Reaction(Reaction::Emoji(emoji)) => text(emoji.clone()).size(18).shaping(Shaping::Advanced).into(),
135 What::Reaction(Reaction::Like) => picture(like_icon(true)),
136 What::Repost => picture(repost_icon()),
137 What::Zap { .. } => picture(zap_icon()),
138 _ => picture(reply_icon()),
139 };
140 container(shown).center_x(Length::Fixed(GLYPH_WIDTH)).center_y(Length::Fixed(NOTE_AVATAR_SIZE)).into()
141}
142
143fn short_row<'a>(notification: &'a Notification, context: &RowContext<'a>) -> Element<'a, Message> {
148 let RowContext { profiles, images, now, sizes, accent, .. } = *context;
149 let text_color: Color = cosmic::theme::active().cosmic().on_bg_color().into();
150 let dim = Color { a: NOTE_ACTION_DIM, ..text_color };
151 let name = display_name(profiles, ¬ification.who);
152 let picture = profiles.get(¬ification.who).and_then(|profile| profile.picture.as_deref());
153 let picture = opening_profile(avatar(images, picture, ¬ification.who, &name, NOTE_AVATAR_SIZE), notification.who);
154
155 let who = opening_profile(
158 text(name.into_owned()).size(sizes.name()).font(cosmic::font::bold()).wrapping(Wrapping::None),
159 notification.who,
160 );
161 let head = widget::Row::new()
162 .push(container(who).max_width(160.0).clip(true))
163 .push(one_line(deed(¬ification.what), sizes.time(), dim))
164 .push(text(relative_time(now, notification.at)).size(sizes.time()).wrapping(Wrapping::None))
165 .spacing(6)
166 .height(Length::Fixed(line_height(sizes.name())))
167 .align_y(Alignment::Center);
168
169 let (comment, preview) = lines_under(notification);
170 let lines = widget::Column::new()
171 .push(head)
172 .push_maybe(comment.map(|comment| one_line(comment, sizes.text(), text_color)))
173 .push_maybe(preview.map(|preview| one_line(preview, sizes.time(), dim)))
174 .spacing(LINE_GAP)
175 .width(Length::Fill);
176
177 let body = widget::Row::new()
178 .push(glyph(¬ification.what, accent))
179 .push(picture)
180 .push(lines)
181 .spacing(NOTE_AVATAR_GAP)
182 .align_y(Alignment::Start)
183 .height(Length::Fixed(short_height(notification, sizes) - f32::from(NOTE_PADDING_TOP) - NOTE_DIVIDER_HEIGHT));
185 let row = widget::Column::new()
186 .push(body)
187 .push(widget::divider::horizontal::default())
188 .padding([NOTE_PADDING_TOP, 0, 0, 0])
189 .width(Length::Fill);
190
191 let area = widget::mouse_area(row);
192 if context.under_a_menu() {
193 return area.into();
194 }
195 let leads = match notification.about {
196 Some(about) => Message::OpenThread(about, Whereabouts::default()),
197 None => Message::OpenProfile(notification.who),
198 };
199 area.on_press(leads).interaction(mouse::Interaction::Pointer).into()
200}
201
202pub fn notification_row<'a>(notification: &'a Notification, context: &RowContext<'a>, is_new: bool) -> Element<'a, Message> {
206 let sizes = context.sizes;
207 let row: Element<'a, Message> = match ¬ification.note {
208 Some(note) => {
209 let text_color: Color = cosmic::theme::active().cosmic().on_bg_color().into();
210 let dim = Color { a: NOTE_ACTION_DIM, ..text_color };
211 let reason = container(one_line(reason(¬ification.what), sizes.time(), dim))
212 .padding([REASON_PADDING_TOP, 0.0, 0.0, 0.0])
213 .height(Length::Fixed(reason_height(sizes)));
214 widget::Column::new().push(reason).push(opening_thread(note_row(note, context), note.id, context)).into()
216 }
217 None => short_row(notification, context),
218 };
219 if !is_new {
220 return row;
221 }
222 let tint = Color { a: NEW_TINT, ..context.accent };
223 container(row)
224 .class(cosmic::theme::Container::custom(move |_theme| container::Style {
225 background: Some(Background::Color(tint)),
226 ..Default::default()
227 }))
228 .into()
229}
230
231#[cfg(test)]
232mod tests {
233 use super::{estimated_notification_height, notification_row, reason_height, short_height};
234 use crate::images::ImageStore;
235 use crate::messages::Message;
236 use crate::nostr::content::{self, FEED_NOTE_MAX_CHARS};
237 use crate::nostr::engagement::Reaction;
238 use crate::nostr::models::Note;
239 use crate::nostr::notifications::{Notification, What};
240 use crate::previews::PreviewStore;
241 use crate::state::Expanded;
242 use crate::video::Videos;
243 use crate::views::components::{Bookmarking, Reacting, RowContext, RowSizes, note_row, opening_thread};
244 use cosmic::iced::core::widget::Tree;
245 use cosmic::iced::core::{clipboard, layout};
246 use cosmic::iced::runtime::user_interface::{Cache, UserInterface};
247 use cosmic::iced::{Color, Event, Point, Size, mouse};
248 use nostr_sdk::prelude::{EventId, Keys, Kind, PublicKey};
249 use std::collections::HashMap;
250
251 const WIDTH: f32 = 394.0;
252
253 fn told(what: What, preview: Option<&str>) -> Notification {
256 Notification {
257 id: EventId::from_byte_array([1; 32]),
258 at: 0,
259 who: Keys::generate().public_key(),
260 what,
261 note: None,
262 about: Some(EventId::from_byte_array([2; 32])),
263 preview: preview.map(String::from),
264 }
265 }
266
267 fn reply(text: &str) -> Notification {
269 let note = Note {
270 id: EventId::from_byte_array([3; 32]),
271 kind: Kind::TextNote,
272 author: Keys::generate().public_key(),
273 created_at: 0,
274 content: content::parse(text, FEED_NOTE_MAX_CHARS),
275 reply_to: None,
276 quoted: Vec::new(),
277 };
278 Notification { id: note.id, who: note.author, what: What::Reply, note: Some(note), ..told(What::Repost, None) }
279 }
280
281 fn with_context<T>(size: u16, with: impl FnOnce(&RowContext<'_>) -> T) -> T {
283 let (profiles, images, previews, videos) =
284 (HashMap::new(), ImageStore::new(1_000_000).0, PreviewStore::new().0, Videos::default());
285 let (engagement, seen_on, expanded) = (HashMap::new(), HashMap::new(), Expanded::default());
286 let context = RowContext {
287 profiles: &profiles,
288 images: &images,
289 previews: &previews,
290 videos: &videos,
291 engagement: &engagement,
292 seen_on: &seen_on,
293 now: 0,
294 accent: Color::WHITE,
295 can_publish: true,
296 repost_menu: None,
297 who: None,
298 reacting: Reacting::NONE,
299 expanded: &expanded,
300 marked: None,
301 share_copied: None,
302 picture_copied: None,
303 bookmarking: Bookmarking::Unavailable,
304 menu_open: false,
305 sizes: RowSizes::new(size),
306 };
307 with(&context)
308 }
309
310 fn measured(notification: &Notification, size: u16, is_new: bool) -> f32 {
312 with_context(size, |context| {
313 let renderer = crate::views::components::testing::renderer();
314 let mut row = notification_row(notification, context, is_new);
315 let mut tree = Tree::new(row.as_widget());
316 let limits = layout::Limits::new(Size::ZERO, Size::new(WIDTH, f32::INFINITY));
317 row.as_widget_mut().layout(&mut tree, &renderer, &limits).size().height
318 })
319 }
320
321 #[test]
322 fn a_short_row_is_exactly_as_tall_as_it_is_said_to_be_whatever_it_says() {
323 let long = "what was said, at a length no line of a row this narrow has the room for, and then some more of it";
324 let zap = |comment: &str| What::Zap { sats: 21, comment: comment.into(), issuer: Keys::generate().public_key() };
325 for size in [10, 13, 18, 24] {
326 let sizes = RowSizes::new(size);
327 for notification in [
328 told(What::Repost, None),
329 told(What::Reaction(Reaction::Like), Some("a note")),
330 told(What::Reaction(Reaction::Emoji("🤙".into())), Some(long)),
331 told(zap(""), Some(long)),
332 told(zap(long), None),
333 told(zap(long), Some(long)),
334 ] {
335 let said = short_height(¬ification, sizes);
336 assert_eq!(estimated_notification_height(¬ification, sizes, WIDTH, false), said);
337 for is_new in [false, true] {
338 let height = measured(¬ification, size, is_new);
339 assert!((height - said).abs() < 0.01, "at size {size}: {height} against {said} for {notification:?}");
340 }
341 }
342 let (bare, full) = (told(zap(""), None), told(zap("thanks"), Some("a note")));
345 assert!(short_height(&full, sizes) > short_height(&bare, sizes));
346 assert!(short_height(&told(zap("thanks"), None), sizes) >= short_height(&bare, sizes));
347 }
348 }
349
350 #[test]
351 fn a_note_is_under_what_it_is_to_the_account_and_as_tall_new_as_old() {
352 for size in [10, 13, 24] {
353 let notification = reply("an answer, of a line or two, as answers are when there is not much to add");
354 let note = notification.note.as_ref().unwrap();
355 let alone = with_context(size, |context| {
356 let renderer = crate::views::components::testing::renderer();
357 let mut row = opening_thread(note_row(note, context), note.id, context);
358 let mut tree = Tree::new(row.as_widget());
359 let limits = layout::Limits::new(Size::ZERO, Size::new(WIDTH, f32::INFINITY));
360 row.as_widget_mut().layout(&mut tree, &renderer, &limits).size().height
361 });
362 let height = measured(¬ification, size, false);
363 assert!((height - alone - reason_height(RowSizes::new(size))).abs() < 0.01, "at size {size}: {height}");
364 assert_eq!(measured(¬ification, size, true), height, "the tint takes no room");
365 let estimated = estimated_notification_height(¬ification, RowSizes::new(size), WIDTH, false);
366 assert!((estimated - height).abs() <= height * 0.3, "estimated {estimated}, measured {height}");
367 }
368 }
369
370 fn clicked(notification: &Notification, point: Point) -> Vec<Message> {
372 with_context(13, |context| {
373 let mut renderer = crate::views::components::testing::renderer();
374 let row = notification_row(notification, context, false);
375 let mut interface = UserInterface::build(row, Size::new(WIDTH, 300.0), Cache::new(), &mut renderer);
376 let mut messages = Vec::new();
377 for event in [
378 mouse::Event::CursorMoved { position: point },
379 mouse::Event::ButtonPressed(mouse::Button::Left),
380 mouse::Event::ButtonReleased(mouse::Button::Left),
381 ] {
382 let _ = interface.update(
383 &[Event::Mouse(event)],
384 mouse::Cursor::Available(point),
385 &mut renderer,
386 &mut clipboard::Null,
387 &mut messages,
388 );
389 }
390 messages
391 })
392 }
393
394 #[test]
395 fn a_click_on_a_short_row_opens_the_note_it_is_about_and_who_did_it_by_their_picture() {
396 let liked = told(What::Reaction(Reaction::Like), Some("a note of mine"));
397 let opened = |messages: Vec<Message>| -> Vec<(Option<EventId>, Option<PublicKey>)> {
398 messages
399 .into_iter()
400 .map(|message| match message {
401 Message::OpenThread(id, _) => (Some(id), None),
402 Message::OpenProfile(who) => (None, Some(who)),
403 other => panic!("nothing a click here asks for: {other:?}"),
404 })
405 .collect()
406 };
407 assert_eq!(opened(clicked(&liked, Point::new(300.0, 36.0))), [(liked.about, None)]);
409 assert_eq!(opened(clicked(&liked, Point::new(50.0, 24.0))), [(None, Some(liked.who))]);
411
412 let issuer = Keys::generate().public_key();
414 let zapped = Notification { about: None, ..told(What::Zap { sats: 21, comment: String::new(), issuer }, None) };
415 assert_eq!(opened(clicked(&zapped, Point::new(300.0, 24.0))), [(None, Some(zapped.who))]);
416 }
417}