Created
November 11, 2023 08:28
-
-
Save carina-akaia/545a583ec732372284d5b6c045d09374 to your computer and use it in GitHub Desktop.
link.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use {dioxus::prelude::*, | |
dioxus_class::prelude::*, | |
dioxus_free_icons::{icons::hi_solid_icons::*, Icon}, | |
regex::Regex, | |
scraper::{Html, Selector}, | |
url::*}; | |
fn use_favicon_url<'a>(cx: Scope<'a, LinkProps<'a>>, url: Url) -> Option<String> { | |
let body = use_future(cx, (), |_| async move { | |
reqwest::get(url.to_owned()).await.unwrap().text().await | |
}); | |
return match body.value() { | |
| Some(Ok(body)) => { | |
let document = Html::parse_document(&body); | |
let favicon_link = document.select(&Selector::parse("link[rel*='icon']").unwrap()) | |
.next()?; | |
let favicon_url = favicon_link.value().attr("href")?; | |
Some(favicon_url.to_owned().to_string()) | |
}, | |
| _ => None, | |
}; | |
} | |
#[derive(Props)] | |
pub struct LinkProps<'a> { | |
address: &'a str, | |
#[props(default = Element::None)] | |
custom_icon: Element<'a>, | |
#[props(default = "")] | |
class: &'a str, | |
label: Option<&'a str>, | |
#[props(default = false)] | |
with_icon: bool, | |
} | |
pub fn Link<'a>(cx: Scope<'a, LinkProps<'a>>) -> Element { | |
let LinkProps { address, | |
class, | |
custom_icon, | |
label, | |
with_icon, | |
.. } = cx.props; | |
let url = Url::parse(address); | |
let icon = if with_icon.to_owned() { | |
if custom_icon.is_some() { | |
rsx! {custom_icon} | |
} else { | |
rsx! { Icon { class: uno![cx; "fill-current"], icon: HiLink, width: 24, height: 24 } } | |
} | |
} else { | |
rsx! {Element::None} | |
}; | |
let address_shorthand = Regex::new(r"^(https?|mailto):(//)?").unwrap() | |
.replace(address, "") | |
.into_owned(); | |
let root_class = class!( | |
uno![cx; | |
"flex-(~)", | |
"items-center", | |
"gap-2", | |
"text-(current 4)", | |
"decoration-dotted", | |
"print-decoration-none", | |
"hover:decoration-solid", | |
"m-0", | |
] | |
class.to_owned() | |
); | |
render!( | |
a { class: root_class, href: address.to_owned(), | |
icon, | |
span { class: uno![cx; "block", "print-hidden"], label.unwrap_or(&address_shorthand) } | |
span { class: uno![cx; "hidden", "print-block"], address_shorthand } | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment