use std::rc::Rc;
use gpui::{div, prelude::*, AnyElement, App, ElementId, SharedString, StyleRefinement, Window};
use super::{
is_active, navigate, preload, preload_once_visible, replace, with_window, Location, Route,
Search,
};
use crate::{
styles,
styles::ApplyStyleOverrides,
sx::{Sx, SxStyled},
};
styles! {
LINK = {
root: {
cursor: pointer,
color: primary,
border: 1,
border_color: transparent,
radius: sm,
hover: { underline: true },
focus: { border_color: ring },
},
active: { font: semibold },
}
}
#[derive(IntoElement)]
pub struct Link {
id: ElementId,
to: SharedString,
replace: bool,
preload: bool,
preload_visible: bool,
exact: bool,
children: Vec<AnyElement>,
sx: Sx,
style_overrides: StyleRefinement,
}
crate::implement_style_overrides!(Link);
impl Link {
pub fn new(id: impl Into<ElementId>, to: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
to: to.into(),
replace: false,
preload: false,
preload_visible: false,
exact: false,
children: Vec::new(),
sx: Sx::new(),
style_overrides: StyleRefinement::default(),
}
}
pub fn to<R: Route>(route: &R) -> Self {
let href = route.href();
Self::new(ElementId::Name(href.clone()), href)
}
#[must_use]
pub fn search<S: Search>(mut self, search: &S) -> Self {
let location = Location::parse(&self.to);
self.to = Location::build(location.path(), &search.to_query()).into();
self
}
#[must_use]
pub fn preload(mut self, preload: bool) -> Self {
self.preload = preload;
self
}
#[must_use]
pub fn preload_visible(mut self, preload: bool) -> Self {
self.preload_visible = preload;
self
}
#[must_use]
pub fn replace(mut self, replace: bool) -> Self {
self.replace = replace;
self
}
#[must_use]
pub fn exact(mut self, exact: bool) -> Self {
self.exact = exact;
self
}
}
impl ParentElement for Link {
fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
self.children.extend(elements);
}
}
impl RenderOnce for Link {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let active = is_active(&self.to, self.exact, cx);
let (to, replace_entry) = (self.to, self.replace);
let preload_target = self.preload.then(|| to.clone());
let visible_target = self.preload_visible.then(|| to.clone());
let element = div()
.id(self.id)
.tab_index(0)
.when_some(visible_target, |element, target| {
element.relative().child(
gpui::canvas(
move |bounds, window, cx| {
if window.content_mask().bounds.intersects(&bounds) {
preload_once_visible(target, window, cx);
}
},
|_, (), _, _| {},
)
.absolute()
.size_full(),
)
})
.when_some(preload_target, |element, target| {
element.on_hover(move |hovered, _, cx| {
if *hovered {
preload(&target, cx);
}
})
})
.sx((&LINK.root, active.then_some(&LINK.active), &self.sx))
.children(self.children)
.apply_style_overrides(&self.style_overrides);
crate::components::interaction::on_activate(
element,
Rc::new(move |window: &mut Window, cx: &mut App| {
with_window(window.window_handle(), || {
if replace_entry {
replace(to.clone(), cx);
} else {
navigate(to.clone(), cx);
}
});
}),
)
}
}