Skip to main content

cosmic_applet_avestruz/views/
feed.rs

1// SPDX-License-Identifier: MIT
2
3//! The feed view for Avestruz: the notes of the people the account follows,
4//! newest first, in a scroller.
5//!
6//! The notes are in a [`VirtualList`], so only the rows on screen are ever
7//! built, however far the feed has been scrolled into the past.
8//!
9//! What is on show is the reader's, and stays put. Notes that turned up
10//! since are offered by a button over the list, as Jumble does.
11
12use cosmic::Element;
13use cosmic::iced::widget::Stack;
14use cosmic::iced::{Alignment, Length, Point, mouse};
15use cosmic::widget::popover::{Position, popover};
16use cosmic::widget::{self, button, container, text};
17use nostr_sdk::prelude::PublicKey;
18
19use crate::fl;
20use crate::messages::Message;
21use crate::nostr::account::Account;
22use crate::nostr::models::{Note, display_name};
23use crate::state::{AppModel, FeedState};
24use crate::views::components::{
25    MENU_GAP, MENU_WIDTH, VirtualList, avatar, bell_icon, bookmark_icon, count_badge, estimated_note_height, list_scroller,
26    marking, menu, menu_height, note_row, opening_thread, status_line,
27};
28
29/// How close to its end, in pixels, a list of notes is scrolled before the
30/// next older page is fetched: about two popups' worth, so the page is
31/// usually there before the end is.
32pub(crate) const LOAD_OLDER_WITHIN: f32 = 1_000.0;
33
34/// How wide each choice of which notes to show is, at the least: the two
35/// are as wide as each other, whatever their words.
36const FEED_MODE_WIDTH: u16 = 84;
37
38/// The button that offers new notes: how many of their authors it shows,
39/// how wide each picture is and how far each starts from the one before,
40/// and the most notes it counts before saying only that there are more.
41const NEW_NOTES_AVATARS: usize = 3;
42const NEW_NOTES_AVATAR_SIZE: f32 = 20.0;
43const NEW_NOTES_AVATAR_STEP: f32 = 12.0;
44const NEW_NOTES_COUNTED: usize = 99;
45
46/// The most new notifications the bell counts before saying only that
47/// there are more.
48const NEW_NOTIFICATIONS_COUNTED: usize = 9;
49
50/// How wide the account's picture is above the feed: as the buttons beside
51/// it are.
52const ACCOUNT_AVATAR_SIZE: f32 = 32.0;
53
54/// How wide and tall the cog above the feed is, which its menu opens
55/// under.
56const COG_SIZE: f32 = 32.0;
57
58/// How many things the menu under the cog offers, and the room above and
59/// below the line the cog is in.
60const COG_MENU_ITEMS: usize = 5;
61const HEADER_PADDING: f32 = 4.0;
62
63impl AppModel {
64    /// The account's picture, which leads to its profile.
65    fn view_account_button(&self, account: &Account) -> Element<'_, Message> {
66        let name = display_name(&self.profiles, &account.public_key);
67        let picture = self.profiles.get(&account.public_key).and_then(|profile| profile.picture.as_deref());
68        let picture = avatar(&self.images, picture, &account.public_key, &name, ACCOUNT_AVATAR_SIZE);
69        let to_profile = widget::mouse_area(picture)
70            .on_press(Message::OpenProfile(account.public_key))
71            .interaction(mouse::Interaction::Pointer);
72        widget::tooltip(to_profile, text(fl!("feed-profile")), widget::tooltip::Position::Bottom).into()
73    }
74
75    /// The choice between the notes that start a conversation and those
76    /// with the replies among them, for above a list of notes. A segmented
77    /// control: two choices, one of them always made, and seen at a glance.
78    pub(crate) fn view_feed_modes(&self) -> Element<'_, Message> {
79        widget::segmented_control::horizontal(&self.feed_modes)
80            .on_activate(Message::SelectFeedMode)
81            .minimum_button_width(FEED_MODE_WIDTH)
82            .width(Length::Shrink)
83            .into()
84    }
85
86    /// The cog above the feed, and the menu that opens under it: the
87    /// account's bookmarks, for an account that keeps any, its relays, its
88    /// media servers, and the settings. A click anywhere else puts the menu away.
89    fn view_cog(&self) -> Element<'_, Message> {
90        let cog = button::icon(widget::icon::from_name("emblem-system-symbolic"))
91            .tooltip(fl!("feed-menu"))
92            .on_press(Message::ToggleMenu);
93        // Under the cog, its right edge at the cog's.
94        let under = Point::new(COG_SIZE - MENU_WIDTH, COG_SIZE + MENU_GAP);
95        let cog = popover(cog).position(Position::Point(under)).on_close(Message::CloseMenu);
96        if !self.menu_open {
97            return cog.into();
98        }
99        let settings = widget::icon::from_name("emblem-system-symbolic").handle();
100        let relays = widget::icon::from_name("network-server-symbolic").handle();
101        let media = widget::icon::from_name("folder-pictures-symbolic").handle();
102        let keys = widget::icon::from_name("input-keyboard-symbolic").handle();
103        let items: [_; COG_MENU_ITEMS] = [
104            (bookmark_icon(false), fl!("menu-bookmarks"), self.can_publish().then_some(Message::OpenBookmarks)),
105            (relays, fl!("menu-relays"), self.account.is_some().then_some(Message::OpenRelays)),
106            (media, fl!("menu-media"), self.account.is_some().then_some(Message::OpenMedia)),
107            (keys, fl!("menu-keys"), Some(Message::OpenKeys)),
108            (settings, fl!("feed-settings"), Some(Message::OpenSettings)),
109        ];
110        cog.popup(menu(items)).into()
111    }
112
113    /// The bell above the feed: the way to what the account is told of,
114    /// with how many of those are new over its corner, when any are. The
115    /// count is over the bell and takes no room: the line is the same
116    /// with it and without.
117    fn view_bell(&self) -> Element<'_, Message> {
118        let new = self.unread_notifications();
119        let tooltip = if new == 0 { fl!("feed-notifications") } else { fl!("feed-notifications-new", count = new) };
120        let bell = button::icon(bell_icon()).tooltip(tooltip).on_press(Message::OpenNotifications);
121        if new == 0 {
122            return bell.into();
123        }
124        let count = if new > NEW_NOTIFICATIONS_COUNTED { format!("{NEW_NOTIFICATIONS_COUNTED}+") } else { new.to_string() };
125        Stack::new().push(bell).push(container(count_badge(count)).align_right(Length::Fill)).into()
126    }
127
128    /// The line above the feed: writing a note, Refresh and Search on the left; in
129    /// the middle, which notes it shows; the bell, the cog, with the
130    /// bookmarks and the settings behind it, and the account's picture on
131    /// the right.
132    fn view_feed_header(&self) -> Element<'_, Message> {
133        let refresh = button::icon(widget::icon::from_name("view-refresh-symbolic"))
134            .tooltip(fl!("feed-refresh"))
135            // Not while one asked for by hand is on its way. A look in
136            // passing for new notes doesn't grey it out.
137            .on_press_maybe((!self.following.show_when_fetched && self.nostr.is_some()).then_some(Message::RefreshFeed));
138
139        let mut left = widget::Row::new().spacing(8).align_y(Alignment::Center);
140        if self.can_publish() {
141            let compose = button::icon(widget::icon::from_name("edit-symbolic"))
142                .tooltip(fl!("feed-compose"))
143                .on_press(Message::ComposeNote);
144            left = left.push(compose);
145        }
146        let search = button::icon(widget::icon::from_name("system-search-symbolic"))
147            .tooltip(fl!("feed-search"))
148            .on_press_maybe(self.account.is_some().then_some(Message::OpenSearch));
149        let left = left.push(refresh).push(search);
150        let mut right = widget::Row::new().spacing(8).align_y(Alignment::Center);
151        if self.account.is_some() {
152            right = right.push(self.view_bell());
153        }
154        right = right.push(self.view_cog());
155        // At startup, who is signed in is known a moment after the feed
156        // view shows.
157        if let Some(account) = &self.account {
158            right = right.push(self.view_account_button(account));
159        }
160
161        // The two sides share what the middle leaves, half each, so the
162        // middle is the middle of the popup whatever is on either side.
163        widget::Row::new()
164            .push(container(left).width(Length::Fill).align_x(Alignment::Start))
165            .push(self.view_feed_modes())
166            .push(container(right).width(Length::Fill).align_x(Alignment::End))
167            .spacing(8)
168            .align_y(Alignment::Center)
169            .padding([4, 12])
170            .into()
171    }
172
173    /// The button that offers the notes waiting for the list `state`, as
174    /// it is read now: who wrote the first few, and how many there are.
175    /// Pressing it shows them, and goes to the top of the list.
176    fn view_new_notes_button(&self, state: &FeedState) -> Option<Element<'_, Message>> {
177        let waiting = state.pending.notes(self.config.feed_mode);
178        if waiting.is_empty() {
179            return None;
180        }
181        let mut authors: Vec<PublicKey> = Vec::new();
182        for note in waiting {
183            if authors.len() == NEW_NOTES_AVATARS {
184                break;
185            }
186            if !authors.contains(&note.author) {
187                authors.push(note.author);
188            }
189        }
190        // Each picture half over the one before it. The first thing in a
191        // stack sets its size: room for them all.
192        let width = NEW_NOTES_AVATAR_SIZE + NEW_NOTES_AVATAR_STEP * authors.len().saturating_sub(1) as f32;
193        let pictures = authors.iter().enumerate().fold(
194            Stack::new().push(widget::Space::new().width(width).height(NEW_NOTES_AVATAR_SIZE)),
195            |pictures, (place, author)| {
196                let name = display_name(&self.profiles, author);
197                let picture = self.profiles.get(author).and_then(|profile| profile.picture.as_deref());
198                let picture = avatar(&self.images, picture, author, &name, NEW_NOTES_AVATAR_SIZE);
199                pictures.push(container(picture).padding([0.0, 0.0, 0.0, NEW_NOTES_AVATAR_STEP * place as f32]))
200            },
201        );
202
203        // When there may be more than wait here, there are at least so many.
204        let label = match (waiting.len(), state.pending.is_detached()) {
205            (1, false) => fl!("feed-new-note"),
206            (count, _) if count > NEW_NOTES_COUNTED => fl!("feed-new-notes", count = format!("{NEW_NOTES_COUNTED}+")),
207            (count, true) => fl!("feed-new-notes", count = format!("{count}+")),
208            (count, false) => fl!("feed-new-notes", count = count.to_string()),
209        };
210        let content = widget::Row::new()
211            .push(pictures)
212            .push(text(label).size(13).font(cosmic::font::semibold()))
213            .push(widget::icon::from_name("go-up-symbolic").size(14))
214            .spacing(8)
215            .align_y(Alignment::Center);
216        let show = button::custom(content)
217            .padding([6, 12, 6, 8])
218            .class(cosmic::theme::Button::Suggested)
219            .on_press(Message::ShowNewNotes(state.id));
220        // The key that does the same, for whoever would rather.
221        Some(widget::tooltip(show, text(fl!("feed-new-notes-key")).size(12), widget::tooltip::Position::Top).into())
222    }
223
224    /// `list`, the scroller of the list `state`, with the button that
225    /// offers its new notes over it, at the bottom, when there are any.
226    /// Over the list rather than in it: it takes no room, so its coming
227    /// and going moves nothing.
228    pub(crate) fn with_new_notes<'a>(&'a self, list: Element<'a, Message>, state: &'a FeedState) -> Element<'a, Message> {
229        let over: Element<'a, Message> = match self.view_new_notes_button(state) {
230            Some(show) => container(show)
231                .width(Length::Fill)
232                .height(Length::Fill)
233                .align_x(Alignment::Center)
234                .align_y(Alignment::End)
235                .padding([0, 0, 12, 0])
236                .into(),
237            // Nothing, in the same place: the list under it keeps its
238            // widget state whether or not the button is there.
239            None => widget::Row::new().into(),
240        };
241        Stack::new().push(list).push(over).into()
242    }
243
244    /// What is going on at the end of the list `state`, if anything is:
245    /// an older page on its way, nothing older to be had, or a stop after
246    /// page upon page with nothing to show, and the way on.
247    pub(crate) fn view_list_end(&self, state: &FeedState) -> Option<Element<'_, Message>> {
248        if state.loading_older {
249            Some(status_line(fl!("feed-loading-older")))
250        } else if state.end_reached {
251            Some(status_line(fl!("feed-end")))
252        } else if state.paused() {
253            let further = button::text(fl!("feed-look-further")).on_press(Message::LoadOlderNotes(state.id));
254            Some(
255                widget::Column::new()
256                    .push(text(fl!("feed-nothing-recent")).size(12))
257                    .push(further)
258                    .spacing(4)
259                    .padding(12)
260                    .width(Length::Fill)
261                    .align_x(Alignment::Center)
262                    .into(),
263            )
264        } else {
265            None
266        }
267    }
268
269    /// The notes of `state` that are to show, as a list, and under them
270    /// what is going on at the list's end. With none to show, `nothing`
271    /// says so in their place. For a scroller: the feed's, a profile's.
272    pub(crate) fn view_notes<'a>(&'a self, state: &'a FeedState, nothing: String) -> Element<'a, Message> {
273        let notes = state.feed.notes(self.config.feed_mode);
274        if notes.is_empty() {
275            // While it is looking further back, or stopped short of the
276            // end, the list's end says what there is to say. Otherwise
277            // there is nothing, and `nothing` says so.
278            return match self.view_list_end(state) {
279                Some(end) if !state.end_reached => end,
280                _ => status_line(nothing),
281            };
282        }
283
284        let context = self.row_context(&state.expanded, state.marked);
285        let sizes = context.sizes;
286        let list: VirtualList<'_, Note, _, Message, cosmic::Theme, cosmic::Renderer> = VirtualList::new(
287            notes,
288            &state.heights,
289            |note: &Note| note.id,
290            move |note, width| estimated_note_height(note, sizes, width, context.expanded.has(&note.id)),
291            move |_index, note| marking(opening_thread(note_row(note, &context), note.id, &context), note.id, &context),
292        )
293        .on_near_end(LOAD_OLDER_WITHIN, Message::LoadOlderNotes(state.id));
294
295        widget::Column::new().push(list).push_maybe(self.view_list_end(state)).into()
296    }
297
298    /// What the feed view says in place of notes, when the feed has none
299    /// to show.
300    fn empty_feed_text(&self) -> String {
301        match &self.follows {
302            _ if self.nostr.is_none() => fl!("feed-loading"),
303            None => fl!("feed-following-unknown"),
304            Some(follows) if follows.is_empty() => fl!("feed-following-nobody"),
305            _ if self.following.refreshing => fl!("feed-loading"),
306            _ => fl!("feed-empty"),
307        }
308    }
309
310    /// Render the feed view.
311    pub fn view_feed(&self) -> Element<'_, Message> {
312        let state = &self.following;
313        let list = list_scroller(&state.position, self.view_notes(state, self.empty_feed_text()));
314        let body = self.with_new_notes(list, state);
315
316        let feed = widget::Column::new().push(self.view_feed_header()).push(widget::divider::horizontal::default()).push(body);
317        if !self.menu_open {
318            return feed.into();
319        }
320        // The menu opens inside the popup, which is no taller than what
321        // is in it: over a feed with nothing to show, it is made tall
322        // enough for all the menu offers.
323        let room = HEADER_PADDING + COG_SIZE + MENU_GAP + menu_height(COG_MENU_ITEMS) + HEADER_PADDING;
324        widget::Row::new().push(widget::Space::new().height(Length::Fixed(room))).push(feed).into()
325    }
326}