Skip to main content

cosmic_applet_avestruz/views/
bookmarks.rs

1// SPDX-License-Identifier: MIT
2
3//! The bookmarks view for Avestruz: the notes the account has bookmarked,
4//! the one bookmarked last first.
5//!
6//! These are the bookmarks the account's list keeps to itself, which are
7//! the only ones made here and the only ones read. A click on a note opens
8//! its thread, and its ribbon takes the bookmark off, or puts it back.
9//!
10//! The notes are looked up a page at a time as the list is scrolled, and
11//! what is on show stays as it was when the page was opened: a note whose
12//! bookmark is taken off stays in its place, with an empty ribbon, so that
13//! nothing moves under the pointer.
14
15use cosmic::Element;
16use cosmic::iced::{Alignment, Length};
17use cosmic::widget::{self, button, container, text};
18
19use crate::fl;
20use crate::messages::Message;
21use crate::nostr::models::Note;
22use crate::state::{AppModel, BookmarkState, BookmarkedNotes, BookmarksPage};
23use crate::views::components::{
24    VirtualList, estimated_note_height, list_scroller, marking, note_row, opening_thread, status_line,
25};
26use crate::views::feed::LOAD_OLDER_WITHIN;
27
28/// What is said under the notes of `listed` once every one of them has
29/// been looked up, or in their place when there is none to show: that this
30/// is all, and how many bookmarks are not shown.
31fn end_text(listed: &BookmarkedNotes) -> String {
32    let hidden = listed.hidden();
33    match (listed.notes.is_empty(), hidden) {
34        (true, 0) => fl!("bookmarks-none"),
35        (true, _) => fl!("bookmarks-hidden", count = hidden),
36        (false, 0) => fl!("bookmarks-end"),
37        (false, _) => format!("{} {}", fl!("bookmarks-end"), fl!("bookmarks-hidden", count = hidden)),
38    }
39}
40
41impl AppModel {
42    /// The line above the bookmarks: the way back, and what this is.
43    fn view_bookmarks_header(&self) -> Element<'_, Message> {
44        let back = button::icon(widget::icon::from_name("go-previous-symbolic"))
45            .tooltip(fl!("bookmarks-back"))
46            .on_press(Message::ClosePage);
47        let title = container(text(fl!("bookmarks-title")).size(16).font(cosmic::font::bold())).width(Length::Fill);
48        widget::Row::new().push(back).push(title).spacing(8).align_y(Alignment::Center).padding([4, 12]).into()
49    }
50
51    /// The notes of the bookmarks page `page`, in the scroller, and under
52    /// them what is going on at their end.
53    fn view_bookmarked_notes<'a>(&'a self, page: &'a BookmarksPage) -> Element<'a, Message> {
54        let listed = &page.notes;
55        let end = if listed.all_asked() { end_text(listed) } else { fl!("bookmarks-loading") };
56        if listed.notes.is_empty() {
57            return status_line(end);
58        }
59        let context = self.row_context(&listed.expanded, listed.marked);
60        let sizes = context.sizes;
61        let list: VirtualList<'_, Note, _, Message, cosmic::Theme, cosmic::Renderer> = VirtualList::new(
62            &listed.notes,
63            &listed.heights,
64            |note: &Note| note.id,
65            move |note, width| estimated_note_height(note, sizes, width, context.expanded.has(&note.id)),
66            move |_index, note| marking(opening_thread(note_row(note, &context), note.id, &context), note.id, &context),
67        )
68        .on_near_end(LOAD_OLDER_WITHIN, Message::LoadBookmarkedNotes(page.id));
69
70        // Said once the notes are all there, or while more are on their
71        // way; between pages there is nothing to say.
72        let end = (listed.all_asked() || listed.loading).then(|| status_line(end));
73        list_scroller(&listed.position, widget::Column::new().push(list).push_maybe(end))
74    }
75
76    /// Render the bookmarks view, of the page `page`.
77    pub fn view_bookmarks<'a>(&'a self, page: &'a BookmarksPage) -> Element<'a, Message> {
78        let body = match &self.bookmarks {
79            BookmarkState::Unknown => status_line(fl!("bookmarks-reading")),
80            BookmarkState::Unreadable(why) => status_line(fl!("note-bookmark-unreadable", error = why.as_str())),
81            BookmarkState::Known(_) => self.view_bookmarked_notes(page),
82        };
83        widget::Column::new().push(self.view_bookmarks_header()).push(widget::divider::horizontal::default()).push(body).into()
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::end_text;
90    use crate::nostr::bookmarks::Bookmarks;
91    use crate::nostr::content::{self, FEED_NOTE_MAX_CHARS};
92    use crate::nostr::models::Note;
93    use crate::state::BookmarkedNotes;
94    use nostr_sdk::prelude::{EventId, Keys, Kind};
95
96    fn id(byte: u8) -> EventId {
97        EventId::from_byte_array([byte; 32])
98    }
99
100    fn e(byte: u8) -> Vec<String> {
101        vec!["e".to_string(), id(byte).to_hex()]
102    }
103
104    fn note(byte: u8) -> Note {
105        Note {
106            id: id(byte),
107            kind: Kind::TextNote,
108            author: Keys::generate().public_key(),
109            created_at: 0,
110            content: content::parse("worth finding again", FEED_NOTE_MAX_CHARS),
111            reply_to: None,
112            quoted: Vec::new(),
113        }
114    }
115
116    #[test]
117    fn a_page_keeps_what_it_found_until_the_bookmarks_are_others() {
118        let mut side = BookmarkedNotes::default();
119        assert!(side.all_asked(), "nothing to ask about before the bookmarks are known");
120
121        let bookmarks = Bookmarks::new(None, vec![e(1), e(2), e(3)]);
122        assert!(side.take(&bookmarks));
123        assert_eq!((side.taken, &side.ids[..]), (1, &[id(3), id(2), id(1)][..]), "the last bookmarked first");
124        assert!(!side.all_asked());
125
126        // Two of them were looked up, one found, and the list scrolled.
127        side.notes.push(note(3));
128        side.asked = 2;
129        side.missing = 1;
130        side.position.set(120.0);
131
132        // The same bookmarks again, as when the relays have what the
133        // store had: nothing starts over.
134        assert!(!side.take(&bookmarks));
135        assert_eq!((side.taken, side.asked, side.missing, side.notes.len()), (1, 2, 1, 1));
136        assert_eq!(side.position.get(), 120.0);
137
138        // Others: from the top, and what is asked of the old ones is
139        // known for stale by the count.
140        let more = Bookmarks::new(None, vec![e(1), e(2), e(3), e(4)]);
141        assert!(side.take(&more));
142        assert_eq!((side.taken, side.asked, side.missing, side.notes.len()), (2, 0, 0, 0));
143        assert_eq!(side.ids.first(), Some(&id(4)));
144        assert_eq!(side.position.get(), 0.0);
145    }
146
147    #[test]
148    fn the_end_of_the_bookmarks_says_what_is_not_shown() {
149        let mut side = BookmarkedNotes::default();
150
151        // No bookmarks kept that way at all.
152        side.take(&Bookmarks::default());
153        assert!(side.all_asked());
154        assert!(end_text(&side).starts_with("No bookmarks yet"), "{}", end_text(&side));
155
156        // Bookmarks, none of which is a note to show.
157        let article = vec!["a".to_string(), "30023:abc:post".to_string()];
158        side.take(&Bookmarks::new(None, vec![article.clone()]));
159        assert!(end_text(&side).starts_with("1 bookmark is not shown"), "{}", end_text(&side));
160
161        // Two notes nobody has, and the article.
162        side.take(&Bookmarks::new(None, vec![e(1), article, e(2), e(3)]));
163        assert!(!side.all_asked());
164        side.asked = 2;
165        side.missing = 2;
166        let three = end_text(&side);
167        assert!(three.contains('3') && three.contains("bookmarks are not shown"), "{three}");
168
169        // With a note to show above it, it follows what says that is all.
170        side.notes.push(note(3));
171        side.asked = 3;
172        let after = end_text(&side);
173        assert!(after.starts_with("That is all of them.") && after.contains("bookmarks are not shown"), "{after}");
174        side.missing = 0;
175        side.others = 0;
176        assert_eq!(end_text(&side), "That is all of them.");
177    }
178}