Skip to main content

cosmic_applet_avestruz/views/components/
note_row.rs

1// SPDX-License-Identifier: MIT
2
3//! One note as a row of a list: who wrote it and when, what it says, its
4//! images, its videos, the notes it quotes, and a preview of the web page
5//! it links to.
6//! The feed, a thread and the notes on a profile are lists of these.
7//!
8//! The author's picture sits beside their name, and what they wrote runs
9//! under both, the full width of the list. Set in beside the picture, a
10//! note would leave a margin as wide as the picture empty all the way down.
11//!
12//! How large a row is set is the reader's to say, in the settings: see
13//! [`RowSizes`].
14//!
15//! A long note is cut, and says so with a button under its text that
16//! shows the rest where the note is, in its row: nothing above the row
17//! moves, and what is under it makes room. Under all of the text the
18//! button shows less again. See [`Reading`].
19
20use std::cell::LazyCell;
21use std::collections::HashMap;
22
23use cosmic::Element;
24use cosmic::iced::font::{Style as FontStyle, Weight};
25use cosmic::iced::widget::Stack;
26use cosmic::iced::widget::text::{Shaping, Span, Wrapping};
27use cosmic::iced::widget::{rich_text, span, svg};
28use cosmic::iced::{Alignment, Background, Border, Color, Font, Length, Point, border, mouse};
29use cosmic::widget::menu::menu_button;
30use cosmic::widget::popover::{Position, popover};
31use cosmic::widget::{self, button, container, icon, text};
32use nostr_sdk::prelude::{EventId, PublicKey, RelayUrl};
33
34use crate::fl;
35use crate::helpers::{compact_count, relative_time, truncate_chars};
36use crate::images::{ImageShape, ImageState, ImageStore};
37use crate::messages::Message;
38use crate::nostr::bookmarks::Bookmarks;
39use crate::nostr::content::{NoteImage, Segment, link_label};
40use crate::nostr::engagement::{Did, Engagement, Left, Reaction};
41use crate::nostr::markdown::{Align, Block, Style};
42use crate::nostr::models::{Note, Profile, display_name};
43use crate::nostr::outbox::Whereabouts;
44use crate::previews::{PreviewState, PreviewStore};
45use crate::state::{Expanded, Passing, ReactionMenu, RepostMenu, WHO_SHOWN, WhoMenu};
46use crate::video::Videos;
47use crate::views::components::table_grid::{TABLE_CELL_PADDING_X, TABLE_CELL_PADDING_Y, TABLE_LINE, TableGrid, column_widths};
48use crate::views::components::{
49    MENU_GAP, MediaPlaceholder, POPUP_MAX_WIDTH, Picture, ScrollPosition, avatar, bookmark_icon, fold_icon, like_icon, link_icon,
50    link_preview, link_preview_height, menu_at, quote_link, quoted_note, quoted_note_height, reaction_menu, relays_icon,
51    reply_icon, repost_icon, shown_size, video_box, video_height, zap_icon,
52};
53
54/// The sizes a row is set in, all from one: the size of a note's text,
55/// which the settings keep.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct RowSizes {
58    text: u16,
59}
60
61impl RowSizes {
62    /// The sizes that go with note text of size `text`.
63    pub fn new(text: u16) -> Self {
64        Self { text }
65    }
66
67    /// What a note says.
68    pub(super) fn text(self) -> u16 {
69        self.text
70    }
71
72    /// Who wrote it: as large as what they wrote, and bold.
73    pub(super) fn name(self) -> u16 {
74        self.text
75    }
76
77    /// How long ago: small print.
78    pub(super) fn time(self) -> u16 {
79        self.text.saturating_sub(2)
80    }
81
82    /// The count beside an action.
83    fn action_text(self) -> u16 {
84        self.text.saturating_sub(1)
85    }
86
87    /// The icon of an action.
88    fn action_icon(self) -> u16 {
89        self.text + 1
90    }
91
92    /// The site a previewed page is on: small print, as the time is.
93    pub(super) fn preview_site(self) -> u16 {
94        self.time()
95    }
96
97    /// The title of a previewed page: as large as what the note says, and
98    /// bold.
99    pub(super) fn preview_title(self) -> u16 {
100        self.text
101    }
102
103    /// The few words about a previewed page: a little smaller than what
104    /// the note says.
105    pub(super) fn preview_description(self) -> u16 {
106        self.text.saturating_sub(1)
107    }
108}
109
110/// What a row is told of the account's bookmarks.
111#[derive(Clone, Copy)]
112pub enum Bookmarking<'a> {
113    /// The account keeps none: nobody is signed in with a key, which
114    /// reading and writing them takes.
115    Unavailable,
116    /// What it has bookmarked is not known yet.
117    Unknown,
118    /// What it has bookmarked, and the one note whose bookmark is being
119    /// put on (`true`) or taken off just now.
120    Known { bookmarks: &'a Bookmarks, pending: Option<(EventId, bool)> },
121    /// Its bookmarks could not be read: why, in the user's language.
122    Unreadable(&'a str),
123}
124
125impl Bookmarking<'_> {
126    /// Whether the note `id` shows as bookmarked: as the change on its way
127    /// will leave it, if one is, and as the bookmarks have it otherwise.
128    /// `None` for an account that keeps no bookmarks.
129    fn shows(self, id: &EventId) -> Option<bool> {
130        match self {
131            Self::Unavailable => None,
132            Self::Unknown | Self::Unreadable(_) => Some(false),
133            Self::Known { pending: Some((changing, to)), .. } if changing == *id => Some(to),
134            Self::Known { bookmarks, .. } => Some(bookmarks.has(id)),
135        }
136    }
137}
138
139/// What a row is told of reacting to notes.
140#[derive(Clone, Copy)]
141pub struct Reacting<'a> {
142    /// What to react with is on offer, for one note, if it is.
143    pub menu: Option<&'a ReactionMenu>,
144    /// The emoji offered first: the ones the reader reacts with most.
145    pub suggested: &'a [String],
146}
147
148impl Reacting<'_> {
149    /// Nothing on offer, and nothing to offer.
150    pub const NONE: Self = Self { menu: None, suggested: &[] };
151}
152
153/// What every row of a list is built with, beside its own note.
154#[derive(Clone, Copy)]
155pub struct RowContext<'a> {
156    /// What is known about note authors.
157    pub profiles: &'a HashMap<PublicKey, Profile>,
158    /// Avatars and the images in notes.
159    pub images: &'a ImageStore,
160    /// What the web pages notes link to say of themselves.
161    pub previews: &'a PreviewStore,
162    /// The video that plays, if one does.
163    pub videos: &'a Videos,
164    /// What was made of the notes seen.
165    pub engagement: &'a HashMap<EventId, Engagement>,
166    /// The relays each note was seen on, for the notes seen on any.
167    pub seen_on: &'a HashMap<EventId, Vec<RelayUrl>>,
168    /// Now, in seconds since the Unix epoch: what "5m" is counted from.
169    pub now: u64,
170    /// The colour links, mentions and the account's own likes and reposts
171    /// are set in.
172    pub accent: Color,
173    /// Whether the account can publish: reply to a note, repost it, like
174    /// it.
175    pub can_publish: bool,
176    /// The repost menu that is open, if one is.
177    pub repost_menu: Option<RepostMenu>,
178    /// Who left something on a note, if that is on show.
179    pub who: Option<&'a WhoMenu>,
180    /// What there is to react with, and whether it is on offer.
181    pub reacting: Reacting<'a>,
182    /// The long notes whose rows show all they say.
183    pub expanded: &'a Expanded,
184    /// The row the keyboard is at, in this list, if it is at any: the one
185    /// that is marked.
186    pub marked: Option<EventId>,
187    /// The note a share link to which was copied just now, if one was.
188    pub share_copied: Option<EventId>,
189    /// The picture that was copied just now, if one was: where it is.
190    pub picture_copied: Option<&'a str>,
191    /// A menu that is no row's own is open over the list: the one behind
192    /// the cog.
193    pub menu_open: bool,
194    /// What the account has bookmarked.
195    pub bookmarking: Bookmarking<'a>,
196    /// How large the row is set.
197    pub sizes: RowSizes,
198}
199
200impl RowContext<'_> {
201    /// Whether a menu is open over the list: a row's own, or the one
202    /// behind the cog. A click beside it is to put it away, and no more.
203    pub(super) fn under_a_menu(&self) -> bool {
204        self.repost_menu.is_some()
205            || self.who.is_some()
206            || self.reacting.menu.is_some()
207            || self.menu_open
208            || self.videos.speed_menu()
209    }
210}
211
212/// Space above a row's content, and between its parts.
213pub(super) const NOTE_PADDING_TOP: u16 = 8;
214pub(super) const NOTE_SPACING: u16 = 4;
215
216/// How wide the author's picture is, and the gap between it and their
217/// name.
218pub(super) const NOTE_AVATAR_SIZE: f32 = 32.0;
219pub(super) const NOTE_AVATAR_GAP: u16 = 8;
220
221/// A note's image is shown as wide as the note, from one edge to the
222/// other, unless it is narrower than that itself (see [`shown_size`]), with
223/// its corners rounded this much. Until it has loaded it is given the room
224/// it will take, if the note says its size, and this height if not.
225const NOTE_IMAGE_RADIUS: f32 = 6.0;
226const NOTE_IMAGE_FALLBACK_HEIGHT: f32 = 180.0;
227
228/// How much of the text's colour what a note quotes is set in, and how
229/// much of it stands behind code.
230const QUIET_TEXT_ALPHA: f32 = 0.65;
231const BEHIND_CODE_ALPHA: f32 = 0.12;
232
233/// The corners of what stands behind code, and how far it reaches past
234/// the code at either side. It takes no room: the text is where it would
235/// be without it.
236const CODE_RADIUS: f32 = 3.0;
237const CODE_PADDING: [f32; 2] = [0.0, 2.0];
238
239/// Lines of code that stand apart: the room around them, and the corners
240/// of what is behind them.
241const CODE_BLOCK_PADDING: u16 = 8;
242const CODE_BLOCK_RADIUS: f32 = 6.0;
243
244/// How much larger than the text the headings of the first three levels
245/// are. The others are as large as the text, and bold as these.
246const HEADING_SCALES: [f32; 3] = [1.5, 1.3, 1.15];
247
248/// A rule between two parts of a note: how thick, and how much of the
249/// text's colour.
250const RULE_HEIGHT: f32 = 1.0;
251const RULE_ALPHA: f32 = 0.35;
252
253/// How much of the text's colour the line under the first row of a table
254/// is, and the lines under the others.
255const TABLE_HEAD_LINE_ALPHA: f32 = 0.5;
256const TABLE_LINE_ALPHA: f32 = 0.2;
257
258/// How many letters wide someone's name is taken to be, in a cell of a
259/// table, before it is known who they are.
260const MENTION_WIDTH_CHARS: usize = 12;
261
262/// How wide a letter of code is, as a share of its size: all of them are.
263const CODE_CHAR_WIDTH_PER_SIZE: f32 = 0.6;
264
265/// The line of actions under a note: how much room each action has around
266/// it.
267const NOTE_ACTION_PADDING: [u16; 2] = [2, 6];
268
269/// How wide each action is, count and all, so that the same action sits at
270/// the same place in every row whatever the counts are. Narrow enough
271/// that the four of them and what is at the right end of the line all
272/// have their room in the narrowest popup, at the largest size.
273const NOTE_ACTION_WIDTH: f32 = 60.0;
274
275/// How much dimmer than the text an action is that hasn't been taken.
276pub(super) const NOTE_ACTION_DIM: f32 = 0.6;
277
278/// The gap between an action's icon and the count beside it.
279const NOTE_ACTION_GAP: f32 = 4.0;
280
281/// How wide a figure of a count is, as a share of the count's size, at
282/// the most.
283const FIGURE_WIDTH_PER_SIZE: f32 = 0.65;
284
285/// How much of why the bookmarks could not be read is said to whoever
286/// points at the bookmark action.
287const BOOKMARK_REASON_MAX_CHARS: usize = 120;
288
289/// The thickness of the line under a row.
290pub(super) const NOTE_DIVIDER_HEIGHT: f32 = 1.0;
291
292/// The button under a long note's text, which shows more of it or less:
293/// the room above and under its label, the room before the label and
294/// after the arrows beside it, and the gap between the two. Less room
295/// after than before: the arrows are drawn well inside the square they
296/// are given, and what shows on either side is then the same.
297const FOLD_PADDING_Y: u16 = 3;
298const FOLD_PADDING_BEFORE: u16 = 12;
299const FOLD_PADDING_AFTER: u16 = 8;
300const FOLD_GAP: f32 = 4.0;
301
302/// How much of what a long note says is shown.
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub(super) enum Reading {
305    /// Cut, and no more to be had here: a note quoted in another, whose
306    /// own view has the rest.
307    Quoted,
308    /// Cut, with a button under it that shows the rest: a row, as it
309    /// first shows.
310    Cut,
311    /// All of it, with a button under it that cuts it again: a row that
312    /// was asked for the rest.
313    Whole,
314}
315
316impl Reading {
317    /// How the row of a note is read: all of it if `in_full`.
318    fn of_row(in_full: bool) -> Self {
319        if in_full { Self::Whole } else { Self::Cut }
320    }
321}
322
323/// What [`estimated_note_height`] assumes of text it hasn't seen laid out:
324/// how tall a line is and how wide a character is on average, both as a
325/// share of the text's size. Read off rows laid out with the real text
326/// renderer; `the_estimate_is_close_to_the_measured_row` holds them to it.
327const LINE_HEIGHT_PER_SIZE: f32 = 1.4;
328const CHAR_WIDTH_PER_SIZE: f32 = 0.48;
329
330/// How wide a list is taken to be before it has been laid out once: as
331/// wide as the popup opens, less the room around the list.
332const UNMEASURED_LIST_WIDTH: f32 = POPUP_MAX_WIDTH - 26.0;
333
334/// How tall a line of text of `size` is.
335pub(super) fn line_height(size: u16) -> f32 {
336    f32::from(size) * LINE_HEIGHT_PER_SIZE
337}
338
339/// How tall the line of actions under a note is: its icons or its counts,
340/// whichever are taller, and the room around them.
341fn action_height(sizes: RowSizes) -> f32 {
342    f32::from(sizes.action_icon()).max(line_height(sizes.action_text())) + 2.0 * f32::from(NOTE_ACTION_PADDING[0])
343}
344
345/// How tall the button under a long note's text is: its label, and the
346/// room above and under it.
347fn fold_height(sizes: RowSizes) -> f32 {
348    line_height(sizes.action_text()).max(f32::from(sizes.action_icon())) + 2.0 * f32::from(FOLD_PADDING_Y)
349}
350
351/// How tall what `note` says will be, near enough, set in `sizes` in room
352/// `width` wide and read as `reading` says, with the space above each
353/// part of it: each line of its text wrapped at a typical line length,
354/// the button under a long one, each image at the height it will be
355/// shown, each video in the room it has, each note it quotes as its card
356/// or its link, and the preview of a page it links to, which is the
357/// height it is.
358pub(super) fn said_height(note: &Note, sizes: RowSizes, width: f32, reading: Reading) -> f32 {
359    let spacing = f32::from(NOTE_SPACING);
360
361    let chars_per_line = ((width / (f32::from(sizes.text()) * CHAR_WIDTH_PER_SIZE)) as usize).max(1);
362    let (segments, line_chars) = note.content.text(reading == Reading::Whole);
363    // The lines of its text, of which there are none where all of it
364    // stands apart.
365    let lines: usize = match segments.iter().all(stands_apart) {
366        true => 0,
367        false => line_chars.iter().map(|chars| chars.div_ceil(chars_per_line).max(1)).sum(),
368    };
369    // What stands apart, and the room between the parts.
370    let apart: f32 = segments
371        .iter()
372        .filter_map(|segment| match segment {
373            Segment::Block(block) => Some(block_height(block, sizes, width)),
374            _ => None,
375        })
376        .sum();
377    let between = parts(segments).count().saturating_sub(1) as f32 * spacing;
378    let text = if segments.is_empty() { 0.0 } else { spacing + lines as f32 * line_height(sizes.text()) + apart + between };
379    let fold = if note.content.whole.is_some() && reading != Reading::Quoted { spacing + fold_height(sizes) } else { 0.0 };
380    let images: f32 = note
381        .content
382        .images
383        .iter()
384        .map(|image| spacing + image.size.map_or(NOTE_IMAGE_FALLBACK_HEIGHT, |size| shown_size(size, width).height))
385        .sum();
386    let videos: f32 = note.content.videos.iter().map(|video| spacing + video_height(video.size, width)).sum();
387    let quotes: f32 = note
388        .quotes_shown()
389        .map(|quote| {
390            spacing + note.quoted(quote.id).map_or(line_height(sizes.text()), |quoted| quoted_note_height(quoted, sizes, width))
391        })
392        .sum();
393    let preview = note.content.preview.as_ref().map_or(0.0, |_| spacing + link_preview_height(sizes));
394    text + fold + images + videos + quotes + preview
395}
396
397/// How tall what stands apart from a note's text will be, near enough:
398/// lines of code wrapped at how many of its letters fit, a rule, and a
399/// table of rows a line of text tall each.
400fn block_height(block: &Block<Vec<Segment>>, sizes: RowSizes, width: f32) -> f32 {
401    let line = line_height(sizes.text());
402    match block {
403        Block::Code(code) => {
404            let around = 2.0 * f32::from(CODE_BLOCK_PADDING);
405            let per_line = (((width - around) / (f32::from(sizes.text()) * CODE_CHAR_WIDTH_PER_SIZE)) as usize).max(1);
406            let lines: usize = code.split('\n').map(|line| line.chars().count().div_ceil(per_line).max(1)).sum();
407            lines as f32 * line + around
408        }
409        Block::Rule => RULE_HEIGHT,
410        Block::Table(table) => {
411            // Each column as wide as the longest of its cells would be, or
412            // as it comes out where they don't all fit; each row as many
413            // lines as the cell of it that wraps most.
414            let letter = f32::from(sizes.text()) * CHAR_WIDTH_PER_SIZE;
415            let wide = |cell: &Vec<Segment>| {
416                cell.iter().map(|piece| piece.words(&|_| "@".repeat(MENTION_WIDTH_CHARS)).chars().count()).sum::<usize>() as f32
417                    * letter
418            };
419            let mut natural = vec![0.0_f32; table.columns.len()];
420            for row in &table.rows {
421                for (widest, cell) in natural.iter_mut().zip(row) {
422                    *widest = widest.max(wide(cell));
423                }
424            }
425            let room = (width - 2.0 * TABLE_CELL_PADDING_X * natural.len() as f32).max(0.0);
426            let widths = column_widths(&natural, room);
427            let lines: f32 = table
428                .rows
429                .iter()
430                .map(|row| {
431                    row.iter().zip(&widths).map(|(cell, width)| (wide(cell) / width.max(1.0)).ceil().max(1.0)).fold(1.0, f32::max)
432                })
433                .sum();
434            let rows = table.rows.len() as f32;
435            lines * line + rows * 2.0 * TABLE_CELL_PADDING_Y + (rows - 1.0).max(0.0) * TABLE_LINE
436        }
437    }
438}
439
440/// How tall a note's row will be, near enough, before it has been laid out,
441/// set in `sizes` in a list `width` wide: what the note says, all of it
442/// if a long one shows `in_full`, and around it the room above, the
443/// author's picture or their name beside it, whichever is taller, the
444/// line of actions, and the line under the row. The list replaces this
445/// with the measured height once the row has been in view.
446pub fn estimated_note_height(note: &Note, sizes: RowSizes, width: f32, in_full: bool) -> f32 {
447    let width = if width > 0.0 { width } else { UNMEASURED_LIST_WIDTH };
448    let spacing = f32::from(NOTE_SPACING);
449    let header = NOTE_AVATAR_SIZE.max(line_height(sizes.name()));
450    f32::from(NOTE_PADDING_TOP)
451        + header
452        + said_height(note, sizes, width, Reading::of_row(in_full))
453        + spacing
454        + action_height(sizes)
455        + spacing
456        + NOTE_DIVIDER_HEIGHT
457}
458
459/// A link on a line of its own, in text of `size`: a picture that could
460/// not be shown, a website.
461pub fn link_line<'a>(url: &'a str, label: &'a str, accent: Color, size: u16) -> Element<'a, Message> {
462    let spans: Vec<Span<'a, String>> = vec![span(label).color(accent).underline(true).link(url.to_string())];
463    rich_text(spans).size(size).wrapping(Wrapping::WordOrGlyph).width(Length::Fill).on_link_click(Message::OpenUrl).into()
464}
465
466/// One of a note's images: the picture, once it is here; the room it will
467/// take, until then; and if it can't be had, the link it came as.
468fn note_image<'a>(image: &'a NoteImage, context: &RowContext<'a>) -> Element<'a, Message> {
469    let RowContext { images, accent, sizes, .. } = *context;
470    match images.get(&image.url, ImageShape::Original) {
471        ImageState::Ready(loaded) => {
472            // As wide as the room there is, and no wider than it is.
473            // A click on a picture is a click on the row: it opens the
474            // note, as one on its text does. The picture takes none
475            // itself but one with the right button, which copies it.
476            let picture = Picture::new(loaded).radius(NOTE_IMAGE_RADIUS).on_right_press(Message::CopyPicture(image.url.clone()));
477            if context.picture_copied != Some(image.url.as_str()) {
478                return picture.into();
479            }
480            // Said over its corner, where it takes no room: the left one,
481            // which is over the picture however narrow that is.
482            let said = container(text(fl!("picture-copied")).size(sizes.time())).padding([2, 8]).class(
483                cosmic::theme::Container::custom(|theme| {
484                    let cosmic = theme.cosmic();
485                    container::Style {
486                        background: Some(Background::Color(cosmic.accent_color().into())),
487                        text_color: Some(cosmic.on_accent_color().into()),
488                        border: Border { radius: cosmic.corner_radii.radius_s.into(), ..Border::default() },
489                        ..container::Style::default()
490                    }
491                }),
492            );
493            Stack::new().push(picture).push(container(said).padding(8)).into()
494        }
495        ImageState::Loading => MediaPlaceholder::new(image.size, NOTE_IMAGE_FALLBACK_HEIGHT).radius(NOTE_IMAGE_RADIUS).into(),
496        ImageState::Failed => link_line(&image.url, &image.label, accent, sizes.text()),
497    }
498}
499
500/// Where a click on part of a note's text leads.
501#[derive(Debug, Clone, PartialEq, Eq)]
502enum NoteLink {
503    /// To a web page, in the browser.
504    Web(String),
505    /// To someone mentioned, on their profile.
506    Profile(PublicKey),
507}
508
509impl NoteLink {
510    /// Where a click on `segment` leads, if anywhere.
511    fn of(segment: &Segment) -> Option<Self> {
512        match segment {
513            Segment::Link { url, .. } => Some(Self::Web(url.clone())),
514            Segment::Mention(public_key) => Some(Self::Profile(*public_key)),
515            Segment::Text(_) | Segment::Styled { .. } | Segment::Hashtag(_) | Segment::Reference(_) | Segment::Block(_) => None,
516        }
517    }
518
519    /// What following the link asks of the app.
520    fn follow(self) -> Message {
521        match self {
522            Self::Web(url) => Message::OpenUrl(url),
523            Self::Profile(public_key) => Message::OpenProfile(public_key),
524        }
525    }
526}
527
528/// What text a note marks is set in, beside the size and the face all
529/// its text has: the faces of what is stressed and of code, and the
530/// colours of what is quiet and of what is behind code.
531struct Faces {
532    text: Font,
533    code: Font,
534    quiet: Color,
535    behind_code: Color,
536    /// The colour of the text itself: what lines are drawn in, thinned.
537    on_background: Color,
538}
539
540impl Faces {
541    /// As the theme has them now. Asked for once for a note that marks
542    /// something, and not at all for one that doesn't.
543    fn of_the_theme() -> Self {
544        let theme = cosmic::theme::active();
545        let on_background: Color = theme.cosmic().on_bg_color().into();
546        Self {
547            text: cosmic::font::default(),
548            code: cosmic::font::mono(),
549            quiet: Color { a: QUIET_TEXT_ALPHA, ..on_background },
550            behind_code: Color { a: BEHIND_CODE_ALPHA, ..on_background },
551            on_background,
552        }
553    }
554
555    /// `text` as a span set in `style`, in text of `size`.
556    fn styled<'a>(&self, text: &'a str, style: Style, size: u16) -> Span<'a, NoteLink> {
557        let mut font = if style.code { self.code } else { self.text };
558        if style.bold {
559            font.weight = Weight::Bold;
560        }
561        if style.italic {
562            font.style = FontStyle::Italic;
563        }
564        let shown = span(text).font(font).strikethrough(style.strike).color_maybe(style.quiet.then_some(self.quiet));
565        // A heading is larger, and its line as much taller.
566        let larger = style.heading.checked_sub(1).and_then(|level| HEADING_SCALES.get(usize::from(level)));
567        let shown = match larger {
568            Some(scale) => shown.size(f32::from(size) * scale),
569            None => shown,
570        };
571        if style.code {
572            shown.background(self.behind_code).border(border::rounded(CODE_RADIUS)).padding(CODE_PADDING)
573        } else {
574            shown
575        }
576    }
577}
578
579/// Whether `segment` stands apart from the text.
580fn stands_apart(segment: &Segment) -> bool {
581    matches!(segment, Segment::Block(_))
582}
583
584/// The parts what a note says is shown in, one under the other: each
585/// stretch of its text, and each thing that stands apart from it.
586fn parts(segments: &[Segment]) -> impl Iterator<Item = &[Segment]> {
587    segments.chunk_by(|one, next| !stands_apart(one) && !stands_apart(next))
588}
589
590/// The pieces `segments` of a note's text, as spans: links and mentions
591/// can be clicked, and they and hashtags are set in `accent`; what the
592/// note marks is set as it marks it. `stressed`, all of it is bold: what
593/// says what the columns of a table are.
594fn spans<'a>(
595    segments: &'a [Segment],
596    context: &RowContext<'a>,
597    faces: &LazyCell<Faces>,
598    stressed: bool,
599) -> Vec<Span<'a, NoteLink>> {
600    let RowContext { profiles, accent, sizes, .. } = *context;
601    let bold = Style { bold: true, ..Style::default() };
602    segments
603        .iter()
604        .map(|segment| {
605            let shown = match segment {
606                Segment::Text(text) if stressed => faces.styled(text, bold, sizes.text()),
607                Segment::Text(text) => span(text.as_str()),
608                Segment::Styled { text, style } => {
609                    faces.styled(text, Style { bold: style.bold || stressed, ..*style }, sizes.text())
610                }
611                Segment::Link { label, .. } => span(label.as_str()).color(accent).underline(true),
612                Segment::Mention(public_key) => span(format!("@{}", display_name(profiles, public_key))).color(accent),
613                Segment::Hashtag(tag) => span(format!("#{tag}")).color(accent),
614                Segment::Reference(reference) => span(reference.as_str()).color(accent),
615                // What stands apart is no part of a line of text.
616                Segment::Block(_) => span(""),
617            };
618            match NoteLink::of(segment) {
619                Some(link) => shown.link(link),
620                None => shown,
621            }
622        })
623        .collect()
624}
625
626/// `spans` as text of the note's size, `width` wide.
627fn rich<'a>(spans: Vec<Span<'a, NoteLink>>, sizes: RowSizes, width: Length) -> Element<'a, Message> {
628    rich_text(spans).size(sizes.text()).wrapping(Wrapping::WordOrGlyph).width(width).on_link_click(NoteLink::follow).into()
629}
630
631/// What stands apart from a note's text: lines of code, on what stands
632/// behind code, from one edge to the other; a rule; a table.
633fn block<'a>(block: &'a Block<Vec<Segment>>, context: &RowContext<'a>, faces: &LazyCell<Faces>) -> Element<'a, Message> {
634    let sizes = context.sizes;
635    match block {
636        Block::Code(code) => {
637            let behind = faces.behind_code;
638            container(text(code.as_str()).size(sizes.text()).font(faces.code).wrapping(Wrapping::WordOrGlyph))
639                .padding(CODE_BLOCK_PADDING)
640                .width(Length::Fill)
641                .class(cosmic::theme::Container::custom(move |_| container::Style {
642                    background: Some(Background::Color(behind)),
643                    border: border::rounded(CODE_BLOCK_RADIUS),
644                    ..container::Style::default()
645                }))
646                .into()
647        }
648        Block::Rule => {
649            let line = faces.on_background;
650            container(widget::Space::new().width(Length::Fill).height(RULE_HEIGHT))
651                .class(cosmic::theme::Container::custom(move |_| container::Style {
652                    background: Some(Background::Color(Color { a: RULE_ALPHA, ..line })),
653                    ..container::Style::default()
654                }))
655                .into()
656        }
657        Block::Table(table) => {
658            let columns = table
659                .columns
660                .iter()
661                .map(|align| match align {
662                    Align::Left => Alignment::Start,
663                    Align::Middle => Alignment::Center,
664                    Align::Right => Alignment::End,
665                })
666                .collect();
667            let cells = table
668                .rows
669                .iter()
670                .enumerate()
671                .flat_map(|(row, cells)| cells.iter().map(move |cell| (row == 0, cell)))
672                .map(|(head, cell)| rich(spans(cell, context, faces, head), sizes, Length::Shrink))
673                .collect();
674            let line = faces.on_background;
675            TableGrid::new(columns, cells, Color { a: TABLE_HEAD_LINE_ALPHA, ..line }, Color { a: TABLE_LINE_ALPHA, ..line })
676                .into()
677        }
678    }
679}
680
681/// What a note says, the `segments` of it: its text as rich text, and
682/// what stands apart from the text between the stretches of it, one
683/// under the other.
684fn note_text<'a>(segments: &'a [Segment], context: &RowContext<'a>) -> Element<'a, Message> {
685    let sizes = context.sizes;
686    let faces = LazyCell::<Faces>::new(Faces::of_the_theme);
687    if !segments.iter().any(stands_apart) {
688        return rich(spans(segments, context, &faces, false), sizes, Length::Fill);
689    }
690    let mut column = widget::Column::new().spacing(NOTE_SPACING).width(Length::Fill);
691    for part in parts(segments) {
692        column = column.push(match part {
693            [Segment::Block(apart)] => block(apart, context, &faces),
694            text => rich(spans(text, context, &faces, false), sizes, Length::Fill),
695        });
696    }
697    column.into()
698}
699
700/// The button under the text of the long note `id`: it shows the rest of
701/// the note where it is, in a row that shows it cut, and cuts it again in
702/// one that shows it `in_full`. In the middle of the row, as tall at
703/// every size as [`fold_height`] says; the way to more stands out as a
704/// button does, and the way back is no louder than the actions under it.
705fn fold_button<'a>(id: EventId, in_full: bool, context: &RowContext<'a>) -> Element<'a, Message> {
706    let sizes = context.sizes;
707    let (label, message) = match in_full {
708        true => (fl!("note-show-less"), Message::CollapseNote(id)),
709        false => (fl!("note-show-more"), Message::ExpandNote(id)),
710    };
711    let mut label = text(label).size(sizes.action_text()).wrapping(Wrapping::None);
712    let mut arrows = icon::icon(fold_icon(in_full)).size(sizes.action_icon());
713    if in_full {
714        let text_color: Color = cosmic::theme::active().cosmic().on_bg_color().into();
715        let dim = Color { a: NOTE_ACTION_DIM, ..text_color };
716        label = label.class(cosmic::theme::Text::Color(dim));
717        arrows = arrows.class(cosmic::theme::Svg::custom(move |_theme| svg::Style { color: Some(dim) }));
718    }
719    // As tall as the button, so that the label is in the middle of it: a
720    // button puts what is in it at its top.
721    let content = widget::Row::new().push(label).push(arrows).spacing(FOLD_GAP).height(Length::Fill).align_y(Alignment::Center);
722    let fold = button::custom(content)
723        .padding([0, FOLD_PADDING_AFTER, 0, FOLD_PADDING_BEFORE])
724        .height(Length::Fixed(fold_height(sizes)))
725        .class(if in_full { cosmic::theme::Button::Text } else { cosmic::theme::Button::Standard })
726        .on_press(message);
727    container(fold).center_x(Length::Fill).into()
728}
729
730/// `row`, the row of the note `id`, opening that note's thread when it is
731/// clicked anywhere that doesn't lead somewhere of its own (a link, a
732/// picture, the author). Not while a menu is open over the list: a click on
733/// a row beside the menu was meant to put the menu away, and that is all
734/// it does.
735pub fn opening_thread<'a>(row: Element<'a, Message>, id: EventId, context: &RowContext<'_>) -> Element<'a, Message> {
736    let area = widget::mouse_area(row);
737    if context.under_a_menu() {
738        area.into()
739    } else {
740        area.on_press(Message::OpenThread(id, Whereabouts::default())).interaction(mouse::Interaction::Pointer).into()
741    }
742}
743
744/// How round the corners of the line around the marked row are.
745const MARK_RADIUS: f32 = 8.0;
746
747/// `row`, the row told apart by `id`, with a line around it in the accent
748/// colour if it is the one the keyboard is at. The line is drawn over the
749/// row's edge and takes no room: a row is the same size marked and not.
750pub fn marking<'a>(row: Element<'a, Message>, id: EventId, context: &RowContext<'_>) -> Element<'a, Message> {
751    if context.marked != Some(id) {
752        return row;
753    }
754    let accent = context.accent;
755    container(row)
756        .class(cosmic::theme::Container::custom(move |_theme| container::Style {
757            border: Border { color: accent, width: 1.0, radius: MARK_RADIUS.into() },
758            ..container::Style::default()
759        }))
760        .into()
761}
762
763/// One of a note's actions, to be pressed: its icon in `color`, the count
764/// beside it when there is something to count, and what pressing it does,
765/// if anything.
766fn action_button<'a>(
767    icon_handle: icon::Handle,
768    count: u64,
769    color: Color,
770    tooltip: String,
771    on_press: Option<Message>,
772    sizes: RowSizes,
773) -> Element<'a, Message> {
774    let picture = icon::icon(icon_handle)
775        .size(sizes.action_icon())
776        .class(cosmic::theme::Svg::custom(move |_theme| svg::Style { color: Some(color) }));
777    action_showing(picture.into(), count, color, tooltip, on_press, sizes)
778}
779
780/// As [`action_button`], with `picture` where its icon would be: what is
781/// no icon, as the emoji a note was reacted to with.
782fn action_showing<'a>(
783    picture: Element<'a, Message>,
784    count: u64,
785    color: Color,
786    tooltip: String,
787    on_press: Option<Message>,
788    sizes: RowSizes,
789) -> Element<'a, Message> {
790    let mut content = widget::Row::new().push(picture).spacing(NOTE_ACTION_GAP).align_y(Alignment::Center);
791    if count > 0 {
792        content = content.push(text(compact_count(count)).size(sizes.action_text()).class(cosmic::theme::Text::Color(color)));
793    }
794    let action = button::custom(content).padding(NOTE_ACTION_PADDING).class(cosmic::theme::Button::Text).on_press_maybe(on_press);
795    widget::tooltip(action, text(tooltip).size(12), widget::tooltip::Position::Top).into()
796}
797
798/// `action`, one of a note's actions, in the room every action is given.
799fn action_cell<'a>(action: impl Into<Element<'a, Message>>) -> Element<'a, Message> {
800    container(action).width(Length::Fixed(NOTE_ACTION_WIDTH)).into()
801}
802
803/// What the repost action offers for the note `id`: reposting it as it is,
804/// which is done once (`reposted`) and not again, or quoting it in a note
805/// of one's own. The one the keyboard is `at`, if it is at one, is shown
806/// as one the pointer is over.
807fn repost_menu<'a>(id: EventId, reposted: bool, at: Option<Passing>) -> Element<'a, Message> {
808    let offered = [Passing::Repost, Passing::Quote];
809    menu_at(
810        [
811            (repost_icon(), fl!("note-repost"), (!reposted).then_some(Message::Repost(id))),
812            (icon::from_name("edit-symbolic").handle(), fl!("note-quote"), Some(Message::ComposeQuote(id))),
813        ],
814        at.and_then(|at| offered.iter().position(|way| *way == at)),
815    )
816}
817
818/// How wide the list of who left something on a note is, how tall one of
819/// them is in it, and how tall the list is at the most: more of them are
820/// scrolled to.
821const WHO_WIDTH: f32 = 240.0;
822const WHO_ROW_HEIGHT: f32 = 30.0;
823const WHO_MAX_HEIGHT: f32 = 8.0 * WHO_ROW_HEIGHT;
824
825/// How wide the picture of one of them is.
826const WHO_AVATAR_SIZE: f32 = 20.0;
827
828/// What one of those who left something on a note left, at the right end
829/// of their line: the emoji they reacted with, or a heart; how much they
830/// zapped; and nothing for a repost, which is all the list says.
831fn who_did<'a>(did: &Did, context: &RowContext<'a>) -> Option<Element<'a, Message>> {
832    let small = context.sizes.action_text();
833    match did {
834        Did::Reposted => None,
835        Did::Reacted(Reaction::Emoji(emoji)) => Some(text(emoji.clone()).size(small).shaping(Shaping::Advanced).into()),
836        Did::Reacted(Reaction::Like) => {
837            let accent = context.accent;
838            let heart = icon::icon(like_icon(true))
839                .size(small)
840                .class(cosmic::theme::Svg::custom(move |_theme| svg::Style { color: Some(accent) }));
841            Some(heart.into())
842        }
843        Did::Zapped(sats) => Some(text(fl!("who-sats", sats = compact_count(*sats))).size(small).wrapping(Wrapping::None).into()),
844    }
845}
846
847/// Who left something on a note, under the count of them: what the list
848/// is of, and each of them on a line, with their picture, their name and
849/// what they left. A press on one opens their profile. Until the store
850/// has been read it says so, and if nobody did, that.
851fn who_menu<'a>(menu: &'a WhoMenu, context: &RowContext<'a>) -> Element<'a, Message> {
852    let title = match menu.what {
853        Left::Reposts => fl!("who-reposted"),
854        Left::Reactions => fl!("who-reacted"),
855        Left::Zaps => fl!("who-zapped"),
856    };
857    let note = |said: String| -> Element<'a, Message> {
858        container(text(said).size(12).wrapping(Wrapping::WordOrGlyph)).padding([4, 8]).width(Length::Fill).into()
859    };
860    let body: Element<'a, Message> = match &menu.people {
861        None => note(fl!("who-reading")),
862        Some(people) if people.is_empty() => note(fl!("who-nobody")),
863        Some(people) => {
864            let mut lines = people.iter().take(WHO_SHOWN).fold(widget::Column::new(), |lines, doer| {
865                let (name, picture) = match &doer.who {
866                    Some(who) => (
867                        display_name(context.profiles, who),
868                        Some(avatar(
869                            context.images,
870                            context.profiles.get(who).and_then(|profile| profile.picture.as_deref()),
871                            who,
872                            "",
873                            WHO_AVATAR_SIZE,
874                        )),
875                    ),
876                    None => (fl!("who-unsaid").into(), None),
877                };
878                let picture = picture.unwrap_or_else(|| widget::Space::new().width(Length::Fixed(WHO_AVATAR_SIZE)).into());
879                let mut line = vec![
880                    picture,
881                    widget::Space::new().width(8).into(),
882                    container(text(name).size(13).wrapping(Wrapping::None)).width(Length::Fill).clip(true).into(),
883                ];
884                line.extend(who_did(&doer.did, context));
885                let line = menu_button(line).height(Length::Fixed(WHO_ROW_HEIGHT)).padding([2, 8]);
886                lines.push(line.on_press_maybe(doer.who.map(Message::OpenProfile)))
887            });
888            let more = people.len().saturating_sub(WHO_SHOWN);
889            if more > 0 {
890                lines = lines.push(note(fl!("who-more", count = more)));
891            }
892            container(widget::scrollable(lines)).max_height(WHO_MAX_HEIGHT).into()
893        }
894    };
895    let title = container(text(title).size(12).font(cosmic::font::bold()).wrapping(Wrapping::None)).padding([4, 8]);
896    container(widget::Column::new().push(title).push(body))
897        .padding(4)
898        .width(Length::Fixed(WHO_WIDTH))
899        .class(cosmic::theme::Container::Dropdown)
900        .into()
901}
902
903/// `action`, one of a note's actions that counts what others left on it,
904/// with who they were under it for whoever asks: a click on it with the
905/// right button shows them, and one anywhere else puts them away. `own`
906/// is what the action itself opens under it, if it opens something and
907/// that is open, and what closing it says.
908fn counted<'a>(
909    action: Element<'a, Message>,
910    note: &Note,
911    what: Left,
912    context: &RowContext<'a>,
913    own: Option<(Option<Element<'a, Message>>, Message)>,
914) -> Element<'a, Message> {
915    // Under the action, from its left edge; over it, where the popup has
916    // no room left under.
917    let under = Point::new(0.0, action_height(context.sizes) + MENU_GAP);
918    let action = widget::mouse_area(action).on_right_press(Message::ShowWho(note.id, what));
919    let who = context.who.filter(|menu| menu.note == note.id && menu.what == what);
920    let (own, own_closes) = own.unwrap_or((None, Message::CloseWho));
921    let action = popover(action).position(Position::Point(under));
922    match (who, own) {
923        (Some(who), _) => action.on_close(Message::CloseWho).popup(who_menu(who, context)).into(),
924        (None, Some(own)) => action.on_close(own_closes).popup(own).into(),
925        (None, None) => action.on_close(own_closes).into(),
926    }
927}
928
929/// The reaction action of `note`: a heart, with how many reacted. Pressed,
930/// it offers what to react with under it (see
931/// [`reaction_menu`](mod@crate::views::components::reaction_menu)), over
932/// it where there is no room under, and a click anywhere else puts the
933/// offer away. Once the account has reacted it shows what with, in
934/// `accent`: the heart filled, or the emoji in the icon's place, set no
935/// taller than the line. Once is enough: it can't be pressed again.
936fn reaction_action<'a>(note: &Note, engagement: &Engagement, context: &RowContext<'a>, dim: Color) -> Element<'a, Message> {
937    let sizes = context.sizes;
938    let count = engagement.likes as u64;
939    let react = (context.can_publish && engagement.reaction.is_none()).then_some(Message::ToggleReactionMenu(note.id));
940    let action = match &engagement.reaction {
941        Some(Reaction::Emoji(emoji)) => {
942            let shown = text(emoji.clone())
943                .size(sizes.action_text())
944                .shaping(Shaping::Advanced)
945                .class(cosmic::theme::Text::Color(context.accent));
946            action_showing(shown.into(), count, context.accent, fl!("note-reacted"), react, sizes)
947        }
948        Some(Reaction::Like) => action_button(like_icon(true), count, context.accent, fl!("note-reacted"), react, sizes),
949        None => action_button(like_icon(false), count, dim, fl!("note-react"), react, sizes),
950    };
951
952    let menu = context.reacting.menu.filter(|menu| menu.note == note.id);
953    let menu = menu.map(|menu| reaction_menu(menu, context.reacting.suggested));
954    counted(action, note, Left::Reactions, context, Some((menu, Message::CloseReactionMenu)))
955}
956
957/// What a relay is called: its address without the scheme, which is the
958/// same for nearly all of them, and without a slash at its end.
959pub fn relay_name(relay: &RelayUrl) -> &str {
960    let address = relay.as_str();
961    address.split_once("://").map_or(address, |(_, name)| name).trim_end_matches('/')
962}
963
964/// How many relays a note was seen on, for the right end of its line of
965/// actions: nothing to press, and which relays they were for whoever
966/// points at it. Set as an action is, so that it lines up with them.
967fn seen_on<'a>(relays: &[RelayUrl], color: Color, sizes: RowSizes) -> Element<'a, Message> {
968    let picture = icon::icon(relays_icon())
969        .size(sizes.action_icon())
970        .class(cosmic::theme::Svg::custom(move |_theme| svg::Style { color: Some(color) }));
971    let count = text(compact_count(relays.len() as u64)).size(sizes.action_text()).class(cosmic::theme::Text::Color(color));
972    let shown = container(widget::Row::new().push(picture).push(count).spacing(NOTE_ACTION_GAP).align_y(Alignment::Center))
973        .padding(NOTE_ACTION_PADDING);
974
975    let named = relays.iter().map(|relay| format!("\n{}", relay_name(relay)));
976    let said = std::iter::once(fl!("note-seen-on", count = relays.len())).chain(named).collect::<String>();
977    widget::tooltip(shown, text(said).size(12), widget::tooltip::Position::Top).into()
978}
979
980/// How wide the room is that is kept at the right end of a line of
981/// actions for how many relays the note was seen on: its icon and a count
982/// of two figures. Kept before that is known as after, so that the
983/// bookmark beside it stays where it is when it comes.
984fn seen_on_width(sizes: RowSizes) -> f32 {
985    let count = 2.0 * f32::from(sizes.action_text()) * FIGURE_WIDTH_PER_SIZE;
986    2.0 * f32::from(NOTE_ACTION_PADDING[1]) + f32::from(sizes.action_icon()) + NOTE_ACTION_GAP + count
987}
988
989/// The share action of `note`: two links of a chain, which copy a link to
990/// the note that anyone can open. Once that is done it is a tick, in
991/// `accent`, until the popup closes or another note's link is copied.
992fn share_action<'a>(note: &Note, context: &RowContext<'a>, dim: Color) -> Element<'a, Message> {
993    let press = Some(Message::CopyShareLink(note.id));
994    if context.share_copied == Some(note.id) {
995        let tick = icon::from_name("object-select-symbolic").handle();
996        action_button(tick, 0, context.accent, fl!("note-share-copied"), press, context.sizes)
997    } else {
998        action_button(link_icon(), 0, dim, fl!("note-share"), press, context.sizes)
999    }
1000}
1001
1002/// The bookmark action of `note`: a ribbon, filled and in `accent` when the
1003/// account has the note bookmarked, which pressing it changes. It shows
1004/// the change at once, while the changed list is on its way. `None` for an
1005/// account that keeps no bookmarks.
1006///
1007/// It can always be pressed, and what a press does, if anything, is the
1008/// handler's to say: a press that found nothing to press would open the
1009/// note's thread instead, as a click anywhere else on the row does.
1010fn bookmark_action<'a>(note: &Note, context: &RowContext<'a>, dim: Color) -> Option<Element<'a, Message>> {
1011    let bookmarked = context.bookmarking.shows(&note.id)?;
1012    let tooltip = match context.bookmarking {
1013        Bookmarking::Unreadable(why) => {
1014            let why = truncate_chars(why.lines().next().unwrap_or_default(), BOOKMARK_REASON_MAX_CHARS);
1015            fl!("note-bookmark-unreadable", error = why.as_ref())
1016        }
1017        _ if bookmarked => fl!("note-bookmark-remove"),
1018        _ => fl!("note-bookmark"),
1019    };
1020    let color = if bookmarked { context.accent } else { dim };
1021    Some(action_button(bookmark_icon(bookmarked), 0, color, tooltip, Some(Message::Bookmark(note.id)), context.sizes))
1022}
1023
1024/// The line of actions under a note: answer it, repost or quote it, react
1025/// to it, zap it. Each says how many did (for zaps, how many sats); the
1026/// account's own repost and like are in `accent`. Reposting opens a menu
1027/// under the action, which a click anywhere else puts away. An account that
1028/// can't publish sees the counts of the first three and can press none.
1029/// Anyone can zap an author who has a Lightning address. At the right end,
1030/// copying a link to the note, bookmarking it, and, once that is known,
1031/// how many relays it was seen on.
1032fn note_actions<'a>(note: &Note, context: &RowContext<'a>) -> Element<'a, Message> {
1033    let engagement = context.engagement.get(&note.id).cloned().unwrap_or_default();
1034    let text_color: Color = cosmic::theme::active().cosmic().on_bg_color().into();
1035    let dim = Color { a: NOTE_ACTION_DIM, ..text_color };
1036    let can = |message: Message| context.can_publish.then_some(message);
1037    let sizes = context.sizes;
1038
1039    let repost = action_button(
1040        repost_icon(),
1041        engagement.reposts as u64,
1042        if engagement.reposted { context.accent } else { dim },
1043        fl!("note-repost-how"),
1044        can(Message::ToggleRepostMenu(note.id)),
1045        sizes,
1046    );
1047    // Its menu opens under it, and so does who reposted.
1048    let menu = context.repost_menu.filter(|menu| menu.note == note.id);
1049    let menu = menu.map(|menu| repost_menu(note.id, engagement.reposted, menu.at));
1050    let repost = counted(repost, note, Left::Reposts, context, Some((menu, Message::CloseRepostMenu)));
1051
1052    let can_be_zapped = context.profiles.get(&note.author).is_some_and(|profile| profile.lightning.is_some());
1053    widget::Row::new()
1054        .push(action_cell(action_button(
1055            reply_icon(),
1056            engagement.replies as u64,
1057            dim,
1058            fl!("note-reply"),
1059            can(Message::ComposeReply(note.id)),
1060            sizes,
1061        )))
1062        .push(action_cell(repost))
1063        .push(action_cell(reaction_action(note, &engagement, context, dim)))
1064        .push(action_cell(counted(
1065            action_button(
1066                zap_icon(),
1067                engagement.zap_sats,
1068                dim,
1069                if can_be_zapped { fl!("note-zap") } else { fl!("note-zap-unavailable") },
1070                can_be_zapped.then_some(Message::ZapNote(note.id)),
1071                sizes,
1072            ),
1073            note,
1074            Left::Zaps,
1075            context,
1076            None,
1077        )))
1078        .push(widget::Space::new().width(Length::Fill))
1079        .push(share_action(note, context, dim))
1080        .push_maybe(bookmark_action(note, context, dim))
1081        .push(
1082            container(widget::Row::new().push_maybe(
1083                context.seen_on.get(&note.id).filter(|relays| !relays.is_empty()).map(|relays| seen_on(relays, dim, sizes)),
1084            ))
1085            .width(Length::Fixed(seen_on_width(sizes)))
1086            .align_x(Alignment::End),
1087        )
1088        // As tall with counts as without: a count is taller than an icon,
1089        // and the first one to arrive must not make the row grow.
1090        .height(Length::Fixed(action_height(sizes)))
1091        .align_y(Alignment::Center)
1092        .into()
1093}
1094
1095/// `part`, a part of a note's row that stands for its author, opening
1096/// their profile when it is clicked.
1097pub(super) fn opening_profile<'a>(part: impl Into<Element<'a, Message>>, author: PublicKey) -> Element<'a, Message> {
1098    widget::mouse_area(part).on_press(Message::OpenProfile(author)).interaction(mouse::Interaction::Pointer).into()
1099}
1100
1101/// `column`, with what `note` says under what is in it already: its text,
1102/// as much of it as `reading` says, with the button that shows more of a
1103/// long one or less; its images, its videos, the notes it quotes (each as
1104/// a card if it is at hand, and as a link if not), and the preview of the
1105/// page it links to.
1106///
1107/// A page that turned out to be a video, and was played, has the room of
1108/// a video from then on in place of its card: the one time a row changes
1109/// height under its reader, and at their pressing.
1110pub(super) fn said<'a>(
1111    mut column: widget::Column<'a, Message, cosmic::Theme>,
1112    note: &'a Note,
1113    context: &RowContext<'a>,
1114    reading: Reading,
1115) -> widget::Column<'a, Message, cosmic::Theme> {
1116    let in_full = reading == Reading::Whole;
1117    let (segments, _) = note.content.text(in_full);
1118    if !segments.is_empty() {
1119        column = column.push(note_text(segments, context));
1120    }
1121    if note.content.whole.is_some() && reading != Reading::Quoted {
1122        column = column.push(fold_button(note.id, in_full, context));
1123    }
1124    for image in &note.content.images {
1125        column = column.push(note_image(image, context));
1126    }
1127    for video in &note.content.videos {
1128        // A page that shows a video is called what it calls itself, once
1129        // it has said; a file by its address.
1130        let label = match video.page.then(|| context.previews.get(&video.url)) {
1131            Some(PreviewState::Ready(page)) => page.title.as_str(),
1132            _ => video.label.as_str(),
1133        };
1134        column = column.push(video_box(&video.url, label, video.size, &video.posters, context));
1135    }
1136    for quote in note.quotes_shown() {
1137        column = column.push(match note.quoted(quote.id) {
1138            Some(quoted) => quoted_note(quoted, context),
1139            None => quote_link(quote, context),
1140        });
1141    }
1142    if let Some(page) = &note.content.preview {
1143        column = column.push_maybe(if context.videos.opened.contains(page) {
1144            let label = reqwest::Url::parse(page).map_or_else(|_| page.clone(), |url| link_label(&url));
1145            Some(video_box(page, label, None, &[], context))
1146        } else {
1147            link_preview(page, context)
1148        });
1149    }
1150    column
1151}
1152
1153/// One row: the author's picture, and beside it who they are and how long
1154/// ago they wrote; under those, as wide as the row, what the note says and
1155/// the line of actions; and under it all a line that sets the row apart
1156/// from the next. The picture and the name lead to the author's profile.
1157///
1158/// The row of a long note that shows in full keeps how far its top is
1159/// above what is in view, for showing less of it to scroll back by (see
1160/// [`Expanded`]).
1161pub fn note_row<'a>(note: &'a Note, context: &RowContext<'a>) -> Element<'a, Message> {
1162    let above = context.expanded.above(&note.id);
1163    let reading = Reading::of_row(above.is_some());
1164    let body = said(
1165        widget::Column::new().push(who_and_when(note, context)).spacing(NOTE_SPACING).width(Length::Fill),
1166        note,
1167        context,
1168        reading,
1169    )
1170    .push(note_actions(note, context));
1171
1172    let row = widget::Column::new()
1173        .push(body)
1174        .push(widget::divider::horizontal::default())
1175        .spacing(NOTE_SPACING)
1176        .padding([NOTE_PADDING_TOP, 0, 0, 0])
1177        .width(Length::Fill);
1178    match above {
1179        // Over the row and not in it: what is in the row has space
1180        // between its parts, and this is no part to set apart.
1181        Some(above) => widget::Column::new().push(ScrollPosition::new(above)).push(row).into(),
1182        None => row.into(),
1183    }
1184}
1185
1186/// A note that is being written, as its row would show it once it is out:
1187/// who writes it, and all it says. Without the line of actions and the
1188/// line under a row: there is nothing to act on yet, and no row after it.
1189pub fn note_being_written<'a>(note: &'a Note, context: &RowContext<'a>) -> Element<'a, Message> {
1190    let column = widget::Column::new().push(who_and_when(note, context)).spacing(NOTE_SPACING).width(Length::Fill);
1191    said(column, note, context, Reading::Whole).into()
1192}
1193
1194/// The first line of a row: the picture of who wrote `note`, their name,
1195/// and how long ago they wrote it.
1196fn who_and_when<'a>(note: &'a Note, context: &RowContext<'a>) -> Element<'a, Message> {
1197    let RowContext { profiles, images, now, sizes, .. } = *context;
1198    let name = display_name(profiles, &note.author);
1199    let picture = profiles.get(&note.author).and_then(|profile| profile.picture.as_deref());
1200    let author_picture = opening_profile(avatar(images, picture, &note.author, &name, NOTE_AVATAR_SIZE), note.author);
1201
1202    widget::Row::new()
1203        .push(author_picture)
1204        // The name takes the room the time leaves, and is cut rather than
1205        // wrapped when it doesn't fit.
1206        .push(
1207            container(opening_profile(
1208                text(name).size(sizes.name()).font(cosmic::font::bold()).wrapping(Wrapping::None),
1209                note.author,
1210            ))
1211            .width(Length::Fill)
1212            .clip(true),
1213        )
1214        .push(text(relative_time(now, note.created_at)).size(sizes.time()).wrapping(Wrapping::None))
1215        .spacing(NOTE_AVATAR_GAP)
1216        .align_y(Alignment::Center)
1217        .into()
1218}
1219
1220#[cfg(test)]
1221mod tests {
1222    use super::{
1223        Bookmarking, NOTE_ACTION_WIDTH, NOTE_SPACING, NoteLink, Reacting, RowContext, RowSizes, estimated_note_height,
1224        fold_height, note_being_written, note_row, opening_thread, relay_name, seen_on_width,
1225    };
1226    use crate::emoji::Group;
1227    use crate::images::{ImageRequest, ImageShape, ImageStore, LoadedImage};
1228    use crate::messages::Message;
1229    use crate::nostr::bookmarks::Bookmarks;
1230    use crate::nostr::content::{self, FEED_NOTE_MAX_CHARS};
1231    use crate::nostr::engagement::{Did, Doer, Engagement, Left, Reaction};
1232    use crate::nostr::models::Note;
1233    use crate::nostr::outbox::Whereabouts;
1234    use crate::previews::{LinkPreview, Linked, PreviewStore};
1235    use crate::state::{EmojiPicker, Expanded, ReactionMenu, RepostMenu, WhoMenu};
1236    use crate::video::{Playback, Videos};
1237    use crate::views::components::{LIST_MAX_WIDTH, link_preview_height, shown_size, video_height};
1238    use cosmic::iced::core::widget::Tree;
1239    use cosmic::iced::core::{clipboard, layout};
1240    use cosmic::iced::runtime::user_interface::{Cache, UserInterface};
1241    use cosmic::iced::widget::text::Wrapping;
1242    use cosmic::iced::{Color, Event, Length, Point, Rectangle, Size, Vector, mouse};
1243    use cosmic::widget::image::Handle;
1244    use nostr_sdk::prelude::{EventId, Keys, Kind, Nip19Event, RelayUrl, ToBech32};
1245    use std::collections::HashMap;
1246
1247    #[test]
1248    fn a_click_on_a_mention_or_a_link_leads_where_it_says() {
1249        let someone = Keys::generate().public_key();
1250        let said = note(&format!("hey nostr:{} look at https://example.com/page #birds", someone.to_bech32().unwrap()));
1251
1252        let led: Vec<String> = said
1253            .content
1254            .segments
1255            .iter()
1256            .filter_map(NoteLink::of)
1257            .map(|link| match link.follow() {
1258                Message::OpenProfile(public_key) => format!("profile {}", public_key.to_hex()),
1259                Message::OpenUrl(url) => format!("web {url}"),
1260                other => panic!("nowhere a note leads: {other:?}"),
1261            })
1262            .collect();
1263
1264        // The plain text and the hashtag lead nowhere.
1265        assert_eq!(led, [format!("profile {}", someone.to_hex()), "web https://example.com/page".to_string()]);
1266    }
1267
1268    fn note(text: &str) -> Note {
1269        Note {
1270            id: EventId::from_byte_array([7; 32]),
1271            kind: Kind::TextNote,
1272            author: Keys::generate().public_key(),
1273            created_at: 0,
1274            content: content::parse(text, FEED_NOTE_MAX_CHARS),
1275            reply_to: None,
1276            quoted: Vec::new(),
1277        }
1278    }
1279
1280    /// A store with nothing in it: every picture is still loading.
1281    fn no_images() -> ImageStore {
1282        ImageStore::new(1_000_000).0
1283    }
1284
1285    /// How wide the list is in a popup at its widest, and the size note
1286    /// text is set in unless the settings say otherwise.
1287    const WIDTH: f32 = LIST_MAX_WIDTH;
1288    const SIZE: u16 = 13;
1289
1290    /// How tall the real row for `note` lays out, in a list as wide as the
1291    /// popup's, with the real text renderer.
1292    fn measured_height(note: &Note) -> f32 {
1293        measured_height_with(note, &no_images(), SIZE, WIDTH)
1294    }
1295
1296    fn measured_height_with(note: &Note, images: &ImageStore, size: u16, width: f32) -> f32 {
1297        measured_height_in(note, images, &no_previews(), size, width)
1298    }
1299
1300    /// A store that was asked about no page yet: every preview is still
1301    /// loading.
1302    fn no_previews() -> PreviewStore {
1303        PreviewStore::new().0
1304    }
1305
1306    /// A store that knows what the page at `url` says of itself, which may
1307    /// be nothing.
1308    fn previews_knowing(url: &str, preview: Option<LinkPreview>) -> PreviewStore {
1309        let mut previews = no_previews();
1310        assert!(previews.begin(&url.to_string()));
1311        previews.finish(url.to_string(), preview.map(Linked::Page));
1312        previews
1313    }
1314
1315    fn measured_height_in(note: &Note, images: &ImageStore, previews: &PreviewStore, size: u16, width: f32) -> f32 {
1316        measured_height_playing(note, images, previews, &Videos::default(), size, width)
1317    }
1318
1319    /// As [`measured_height_in`], with `videos` as the model has them.
1320    fn measured_height_playing(
1321        note: &Note,
1322        images: &ImageStore,
1323        previews: &PreviewStore,
1324        videos: &Videos,
1325        size: u16,
1326        width: f32,
1327    ) -> f32 {
1328        measured_height_among(note, images, previews, videos, &Expanded::default(), size, width)
1329    }
1330
1331    /// How tall the row of `note` lays out with the note shown in full,
1332    /// if it is a long one.
1333    fn measured_height_in_full(note: &Note, size: u16, width: f32) -> f32 {
1334        let mut expanded = Expanded::default();
1335        expanded.expand(note.id);
1336        measured_height_among(note, &no_images(), &no_previews(), &Videos::default(), &expanded, size, width)
1337    }
1338
1339    /// As [`measured_height_playing`], with the long notes among
1340    /// `expanded` in full.
1341    fn measured_height_among(
1342        note: &Note,
1343        images: &ImageStore,
1344        previews: &PreviewStore,
1345        videos: &Videos,
1346        expanded: &Expanded,
1347        size: u16,
1348        width: f32,
1349    ) -> f32 {
1350        measured(note, images, previews, videos, expanded, size, width, false)
1351    }
1352
1353    /// How tall `note` lays out: as its row, or as it shows while it is
1354    /// `being_written`.
1355    #[allow(clippy::too_many_arguments)]
1356    fn measured(
1357        note: &Note,
1358        images: &ImageStore,
1359        previews: &PreviewStore,
1360        videos: &Videos,
1361        expanded: &Expanded,
1362        size: u16,
1363        width: f32,
1364        being_written: bool,
1365    ) -> f32 {
1366        let renderer = crate::views::components::testing::renderer();
1367        let profiles = HashMap::new();
1368        let engagement = HashMap::new();
1369        let seen_on = HashMap::new();
1370        let context = RowContext {
1371            profiles: &profiles,
1372            images,
1373            previews,
1374            videos,
1375            engagement: &engagement,
1376            seen_on: &seen_on,
1377            now: 0,
1378            accent: Color::WHITE,
1379            can_publish: true,
1380            repost_menu: None,
1381            who: None,
1382            reacting: Reacting::NONE,
1383            expanded,
1384            marked: None,
1385            share_copied: None,
1386            picture_copied: None,
1387            bookmarking: Bookmarking::Unavailable,
1388            menu_open: false,
1389            sizes: RowSizes::new(size),
1390        };
1391        let mut element = if being_written { note_being_written(note, &context) } else { note_row(note, &context) };
1392        let mut tree = Tree::new(element.as_widget());
1393        let limits = layout::Limits::new(Size::ZERO, Size::new(width, f32::INFINITY));
1394        element.as_widget_mut().layout(&mut tree, &renderer, &limits).size().height
1395    }
1396
1397    #[test]
1398    fn a_note_being_written_shows_whole_and_without_what_a_row_ends_with() {
1399        let me = Keys::generate().public_key();
1400        let being_written = |text: &str| {
1401            let note = Note::being_written(text, &[], me, 0);
1402            measured(&note, &no_images(), &no_previews(), &Videos::default(), &Expanded::default(), SIZE, WIDTH, true)
1403        };
1404
1405        // Short of the line of actions, the line under the row and the room
1406        // above it: there is nothing to act on, and no row after it.
1407        let less = measured_height(&note("gm")) - being_written("gm");
1408        assert!((20.0..60.0).contains(&less), "{less} shorter than the row");
1409        // What is marked shows as it marks it, here as in a row.
1410        let marked = "# gm\n| a | b |\n|---|---|\n| 1 | 2 |";
1411        assert_eq!(measured_height(&note(marked)) - being_written(marked), less);
1412
1413        // A long one shows all it says, with nothing to press for the
1414        // rest: as tall as its row in full, less what that ends with and
1415        // the button that shows less.
1416        let long = "the quick brown fox jumps over the lazy dog ".repeat(60);
1417        let (cut, in_full) = (measured_height(&note(&long)), measured_height_in_full(&note(&long), SIZE, WIDTH));
1418        assert!(in_full > cut + 100.0, "{in_full} in full, {cut} cut");
1419        let whole = being_written(&long);
1420        assert!(whole > cut && whole < in_full - less, "{whole} being written, {in_full} in full");
1421    }
1422
1423    /// How tall `said` lays out on its own, in text of `size`, `width` wide.
1424    fn text_height(said: &str, size: u16, width: f32) -> f32 {
1425        let renderer = crate::views::components::testing::renderer();
1426        let mut element: cosmic::Element<'_, Message> =
1427            cosmic::widget::text(said).size(size).wrapping(Wrapping::WordOrGlyph).width(Length::Fill).into();
1428        let mut tree = Tree::new(element.as_widget());
1429        let limits = layout::Limits::new(Size::ZERO, Size::new(width, f32::INFINITY));
1430        element.as_widget_mut().layout(&mut tree, &renderer, &limits).size().height
1431    }
1432
1433    #[test]
1434    fn a_note_is_as_wide_as_its_row() {
1435        // What a note says wraps as it would with the whole width of the
1436        // row to itself: nothing is set in beside the author's picture.
1437        let said = "wide ".repeat(60);
1438        let row = |text: &str| measured_height_with(&note(text), &no_images(), SIZE, 300.0);
1439        let alone = |text: &str| text_height(text.trim(), SIZE, 300.0);
1440
1441        assert!(alone(&said) > 3.0 * alone("wide"), "several lines: {}", alone(&said));
1442        let (in_row, by_itself) = (row(&said) - row("wide"), alone(&said) - alone("wide"));
1443        assert!((in_row - by_itself).abs() < 0.01, "{in_row} in the row, {by_itself} alone");
1444        // A little narrower, and it would take another line.
1445        assert!(text_height(said.trim(), SIZE, 300.0 - 40.0) > alone(&said));
1446    }
1447
1448    #[test]
1449    fn larger_text_makes_a_taller_row() {
1450        let said = note(&"the quick brown fox jumps over the lazy dog ".repeat(6));
1451        let heights: Vec<f32> =
1452            [10, 13, 18, 24].into_iter().map(|size| measured_height_with(&said, &no_images(), size, WIDTH)).collect();
1453        assert!(heights.windows(2).all(|pair| pair[0] < pair[1]), "{heights:?}");
1454    }
1455
1456    #[test]
1457    fn a_longer_note_makes_a_taller_row() {
1458        let short = note("gm");
1459        let long = note(&"the quick brown fox jumps over the lazy dog ".repeat(12));
1460        let lines = note("one\ntwo\nthree\nfour\nfive");
1461
1462        assert!(measured_height(&long) > measured_height(&short) + 60.0);
1463        assert!(measured_height(&lines) > measured_height(&short) + 50.0);
1464    }
1465
1466    #[test]
1467    fn a_very_long_note_is_cut_in_the_feed() {
1468        let long = note(&"word ".repeat(200));
1469        let endless = note(&"word ".repeat(5_000));
1470        assert_eq!(measured_height(&long), measured_height(&endless));
1471    }
1472
1473    /// What comes of clicking the row of `note` at `point`, in a list as
1474    /// wide as the popup's with room under the row: the row as a list
1475    /// shows it, opening the note's thread, with the repost menu open on
1476    /// the note or not, for an account that has `reposted` it or not, and
1477    /// with `previews` of the pages it links to.
1478    fn clicked(note: &Note, previews: &PreviewStore, menu_open: bool, reposted: bool, point: Point) -> Vec<Message> {
1479        clicked_by(note, previews, menu_open, reposted, Bookmarking::Unavailable, &HashMap::new(), point)
1480    }
1481
1482    /// As [`clicked`], by an account that keeps bookmarks as `bookmarking`
1483    /// says, in a row whose note was seen on the relays `seen_on` says.
1484    fn clicked_by(
1485        note: &Note,
1486        previews: &PreviewStore,
1487        menu_open: bool,
1488        reposted: bool,
1489        bookmarking: Bookmarking<'_>,
1490        seen_on: &HashMap<EventId, Vec<RelayUrl>>,
1491        point: Point,
1492    ) -> Vec<Message> {
1493        let (profiles, images) = (HashMap::new(), no_images());
1494        let made = Engagement { reposts: usize::from(reposted), reposted, ..Engagement::default() };
1495        let engagement = HashMap::from([(note.id, made)]);
1496        let videos = Videos::default();
1497        let expanded = Expanded::default();
1498        let context = RowContext {
1499            profiles: &profiles,
1500            images: &images,
1501            previews,
1502            videos: &videos,
1503            engagement: &engagement,
1504            seen_on,
1505            now: 0,
1506            accent: Color::WHITE,
1507            can_publish: true,
1508            repost_menu: menu_open.then_some(RepostMenu::of(note.id)),
1509            who: None,
1510            reacting: Reacting::NONE,
1511            expanded: &expanded,
1512            marked: None,
1513            share_copied: None,
1514            picture_copied: None,
1515            bookmarking,
1516            menu_open: false,
1517            sizes: RowSizes::new(SIZE),
1518        };
1519        clicked_in(note, &context, point)
1520    }
1521
1522    /// What comes of clicking the row of `note`, built with `context`, at
1523    /// `point`.
1524    fn clicked_in(note: &Note, context: &RowContext<'_>, point: Point) -> Vec<Message> {
1525        let mut renderer = crate::views::components::testing::renderer();
1526        let row = opening_thread(note_row(note, context), note.id, context);
1527        let mut interface = UserInterface::build(row, Size::new(WIDTH, 300.0), Cache::new(), &mut renderer);
1528
1529        let mut messages = Vec::new();
1530        for event in [
1531            mouse::Event::CursorMoved { position: point },
1532            mouse::Event::ButtonPressed(mouse::Button::Left),
1533            mouse::Event::ButtonReleased(mouse::Button::Left),
1534        ] {
1535            let _ = interface.update(
1536                &[Event::Mouse(event)],
1537                mouse::Cursor::Available(point),
1538                &mut renderer,
1539                &mut clipboard::Null,
1540                &mut messages,
1541            );
1542        }
1543        messages
1544    }
1545
1546    /// What comes of a click at each of a column of points `x` across, top
1547    /// to bottom, told in brief; the same thing twice running is told once.
1548    fn clicked_down(x: f32, click: impl Fn(Point) -> Vec<Message>) -> Vec<String> {
1549        let mut told: Vec<String> = Vec::new();
1550        for y in (0..300).step_by(4) {
1551            let came: Vec<&str> = click(Point::new(x, y as f32))
1552                .iter()
1553                .map(|message| match message {
1554                    Message::OpenProfile(_) => "profile",
1555                    Message::OpenThread(..) => "thread",
1556                    Message::OpenUrl(_) => "page",
1557                    Message::ToggleRepostMenu(_) => "menu",
1558                    Message::CloseRepostMenu => "close",
1559                    Message::Repost(_) => "repost",
1560                    Message::ComposeQuote(_) => "quote",
1561                    Message::Bookmark(_) => "bookmark",
1562                    Message::ComposeReply(_) => "reply",
1563                    Message::ToggleReactionMenu(_) => "reactions",
1564                    Message::CloseReactionMenu => "close",
1565                    Message::React(_, Reaction::Like) => "like",
1566                    Message::React(_, Reaction::Emoji(_)) => "emoji",
1567                    Message::OpenEmojiPicker => "more",
1568                    Message::EmojiGroup(_) => "group",
1569                    Message::CopyShareLink(_) => "share",
1570                    Message::ExpandNote(_) => "show more",
1571                    Message::CollapseNote(_) => "show less",
1572                    Message::VideoPress(_) => "play",
1573                    Message::VideoMute => "mute",
1574                    Message::VideoSpeedMenu => "speeds",
1575                    Message::CloseVideoSpeedMenu => "close",
1576                    Message::VideoSpeed(_) => "speed",
1577                    Message::VideoVolume(_) => "volume",
1578                    Message::VideoVolumeSet => "set",
1579                    Message::VideoSound(true) => "over",
1580                    Message::VideoSound(false) => "left",
1581                    Message::VideoSeeking(_) => "seeking",
1582                    Message::VideoSeek => "seek",
1583                    other => panic!("nothing a click here asks for: {other:?}"),
1584                })
1585                .collect();
1586            let came = came.join("+");
1587            if told.last() != Some(&came) {
1588                told.push(came);
1589            }
1590        }
1591        told
1592    }
1593
1594    /// What comes of clicks down the middle of the repost action of `note`.
1595    fn clicked_down_the_repost_action(note: &Note, menu_open: bool, reposted: bool) -> Vec<String> {
1596        // The action is the second of the line, and its button is at the
1597        // left of the room it has.
1598        clicked_down(NOTE_ACTION_WIDTH + 12.0, |point| clicked(note, &no_previews(), menu_open, reposted, point))
1599    }
1600
1601    /// What a page says of itself, for a card: with a picture or not.
1602    fn page(description: Option<&str>, image: Option<&str>) -> LinkPreview {
1603        LinkPreview {
1604            title: "A page worth the click, with a title long enough to be cut where the card ends, and then some".into(),
1605            description: description.map(String::from),
1606            image: image.map(String::from),
1607            site: "example.com".into(),
1608        }
1609    }
1610
1611    #[test]
1612    fn a_row_keeps_its_height_when_the_preview_of_its_link_arrives() {
1613        let url = "https://example.com/a/page";
1614        let linking = note(&format!("worth reading\n{url}"));
1615        // The same, as far as its text goes, with nothing to preview.
1616        let plain = note("worth reading\nexample.com/a/page");
1617        let height = |images: &ImageStore, previews: &PreviewStore| measured_height_in(&linking, images, previews, SIZE, WIDTH);
1618
1619        // While the page is asked, room is kept for its card.
1620        let waiting = height(&no_images(), &no_previews());
1621        let card = link_preview_height(RowSizes::new(SIZE)) + f32::from(NOTE_SPACING);
1622        assert!((waiting - measured_height(&plain) - card).abs() < 0.01, "{waiting}");
1623
1624        // Whatever the page says, the card is that tall: a title alone, a
1625        // description of one line or of many, a picture or none.
1626        let picture = "https://example.com/card.png";
1627        for said in [
1628            page(None, None),
1629            page(Some("Short."), None),
1630            page(Some(&"A description that goes on and on. ".repeat(20)), None),
1631            page(Some("With a picture on its way."), Some(picture)),
1632        ] {
1633            assert_eq!(height(&no_images(), &previews_knowing(url, Some(said.clone()))), waiting, "{said:?}");
1634        }
1635
1636        // And as tall when the picture is there, or can't be had.
1637        let previews = previews_knowing(url, Some(page(Some("With a picture."), Some(picture))));
1638        let request = ImageRequest { url: picture.to_string(), shape: ImageShape::Thumbnail };
1639        let (mut arrived, mut failed) = (no_images(), no_images());
1640        arrived.begin(&request);
1641        arrived.finish(
1642            request.clone(),
1643            Ok(LoadedImage { handle: Handle::from_rgba(160, 90, vec![0; 160 * 90 * 4]), width: 160, height: 90 }),
1644        );
1645        failed.begin(&request);
1646        failed.finish(request, Err("404".into()));
1647        assert_eq!(height(&arrived, &previews), waiting);
1648        assert_eq!(height(&failed, &previews), waiting);
1649    }
1650
1651    #[test]
1652    fn a_page_with_nothing_to_say_gets_no_card_and_leaves_no_gap() {
1653        let url = "https://example.com/a/page";
1654        let linking = note(&format!("worth reading\n{url}"));
1655        let plain = note("worth reading\nexample.com/a/page");
1656        let silent = measured_height_in(&linking, &no_images(), &previews_knowing(url, None), SIZE, WIDTH);
1657        assert_eq!(silent, measured_height(&plain));
1658    }
1659
1660    #[test]
1661    fn a_click_on_the_preview_opens_the_page_and_not_the_thread() {
1662        let url = "https://example.com/a/page";
1663        let linking = note(&format!("worth reading\n{url}"));
1664        let down_the_middle =
1665            |previews: &PreviewStore| clicked_down(WIDTH / 2.0, |point| clicked(&linking, previews, false, false, point));
1666
1667        // Down the middle of the row: the note, the card, the line of
1668        // actions beside the actions, and nothing under the row.
1669        let shown = previews_knowing(url, Some(page(Some("About it."), None)));
1670        assert_eq!(down_the_middle(&shown), ["thread", "page", "thread", ""]);
1671        let opened = clicked(&linking, &shown, false, false, Point::new(WIDTH / 2.0, 120.0));
1672        assert!(matches!(&opened[..], [Message::OpenUrl(opened)] if opened == url), "{opened:?}");
1673
1674        // While the page is asked there is nothing to click but the row.
1675        assert_eq!(down_the_middle(&no_previews()), ["thread", ""]);
1676    }
1677
1678    /// The videos of a model in which `playing` plays, or did last, and
1679    /// the links `opened` were played as the videos they turned out to be.
1680    fn videos_having(playing: Option<Playback>, opened: &[&str]) -> Videos {
1681        let mut videos = Videos::default();
1682        videos.playing = playing;
1683        videos.opened = opened.iter().map(|url| (*url).to_string()).collect();
1684        videos
1685    }
1686
1687    /// What the model has of the video at `url` once it was played: a
1688    /// picture of it, how long it is, and whether it plays just now.
1689    fn videos_with(url: &str, playing: bool) -> Videos {
1690        let mut playback = Playback::held(url);
1691        playback.frame = Some(Handle::from_rgba(64, 36, vec![0; 64 * 36 * 4]));
1692        playback.duration = Some(90.0);
1693        playback.playing = playing;
1694        videos_having(Some(playback), &[])
1695    }
1696
1697    #[test]
1698    fn a_video_has_the_same_room_before_while_and_after_it_plays() {
1699        let url = "https://example.com/clip.mp4";
1700        let plain = measured_height(&note("watch this"));
1701        // Not said, wide, upright and small: the room kept is the room
1702        // taken, and the room the estimate counts.
1703        for size in [None, Some((1920, 1080)), Some((1080, 1920)), Some((320, 240))] {
1704            let mut with_video = note(&format!("watch this\n{url}"));
1705            with_video.content.videos[0].size = size;
1706            let height =
1707                |videos: &Videos| measured_height_playing(&with_video, &no_images(), &no_previews(), videos, SIZE, WIDTH);
1708
1709            let unplayed = height(&Videos::default());
1710            let room = video_height(size, WIDTH) + f32::from(NOTE_SPACING);
1711            assert!((unplayed - plain - room).abs() < 0.01, "room is kept for a video of {size:?}: {unplayed}");
1712            let estimated = |note: &Note| estimated_note_height(note, RowSizes::new(SIZE), WIDTH, false);
1713            assert!((estimated(&with_video) - estimated(&note("watch this")) - room).abs() < 0.01);
1714
1715            assert_eq!(height(&videos_with(url, true)), unplayed, "playing");
1716            assert_eq!(height(&videos_with(url, false)), unplayed, "held");
1717            let mut with_slider = videos_with(url, true);
1718            with_slider.sound_over(true);
1719            assert_eq!(height(&with_slider), unplayed, "with the slider of its sound showing");
1720            assert_eq!(height(&videos_with("https://example.com/another.mp4", true)), unplayed, "another one playing");
1721            // On its way, with nothing to show yet; and failed, with a
1722            // lot to say about why.
1723            let mut loading = Playback::held(url);
1724            loading.playing = true;
1725            assert_eq!(height(&videos_having(Some(loading), &[])), unplayed, "loading");
1726            let mut failed = Playback::held(url);
1727            failed.error = Some("no decoder for this, and a long account of which one. ".repeat(20));
1728            assert_eq!(height(&videos_having(Some(failed), &[])), unplayed, "failed");
1729        }
1730    }
1731
1732    /// What comes of clicks down the row of `note`, `x` across, with
1733    /// `videos` and `previews` as the model has them.
1734    fn clicked_down_with(note: &Note, previews: &PreviewStore, videos: &Videos, x: f32) -> Vec<String> {
1735        let (profiles, images, engagement, seen_on) = (HashMap::new(), no_images(), HashMap::new(), HashMap::new());
1736        let expanded = Expanded::default();
1737        let context = RowContext {
1738            profiles: &profiles,
1739            images: &images,
1740            previews,
1741            videos,
1742            engagement: &engagement,
1743            seen_on: &seen_on,
1744            now: 0,
1745            accent: Color::WHITE,
1746            can_publish: true,
1747            repost_menu: None,
1748            who: None,
1749            reacting: Reacting::NONE,
1750            expanded: &expanded,
1751            marked: None,
1752            share_copied: None,
1753            picture_copied: None,
1754            bookmarking: Bookmarking::Unavailable,
1755            menu_open: false,
1756            sizes: RowSizes::new(SIZE),
1757        };
1758        clicked_down(x, |point| clicked_in(note, &context, point))
1759    }
1760
1761    #[test]
1762    fn a_click_on_a_video_plays_it_and_its_bar_does_what_it_says() {
1763        let url = "https://example.com/clip.mp4";
1764        let mut with_video = note(&format!("watch this\n{url}"));
1765        // Low and wide, so that the whole row is within reach.
1766        with_video.content.videos[0].size = Some((640, 100));
1767        let down = |videos: &Videos, x: f32| clicked_down_with(&with_video, &no_previews(), videos, x);
1768        let (left, middle, right) = (16.0, WIDTH / 2.0, WIDTH - 16.0);
1769
1770        // Not played yet: the picture and the bar play it, wherever they
1771        // are clicked, but for the end of the bar, which opens the link.
1772        // The rest of the row opens the thread, as ever.
1773        let unplayed = Videos::default();
1774        let beside_the_actions = ["thread", "profile", "thread", "play", "thread", "reply", "thread", ""];
1775        assert_eq!(down(&unplayed, middle), ["thread", "play", "thread", ""]);
1776        assert_eq!(down(&unplayed, left), beside_the_actions);
1777        assert_eq!(down(&unplayed, right), ["thread", "play", "page", "thread", ""]);
1778
1779        // Playing: the picture and the button hold it, the middle of the
1780        // bar is where it is dragged, and beside the way out is its sound.
1781        let playing = videos_with(url, true);
1782        assert_eq!(down(&playing, left), beside_the_actions);
1783        assert_eq!(down(&playing, middle), ["thread", "play", "seeking+seek", "play", "thread", ""]);
1784        // Its sound: the pointer coming over the button is told, for the
1785        // slider to show, and a press turns the sound off.
1786        let (at_speed, at_sound) = (right - 48.0, right - 92.0);
1787        assert_eq!(down(&playing, at_sound), ["thread", "play", "over+over+mute", "thread", ""]);
1788        // With the slider showing, left of the button, that is where
1789        // it is dragged. A press over or under it, in the room the two
1790        // have, is neither the slider's nor the video's: nothing plays
1791        // or stops for it. The bar is as it was beside them.
1792        let mut open = videos_with(url, true);
1793        open.sound_over(true);
1794        let on_the_slider = down(&open, at_sound - 60.0);
1795        assert_eq!(on_the_slider, ["thread", "play", "over+over+volume+set", "over+over+over", "thread", ""]);
1796        assert_eq!(down(&open, at_sound), ["thread", "play", "over+over+mute", "thread", ""]);
1797        assert_eq!(down(&open, middle), down(&playing, middle));
1798
1799        // How fast it plays, between its sound and the way out, opens the
1800        // menu of speeds.
1801        // (Under it, in the line of actions, is the note's share link.)
1802        assert_eq!(down(&playing, at_speed), ["thread", "play", "speeds", "play", "thread", "share", "thread", ""]);
1803        let mut choosing = videos_with(url, true);
1804        choosing.toggle_speed_menu();
1805        // With it open, a speed is there to choose; and a click beside
1806        // the menu puts it away, and neither plays nor holds the video,
1807        // nor opens the thread. What is the bar's own still does its own.
1808        let over_the_menu = down(&choosing, at_speed);
1809        assert!(over_the_menu.iter().any(|came| came == "speed"), "{over_the_menu:?}");
1810        assert_eq!(down(&choosing, middle), ["close", "seeking+close+seek", "close"]);
1811        for x in [left, middle, at_sound, at_speed, right] {
1812            let came = down(&choosing, x);
1813            assert!(came.iter().all(|came| came != "play" && !came.contains("thread")), "{x}: {came:?}");
1814        }
1815        assert_eq!(down(&playing, right), ["thread", "play", "page", "thread", ""]);
1816
1817        // Another video playing leaves this one as it was.
1818        assert_eq!(down(&videos_with("https://example.com/another.mp4", true), middle), ["thread", "play", "thread", ""]);
1819    }
1820
1821    #[test]
1822    fn a_youtube_video_has_a_videos_room_whatever_is_known_of_it() {
1823        let link = "https://www.youtube.com/watch?v=aqz-KE-bpKQ";
1824        let linking = note(&format!("worth an evening\n{link}"));
1825        let height = |images: &ImageStore, previews: &PreviewStore, videos: &Videos| {
1826            measured_height_playing(&linking, images, previews, videos, SIZE, WIDTH)
1827        };
1828        let room = video_height(None, WIDTH) + f32::from(NOTE_SPACING);
1829        let unknown = height(&no_images(), &no_previews(), &Videos::default());
1830        assert!((unknown - measured_height(&note("worth an evening")) - room).abs() < 0.01, "{unknown}");
1831
1832        // Its title come, or not to be had; its picture here, the large
1833        // one or, that one not to be had, the small.
1834        let titled = previews_knowing(link, Some(page(None, None)));
1835        assert_eq!(height(&no_images(), &titled, &Videos::default()), unknown);
1836        assert_eq!(height(&no_images(), &previews_knowing(link, None), &Videos::default()), unknown);
1837        let (large, small) = (&linking.content.videos[0].posters[0], &linking.content.videos[0].posters[1]);
1838        assert_eq!(height(&images_with(large, (1280, 720)), &titled, &Videos::default()), unknown);
1839        let mut only_small = images_with(small, (320, 180));
1840        let gone = ImageRequest { url: large.clone(), shape: ImageShape::Original };
1841        only_small.begin(&gone);
1842        only_small.finish(gone, Err("404".into()));
1843        assert_eq!(height(&only_small, &titled, &Videos::default()), unknown);
1844
1845        // On its way, while what there is to play of it is looked for;
1846        // and not found.
1847        let mut videos = Videos::default();
1848        assert!(videos.press(link).is_some());
1849        assert_eq!(height(&no_images(), &titled, &videos), unknown, "on its way");
1850        videos.found(link, Err("yt-dlp says: sign in to confirm you are not a bot. ".repeat(10)));
1851        assert_eq!(height(&no_images(), &titled, &videos), unknown, "not found");
1852
1853        // A click on it plays it, as any video. (The row is taller than
1854        // the clicks go down.)
1855        let clicked = clicked_down_with(&linking, &titled, &Videos::default(), WIDTH / 2.0);
1856        assert_eq!(clicked.get(..2), Some(&["thread".to_string(), "play".to_string()][..]), "{clicked:?}");
1857    }
1858
1859    #[test]
1860    fn a_link_that_turned_out_to_be_a_video_offers_to_play_it_and_then_has_a_videos_room() {
1861        let url = "https://example.com/a/page";
1862        let linking = note(&format!("worth watching\n{url}"));
1863        let mut found = no_previews();
1864        assert!(found.begin(&url.to_string()));
1865        found.finish(url.to_string(), Some(Linked::Video));
1866        let height = |previews: &PreviewStore, videos: &Videos| {
1867            measured_height_playing(&linking, &no_images(), previews, videos, SIZE, WIDTH)
1868        };
1869
1870        // The offer is the card a page would have had, and a click on it
1871        // plays the video.
1872        let waiting = height(&no_previews(), &Videos::default());
1873        assert_eq!(height(&found, &Videos::default()), waiting);
1874        assert_eq!(clicked_down_with(&linking, &found, &Videos::default(), WIDTH / 2.0), ["thread", "play", "thread", ""]);
1875
1876        // Played once, it has the room of a video in place of the card,
1877        // whether or not it is still the one that plays.
1878        let played = videos_having(None, &[url]);
1879        let grown = video_height(None, WIDTH) - link_preview_height(RowSizes::new(SIZE));
1880        assert!((height(&found, &played) - waiting - grown).abs() < 0.01);
1881        // Another link is no video for that.
1882        let other = videos_having(None, &["https://example.com/another"]);
1883        assert_eq!(height(&found, &other), waiting);
1884    }
1885
1886    /// What comes of pressing `button` at each of a column of points `x`
1887    /// across the row of `note`, top to bottom, with `who` on show.
1888    fn pressed_down(note: &Note, who: Option<&WhoMenu>, button: mouse::Button, x: f32) -> Vec<Message> {
1889        let (profiles, images, previews) = (HashMap::new(), no_images(), no_previews());
1890        let (engagement, seen_on) = (HashMap::new(), HashMap::new());
1891        let (videos, expanded) = (Videos::default(), Expanded::default());
1892        let context = RowContext {
1893            profiles: &profiles,
1894            images: &images,
1895            previews: &previews,
1896            videos: &videos,
1897            engagement: &engagement,
1898            seen_on: &seen_on,
1899            now: 0,
1900            accent: Color::WHITE,
1901            can_publish: true,
1902            repost_menu: None,
1903            who,
1904            reacting: Reacting::NONE,
1905            expanded: &expanded,
1906            marked: None,
1907            share_copied: None,
1908            picture_copied: None,
1909            bookmarking: Bookmarking::Unavailable,
1910            menu_open: false,
1911            sizes: RowSizes::new(SIZE),
1912        };
1913        let mut renderer = crate::views::components::testing::renderer();
1914        let row = opening_thread(note_row(note, &context), note.id, &context);
1915        let mut interface = UserInterface::build(row, Size::new(WIDTH, 300.0), Cache::new(), &mut renderer);
1916        let mut messages = Vec::new();
1917        for y in (0..300).step_by(4) {
1918            let point = Point::new(x, y as f32);
1919            for event in [
1920                mouse::Event::CursorMoved { position: point },
1921                mouse::Event::ButtonPressed(button),
1922                mouse::Event::ButtonReleased(button),
1923            ] {
1924                let _ = interface.update(
1925                    &[Event::Mouse(event)],
1926                    mouse::Cursor::Available(point),
1927                    &mut renderer,
1928                    &mut clipboard::Null,
1929                    &mut messages,
1930                );
1931            }
1932        }
1933        messages
1934    }
1935
1936    #[test]
1937    fn a_right_click_on_a_count_asks_who_they_were_and_they_are_listed_under_it() {
1938        let said = note("worth a look");
1939        // The actions stand in a line, each in as much room as the next:
1940        // answering, reposting, reacting, zapping.
1941        let across = |place: f32| place * NOTE_ACTION_WIDTH + 12.0;
1942        let asked = |place: f32| -> Vec<Left> {
1943            let mut asked: Vec<Left> = pressed_down(&said, None, mouse::Button::Right, across(place))
1944                .into_iter()
1945                .map(|message| match message {
1946                    Message::ShowWho(note, what) if note == said.id => what,
1947                    other => panic!("nothing a right click here asks for: {other:?}"),
1948                })
1949                .collect();
1950            asked.dedup();
1951            asked
1952        };
1953        assert_eq!(asked(0.0), [], "who answered is what the thread shows");
1954        assert_eq!(asked(1.0), [Left::Reposts]);
1955        assert_eq!(asked(2.0), [Left::Reactions]);
1956        assert_eq!(asked(3.0), [Left::Zaps]);
1957
1958        // Listed under the count: a press on one of them opens who they
1959        // are, one on whoever does not say opens nothing, and one
1960        // anywhere else puts the list away.
1961        let someone = Keys::generate().public_key();
1962        let people = vec![Doer { who: Some(someone), did: Did::Zapped(21) }, Doer { who: None, did: Did::Zapped(5) }];
1963        let listed = WhoMenu { note: said.id, what: Left::Zaps, people: Some(people) };
1964        let came = pressed_down(&said, Some(&listed), mouse::Button::Left, across(3.0) + 40.0);
1965        let opened: Vec<_> = came
1966            .iter()
1967            .filter_map(|message| match message {
1968                Message::OpenProfile(who) => Some(who),
1969                _ => None,
1970            })
1971            .collect();
1972        assert!(!opened.is_empty() && opened.iter().all(|who| **who == someone), "{came:?}");
1973        assert!(came.iter().any(|message| matches!(message, Message::CloseWho)), "{came:?}");
1974
1975        // Until they have been read, and when there are none, it says so
1976        // and has nobody to press.
1977        for people in [None, Some(Vec::new())] {
1978            let empty = WhoMenu { note: said.id, what: Left::Zaps, people };
1979            let came = pressed_down(&said, Some(&empty), mouse::Button::Left, across(3.0) + 40.0);
1980            assert!(!came.iter().any(|message| matches!(message, Message::OpenProfile(_))), "{came:?}");
1981        }
1982    }
1983
1984    #[test]
1985    fn the_repost_action_opens_a_menu_that_reposts_or_quotes() {
1986        let said = note("worth passing on");
1987
1988        // With no menu open: the row leads to the thread, the author's name
1989        // to their profile, and the action opens the menu. Under the row
1990        // there is nothing.
1991        assert_eq!(clicked_down_the_repost_action(&said, false, false), ["thread", "profile", "thread", "menu", "thread", ""]);
1992
1993        // With it open: under the action, reposting and then quoting. The
1994        // action puts the menu away, and so does a click anywhere else. On
1995        // the row that is all a click does: the thread is not opened. What
1996        // leads somewhere of its own, as the author's name does, still does.
1997        let open = clicked_down_the_repost_action(&said, true, false);
1998        let beside_closing: Vec<&str> = open.iter().map(String::as_str).filter(|came| !came.ends_with("close")).collect();
1999        assert_eq!(beside_closing, ["menu", "repost", "quote"], "{open:?}");
2000        assert_eq!(open[..3], ["close", "profile+close", "close"], "{open:?}");
2001        assert_eq!(open.last().map(String::as_str), Some("close"), "under the menu, as beside it: {open:?}");
2002
2003        // Reposted already: once is enough, and quoting is still there.
2004        let again = clicked_down_the_repost_action(&said, true, true);
2005        assert!(again.iter().all(|came| came != "repost"), "{again:?}");
2006        assert!(again.iter().any(|came| came == "quote"), "{again:?}");
2007    }
2008
2009    #[test]
2010    fn the_bookmark_action_is_at_the_right_of_the_line_and_stays_there_when_the_relays_come() {
2011        let said = note("worth finding again");
2012        let (none, nowhere) = (Bookmarks::default(), HashMap::new());
2013        let known = Bookmarking::Known { bookmarks: &none, pending: None };
2014        // The action is at the left of the room kept for the relays.
2015        let x = WIDTH - seen_on_width(RowSizes::new(SIZE)) - 14.0;
2016        let down = |bookmarking: Bookmarking<'_>, seen_on: &HashMap<EventId, Vec<RelayUrl>>| {
2017            clicked_down(x, |point| clicked_by(&said, &no_previews(), false, false, bookmarking, seen_on, point))
2018        };
2019
2020        let relay = |name: &str| RelayUrl::parse(&format!("wss://{name}.example.com")).unwrap();
2021        let before = down(known, &nowhere);
2022        assert_eq!(before.iter().filter(|came| *came == "bookmark").count(), 1, "pressed, and nothing else: {before:?}");
2023        let everywhere = HashMap::from([(said.id, vec![relay("r1"), relay("r2")])]);
2024        assert_eq!(down(known, &everywhere), before, "it is where it was");
2025
2026        // It can be pressed whatever is known: what a press does is not
2027        // the row's to say, and it is never the thread that opens.
2028        let changing = Bookmarking::Known { bookmarks: &none, pending: Some((said.id, true)) };
2029        for bookmarking in [Bookmarking::Unknown, Bookmarking::Unreadable("the signer said no"), changing] {
2030            assert_eq!(down(bookmarking, &nowhere), before);
2031        }
2032        // An account without its key keeps no bookmarks, and has no action.
2033        let without = down(Bookmarking::Unavailable, &nowhere);
2034        assert!(without.iter().all(|came| came != "bookmark"), "{without:?}");
2035    }
2036
2037    #[test]
2038    fn the_share_action_is_beside_the_bookmark_and_says_when_it_has_copied() {
2039        let said = note("worth passing around");
2040        let none = Bookmarks::default();
2041        let sizes = RowSizes::new(SIZE);
2042        // Left of the bookmark, which is left of the room kept for the
2043        // relays; and at the left of that room for an account that keeps
2044        // no bookmarks.
2045        let beside_bookmark = WIDTH - seen_on_width(sizes) - 14.0 - f32::from(sizes.action_icon()) - 12.0;
2046        let alone = WIDTH - seen_on_width(sizes) - 14.0;
2047        let down = |bookmarking: Bookmarking<'_>, copied: Option<EventId>, x: f32| {
2048            let (profiles, images, previews, videos) = (HashMap::new(), no_images(), no_previews(), Videos::default());
2049            let (engagement, seen_on) = (HashMap::new(), HashMap::new());
2050            let expanded = Expanded::default();
2051            let context = RowContext {
2052                profiles: &profiles,
2053                images: &images,
2054                previews: &previews,
2055                videos: &videos,
2056                engagement: &engagement,
2057                seen_on: &seen_on,
2058                now: 0,
2059                accent: Color::WHITE,
2060                can_publish: true,
2061                repost_menu: None,
2062                who: None,
2063                reacting: Reacting::NONE,
2064                expanded: &expanded,
2065                marked: None,
2066                share_copied: copied,
2067                picture_copied: None,
2068                bookmarking,
2069                menu_open: false,
2070                sizes,
2071            };
2072            clicked_down(x, |point| clicked_in(&said, &context, point))
2073        };
2074
2075        let known = Bookmarking::Known { bookmarks: &none, pending: None };
2076        let pressed = down(known, None, beside_bookmark);
2077        assert_eq!(pressed.iter().filter(|came| *came == "share").count(), 1, "pressed, and nothing else: {pressed:?}");
2078        assert!(pressed.iter().all(|came| came != "bookmark"), "{pressed:?}");
2079        assert_eq!(down(Bookmarking::Unavailable, None, alone), pressed, "read-only accounts share too");
2080
2081        // Having copied, it is where it was, and can be pressed again;
2082        // another note's having been copied changes nothing here.
2083        assert_eq!(down(known, Some(said.id), beside_bookmark), pressed);
2084        assert_eq!(down(known, Some(EventId::from_byte_array([9; 32])), beside_bookmark), pressed);
2085    }
2086
2087    /// Where every part of the row of `note` is laid out, left to right:
2088    /// where it starts and how wide it is. Set in text of `size` in a list
2089    /// `width` wide, for an account that keeps bookmarks, the note having
2090    /// been made much of and seen on a dozen relays.
2091    fn parts_across(note: &Note, size: u16, width: f32) -> Vec<(f32, f32)> {
2092        fn gather(node: &layout::Node, origin: Vector, found: &mut Vec<(f32, f32)>) {
2093            let bounds = node.bounds() + origin;
2094            found.push((bounds.x, bounds.width));
2095            for child in node.children() {
2096                gather(child, Vector::new(bounds.x, bounds.y), found);
2097            }
2098        }
2099        let renderer = crate::views::components::testing::renderer();
2100        let (profiles, images, previews, videos) = (HashMap::new(), no_images(), no_previews(), Videos::default());
2101        let made = Engagement { replies: 1_200, reposts: 1_200, likes: 1_200, zap_sats: 1_200_000, ..Engagement::default() };
2102        let engagement = HashMap::from([(note.id, made)]);
2103        let relays = (0..12).map(|number| RelayUrl::parse(&format!("wss://r{number}.example.com")).unwrap()).collect();
2104        let seen_on = HashMap::from([(note.id, relays)]);
2105        let none = Bookmarks::default();
2106        let expanded = Expanded::default();
2107        let context = RowContext {
2108            profiles: &profiles,
2109            images: &images,
2110            previews: &previews,
2111            videos: &videos,
2112            engagement: &engagement,
2113            seen_on: &seen_on,
2114            now: 0,
2115            accent: Color::WHITE,
2116            can_publish: true,
2117            repost_menu: None,
2118            who: None,
2119            reacting: Reacting::NONE,
2120            expanded: &expanded,
2121            marked: None,
2122            share_copied: None,
2123            picture_copied: None,
2124            bookmarking: Bookmarking::Known { bookmarks: &none, pending: None },
2125            menu_open: false,
2126            sizes: RowSizes::new(size),
2127        };
2128        let mut element = note_row(note, &context);
2129        let mut tree = Tree::new(element.as_widget());
2130        let limits = layout::Limits::new(Size::ZERO, Size::new(width, f32::INFINITY));
2131        let mut found = Vec::new();
2132        gather(&element.as_widget_mut().layout(&mut tree, &renderer, &limits), Vector::ZERO, &mut found);
2133        found
2134    }
2135
2136    #[test]
2137    fn the_line_of_actions_has_room_for_all_of_them_at_every_size() {
2138        let said = note("worth a look");
2139        // At every size the settings offer, in a popup at its narrowest
2140        // and at its widest.
2141        for (size, width) in [(10, 394.0), (13, 394.0), (18, 394.0), (24, 394.0), (13, 614.0), (24, 614.0)] {
2142            let parts = parts_across(&said, size, width);
2143            let at = format!("at size {size}, {width} wide");
2144            // Nothing reaches past the row's right edge.
2145            assert!(parts.iter().all(|(x, across)| x + across <= width + 0.01), "{at}");
2146            // The room kept for the relays is at that edge, whole: nothing
2147            // before it has pushed it in.
2148            let room = seen_on_width(RowSizes::new(size));
2149            let kept = |(x, across): &(f32, f32)| (across - room).abs() < 0.01 && (x + across - width).abs() < 0.01;
2150            assert!(parts.iter().any(kept), "{at}, the relays' room of {room} is squeezed");
2151            // And the four actions at the left each have theirs.
2152            for place in 0..4 {
2153                let x = place as f32 * NOTE_ACTION_WIDTH;
2154                assert!(parts.iter().any(|part| *part == (x, NOTE_ACTION_WIDTH)), "{at}, action {place}");
2155            }
2156        }
2157    }
2158
2159    #[test]
2160    fn a_note_shows_as_bookmarked_as_the_change_on_its_way_will_leave_it() {
2161        let (kept, other) = (EventId::from_byte_array([1; 32]), EventId::from_byte_array([2; 32]));
2162        let bookmarks = Bookmarks::new(None, vec![vec!["e".to_string(), kept.to_hex()]]);
2163        let known = |pending| Bookmarking::Known { bookmarks: &bookmarks, pending };
2164
2165        assert_eq!(known(None).shows(&kept), Some(true));
2166        assert_eq!(known(None).shows(&other), Some(false));
2167        // Being taken off, being put on, and a change to another note.
2168        assert_eq!(known(Some((kept, false))).shows(&kept), Some(false));
2169        assert_eq!(known(Some((other, true))).shows(&other), Some(true));
2170        assert_eq!(known(Some((other, true))).shows(&kept), Some(true));
2171
2172        assert_eq!(Bookmarking::Unknown.shows(&kept), Some(false));
2173        assert_eq!(Bookmarking::Unreadable("why").shows(&kept), Some(false));
2174        assert_eq!(Bookmarking::Unavailable.shows(&kept), None);
2175    }
2176
2177    /// A note saying `text` and quoting `quoted`, which is at hand or not.
2178    fn quoting(text: &str, quoted: &Note, at_hand: bool) -> Note {
2179        let mut note = note(&format!("{text}\nnostr:{}", quoted.id.to_bech32().unwrap()));
2180        if at_hand {
2181            note.quoted = vec![quoted.clone()];
2182        }
2183        note
2184    }
2185
2186    /// A note to quote: not the one `note` makes, which quotes it.
2187    fn quotable(text: &str) -> Note {
2188        Note { id: EventId::from_byte_array([8; 32]), ..note(text) }
2189    }
2190
2191    #[test]
2192    fn a_quoted_note_shows_as_a_card_when_it_is_at_hand_and_as_a_link_when_not() {
2193        let said = "what was said before, at some length, so that it is worth quoting at all";
2194        let quoted = quotable(said);
2195        let plain = measured_height(&note("look at this"));
2196        let line = text_height("note1…", SIZE, WIDTH);
2197
2198        // Not at hand: one more line, and what is under it.
2199        let linked = measured_height(&quoting("look at this", &quoted, false));
2200        assert!((linked - plain - line - f32::from(NOTE_SPACING)).abs() < 0.01, "{linked} against {plain}");
2201
2202        // At hand: the card, with who wrote the note above what it says.
2203        let shown = measured_height(&quoting("look at this", &quoted, true));
2204        assert!(shown > linked + 40.0, "{shown} against {linked}");
2205
2206        // What the quoted note quotes in turn is a link in the card, one
2207        // more line there, when it is not at hand; and a card in the card
2208        // when it is.
2209        let first = quotable("the first of them");
2210        let deeper = |at_hand: bool| Note { id: EventId::from_byte_array([6; 32]), ..quoting(said, &first, at_hand) };
2211        let nested_link = measured_height(&quoting("look at this", &deeper(false), true));
2212        assert!((nested_link - shown - line - f32::from(NOTE_SPACING)).abs() < 0.01, "{nested_link} against {shown}");
2213        let nested_card = measured_height(&quoting("look at this", &deeper(true), true));
2214        assert!(nested_card > nested_link + 40.0, "{nested_card} against {nested_link}");
2215    }
2216
2217    #[test]
2218    fn a_click_on_a_quoted_note_opens_its_thread_and_not_the_one_of_the_note_quoting_it() {
2219        let quoted = quotable("what was said before");
2220        let down_the_middle = |note: &Note, menu_open: bool| -> Vec<Vec<EventId>> {
2221            let previews = no_previews();
2222            let mut opened: Vec<Vec<EventId>> = Vec::new();
2223            for y in (0..300).step_by(4) {
2224                let threads: Vec<EventId> = clicked(note, &previews, menu_open, false, Point::new(WIDTH / 2.0, y as f32))
2225                    .into_iter()
2226                    .filter_map(|message| match message {
2227                        Message::OpenThread(id, _) => Some(id),
2228                        _ => None,
2229                    })
2230                    .collect();
2231                if opened.last() != Some(&threads) {
2232                    opened.push(threads);
2233                }
2234            }
2235            opened
2236        };
2237
2238        // Down the middle of the row: the note, the card, the note again
2239        // (its line of actions), and nothing under the row.
2240        let shown = quoting("look at this", &quoted, true);
2241        assert_eq!(down_the_middle(&shown, false), [vec![shown.id], vec![quoted.id], vec![shown.id], vec![]]);
2242        // With a menu open over the list the card leads nowhere, as the
2243        // row doesn't.
2244        assert_eq!(down_the_middle(&shown, true), [vec![]]);
2245
2246        // A card in the card leads to its own note, and the card around it
2247        // to its own still, above it and under it.
2248        let inner = Note { id: EventId::from_byte_array([6; 32]), ..quotable("where it started") };
2249        let outer = Note { quoted: vec![inner.clone()], ..quoting("what was said before", &inner, false) };
2250        let outer = Note { id: quoted.id, ..outer };
2251        let nested = quoting("look at this", &outer, true);
2252        assert_eq!(
2253            down_the_middle(&nested, false),
2254            [vec![nested.id], vec![outer.id], vec![inner.id], vec![outer.id], vec![nested.id], vec![]]
2255        );
2256
2257        // Not at hand: the link, at the left, leads to the quoted note, to
2258        // be looked for again; beside it the row is the row.
2259        let linked = quoting("look at this", &quoted, false);
2260        assert_eq!(down_the_middle(&linked, false), [vec![linked.id], vec![]]);
2261        let on_the_link: Vec<Vec<Message>> =
2262            (60..90).step_by(4).map(|y| clicked(&linked, &no_previews(), false, false, Point::new(20.0, y as f32))).collect();
2263        assert!(
2264            on_the_link.iter().any(|came| matches!(&came[..], [Message::OpenThread(id, _)] if *id == quoted.id)),
2265            "{on_the_link:?}"
2266        );
2267
2268        // With where the address said the note is, to look for it there.
2269        let (author, relay) = (Keys::generate().public_key(), RelayUrl::parse("wss://relay.example.com").unwrap());
2270        let address = Nip19Event::new(quoted.id).author(author).relays([relay.clone()]).to_bech32().unwrap();
2271        let addressed = note(&format!("look at this\nnostr:{address}"));
2272        let there = Whereabouts { author: Some(author), relay: Some(relay) };
2273        let on_the_link: Vec<Vec<Message>> =
2274            (60..90).step_by(4).map(|y| clicked(&addressed, &no_previews(), false, false, Point::new(20.0, y as f32))).collect();
2275        assert!(
2276            on_the_link
2277                .iter()
2278                .any(|came| matches!(&came[..], [Message::OpenThread(id, said)] if *id == quoted.id && *said == there)),
2279            "{on_the_link:?}"
2280        );
2281    }
2282
2283    #[test]
2284    fn a_relay_is_called_by_its_address_without_the_scheme() {
2285        let name = |address: &str| relay_name(&RelayUrl::parse(address).unwrap()).to_string();
2286        assert_eq!(name("wss://relay.damus.io"), "relay.damus.io");
2287        assert_eq!(name("wss://nos.lol/"), "nos.lol");
2288        assert_eq!(name("ws://127.0.0.1:10999"), "127.0.0.1:10999");
2289        assert_eq!(name("wss://relay.example.com/inbox"), "relay.example.com/inbox");
2290    }
2291
2292    #[test]
2293    fn a_row_is_as_tall_with_counts_under_it_as_without() {
2294        // What was made of a note arrives after the note: a count beside
2295        // an action is taller than the action's icon alone, and the row
2296        // has to have been that tall already.
2297        let said = note("worth passing on");
2298        let height = |made: Engagement, size: u16| {
2299            let renderer = crate::views::components::testing::renderer();
2300            let (profiles, images, previews, seen_on) = (HashMap::new(), no_images(), no_previews(), HashMap::new());
2301            let engagement = HashMap::from([(said.id, made)]);
2302            let videos = Videos::default();
2303            let expanded = Expanded::default();
2304            let context = RowContext {
2305                profiles: &profiles,
2306                images: &images,
2307                previews: &previews,
2308                videos: &videos,
2309                engagement: &engagement,
2310                seen_on: &seen_on,
2311                now: 0,
2312                accent: Color::WHITE,
2313                can_publish: true,
2314                repost_menu: None,
2315                who: None,
2316                reacting: Reacting::NONE,
2317                expanded: &expanded,
2318                marked: None,
2319                share_copied: None,
2320                picture_copied: None,
2321                bookmarking: Bookmarking::Unavailable,
2322                menu_open: false,
2323                sizes: RowSizes::new(size),
2324            };
2325            let mut element = note_row(&said, &context);
2326            let mut tree = Tree::new(element.as_widget());
2327            let limits = layout::Limits::new(Size::ZERO, Size::new(WIDTH, f32::INFINITY));
2328            element.as_widget_mut().layout(&mut tree, &renderer, &limits).size().height
2329        };
2330        let counted = Engagement {
2331            replies: 3,
2332            reposts: 12,
2333            reposted: true,
2334            likes: 1_500,
2335            reaction: Some(Reaction::Like),
2336            zap_sats: 21_000,
2337        };
2338        // The account's own reaction is an emoji in the heart's place,
2339        // which is a glyph of text where the heart is a picture.
2340        let with_emoji = Engagement { reaction: Some(Reaction::Emoji("🤌".into())), ..counted.clone() };
2341        let only_emoji = Engagement { likes: 1, reaction: Some(Reaction::Emoji("🧨".into())), ..Engagement::default() };
2342        for size in [10, 13, 18, 24] {
2343            let plain = height(Engagement::default(), size);
2344            for made in [&counted, &with_emoji, &only_emoji] {
2345                assert_eq!(height(made.clone(), size), plain, "at size {size}: {made:?}");
2346            }
2347        }
2348    }
2349
2350    /// What comes of clicks down the row of `note`, `x` across, for an
2351    /// account that reacted to it with `reaction`, if it did, with what
2352    /// to react with on offer or not.
2353    fn clicked_down_reacting(note: &Note, reaction: Option<Reaction>, menu: Option<&ReactionMenu>, x: f32) -> Vec<String> {
2354        let (profiles, images, previews, videos) = (HashMap::new(), no_images(), no_previews(), Videos::default());
2355        let made = Engagement { likes: usize::from(reaction.is_some()), reaction, ..Engagement::default() };
2356        let (engagement, seen_on) = (HashMap::from([(note.id, made)]), HashMap::new());
2357        let suggested: Vec<String> = ["👍", "❤️", "😂"].map(String::from).into();
2358        let expanded = Expanded::default();
2359        let context = RowContext {
2360            profiles: &profiles,
2361            images: &images,
2362            previews: &previews,
2363            videos: &videos,
2364            engagement: &engagement,
2365            seen_on: &seen_on,
2366            now: 0,
2367            accent: Color::WHITE,
2368            can_publish: true,
2369            repost_menu: None,
2370            who: None,
2371            reacting: Reacting { menu, suggested: &suggested },
2372            expanded: &expanded,
2373            marked: None,
2374            share_copied: None,
2375            picture_copied: None,
2376            bookmarking: Bookmarking::Unavailable,
2377            menu_open: false,
2378            sizes: RowSizes::new(SIZE),
2379        };
2380        clicked_down(x, |point| clicked_in(note, &context, point))
2381    }
2382
2383    #[test]
2384    fn the_heart_offers_what_to_react_with_and_an_emoji_pressed_reacts() {
2385        let said = note("worth a reaction");
2386        // The action is the third of the line; what it offers opens under
2387        // it, from its left edge, each thing offered a cell wide.
2388        let heart = 2.0 * NOTE_ACTION_WIDTH + 12.0;
2389        let cell = |place: f32| 2.0 * NOTE_ACTION_WIDTH + 4.0 + 34.0 * place + 17.0;
2390
2391        // With nothing on offer: the heart offers, and under the row
2392        // there is nothing.
2393        assert_eq!(clicked_down_reacting(&said, None, None, heart), ["thread", "profile", "thread", "reactions", "thread", ""]);
2394
2395        // On offer: the like first, then the emoji used most, then the
2396        // way to the others. The heart puts the offer away, and so does a
2397        // click anywhere else, which does nothing more.
2398        let menu = ReactionMenu { note: said.id, picker: None };
2399        let offered = |x: f32| clicked_down_reacting(&said, None, Some(&menu), x);
2400        let pressed = |x: f32| offered(x).into_iter().filter(|came| !came.ends_with("close")).collect::<Vec<_>>();
2401        assert_eq!(pressed(cell(0.0)), ["reactions", "like"]);
2402        assert_eq!(pressed(cell(1.0)), ["emoji"]);
2403        assert_eq!(pressed(cell(3.0)), ["emoji"]);
2404        assert_eq!(pressed(cell(4.0)), ["more"]);
2405        assert!(pressed(cell(6.0)).is_empty(), "past the end of what is offered");
2406        assert!(offered(WIDTH / 2.0 + 150.0).iter().all(|came| came == "close"), "beside it, the row does nothing");
2407
2408        // For another note it is not this row's to show.
2409        let another = ReactionMenu { note: EventId::from_byte_array([9; 32]), picker: None };
2410        assert!(clicked_down_reacting(&said, None, Some(&another), cell(1.0)).iter().all(|came| came != "emoji"));
2411
2412        // Every emoji there is, once asked for: the groups, and under
2413        // them the emoji, each of which reacts.
2414        let picking = ReactionMenu { note: said.id, picker: Some(EmojiPicker { typed: String::new(), group: Group::Flags }) };
2415        let picked = clicked_down_reacting(&said, None, Some(&picking), cell(1.0));
2416        assert!(picked.iter().any(|came| came == "group") && picked.iter().any(|came| came == "emoji"), "{picked:?}");
2417
2418        // Having reacted, with a like or an emoji: once is enough.
2419        for reaction in [Reaction::Like, Reaction::Emoji("🤌".into())] {
2420            let reacted = clicked_down_reacting(&said, Some(reaction), None, heart);
2421            assert!(reacted.iter().all(|came| came != "reactions"), "{reacted:?}");
2422        }
2423    }
2424
2425    #[test]
2426    fn an_open_menu_and_the_relays_a_note_was_seen_on_take_no_room_in_its_row() {
2427        let said = note("worth passing on");
2428        let relay = |name: &str| RelayUrl::parse(&format!("wss://{name}.example.com")).unwrap();
2429        let height = |menu_open: bool, seen: usize| {
2430            let renderer = crate::views::components::testing::renderer();
2431            let (profiles, images, previews, engagement) = (HashMap::new(), no_images(), no_previews(), HashMap::new());
2432            let seen_on = HashMap::from([(said.id, (0..seen).map(|number| relay(&format!("r{number}"))).collect())]);
2433            let videos = Videos::default();
2434            let expanded = Expanded::default();
2435            let context = RowContext {
2436                profiles: &profiles,
2437                images: &images,
2438                previews: &previews,
2439                videos: &videos,
2440                engagement: &engagement,
2441                seen_on: &seen_on,
2442                now: 0,
2443                accent: Color::WHITE,
2444                can_publish: true,
2445                repost_menu: menu_open.then_some(RepostMenu::of(said.id)),
2446                who: None,
2447                reacting: Reacting::NONE,
2448                expanded: &expanded,
2449                marked: None,
2450                share_copied: None,
2451                picture_copied: None,
2452                bookmarking: Bookmarking::Unavailable,
2453                menu_open: false,
2454                sizes: RowSizes::new(SIZE),
2455            };
2456            let mut element = note_row(&said, &context);
2457            let mut tree = Tree::new(element.as_widget());
2458            let limits = layout::Limits::new(Size::ZERO, Size::new(WIDTH, f32::INFINITY));
2459            element.as_widget_mut().layout(&mut tree, &renderer, &limits).size().height
2460        };
2461        let plain = height(false, 0);
2462        assert_eq!(height(true, 0), plain, "nothing in the list moves when the menu opens");
2463        // Nor when it is found out where a note is.
2464        assert_eq!(height(false, 3), plain);
2465        assert_eq!(height(false, 12), plain);
2466    }
2467
2468    /// A store in which the picture at `url`, of `size` pixels, has arrived.
2469    fn images_with(url: &str, (width, height): (u32, u32)) -> ImageStore {
2470        let mut images = no_images();
2471        let request = ImageRequest { url: url.to_string(), shape: ImageShape::Original };
2472        images.begin(&request);
2473        let pixels = vec![0; width as usize * height as usize * 4];
2474        images.finish(request, Ok(LoadedImage { handle: Handle::from_rgba(width, height, pixels), width, height }));
2475        images
2476    }
2477
2478    /// Where every part of the row of `note` that is `height` tall is laid
2479    /// out, in a list as wide as the popup's: a picture and what holds it.
2480    fn parts_as_tall_as(note: &Note, images: &ImageStore, height: f32) -> Vec<Rectangle> {
2481        fn gather(node: &layout::Node, origin: Vector, height: f32, found: &mut Vec<Rectangle>) {
2482            let bounds = node.bounds() + origin;
2483            if (bounds.height - height).abs() < 0.01 {
2484                found.push(bounds);
2485            }
2486            for child in node.children() {
2487                gather(child, Vector::new(bounds.x, bounds.y), height, found);
2488            }
2489        }
2490        let renderer = crate::views::components::testing::renderer();
2491        let (profiles, previews, engagement, seen_on) = (HashMap::new(), no_previews(), HashMap::new(), HashMap::new());
2492        let videos = Videos::default();
2493        let expanded = Expanded::default();
2494        let context = RowContext {
2495            profiles: &profiles,
2496            images,
2497            previews: &previews,
2498            videos: &videos,
2499            engagement: &engagement,
2500            seen_on: &seen_on,
2501            now: 0,
2502            accent: Color::WHITE,
2503            can_publish: true,
2504            repost_menu: None,
2505            who: None,
2506            reacting: Reacting::NONE,
2507            expanded: &expanded,
2508            marked: None,
2509            share_copied: None,
2510            picture_copied: None,
2511            bookmarking: Bookmarking::Unavailable,
2512            menu_open: false,
2513            sizes: RowSizes::new(SIZE),
2514        };
2515        let mut element = note_row(note, &context);
2516        let mut tree = Tree::new(element.as_widget());
2517        let limits = layout::Limits::new(Size::ZERO, Size::new(WIDTH, f32::INFINITY));
2518        let node = element.as_widget_mut().layout(&mut tree, &renderer, &limits);
2519        let mut found = Vec::new();
2520        gather(&node, Vector::ZERO, height, &mut found);
2521        found
2522    }
2523
2524    #[test]
2525    fn a_picture_reaches_from_one_edge_of_its_row_to_the_other_unless_it_is_narrower_itself() {
2526        let url = "https://example.com/cat.png";
2527        let with_picture = note(&format!("a cat\n{url}"));
2528        // Wide, tall, a little wider than the row, and exactly as wide: all
2529        // fill the row, and are as tall as that makes them, however tall.
2530        for (size, tall) in [((1200, 800), 614.0 * 800.0 / 1200.0), ((1000, 3000), 1842.0), ((615, 100), 614.0 * 100.0 / 615.0)] {
2531            let parts = parts_as_tall_as(&with_picture, &images_with(url, size), tall);
2532            assert!(!parts.is_empty(), "a picture of {size:?} is {tall} tall");
2533            for part in parts {
2534                assert_eq!((part.x, part.width), (0.0, WIDTH), "a picture of {size:?} touches both edges");
2535            }
2536        }
2537        // Narrower than the row: as large as it is, at the left, and not
2538        // made any larger.
2539        for size in [(200, 100), (613, 900), (40, 300)] {
2540            let parts = parts_as_tall_as(&with_picture, &images_with(url, size), size.1 as f32);
2541            assert!(!parts.is_empty(), "a picture of {size:?} keeps its height");
2542            for part in parts {
2543                assert_eq!((part.x, part.width), (0.0, size.0 as f32), "a picture of {size:?} keeps its width");
2544            }
2545        }
2546    }
2547
2548    #[test]
2549    fn a_row_keeps_its_height_when_a_picture_of_known_size_arrives() {
2550        let url = "https://example.com/cat.png";
2551        let plain = measured_height(&note("a cat"));
2552        // Wide, tall and small: the room kept is the room taken.
2553        for size in [(1200, 800), (1000, 3000), (200, 100), (614, 614)] {
2554            let mut with_picture = note(&format!("a cat\n{url}"));
2555            with_picture.content.images[0].size = Some(size);
2556
2557            let loading = measured_height_with(&with_picture, &no_images(), SIZE, WIDTH);
2558            let room = shown_size(size, WIDTH).height + f32::from(NOTE_SPACING);
2559            assert!((loading - plain - room).abs() < 0.01, "room is kept for a picture of {size:?}: {loading}");
2560
2561            let arrived = measured_height_with(&with_picture, &images_with(url, size), SIZE, WIDTH);
2562            assert!((arrived - loading).abs() < 0.01, "nothing moves when a picture of {size:?} arrives: {arrived}");
2563        }
2564    }
2565
2566    #[test]
2567    fn a_click_on_a_picture_opens_the_note_as_one_on_its_text_does() {
2568        let url = "https://example.com/cat.png";
2569        let with_picture = note(&format!("a cat\n{url}"));
2570        let (profiles, previews, videos) = (HashMap::new(), no_previews(), Videos::default());
2571        let (engagement, seen_on, expanded) = (HashMap::new(), HashMap::new(), Expanded::default());
2572        let down_the_middle = |images: &ImageStore| {
2573            let context = RowContext {
2574                profiles: &profiles,
2575                images,
2576                previews: &previews,
2577                videos: &videos,
2578                engagement: &engagement,
2579                seen_on: &seen_on,
2580                now: 0,
2581                accent: Color::WHITE,
2582                can_publish: true,
2583                repost_menu: None,
2584                who: None,
2585                reacting: Reacting::NONE,
2586                expanded: &expanded,
2587                marked: None,
2588                share_copied: None,
2589                picture_copied: None,
2590                bookmarking: Bookmarking::Unavailable,
2591                menu_open: false,
2592                sizes: RowSizes::new(SIZE),
2593            };
2594            clicked_down(WIDTH / 2.0, |point| clicked_in(&with_picture, &context, point))
2595        };
2596        // Down the middle of the row, text and picture alike: the note,
2597        // and nothing else, least of all the picture in the browser.
2598        assert_eq!(down_the_middle(&images_with(url, (1200, 300))), ["thread", ""]);
2599        // The same until the picture is here.
2600        assert_eq!(down_the_middle(&no_images()), ["thread", ""]);
2601    }
2602
2603    #[test]
2604    fn a_picture_that_failed_leaves_a_link_and_no_gap() {
2605        let url = "https://example.com/gone.png";
2606        let with_picture = note(&format!("a cat\n{url}"));
2607        let mut images = no_images();
2608        let request = ImageRequest { url: url.to_string(), shape: ImageShape::Original };
2609        images.begin(&request);
2610        images.finish(request, Err("404".into()));
2611
2612        let failed = measured_height_with(&with_picture, &images, SIZE, WIDTH);
2613        assert!(failed < measured_height(&note("a cat")) + 40.0, "one line of link, not a picture's room: {failed}");
2614    }
2615
2616    #[test]
2617    fn the_estimate_is_close_to_the_measured_row() {
2618        // The estimate only has to be near: the list corrects it when the row
2619        // comes into view, and what is on screen moves by the difference when
2620        // scrolling back up after a jump.
2621        for text in [
2622            "gm".to_string(),
2623            "the quick brown fox jumps over the lazy dog ".repeat(3),
2624            "the quick brown fox jumps over the lazy dog ".repeat(12),
2625            "one\ntwo\nthree\nfour\nfive".to_string(),
2626            "a paragraph of ordinary words follows.\n\nand another one, a little longer than the first, to wrap.".to_string(),
2627            "links count as shown: https://example.com/some/long/path/that/is/cut/to/fifty/characters/at/most and #tags too"
2628                .to_string(),
2629            "a picture of unknown size\nhttps://example.com/cat.png".to_string(),
2630            "https://example.com/only-a-picture.png".to_string(),
2631            "a video, of no size it says\nhttps://example.com/clip.mp4".to_string(),
2632            "and one of YouTube's\nhttps://youtu.be/aqz-KE-bpKQ".to_string(),
2633            // Marked: a heading, what is stressed, code in a line and in
2634            // lines of its own, something quoted, items, a rule.
2635            "## What is new\nIt is **fully** keyboard-navigable, *at last*, and has a `--toggle` flag.\n\n\
2636             > notes and other stuff\n* a feed\n* threads\n---\n```\nfn main() {\n    println!(\"gm\");\n}\n```"
2637                .to_string(),
2638            "**bold words all the way along the line and round to the next one, twice over** ".repeat(3),
2639            // A table, alone and among text, and one with a cell that wraps.
2640            "|Category|Approximate count|\n|---|---|\n|Large dams in the U.S.|92,000+|\n|Large dams worldwide|~200,000|"
2641                .to_string(),
2642            "# Keys\nThese are they:\n\n| Key | What it does |\n|:--|:--|\n| `j` | The next note |\n| `k` | The one before |\n\n\
2643             - [x] and a list\n- [ ] after it"
2644                .to_string(),
2645            // Long enough to be cut, several times over, in lines and in
2646            // paragraphs.
2647            "the quick brown fox jumps over the lazy dog ".repeat(60),
2648            "a paragraph of ordinary words, as long as they come in a note that has a lot to say, and then says it.\n\n\
2649             and a shorter one after it.\n\n"
2650                .repeat(20),
2651        ] {
2652            let quoted = quotable(&text);
2653            let plain = note(&text);
2654            let nested = Note { id: EventId::from_byte_array([6; 32]), ..quoting(&text, &quoted, true) };
2655            for note in [
2656                plain.clone(),
2657                quoting("see", &quoted, false),
2658                quoting("see", &quoted, true),
2659                quoting(&text, &plain, true),
2660                quoting("see", &nested, true),
2661            ] {
2662                // At every size the settings offer, in a popup at its narrowest
2663                // and at its widest.
2664                for (size, width) in [(10, 394.0), (13, 394.0), (24, 394.0), (10, 614.0), (13, 614.0), (18, 614.0), (24, 614.0)] {
2665                    // As a row first shows it, and in full, which is
2666                    // another thing only of a long note.
2667                    for in_full in [false, true] {
2668                        let estimated = estimated_note_height(&note, RowSizes::new(size), width, in_full);
2669                        let measured = match in_full {
2670                            true => measured_height_in_full(&note, size, width),
2671                            false => measured_height_with(&note, &no_images(), size, width),
2672                        };
2673                        assert!(
2674                            (estimated - measured).abs() <= measured * 0.3,
2675                            "estimated {estimated}, measured {measured} at size {size}, width {width}, in full: {in_full}, \
2676                             for {text:?}, quoting {}",
2677                            note.quoted.len()
2678                        );
2679                    }
2680                }
2681            }
2682        }
2683    }
2684    #[test]
2685    fn a_link_in_a_cell_of_a_table_can_be_clicked() {
2686        let table = note("| Where |\n|---|\n| https://example.com/a |");
2687        let came = pressed_down(&table, None, mouse::Button::Left, 40.0);
2688        assert!(
2689            came.iter().any(|message| matches!(message, Message::OpenUrl(url) if url == "https://example.com/a")),
2690            "{came:?}"
2691        );
2692    }
2693
2694    #[test]
2695    fn what_stands_behind_code_takes_no_room() {
2696        // Code is set in letters of another width, so a line of it may
2697        // break elsewhere; what is drawn behind it adds nothing to that.
2698        let row = |text: &str| measured_height_with(&note(text), &no_images(), SIZE, WIDTH);
2699        assert_eq!(row("run `this` now"), row("run this now"));
2700        assert_eq!(row("*slanted*, **bold**, ~~struck~~"), row("slanted, bold, struck"));
2701    }
2702
2703    /// A note a little longer than a row shows: cut, and not much taller
2704    /// in full.
2705    fn long_note() -> Note {
2706        let long = note(&"the quick brown fox jumps over the lazy dog ".repeat(20));
2707        assert!(long.content.whole.is_some(), "it is cut");
2708        long
2709    }
2710
2711    /// What comes of clicks down the middle of the row of `note`, shown
2712    /// in full or not.
2713    fn clicked_down_the_middle(note: &Note, in_full: bool) -> Vec<String> {
2714        let (profiles, images, previews, videos) = (HashMap::new(), no_images(), no_previews(), Videos::default());
2715        let (engagement, seen_on) = (HashMap::new(), HashMap::new());
2716        let mut expanded = Expanded::default();
2717        if in_full {
2718            expanded.expand(note.id);
2719        }
2720        let context = RowContext {
2721            profiles: &profiles,
2722            images: &images,
2723            previews: &previews,
2724            videos: &videos,
2725            engagement: &engagement,
2726            seen_on: &seen_on,
2727            now: 0,
2728            accent: Color::WHITE,
2729            can_publish: true,
2730            repost_menu: None,
2731            who: None,
2732            reacting: Reacting::NONE,
2733            expanded: &expanded,
2734            marked: None,
2735            share_copied: None,
2736            picture_copied: None,
2737            bookmarking: Bookmarking::Unavailable,
2738            menu_open: false,
2739            sizes: RowSizes::new(SIZE),
2740        };
2741        // Under the row a click comes to nothing, and is not told.
2742        let mut told = clicked_down(WIDTH / 2.0, |point| clicked_in(note, &context, point));
2743        told.retain(|came| !came.is_empty());
2744        told
2745    }
2746
2747    #[test]
2748    fn a_long_note_has_a_button_under_its_text_that_shows_the_rest_and_one_that_shows_less() {
2749        let long = long_note();
2750        // Down the middle of the row: the note, then the button, then the
2751        // note again down to the room between the actions.
2752        assert_eq!(clicked_down_the_middle(&long, false), ["thread", "show more", "thread"]);
2753        assert_eq!(clicked_down_the_middle(&long, true), ["thread", "show less", "thread"]);
2754
2755        // A note that is all there has neither, whatever is asked of it.
2756        let short = note("gm");
2757        assert_eq!(clicked_down_the_middle(&short, false), ["thread"]);
2758        assert_eq!(clicked_down_the_middle(&short, true), ["thread"]);
2759
2760        // A long note quoted in another is cut, and that is that: its
2761        // own view has the rest.
2762        let quoted = Note { id: EventId::from_byte_array([8; 32]), ..long_note() };
2763        assert_eq!(clicked_down_the_middle(&quoting("see", &quoted, true), false), ["thread"]);
2764    }
2765
2766    #[test]
2767    fn the_button_under_a_long_note_takes_its_room_and_no_more_in_full() {
2768        for size in [10, 13, 18, 24] {
2769            let long = long_note();
2770            let room = fold_height(RowSizes::new(size)) + f32::from(NOTE_SPACING);
2771
2772            // Cut: as tall as a note that says what is shown of it, and
2773            // the button under that.
2774            let as_shown = Note { content: content::Content { whole: None, ..long.content.clone() }, ..long.clone() };
2775            let cut = measured_height_with(&long, &no_images(), size, WIDTH);
2776            let plain = measured_height_with(&as_shown, &no_images(), size, WIDTH);
2777            assert!((cut - plain - room).abs() < 0.01, "at size {size}: {cut} against {plain}");
2778
2779            // In full: as tall as a note that says all of it, and the
2780            // button under that. What keeps the row's place takes none.
2781            let whole = long.content.whole.clone().unwrap();
2782            let all =
2783                content::Content { segments: whole.segments, line_chars: whole.line_chars, whole: None, ..long.content.clone() };
2784            let in_full = measured_height_in_full(&long, size, WIDTH);
2785            let plain = measured_height_with(&Note { content: all, ..long.clone() }, &no_images(), size, WIDTH);
2786            assert!((in_full - plain - room).abs() < 0.01, "at size {size}: {in_full} against {plain}");
2787            assert!(in_full > cut, "there is more to read");
2788        }
2789    }
2790
2791    #[test]
2792    fn the_row_of_a_note_in_full_keeps_how_far_its_top_is_above_what_is_in_view() {
2793        let long = long_note();
2794        let (profiles, images, previews, videos) = (HashMap::new(), no_images(), no_previews(), Videos::default());
2795        let (engagement, seen_on) = (HashMap::new(), HashMap::new());
2796        let mut expanded = Expanded::default();
2797        expanded.expand(long.id);
2798        let context = RowContext {
2799            profiles: &profiles,
2800            images: &images,
2801            previews: &previews,
2802            videos: &videos,
2803            engagement: &engagement,
2804            seen_on: &seen_on,
2805            now: 0,
2806            accent: Color::WHITE,
2807            can_publish: true,
2808            repost_menu: None,
2809            who: None,
2810            reacting: Reacting::NONE,
2811            expanded: &expanded,
2812            marked: None,
2813            share_copied: None,
2814            picture_copied: None,
2815            bookmarking: Bookmarking::Unavailable,
2816            menu_open: false,
2817            sizes: RowSizes::new(SIZE),
2818        };
2819        let renderer = crate::views::components::testing::renderer();
2820        // The row as a list shows it: in what opens its thread.
2821        let mut row = opening_thread(note_row(&long, &context), long.id, &context);
2822        let mut tree = Tree::new(row.as_widget());
2823        let limits = layout::Limits::new(Size::ZERO, Size::new(WIDTH, f32::INFINITY));
2824        // The row starts 1000 down the list.
2825        let node = row.as_widget_mut().layout(&mut tree, &renderer, &limits).move_to(Point::new(0.0, 1000.0));
2826        let mut seen_from = |view_top: f32| {
2827            let mut messages = Vec::new();
2828            row.as_widget_mut().update(
2829                &mut tree,
2830                &Event::Mouse(mouse::Event::CursorMoved { position: Point::ORIGIN }),
2831                layout::Layout::new(&node),
2832                mouse::Cursor::Unavailable,
2833                &renderer,
2834                &mut clipboard::Null,
2835                &mut cosmic::iced::core::Shell::new(&mut messages),
2836                &Rectangle::new(Point::new(0.0, view_top), Size::new(WIDTH, 500.0)),
2837            );
2838            expanded.above(&long.id).map(std::cell::Cell::get)
2839        };
2840        // Its top in view, at the top of the view, and scrolled out.
2841        assert_eq!(seen_from(800.0), Some(0.0));
2842        assert_eq!(seen_from(1000.0), Some(0.0));
2843        assert_eq!(seen_from(1130.0), Some(130.0));
2844    }
2845}