Skip to main content

cosmic_applet_avestruz/views/components/
article.rs

1// SPDX-License-Identifier: MIT
2
3//! An article (NIP-23) where it is shown: its card, in a list and under a
4//! note that names it, and what stands over and under what it says where
5//! it is opened.
6//!
7//! The card is the one the preview of a link has, and as tall: the
8//! article's picture at its left end, and beside it what it is and how
9//! long it takes to read, its title, and the first lines of what sums it
10//! up. It is as tall whatever the article says of itself, so a list knows
11//! how tall its row is before it is drawn.
12//!
13//! Opened, an article has its title over it, large; how long it takes to
14//! read and when it was last changed; what sums it up, set apart as a
15//! quote is; and its picture, as a strip across. Under it are its topics.
16//! Between them is what it says, which a note's row shows as it shows
17//! any note's text (see [`said`](super::note_row::said)).
18
19use cosmic::Element;
20use cosmic::iced::widget::text::{Span, Wrapping};
21use cosmic::iced::widget::{rich_text, span};
22use cosmic::iced::{Background, Color, ContentFit, Length, border, mouse};
23use cosmic::widget::{self, container, text};
24
25use crate::fl;
26use crate::helpers::relative_time;
27use crate::images::{ImageShape, ImageState, STRIP_ASPECT};
28use crate::messages::Message;
29use crate::nostr::article::{Article, ArticleLink};
30use crate::nostr::models::{Note, display_name};
31use crate::nostr::outbox::Whereabouts;
32use crate::views::components::link_preview::{Page, link_preview_height, page_card};
33use crate::views::components::note_row::{NOTE_SPACING, RowContext, RowSizes, line_height};
34use crate::views::components::{CARD_RADIUS, MediaPlaceholder};
35
36/// How many times the size of a note's text an opened article's title is
37/// set in: as its largest heading is.
38const TITLE_SCALE: f32 = 1.5;
39
40/// How much quieter than the text the small print of an article is, and
41/// what sums it up.
42const QUIET_ALPHA: f32 = 0.65;
43
44/// The bar before what sums an opened article up, and the room between
45/// the two.
46const SUMMARY_BAR_WIDTH: f32 = 3.0;
47const SUMMARY_BAR_ALPHA: f32 = 0.35;
48const SUMMARY_GAP: f32 = 10.0;
49
50/// What a character of text is taken to be wide, for its size, where it
51/// has not been laid out: as a row takes it.
52const CHAR_WIDTH_PER_SIZE: f32 = 0.48;
53
54/// What an article is called where it says nothing of that.
55fn title(article: &Article) -> String {
56    if article.title.is_empty() { fl!("article-untitled") } else { article.title.clone() }
57}
58
59/// How tall the card of an article is in a row set in `sizes`: as the
60/// preview of a link is.
61pub fn article_card_height(sizes: RowSizes) -> f32 {
62    link_preview_height(sizes)
63}
64
65/// The card of the article `note` is, whose tags said `article`. It opens
66/// the article when it is pressed, if it is `pressed` and no menu is open
67/// over the list; in the article's own row it is not, and a click on it
68/// is a click on the row.
69pub fn article_card<'a>(note: &'a Note, article: &'a Article, pressed: bool, context: &RowContext<'a>) -> Element<'a, Message> {
70    // Under a note that names it, who wrote it is said too: in its own
71    // row that stands over it.
72    let over = if pressed {
73        let name = display_name(context.profiles, &note.author);
74        fl!("article-card-by", name = name.as_ref(), minutes = article.minutes)
75    } else {
76        fl!("article-card", minutes = article.minutes)
77    };
78    let card = page_card(
79        Page {
80            over: over.into(),
81            title: if article.title.is_empty() { fl!("article-untitled").into() } else { article.title.as_str().into() },
82            description: article.summary.as_deref(),
83            image: article.image.as_deref(),
84        },
85        context,
86    );
87    if !pressed || context.under_a_menu() {
88        return card;
89    }
90    widget::mouse_area(card)
91        .on_press(Message::OpenThread(note.id, Whereabouts::default()))
92        .interaction(mouse::Interaction::Pointer)
93        .into()
94}
95
96/// An article a note names that is not at hand: the short form of its
97/// address, on a line of its own, which looks for it and opens it.
98pub fn article_link<'a>(link: &'a ArticleLink, context: &RowContext<'a>) -> Element<'a, Message> {
99    let spans: Vec<Span<'a, ArticleLink>> = vec![span(link.label.as_str()).color(context.accent).link(link.clone())];
100    rich_text(spans)
101        .size(context.sizes.text())
102        .wrapping(Wrapping::WordOrGlyph)
103        .width(Length::Fill)
104        .on_link_click(Message::OpenArticle)
105        .into()
106}
107
108/// How large an opened article's title is set, in a row set in `sizes`.
109fn title_size(sizes: RowSizes) -> f32 {
110    (f32::from(sizes.text()) * TITLE_SCALE).round()
111}
112
113/// How many lines `chars` characters of text of `size` come to in room
114/// `width` wide, near enough.
115fn lines(chars: usize, size: f32, width: f32) -> f32 {
116    let per_line = ((width / (size * CHAR_WIDTH_PER_SIZE)) as usize).max(1);
117    chars.div_ceil(per_line).max(1) as f32
118}
119
120/// How tall what stands over an opened article will be, near enough, set
121/// in `sizes` in a row `width` wide, with the room between its parts and
122/// none around it.
123pub fn article_head_height(article: &Article, sizes: RowSizes, width: f32) -> f32 {
124    let spacing = f32::from(NOTE_SPACING);
125    let size = title_size(sizes);
126    let heading = lines(title(article).chars().count(), size, width) * size * 1.4;
127    let small = spacing + line_height(sizes.time());
128    let summary = article.summary.as_ref().map_or(0.0, |summary| {
129        let room = (width - SUMMARY_BAR_WIDTH - SUMMARY_GAP).max(1.0);
130        let wrapped: f32 = summary.split('\n').map(|line| lines(line.chars().count(), f32::from(sizes.text()), room)).sum();
131        spacing + wrapped * line_height(sizes.text())
132    });
133    let picture = article.image.as_ref().map_or(0.0, |_| spacing + width / STRIP_ASPECT as f32);
134    heading + small + summary + picture
135}
136
137/// What stands over the opened article `note` is, whose tags said
138/// `article`: its title, how long it takes to read and when it was last
139/// changed, what sums it up, and its picture.
140pub fn article_head<'a>(note: &'a Note, article: &'a Article, context: &RowContext<'a>) -> Element<'a, Message> {
141    let RowContext { images, now, sizes, .. } = *context;
142    let on_background: Color = cosmic::theme::active().cosmic().on_bg_color().into();
143    let quiet = Color { a: QUIET_ALPHA, ..on_background };
144
145    let heading = text(title(article))
146        .size(title_size(sizes))
147        .font(cosmic::font::bold())
148        .wrapping(Wrapping::WordOrGlyph)
149        .width(Length::Fill);
150    let when = relative_time(now, note.created_at);
151    let small = text(fl!("article-read", minutes = article.minutes, when = when.as_str()))
152        .size(sizes.time())
153        .wrapping(Wrapping::None)
154        .class(cosmic::theme::Text::Color(quiet));
155    let small = container(small).width(Length::Fill).height(line_height(sizes.time())).clip(true);
156
157    let summary = article.summary.as_deref().map(|summary| {
158        let bar = container(widget::Space::new()).width(Length::Fixed(SUMMARY_BAR_WIDTH)).height(Length::Fill).class(
159            cosmic::theme::Container::custom(move |_| container::Style {
160                background: Some(Background::Color(Color { a: SUMMARY_BAR_ALPHA, ..on_background })),
161                border: border::rounded(SUMMARY_BAR_WIDTH / 2.0),
162                ..container::Style::default()
163            }),
164        );
165        let said = text(summary)
166            .size(sizes.text())
167            .wrapping(Wrapping::WordOrGlyph)
168            .width(Length::Fill)
169            .class(cosmic::theme::Text::Color(quiet));
170        // Said after they are pushed: the row is as tall as the words,
171        // and the bar fills it.
172        widget::Row::new().push(bar).push(said).spacing(SUMMARY_GAP).height(Length::Shrink)
173    });
174
175    // A strip as wide as the row, once it is here; the room it will take,
176    // until then; nothing, if it can't be had.
177    let picture: Option<Element<'a, Message>> =
178        article.image.as_deref().and_then(|image| match images.get(image, ImageShape::Strip) {
179            ImageState::Ready(loaded) => Some(
180                widget::image(loaded.handle.clone())
181                    .width(Length::Fill)
182                    .height(Length::Shrink)
183                    .content_fit(ContentFit::Contain)
184                    .border_radius([CARD_RADIUS; 4])
185                    .into(),
186            ),
187            ImageState::Loading => {
188                Some(MediaPlaceholder::new(Some((STRIP_ASPECT * 1_000, 1_000)), 0.0).radius(CARD_RADIUS).into())
189            }
190            ImageState::Failed => None,
191        });
192
193    widget::Column::new()
194        .push(heading)
195        .push(small)
196        .push_maybe(summary)
197        .push_maybe(picture)
198        .spacing(NOTE_SPACING)
199        .width(Length::Fill)
200        .into()
201}
202
203/// How tall the line of an article's topics is, set in `sizes`.
204pub fn article_topics_height(article: &Article, sizes: RowSizes) -> f32 {
205    if article.topics.is_empty() { 0.0 } else { line_height(sizes.time()) }
206}
207
208/// What the opened article is about, under what it says: its topics, on
209/// one line that is cut where it ends. Nothing for one that names none.
210pub fn article_topics<'a>(article: &Article, context: &RowContext<'a>) -> Option<Element<'a, Message>> {
211    if article.topics.is_empty() {
212        return None;
213    }
214    let small = context.sizes.time();
215    let topics = article.topics.iter().map(|topic| format!("#{topic}")).collect::<Vec<_>>().join("  ");
216    let line = text(topics).size(small).wrapping(Wrapping::None).class(cosmic::theme::Text::Color(context.accent));
217    Some(container(line).width(Length::Fill).height(line_height(small)).clip(true).into())
218}