1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct RowSizes {
58 text: u16,
59}
60
61impl RowSizes {
62 pub fn new(text: u16) -> Self {
64 Self { text }
65 }
66
67 pub(super) fn text(self) -> u16 {
69 self.text
70 }
71
72 pub(super) fn name(self) -> u16 {
74 self.text
75 }
76
77 pub(super) fn time(self) -> u16 {
79 self.text.saturating_sub(2)
80 }
81
82 fn action_text(self) -> u16 {
84 self.text.saturating_sub(1)
85 }
86
87 fn action_icon(self) -> u16 {
89 self.text + 1
90 }
91
92 pub(super) fn preview_site(self) -> u16 {
94 self.time()
95 }
96
97 pub(super) fn preview_title(self) -> u16 {
100 self.text
101 }
102
103 pub(super) fn preview_description(self) -> u16 {
106 self.text.saturating_sub(1)
107 }
108}
109
110#[derive(Clone, Copy)]
112pub enum Bookmarking<'a> {
113 Unavailable,
116 Unknown,
118 Known { bookmarks: &'a Bookmarks, pending: Option<(EventId, bool)> },
121 Unreadable(&'a str),
123}
124
125impl Bookmarking<'_> {
126 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#[derive(Clone, Copy)]
141pub struct Reacting<'a> {
142 pub menu: Option<&'a ReactionMenu>,
144 pub suggested: &'a [String],
146}
147
148impl Reacting<'_> {
149 pub const NONE: Self = Self { menu: None, suggested: &[] };
151}
152
153#[derive(Clone, Copy)]
155pub struct RowContext<'a> {
156 pub profiles: &'a HashMap<PublicKey, Profile>,
158 pub images: &'a ImageStore,
160 pub previews: &'a PreviewStore,
162 pub videos: &'a Videos,
164 pub engagement: &'a HashMap<EventId, Engagement>,
166 pub seen_on: &'a HashMap<EventId, Vec<RelayUrl>>,
168 pub now: u64,
170 pub accent: Color,
173 pub can_publish: bool,
176 pub repost_menu: Option<RepostMenu>,
178 pub who: Option<&'a WhoMenu>,
180 pub reacting: Reacting<'a>,
182 pub expanded: &'a Expanded,
184 pub marked: Option<EventId>,
187 pub share_copied: Option<EventId>,
189 pub picture_copied: Option<&'a str>,
191 pub menu_open: bool,
194 pub bookmarking: Bookmarking<'a>,
196 pub sizes: RowSizes,
198}
199
200impl RowContext<'_> {
201 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
212pub(super) const NOTE_PADDING_TOP: u16 = 8;
214pub(super) const NOTE_SPACING: u16 = 4;
215
216pub(super) const NOTE_AVATAR_SIZE: f32 = 32.0;
219pub(super) const NOTE_AVATAR_GAP: u16 = 8;
220
221const NOTE_IMAGE_RADIUS: f32 = 6.0;
226const NOTE_IMAGE_FALLBACK_HEIGHT: f32 = 180.0;
227
228const QUIET_TEXT_ALPHA: f32 = 0.65;
231const BEHIND_CODE_ALPHA: f32 = 0.12;
232
233const CODE_RADIUS: f32 = 3.0;
237const CODE_PADDING: [f32; 2] = [0.0, 2.0];
238
239const CODE_BLOCK_PADDING: u16 = 8;
242const CODE_BLOCK_RADIUS: f32 = 6.0;
243
244const HEADING_SCALES: [f32; 3] = [1.5, 1.3, 1.15];
247
248const RULE_HEIGHT: f32 = 1.0;
251const RULE_ALPHA: f32 = 0.35;
252
253const TABLE_HEAD_LINE_ALPHA: f32 = 0.5;
256const TABLE_LINE_ALPHA: f32 = 0.2;
257
258const MENTION_WIDTH_CHARS: usize = 12;
261
262const CODE_CHAR_WIDTH_PER_SIZE: f32 = 0.6;
264
265const NOTE_ACTION_PADDING: [u16; 2] = [2, 6];
268
269const NOTE_ACTION_WIDTH: f32 = 60.0;
274
275pub(super) const NOTE_ACTION_DIM: f32 = 0.6;
277
278const NOTE_ACTION_GAP: f32 = 4.0;
280
281const FIGURE_WIDTH_PER_SIZE: f32 = 0.65;
284
285const BOOKMARK_REASON_MAX_CHARS: usize = 120;
288
289pub(super) const NOTE_DIVIDER_HEIGHT: f32 = 1.0;
291
292const 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub(super) enum Reading {
305 Quoted,
308 Cut,
311 Whole,
314}
315
316impl Reading {
317 fn of_row(in_full: bool) -> Self {
319 if in_full { Self::Whole } else { Self::Cut }
320 }
321}
322
323const LINE_HEIGHT_PER_SIZE: f32 = 1.4;
328const CHAR_WIDTH_PER_SIZE: f32 = 0.48;
329
330const UNMEASURED_LIST_WIDTH: f32 = POPUP_MAX_WIDTH - 26.0;
333
334pub(super) fn line_height(size: u16) -> f32 {
336 f32::from(size) * LINE_HEIGHT_PER_SIZE
337}
338
339fn 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
345fn 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
351pub(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 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 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
397fn 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 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
440pub 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
459pub 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
466fn 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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
502enum NoteLink {
503 Web(String),
505 Profile(PublicKey),
507}
508
509impl NoteLink {
510 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 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
528struct Faces {
532 text: Font,
533 code: Font,
534 quiet: Color,
535 behind_code: Color,
536 on_background: Color,
538}
539
540impl Faces {
541 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 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 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
579fn stands_apart(segment: &Segment) -> bool {
581 matches!(segment, Segment::Block(_))
582}
583
584fn parts(segments: &[Segment]) -> impl Iterator<Item = &[Segment]> {
587 segments.chunk_by(|one, next| !stands_apart(one) && !stands_apart(next))
588}
589
590fn 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 Segment::Block(_) => span(""),
617 };
618 match NoteLink::of(segment) {
619 Some(link) => shown.link(link),
620 None => shown,
621 }
622 })
623 .collect()
624}
625
626fn 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
631fn 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
681fn 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
700fn 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 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
730pub 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
744const MARK_RADIUS: f32 = 8.0;
746
747pub 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
763fn 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
780fn 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
798fn action_cell<'a>(action: impl Into<Element<'a, Message>>) -> Element<'a, Message> {
800 container(action).width(Length::Fixed(NOTE_ACTION_WIDTH)).into()
801}
802
803fn 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
818const WHO_WIDTH: f32 = 240.0;
822const WHO_ROW_HEIGHT: f32 = 30.0;
823const WHO_MAX_HEIGHT: f32 = 8.0 * WHO_ROW_HEIGHT;
824
825const WHO_AVATAR_SIZE: f32 = 20.0;
827
828fn 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
847fn 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
903fn 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 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
929fn 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
957pub 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
964fn 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
980fn 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
989fn 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
1002fn bookmark_action<'a>(note: &Note, context: &RowContext<'a>, dim: Color) -> Option<Element<'a, Message>> {
1011 let bookmarked = context.bookmarking.shows(¬e.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
1024fn note_actions<'a>(note: &Note, context: &RowContext<'a>) -> Element<'a, Message> {
1033 let engagement = context.engagement.get(¬e.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 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(¬e.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(¬e.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 .height(Length::Fixed(action_height(sizes)))
1091 .align_y(Alignment::Center)
1092 .into()
1093}
1094
1095pub(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
1101pub(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 ¬e.content.images {
1125 column = column.push(note_image(image, context));
1126 }
1127 for video in ¬e.content.videos {
1128 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) = ¬e.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
1153pub fn note_row<'a>(note: &'a Note, context: &RowContext<'a>) -> Element<'a, Message> {
1162 let above = context.expanded.above(¬e.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 Some(above) => widget::Column::new().push(ScrollPosition::new(above)).push(row).into(),
1182 None => row.into(),
1183 }
1184}
1185
1186pub 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
1194fn 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, ¬e.author);
1199 let picture = profiles.get(¬e.author).and_then(|profile| profile.picture.as_deref());
1200 let author_picture = opening_profile(avatar(images, picture, ¬e.author, &name, NOTE_AVATAR_SIZE), note.author);
1201
1202 widget::Row::new()
1203 .push(author_picture)
1204 .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 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 fn no_images() -> ImageStore {
1282 ImageStore::new(1_000_000).0
1283 }
1284
1285 const WIDTH: f32 = LIST_MAX_WIDTH;
1288 const SIZE: u16 = 13;
1289
1290 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 fn no_previews() -> PreviewStore {
1303 PreviewStore::new().0
1304 }
1305
1306 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 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 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 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 #[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(¬e, &no_images(), &no_previews(), &Videos::default(), &Expanded::default(), SIZE, WIDTH, true)
1403 };
1404
1405 let less = measured_height(¬e("gm")) - being_written("gm");
1408 assert!((20.0..60.0).contains(&less), "{less} shorter than the row");
1409 let marked = "# gm\n| a | b |\n|---|---|\n| 1 | 2 |";
1411 assert_eq!(measured_height(¬e(marked)) - being_written(marked), less);
1412
1413 let long = "the quick brown fox jumps over the lazy dog ".repeat(60);
1417 let (cut, in_full) = (measured_height(¬e(&long)), measured_height_in_full(¬e(&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 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 let said = "wide ".repeat(60);
1438 let row = |text: &str| measured_height_with(¬e(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 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 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 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 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 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 fn clicked_down_the_repost_action(note: &Note, menu_open: bool, reposted: bool) -> Vec<String> {
1596 clicked_down(NOTE_ACTION_WIDTH + 12.0, |point| clicked(note, &no_previews(), menu_open, reposted, point))
1599 }
1600
1601 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 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 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 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 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 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 assert_eq!(down_the_middle(&no_previews()), ["thread", ""]);
1676 }
1677
1678 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 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(¬e("watch this"));
1701 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(¬e("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 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 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 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 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 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 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 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 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 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 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(¬e("worth an evening")) - room).abs() < 0.01, "{unknown}");
1831
1832 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 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 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 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 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 let other = videos_having(None, &["https://example.com/another"]);
1883 assert_eq!(height(&found, &other), waiting);
1884 }
1885
1886 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 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 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 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 assert_eq!(clicked_down_the_repost_action(&said, false, false), ["thread", "profile", "thread", "menu", "thread", ""]);
1992
1993 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 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 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 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 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 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 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 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 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 assert!(parts.iter().all(|(x, across)| x + across <= width + 0.01), "{at}");
2146 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 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 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 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 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(¬e("look at this"));
2196 let line = text_height("note1…", SIZE, WIDTH);
2197
2198 let linked = measured_height("ing("look at this", "ed, false));
2200 assert!((linked - plain - line - f32::from(NOTE_SPACING)).abs() < 0.01, "{linked} against {plain}");
2201
2202 let shown = measured_height("ing("look at this", "ed, true));
2204 assert!(shown > linked + 40.0, "{shown} against {linked}");
2205
2206 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("ing("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("ing("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 let shown = quoting("look at this", "ed, true);
2241 assert_eq!(down_the_middle(&shown, false), [vec![shown.id], vec![quoted.id], vec![shown.id], vec![]]);
2242 assert_eq!(down_the_middle(&shown, true), [vec![]]);
2245
2246 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 let linked = quoting("look at this", "ed, 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 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 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 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 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 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 assert_eq!(clicked_down_reacting(&said, None, None, heart), ["thread", "profile", "thread", "reactions", "thread", ""]);
2394
2395 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 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 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 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 assert_eq!(height(false, 3), plain);
2465 assert_eq!(height(false, 12), plain);
2466 }
2467
2468 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 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 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 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(¬e("a cat"));
2552 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 assert_eq!(down_the_middle(&images_with(url, (1200, 300))), ["thread", ""]);
2599 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(¬e("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 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 "## 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 "|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 "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, "ed, true) };
2655 for note in [
2656 plain.clone(),
2657 quoting("see", "ed, false),
2658 quoting("see", "ed, true),
2659 quoting(&text, &plain, true),
2660 quoting("see", &nested, true),
2661 ] {
2662 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 for in_full in [false, true] {
2668 let estimated = estimated_note_height(¬e, RowSizes::new(size), width, in_full);
2669 let measured = match in_full {
2670 true => measured_height_in_full(¬e, size, width),
2671 false => measured_height_with(¬e, &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 let row = |text: &str| measured_height_with(¬e(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 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 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 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 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 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 let quoted = Note { id: EventId::from_byte_array([8; 32]), ..long_note() };
2763 assert_eq!(clicked_down_the_middle("ing("see", "ed, 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 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 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 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 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 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}