Skip to main content

cosmic_applet_avestruz/views/
thread.rs

1// SPDX-License-Identifier: MIT
2
3//! The thread view for Avestruz: the conversation one note is part of, in
4//! reading order, in a scroller.
5//!
6//! Every note is under the one it answers, set in from it. The popup is
7//! narrow, so only the first few answers deep are set in further; past
8//! that a note keeps the place of the one above it. The note the
9//! thread was opened for is picked out, and shows in full; a click on any
10//! other opens that note's thread over this one.
11
12use cosmic::Element;
13use cosmic::iced::{Alignment, Background, Border, Color, Length};
14use cosmic::widget::{self, button, container, text};
15
16use crate::fl;
17use crate::messages::Message;
18use crate::nostr::thread::ThreadRow;
19use crate::state::{AppModel, Expanded, ThreadState};
20use crate::views::components::{
21    RowSizes, VirtualList, estimated_note_height, list_scroller, marking, note_row, opening_thread, status_line,
22};
23
24/// How far an answer is set in from the note it answers, and how many
25/// answers deep that goes on.
26const THREAD_INDENT: f32 = 14.0;
27const THREAD_MAX_INDENTS: usize = 3;
28
29/// The gap between the line that marks an answer and the answer.
30const THREAD_GUIDE_GAP: f32 = 7.0;
31
32/// How strongly the accent colour tints the note the thread was opened
33/// for, and how much room the tint has around the note.
34const FOCUSED_TINT: f32 = 0.12;
35const FOCUSED_PADDING: u16 = 6;
36const FOCUSED_RADIUS: f32 = 6.0;
37
38/// How tall a thread row will be, near enough, before it has been laid
39/// out, set in `sizes` in a list `width` wide, with the long notes among
40/// `expanded` in full. An answer set in is a little narrower than the
41/// estimate assumes, and so sometimes a line taller: the list finds out
42/// when the row is in view.
43pub fn estimated_row_height(row: &ThreadRow, sizes: RowSizes, width: f32, expanded: &Expanded) -> f32 {
44    estimated_note_height(&row.note, sizes, width, expanded.has(&row.note.id))
45}
46
47/// `note`, the row of an answer `depth` deep, set in under what it answers
48/// with a line down its left.
49fn set_in<'a>(note: Element<'a, Message>, depth: usize) -> Element<'a, Message> {
50    let indents = depth.min(THREAD_MAX_INDENTS);
51    if indents == 0 {
52        return note;
53    }
54    // The line is a pixel wide: with the room before it and the gap after,
55    // it takes the indent.
56    let before = indents as f32 * THREAD_INDENT - THREAD_GUIDE_GAP - 1.0;
57    widget::Row::new()
58        .push(widget::Space::new().width(before))
59        .push(widget::divider::vertical::default())
60        .push(note)
61        .spacing(THREAD_GUIDE_GAP)
62        // A row takes after its children, and the line would fill any
63        // height: said after it is pushed, so the row is as tall as the note.
64        .height(Length::Shrink)
65        .into()
66}
67
68/// `note`, the row of the note the thread was opened for, picked out from
69/// the others by a tint of the accent colour.
70fn picked_out<'a>(note: Element<'a, Message>, accent: Color) -> Element<'a, Message> {
71    container(note)
72        .padding([0, FOCUSED_PADDING])
73        .class(cosmic::theme::Container::custom(move |_theme| container::Style {
74            background: Some(Background::Color(Color { a: FOCUSED_TINT, ..accent })),
75            border: Border { radius: FOCUSED_RADIUS.into(), ..Default::default() },
76            ..Default::default()
77        }))
78        .into()
79}
80
81impl AppModel {
82    /// The line above the thread: the way back, what this is, and, for an
83    /// account that can publish, replying to the note the thread is for.
84    fn view_thread_header(&self, state: &ThreadState) -> Element<'_, Message> {
85        let back = button::icon(widget::icon::from_name("go-previous-symbolic"))
86            .tooltip(fl!("thread-back"))
87            .on_press(Message::ClosePage);
88        let title = container(text(fl!("thread-title")).size(16).font(cosmic::font::bold())).width(Length::Fill);
89        let mut header = widget::Row::new().push(back).push(title);
90        if self.can_publish() && state.thread.focused_row().is_some() {
91            header = header.push(button::text(fl!("thread-reply")).on_press(Message::ComposeReply(state.thread.focused())));
92        }
93        header.spacing(8).align_y(Alignment::Center).padding([4, 12]).into()
94    }
95
96    /// The notes of `state`, in the scroller.
97    fn view_thread_list<'a>(&'a self, state: &'a ThreadState) -> Element<'a, Message> {
98        let context = self.row_context(&state.expanded, state.marked);
99        let (accent, sizes) = (context.accent, context.sizes);
100        let focused = state.thread.focused();
101        let list: VirtualList<'_, ThreadRow, _, Message, cosmic::Theme, cosmic::Renderer> = VirtualList::new(
102            state.thread.rows(),
103            &state.heights,
104            |row: &ThreadRow| row.note.id,
105            move |row, width| estimated_row_height(row, sizes, width, context.expanded),
106            move |_index, row| {
107                let note = note_row(&row.note, &context);
108                let note =
109                    if row.note.id == focused { picked_out(note, accent) } else { opening_thread(note, row.note.id, &context) };
110                set_in(marking(note, row.note.id, &context), row.depth)
111            },
112        );
113
114        // Said only while there are no answers: under a conversation, it
115        // would be about what is already there to read.
116        let mut content = widget::Column::new().push(list);
117        if !state.thread.has_replies() {
118            content = content.push(status_line(if state.loading { fl!("thread-loading") } else { fl!("thread-no-replies") }));
119        }
120        list_scroller(&state.position, content)
121    }
122
123    /// Render the thread view, of the thread `state`.
124    pub fn view_thread<'a>(&'a self, state: &'a ThreadState) -> Element<'a, Message> {
125        let body = if state.thread.rows().is_empty() {
126            status_line(if state.loading { fl!("thread-looking") } else { fl!("thread-not-found") })
127        } else {
128            self.view_thread_list(state)
129        };
130
131        widget::Column::new().push(self.view_thread_header(state)).push(widget::divider::horizontal::default()).push(body).into()
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::{THREAD_MAX_INDENTS, picked_out, set_in};
138    use crate::images::ImageStore;
139    use crate::messages::Message;
140    use crate::nostr::content::{self, FEED_NOTE_MAX_CHARS};
141    use crate::nostr::models::Note;
142    use crate::previews::PreviewStore;
143    use crate::state::Expanded;
144    use crate::video::Videos;
145    use crate::views::components::{Bookmarking, Reacting, RowContext, RowSizes, note_row};
146    use cosmic::Element;
147    use cosmic::iced::core::layout;
148    use cosmic::iced::core::widget::Tree;
149    use cosmic::iced::{Color, Size};
150    use nostr_sdk::prelude::{EventId, Keys, Kind};
151    use std::collections::HashMap;
152
153    /// How tall `dress` makes the row of a note of a few lines, in a list
154    /// as wide as the popup's.
155    fn height(dress: impl for<'a> Fn(Element<'a, Message>) -> Element<'a, Message>) -> f32 {
156        let note = Note {
157            id: EventId::from_byte_array([7; 32]),
158            kind: Kind::TextNote,
159            author: Keys::generate().public_key(),
160            created_at: 0,
161            content: content::parse("one\ntwo\nthree", FEED_NOTE_MAX_CHARS),
162            reply_to: None,
163            quoted: Vec::new(),
164        };
165        let renderer = crate::views::components::testing::renderer();
166        let (profiles, images) = (HashMap::new(), ImageStore::new(1_000_000).0);
167        let previews = PreviewStore::new().0;
168        let engagement = HashMap::new();
169        let seen_on = HashMap::new();
170        let videos = Videos::default();
171        let expanded = Expanded::default();
172        let context = RowContext {
173            profiles: &profiles,
174            images: &images,
175            previews: &previews,
176            videos: &videos,
177            engagement: &engagement,
178            seen_on: &seen_on,
179            now: 0,
180            accent: Color::WHITE,
181            can_publish: true,
182            repost_menu: None,
183            who: None,
184            reacting: Reacting::NONE,
185            expanded: &expanded,
186            marked: None,
187            share_copied: None,
188            picture_copied: None,
189            bookmarking: Bookmarking::Unavailable,
190            menu_open: false,
191            sizes: RowSizes::new(13),
192        };
193        let mut element = dress(note_row(&note, &context));
194        let mut tree = Tree::new(element.as_widget());
195        let limits = layout::Limits::new(Size::ZERO, Size::new(374.0, f32::INFINITY));
196        element.as_widget_mut().layout(&mut tree, &renderer, &limits).size().height
197    }
198
199    #[test]
200    fn a_row_is_as_tall_set_in_or_picked_out_as_it_is_plain() {
201        // The line down an answer's left is as tall as the answer, not as
202        // tall as it is allowed to be.
203        let plain = height(|note| note);
204        assert!(plain > 50.0 && plain < 200.0, "{plain}");
205        assert_eq!(height(|note| set_in(note, 1)), plain);
206        assert_eq!(height(|note| set_in(note, THREAD_MAX_INDENTS + 5)), plain);
207        assert_eq!(height(|note| picked_out(note, Color::WHITE)), plain);
208    }
209}