Skip to main content

cosmic_applet_avestruz/handlers/
thread.rs

1// SPDX-License-Identifier: MIT
2
3//! Thread message handlers for Avestruz.
4//!
5//! A thread opens for one note: from a row of a feed, from a row of another
6//! thread, or from a reference to the note in what another says. It shows at
7//! once with whatever of the conversation is at hand, which is the note
8//! itself when it came from a row. The event store is asked for the rest
9//! and answers within the frame; the relays are asked at the same time and
10//! answer when they do.
11//!
12//! A thread is a page: it opens over whatever is on show, and Back closes
13//! it (see [`crate::handlers::navigation`]).
14
15use cosmic::prelude::*;
16use nostr_sdk::prelude::EventId;
17
18use crate::handlers::feed::fetch_error_text;
19use crate::handlers::navigation::scroll_list_to;
20use crate::messages::Message;
21use crate::nostr::client::{FetchError, Source};
22use crate::nostr::models::Note;
23use crate::nostr::outbox::Whereabouts;
24use crate::nostr::thread::Thread;
25use crate::state::{AppModel, Page, ThreadState, ViewState};
26use crate::views::components::RowSizes;
27use crate::views::thread::estimated_row_height;
28
29/// How far down `state`'s list the focused note starts, its rows set in
30/// `sizes`: nowhere, until it is known.
31fn focused_offset(state: &ThreadState, sizes: RowSizes) -> f32 {
32    let rows = state.thread.rows();
33    let above = state.thread.focused_row().and_then(|row| rows.get(..row)).unwrap_or_default();
34    state.heights.total(above, |row| row.note.id, |row, width| estimated_row_height(row, sizes, width, &state.expanded))
35}
36
37impl AppModel {
38    /// The note `id`, if it is at hand: in the thread, the profile, the
39    /// bookmarks or the search on show, or in the feed.
40    pub(crate) fn note_at_hand(&self, id: EventId) -> Option<Note> {
41        let in_thread = self.thread_on_top().into_iter().flat_map(|state| state.thread.rows()).map(|row| &row.note);
42        let in_profile = self.profile_on_top().into_iter().flat_map(|state| state.notes.feed.all());
43        let in_bookmarks = self.bookmarks_on_top().into_iter().flat_map(|page| &page.notes.notes);
44        let in_search = self.search_on_top().into_iter().flat_map(|page| &page.notes);
45        let told = self.notifications.list.notes();
46        let at_hand =
47            in_thread.chain(in_profile).chain(in_bookmarks).chain(in_search).chain(told).chain(self.following.feed.all());
48        at_hand.into_iter().find(|note| note.id == id).cloned()
49    }
50
51    /// Whether the thread of the note `focused` is the one on show.
52    fn thread_on_show(&self, focused: EventId) -> bool {
53        self.view_state == ViewState::Page && self.thread_on_top().is_some_and(|state| state.thread.focused() == focused)
54    }
55
56    /// Show the thread of the note `id`, over whatever is on show now.
57    /// `whereabouts` is where the note may be if the account's own relays
58    /// don't have it, as whatever named it said.
59    pub fn handle_open_thread(&mut self, id: EventId, whereabouts: Whereabouts) -> Task<cosmic::Action<Message>> {
60        let Some(service) = self.nostr.clone() else {
61            return Task::none();
62        };
63        if self.thread_on_show(id) {
64            return Task::none();
65        }
66        let thread = Thread::new(id, self.note_at_hand(id));
67        let opened = self.open_page(Page::Thread(Box::new(ThreadState::new(thread))));
68
69        let ask = |source: Source| {
70            let (service, whereabouts) = (service.clone(), whereabouts.clone());
71            Task::perform(async move { service.thread(source, id, &whereabouts).await }, move |result| {
72                cosmic::Action::App(Message::ThreadLoaded { focused: id, source, result })
73            })
74        };
75        Task::batch([opened, ask(Source::Store), ask(Source::Relays)])
76    }
77
78    /// The conversation around a thread's note came from the store or from
79    /// the relays (or didn't). It goes to every open thread of that note.
80    pub fn handle_thread_loaded(
81        &mut self,
82        focused: EventId,
83        source: Source,
84        result: Result<Vec<Note>, FetchError>,
85    ) -> Task<cosmic::Action<Message>> {
86        let on_show = self.thread_on_show(focused);
87        let row_before = self.thread_on_top().and_then(|state| state.thread.focused_row());
88
89        let notes = match result {
90            Ok(notes) => {
91                tracing::info!("thread: {} note(s) from {source:?}", notes.len());
92                notes
93            }
94            Err(e) => {
95                tracing::error!("thread could not be fetched from {source:?}: {e:?}");
96                self.error_message = Some(fetch_error_text(e));
97                Vec::new()
98            }
99        };
100        let mut people = Vec::new();
101        for state in self.threads_mut().filter(|state| state.thread.focused() == focused) {
102            people.extend(state.thread.merge(notes.iter().cloned()));
103            if source == Source::Relays {
104                state.loading = false;
105            }
106        }
107        let ids: Vec<EventId> = notes.iter().map(|note| note.id).collect();
108        let looked_up = Task::batch([self.look_up_people(people), self.look_up_engagement(ids)]);
109
110        // Notes that came in above the focused one pushed it down, perhaps
111        // out of view: bring it back to the top. When nothing above it
112        // changed, the list stays where the reader has it.
113        let row_after = self.thread_on_top().and_then(|state| state.thread.focused_row());
114        let anchored = match self.thread_on_top() {
115            Some(state) if on_show && row_after != row_before => {
116                scroll_list_to(focused_offset(state, RowSizes::new(self.config.note_text_size())))
117            }
118            _ => Task::none(),
119        };
120        Task::batch([looked_up, anchored])
121    }
122}