Skip to main content

cosmic_applet_avestruz/views/components/
notification_row.rs

1// SPDX-License-Identifier: MIT
2
3//! One thing the account is told of, as a row of the notifications list.
4//!
5//! What is itself a note (a reply, a mention, a quote) shows as the note
6//! it is, under a line that says which of those it is: it can be read in
7//! full, answered and reacted to where it stands. What is only about a
8//! note (a reaction, a repost, a zap) is one short row: what was done,
9//! who did it and when, what was said with a zap, and the start of the
10//! note it is about, which a click on the row opens.
11//!
12//! A row that is new, written since the notifications were last looked
13//! at, has a tint of the accent colour behind it. The tint takes no room:
14//! a row is as tall new as old.
15//!
16//! Every line of a short row is one line, cut where it runs out of room,
17//! so that the row is as tall as [`estimated_notification_height`] says
18//! before it is ever laid out.
19
20use 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
39/// The room above the line that says what a note is to the account.
40const REASON_PADDING_TOP: f32 = 6.0;
41
42/// How wide the room is for what was done in a short row: an emoji, or
43/// an icon.
44const GLYPH_WIDTH: f32 = 22.0;
45
46/// The gap between the lines of a short row, and the room under them,
47/// above the line that ends the row.
48const LINE_GAP: f32 = 2.0;
49const SHORT_PADDING_BOTTOM: f32 = 8.0;
50
51/// How strongly the accent colour tints a row that is new.
52const NEW_TINT: f32 = 0.10;
53
54/// How tall the line above a note is, which says what the note is to the
55/// account, with the room above it.
56fn reason_height(sizes: RowSizes) -> f32 {
57    REASON_PADDING_TOP + line_height(sizes.time())
58}
59
60/// The lines a short row has under who did it: what was said with a zap,
61/// if anything was, and the start of the note it is about, if that is
62/// at hand.
63fn lines_under(notification: &Notification) -> (Option<&str>, Option<&str>) {
64    let comment = match &notification.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
71/// How tall a short row is: its lines, or the picture of who did it,
72/// whichever is taller, and the room around them.
73fn 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
85/// How tall the row of `notification` will be, set in `sizes` in a list
86/// `width` wide: near enough, for one that is a note (all of it, if a
87/// long one shows `in_full`), and exactly, for a short one.
88pub fn estimated_notification_height(notification: &Notification, sizes: RowSizes, width: f32, in_full: bool) -> f32 {
89    match &notification.note {
90        Some(note) => reason_height(sizes) + estimated_note_height(note, sizes, width, in_full),
91        None => short_height(notification, sizes),
92    }
93}
94
95/// What a note is to the account, in a few words.
96fn 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
105/// What someone did about a note of the account's, after their name.
106fn 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
115/// One line of `said`, of `size`, in `color`: cut where the room ends,
116/// and as tall as a line whatever it says.
117fn 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
127/// What was done, as the picture a short row starts with: the emoji
128/// reacted with, a heart, the arrows of a repost, the bolt of a zap.
129fn 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
143/// The short row of `notification`, which is about a note and is not one.
144/// A click on it opens that note's thread, or the profile of whoever did
145/// it, of a zap that is for no note; their picture and their name lead to
146/// their profile.
147fn 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, &notification.who);
152    let picture = profiles.get(&notification.who).and_then(|profile| profile.picture.as_deref());
153    let picture = opening_profile(avatar(images, picture, &notification.who, &name, NOTE_AVATAR_SIZE), notification.who);
154
155    // Their name, as wide as it is; what they did, in what room is left;
156    // and when, which is never cut.
157    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(&notification.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(&notification.what, accent))
179        .push(picture)
180        .push(lines)
181        .spacing(NOTE_AVATAR_GAP)
182        .align_y(Alignment::Start)
183        // As tall as it is said to be, whichever of the two is taller.
184        .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
202/// The row of `notification`: the note it is, under what that note is to
203/// the account, or the short row of what was done about a note. With a
204/// tint of the accent colour behind it if it `is_new`.
205pub 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 &notification.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(&notification.what), sizes.time(), dim))
212                .padding([REASON_PADDING_TOP, 0.0, 0.0, 0.0])
213                .height(Length::Fixed(reason_height(sizes)));
214            // No space between the two: the note brings its own.
215            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    /// A notification of `what`, about a note the start of which is
254    /// `preview`, if it is at hand.
255    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    /// A reply that says `text`, as a notification.
268    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    /// What `with` makes of a row context of text of `size`.
282    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    /// How tall the row of `notification` lays out, new or not.
311    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(&notification, sizes);
336                assert_eq!(estimated_notification_height(&notification, sizes, WIDTH, false), said);
337                for is_new in [false, true] {
338                    let height = measured(&notification, size, is_new);
339                    assert!((height - said).abs() < 0.01, "at size {size}: {height} against {said} for {notification:?}");
340                }
341            }
342            // Never shorter than who did it is pictured, and taller for
343            // every line there is no room for beside the picture.
344            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(&notification, size, false);
363            assert!((height - alone - reason_height(RowSizes::new(size))).abs() < 0.01, "at size {size}: {height}");
364            assert_eq!(measured(&notification, size, true), height, "the tint takes no room");
365            let estimated = estimated_notification_height(&notification, RowSizes::new(size), WIDTH, false);
366            assert!((estimated - height).abs() <= height * 0.3, "estimated {estimated}, measured {height}");
367        }
368    }
369
370    /// What comes of a click on the row of `notification` at `point`.
371    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        // On the line under their name: the note.
408        assert_eq!(opened(clicked(&liked, Point::new(300.0, 36.0))), [(liked.about, None)]);
409        // On their picture, which is after what was done: their profile.
410        assert_eq!(opened(clicked(&liked, Point::new(50.0, 24.0))), [(None, Some(liked.who))]);
411
412        // A zap for no note has only who sent it to lead to.
413        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}