Skip to main content

cosmic_applet_avestruz/views/components/
link_preview.rs

1// SPDX-License-Identifier: MIT
2
3//! The preview of a web page a note links to: a card under the note with
4//! the picture the page is shared with, the site it is on, its title and a
5//! few words about it. A click opens the page.
6//!
7//! The card is as tall for one page as for another, and as tall while the
8//! page is being asked as when it has answered: a row doesn't change height
9//! because a preview arrived, or its picture did. A page with nothing to
10//! say for itself gets no card, and the room kept for one is given back.
11//!
12//! A link that answered as a video is no page: its card offers to play it,
13//! and pressed, gives way to the video (see
14//! [`video_box`](mod@crate::views::components::video_box)).
15
16use cosmic::Element;
17use cosmic::iced::widget::text::Wrapping;
18use cosmic::iced::{Color, ContentFit, Length, mouse};
19use cosmic::widget::{self, container, text};
20
21use crate::fl;
22use crate::images::{ImageShape, ImageState, THUMBNAIL_ASPECT};
23use crate::messages::Message;
24use crate::previews::PreviewState;
25use crate::views::components::note_row::{RowContext, RowSizes, line_height};
26use crate::views::components::{CARD_BORDER, CARD_RADIUS, MediaPlaceholder, card_style};
27
28/// The room between the card's edge and what it says, and between the
29/// lines it says it in.
30const PREVIEW_PADDING: f32 = 8.0;
31const PREVIEW_SPACING: f32 = 2.0;
32
33/// How many lines of a page's description the card shows.
34const PREVIEW_DESCRIPTION_LINES: f32 = 2.0;
35
36/// How much dimmer than the text the site and the description are.
37const PREVIEW_DIM: f32 = 0.7;
38
39/// How tall the preview of a link is in a row set in `sizes`, whatever the
40/// page says: the site, the title and the lines of description, and the
41/// room around them.
42pub fn link_preview_height(sizes: RowSizes) -> f32 {
43    2.0 * (CARD_BORDER + PREVIEW_PADDING)
44        + line_height(sizes.preview_site())
45        + line_height(sizes.preview_title())
46        + PREVIEW_DESCRIPTION_LINES * line_height(sizes.preview_description())
47        + 2.0 * PREVIEW_SPACING
48}
49
50/// One line of the card, cut where the card ends rather than wrapped.
51fn cut_line<'a>(line: impl Into<Element<'a, Message>>) -> Element<'a, Message> {
52    container(line).width(Length::Fill).clip(true).into()
53}
54
55/// The card of a link that turned out to be a video: as tall as any
56/// preview, saying what it is and where, and playing it when it is
57/// pressed.
58fn video_offer<'a>(url: &'a str, context: &RowContext<'a>) -> Element<'a, Message> {
59    let sizes = context.sizes;
60    let inside = link_preview_height(sizes) - 2.0 * CARD_BORDER;
61    let play = container(widget::icon::from_name("media-playback-start-symbolic").size(24))
62        .center_x(Length::Fixed(inside))
63        .center_y(Length::Fixed(inside));
64
65    let text_color: Color = cosmic::theme::active().cosmic().on_bg_color().into();
66    let dim = cosmic::theme::Text::Color(Color { a: PREVIEW_DIM, ..text_color });
67    let site = reqwest::Url::parse(url).ok().and_then(|url| url.host_str().map(str::to_string)).unwrap_or_default();
68    let site = text(site).size(sizes.preview_site()).class(dim).wrapping(Wrapping::None);
69    let title = text(fl!("video-offer")).size(sizes.preview_title()).font(cosmic::font::bold()).wrapping(Wrapping::None);
70    let words = widget::Column::new().push(cut_line(site)).push(cut_line(title)).spacing(PREVIEW_SPACING);
71    let words = container(words).padding(PREVIEW_PADDING).width(Length::Fill).center_y(Length::Fixed(inside));
72
73    let card = container(widget::Row::new().push(play).push(words))
74        .padding(CARD_BORDER)
75        .width(Length::Fill)
76        .height(Length::Fixed(link_preview_height(sizes)))
77        .class(card_style());
78    widget::mouse_area(card).on_press(Message::VideoPress(url.to_string())).interaction(mouse::Interaction::Pointer).into()
79}
80
81/// The preview of the page at `url`, for under the note that links to it:
82/// the card, once the page has said what it is; the room the card will
83/// take, until then; and nothing, if the page has nothing to say.
84pub fn link_preview<'a>(url: &'a str, context: &RowContext<'a>) -> Option<Element<'a, Message>> {
85    let RowContext { previews, images, sizes, .. } = *context;
86    let height = link_preview_height(sizes);
87    let preview = match previews.get(url) {
88        PreviewState::Ready(preview) => preview,
89        PreviewState::Loading => return Some(MediaPlaceholder::new(None, height).radius(CARD_RADIUS).into()),
90        PreviewState::Video => return Some(video_offer(url, context)),
91        PreviewState::Nothing => return None,
92    };
93
94    // The picture fills the card's left end, top to bottom, cut to the
95    // proportions it is asked for in. A picture that can't be had leaves
96    // the card to the words.
97    let inside = height - 2.0 * CARD_BORDER;
98    let across = (inside * THUMBNAIL_ASPECT.0 as f32 / THUMBNAIL_ASPECT.1 as f32).round();
99    let left_corners = [CARD_RADIUS - CARD_BORDER, 0.0, 0.0, CARD_RADIUS - CARD_BORDER];
100    let picture: Option<Element<'a, Message>> =
101        preview.image.as_deref().and_then(|image| match images.get(image, ImageShape::Thumbnail) {
102            ImageState::Ready(loaded) => Some(
103                widget::image(loaded.handle.clone())
104                    .width(Length::Fixed(across))
105                    .height(Length::Fixed(inside))
106                    .content_fit(ContentFit::Fill)
107                    .border_radius(left_corners)
108                    .into(),
109            ),
110            ImageState::Loading => Some(container(MediaPlaceholder::new(None, inside)).width(Length::Fixed(across)).into()),
111            ImageState::Failed => None,
112        });
113
114    let text_color: Color = cosmic::theme::active().cosmic().on_bg_color().into();
115    let dim = cosmic::theme::Text::Color(Color { a: PREVIEW_DIM, ..text_color });
116    let site = text(preview.site.as_str()).size(sizes.preview_site()).class(dim).wrapping(Wrapping::None);
117    let title = text(preview.title.as_str()).size(sizes.preview_title()).font(cosmic::font::bold()).wrapping(Wrapping::None);
118    let mut words = widget::Column::new().push(cut_line(site)).push(cut_line(title)).spacing(PREVIEW_SPACING);
119    if let Some(description) = &preview.description {
120        // As many lines as fit the room it is given, and no part of the
121        // next.
122        let lines = PREVIEW_DESCRIPTION_LINES * line_height(sizes.preview_description());
123        let description = text(description.as_str()).size(sizes.preview_description()).class(dim).wrapping(Wrapping::WordOrGlyph);
124        words = words.push(container(description).width(Length::Fill).height(Length::Fixed(lines)).clip(true));
125    }
126    let words = container(words).padding(PREVIEW_PADDING).width(Length::Fill).height(Length::Fixed(inside));
127
128    let card = container(widget::Row::new().push_maybe(picture).push(words))
129        .padding(CARD_BORDER)
130        .width(Length::Fill)
131        .height(Length::Fixed(height))
132        .class(card_style());
133    Some(widget::mouse_area(card).on_press(Message::OpenUrl(url.to_string())).interaction(mouse::Interaction::Pointer).into())
134}