use std::time::Duration;
use dioxus::prelude::*;
use crate::class::compose;
use crate::hooks::use_controllable;
use crate::icons::{IconData, icon_svg, icon_svg_class, lucide};
use crate::time::sleep;
use crate::{ButtonSize, ButtonVariant};
use super::copy::CopyButton;
use super::util::{
collapse_whitespace, decode_uri_component, element_text, encode_uri_component, format_template,
optional_text,
};
use super::web::{
Watcher, focus_element_by_id, focus_selector, location_href, scroll_window_to_top,
use_scroll_past, watch_active_section,
};
fn js_number(value: f64) -> String {
if value.fract() == 0.0 && value.abs() < 1e15 {
format!("{value:.0}")
} else {
value.to_string()
}
}
#[derive(Props, Clone, PartialEq)]
pub struct BackToTopProps {
pub reveal_after: Option<f64>,
#[props(into)]
pub focus_target: Option<String>,
pub onclick: Option<EventHandler<MouseEvent>>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = button)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn BackToTop(props: BackToTopProps) -> Element {
let reveal = props
.reveal_after
.filter(|value| value.is_finite() && *value >= 0.0);
let focus_target = optional_text(props.focus_target.as_deref());
let scrolls = reveal.is_some() || focus_target.is_some();
let past = use_scroll_past(reveal);
let mut focused = use_signal(|| false);
let class = compose([Some("ui-back-to-top"), props.class.as_deref()]);
let should_show = past().is_none_or(|past| past);
let hidden = reveal.is_some() && !should_show && !(focused() && focus_target.is_none());
let state = reveal.map(|_| if hidden { "hidden" } else { "visible" });
let mut latest_target = use_hook(|| CopyValue::new(None::<String>));
latest_target.set(focus_target.clone());
use_effect(move || {
let leaving = past() == Some(false) && focused();
if leaving && let Some(selector) = latest_target.peek().clone() {
spawn(async move {
focus_selector(selector).await;
});
}
});
let onclick = props.onclick;
rsx! {
button {
class,
"data-state": state,
"data-ui-back-to-top-reveal": reveal.map(js_number),
inert: hidden,
r#type: "button",
onclick: move |event| {
if let Some(handler) = onclick {
handler.call(event);
}
if !scrolls {
return;
}
scroll_window_to_top();
if let Some(selector) = focus_target.clone() {
spawn(async move {
focus_selector(selector).await;
});
}
},
onfocus: move |_| focused.set(true),
onblur: move |_| focused.set(false),
..props.attributes,
{props.children}
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeadingAnchorLevel {
#[default]
H2,
H3,
H4,
H5,
H6,
}
impl HeadingAnchorLevel {
pub fn from_number(level: u8) -> Self {
match level {
3 => Self::H3,
4 => Self::H4,
5 => Self::H5,
6 => Self::H6,
_ => Self::H2,
}
}
pub fn number(self) -> u8 {
match self {
Self::H2 => 2,
Self::H3 => 3,
Self::H4 => 4,
Self::H5 => 5,
Self::H6 => 6,
}
}
}
pub fn heading_anchor_href(id: &str) -> Option<String> {
let trimmed = id.trim();
(!trimmed.is_empty()).then(|| format!("#{}", encode_uri_component(trimmed)))
}
pub fn heading_anchor_url(id: &str, base: &str) -> Option<String> {
let href = heading_anchor_href(id)?;
let base = base.split_once('#').map_or(base, |(before, _)| before);
if base.is_empty() || !base.contains(':') {
return None;
}
Some(format!("{base}{href}"))
}
const LINK_LABEL: &str = "Link to section: {heading}";
const COPY_LABEL: &str = "Copy link to section: {heading}";
const COPIED_LABEL: &str = "Link copied";
const ERROR_LABEL: &str = "Could not copy the link";
fn heading_label(template: Option<&str>, heading: &str, fallback: &str) -> String {
let template = template
.filter(|value| !value.trim().is_empty())
.unwrap_or(fallback);
format_template(template, &[("heading", heading.trim())])
}
#[derive(Props, Clone, PartialEq)]
pub struct HeadingAnchorProps {
#[props(into)]
pub id: String,
#[props(default)]
pub level: HeadingAnchorLevel,
#[props(into)]
pub label: Option<String>,
#[props(default = true)]
pub copy: bool,
#[props(into)]
pub link_label: Option<String>,
#[props(into)]
pub copy_label: Option<String>,
#[props(into)]
pub copied_label: Option<String>,
#[props(into)]
pub error_label: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = div)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
fn heading_element(level: HeadingAnchorLevel, id: Option<String>, children: Element) -> Element {
match level {
HeadingAnchorLevel::H2 => {
rsx! { h2 { class: "ui-heading-anchor__heading", id, {children} } }
}
HeadingAnchorLevel::H3 => {
rsx! { h3 { class: "ui-heading-anchor__heading", id, {children} } }
}
HeadingAnchorLevel::H4 => {
rsx! { h4 { class: "ui-heading-anchor__heading", id, {children} } }
}
HeadingAnchorLevel::H5 => {
rsx! { h5 { class: "ui-heading-anchor__heading", id, {children} } }
}
HeadingAnchorLevel::H6 => {
rsx! { h6 { class: "ui-heading-anchor__heading", id, {children} } }
}
}
}
#[component]
pub fn HeadingAnchor(props: HeadingAnchorProps) -> Element {
let mut location = use_signal(|| None::<String>);
let heading_id = props.id.trim().to_string();
let href = heading_anchor_href(&heading_id);
let section = optional_text(props.label.as_deref())
.unwrap_or_else(|| collapse_whitespace(&element_text(&props.children)));
let url = location().and_then(|base| heading_anchor_url(&heading_id, &base));
let class = compose([Some("ui-heading-anchor"), props.class.as_deref()]);
let refresh = move || {
spawn(async move {
let next = location_href().await;
if next.is_some() && *location.peek() != next {
location.set(next);
}
});
};
use_effect(refresh);
let level = props.level;
let link_label = heading_label(props.link_label.as_deref(), §ion, LINK_LABEL);
let copy_label = heading_label(props.copy_label.as_deref(), §ion, COPY_LABEL);
let copied_label =
optional_text(props.copied_label.as_deref()).unwrap_or_else(|| COPIED_LABEL.to_string());
let error_label =
optional_text(props.error_label.as_deref()).unwrap_or_else(|| ERROR_LABEL.to_string());
let copy_value = url.clone().or_else(|| href.clone()).unwrap_or_default();
rsx! {
div {
class,
"data-level": "{level.number()}",
"data-slot": "heading-anchor",
"data-ui-heading-anchor": "",
"data-ui-owner": "dioxus",
..props.attributes,
{heading_element(level, (!heading_id.is_empty()).then(|| heading_id.clone()), props.children)}
if let Some(href) = href {
span {
class: "ui-heading-anchor__actions",
"data-slot": "heading-anchor-actions",
onfocusin: move |_| refresh(),
onpointerenter: move |_| refresh(),
a {
aria_label: link_label,
class: "ui-heading-anchor__link",
"data-slot": "heading-anchor-link",
href,
span { aria_hidden: "true", class: "ui-heading-anchor__hash", "#" }
}
if props.copy {
CopyButton {
class: "ui-heading-anchor__copy",
copied_content: rsx! { {heading_icon(&lucide::CHECK)} },
copied_label,
error_content: rsx! { {heading_icon(&lucide::X)} },
error_label,
hidden: url.is_none(),
label: copy_label,
size: ButtonSize::Icon,
value: copy_value,
variant: ButtonVariant::Ghost,
{heading_icon(&lucide::COPY)}
}
}
}
}
}
}
}
fn heading_icon(icon: &'static IconData) -> Element {
icon_svg(
icon,
&format!("{} ui-heading-anchor__icon", icon_svg_class(icon)),
)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AnchorLink {
pub href: String,
pub label: String,
pub description: Option<String>,
pub depth: Option<u8>,
pub index: Option<String>,
}
impl AnchorLink {
pub fn new(href: impl Into<String>, label: impl Into<String>) -> Self {
Self {
href: href.into(),
label: label.into(),
..Self::default()
}
}
#[must_use]
pub fn depth(mut self, depth: u8) -> Self {
self.depth = Some(depth.clamp(1, 6));
self
}
}
fn fragment_id(href: &str) -> Option<String> {
href.strip_prefix('#')
.filter(|fragment| !fragment.is_empty())
.map(decode_uri_component)
}
#[derive(Props, Clone, PartialEq)]
pub struct AnchorProps {
#[props(default)]
pub items: Vec<AnchorLink>,
#[props(into)]
pub value: Option<String>,
pub on_value_change: Option<EventHandler<String>>,
#[props(default = 96.0)]
pub activation_offset: f64,
#[props(default = "On this page".to_string(), into)]
pub aria_label: String,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = nav)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn Anchor(props: AnchorProps) -> Element {
let first = props
.items
.first()
.map_or_else(String::new, |item| item.href.clone());
let active = use_controllable(props.value.clone(), || first, props.on_value_change);
let offset = if props.activation_offset.is_finite() {
props.activation_offset.max(0.0)
} else {
0.0
};
let class = compose([Some("ui-anchor"), props.class.as_deref()]);
let current = active.get();
let sections: Vec<(String, String)> = props
.items
.iter()
.filter_map(|item| fragment_id(&item.href).map(|id| (id, item.href.clone())))
.collect();
let mut watcher = use_hook(|| CopyValue::new(None::<Watcher>));
use_effect(use_reactive(
(§ions, &offset),
move |(sections, offset)| {
if let Some(previous) = watcher.write().take() {
previous.stop();
}
if sections.is_empty() {
return;
}
let ids = sections.iter().map(|(id, _)| id.clone()).collect();
let next = watch_active_section(ids, offset, move |index| {
if let Some((_, href)) = sections.get(index) {
active.set(href.clone());
}
});
watcher.set(Some(next));
},
));
use_drop(move || {
if let Some(previous) = watcher.write().take() {
previous.stop();
}
});
rsx! {
nav {
aria_label: props.aria_label,
class,
"data-ui-anchor": "true",
"data-ui-anchor-offset": js_number(offset),
"data-ui-owner": "dioxus",
..props.attributes,
if !props.items.is_empty() {
ol {
for item in props.items {
{
let is_active = item.href == current;
let href = item.href.clone();
rsx! {
li { key: "{item.href}",
a {
aria_current: is_active.then_some("location"),
"data-active": if is_active { "true" } else { "false" },
"data-depth": item.depth.map(|depth| depth.to_string()),
href: item.href.clone(),
onclick: move |_| {
active.set(href.clone());
if let Some(id) = fragment_id(&href) {
spawn(async move {
sleep(Duration::ZERO).await;
focus_element_by_id(id, None).await;
});
}
},
if let Some(index) = item.index {
span { class: "ui-anchor__index", "{index}" }
}
span { class: "ui-anchor__content",
span { class: "ui-anchor__label", "{item.label}" }
if let Some(description) = item.description.filter(|text| !text.is_empty()) {
span { class: "ui-anchor__description", "{description}" }
}
}
}
}
}
}
}
}
}
{props.children}
}
}
}
#[cfg(test)]
mod tests {
use super::{
HeadingAnchorLevel, fragment_id, heading_anchor_href, heading_anchor_url, heading_label,
js_number,
};
#[test]
fn heading_hrefs_and_urls_follow_lumen_core() {
assert_eq!(
heading_anchor_href(" install ").as_deref(),
Some("#install")
);
assert_eq!(heading_anchor_href("a b/c").as_deref(), Some("#a%20b%2Fc"));
assert_eq!(heading_anchor_href(" "), None);
assert_eq!(
heading_anchor_url("install", "https://example.com/docs?x=1#old").as_deref(),
Some("https://example.com/docs?x=1#install")
);
assert_eq!(heading_anchor_url("install", "not a url"), None);
assert_eq!(heading_anchor_url("", "https://example.com/"), None);
}
#[test]
fn levels_and_labels_normalize() {
assert_eq!(HeadingAnchorLevel::from_number(1), HeadingAnchorLevel::H2);
assert_eq!(HeadingAnchorLevel::from_number(4).number(), 4);
assert_eq!(
heading_label(None, " Install ", "Link to section: {heading}"),
"Link to section: Install"
);
assert_eq!(heading_label(Some(" "), "A", "Go {heading}"), "Go A");
assert_eq!(heading_label(Some("Ir a {heading}"), "A", "x"), "Ir a A");
}
#[test]
fn fragments_decode_and_numbers_format() {
assert_eq!(fragment_id("#a%20b").as_deref(), Some("a b"));
assert_eq!(fragment_id("#100%").as_deref(), Some("100%"));
assert_eq!(fragment_id("/page"), None);
assert_eq!(fragment_id("#"), None);
assert_eq!(js_number(96.0), "96");
assert_eq!(js_number(12.5), "12.5");
}
}