1use std::time::Duration;
5
6use dioxus::prelude::*;
7
8use crate::class::compose;
9use crate::hooks::use_controllable;
10use crate::icons::{IconData, icon_svg, icon_svg_class, lucide};
11use crate::time::sleep;
12use crate::{ButtonSize, ButtonVariant};
13
14use super::copy::CopyButton;
15use super::util::{
16 collapse_whitespace, decode_uri_component, element_text, encode_uri_component, format_template,
17 optional_text,
18};
19use super::web::{
20 Watcher, focus_element_by_id, focus_selector, location_href, scroll_window_to_top,
21 use_scroll_past, watch_active_section,
22};
23
24fn js_number(value: f64) -> String {
26 if value.fract() == 0.0 && value.abs() < 1e15 {
27 format!("{value:.0}")
28 } else {
29 value.to_string()
30 }
31}
32
33#[derive(Props, Clone, PartialEq)]
35pub struct BackToTopProps {
36 pub reveal_after: Option<f64>,
38 #[props(into)]
40 pub focus_target: Option<String>,
41 pub onclick: Option<EventHandler<MouseEvent>>,
43 #[props(into)]
45 pub class: Option<String>,
46 #[props(extends = GlobalAttributes, extends = button)]
48 pub attributes: Vec<Attribute>,
49 pub children: Element,
51}
52
53#[component]
61pub fn BackToTop(props: BackToTopProps) -> Element {
62 let reveal = props
63 .reveal_after
64 .filter(|value| value.is_finite() && *value >= 0.0);
65 let focus_target = optional_text(props.focus_target.as_deref());
66 let scrolls = reveal.is_some() || focus_target.is_some();
67 let past = use_scroll_past(reveal);
68 let mut focused = use_signal(|| false);
69 let class = compose([Some("ui-back-to-top"), props.class.as_deref()]);
70 let should_show = past().is_none_or(|past| past);
72 let hidden = reveal.is_some() && !should_show && !(focused() && focus_target.is_none());
74 let state = reveal.map(|_| if hidden { "hidden" } else { "visible" });
75 let mut latest_target = use_hook(|| CopyValue::new(None::<String>));
76 latest_target.set(focus_target.clone());
77
78 use_effect(move || {
79 let leaving = past() == Some(false) && focused();
80
81 if leaving && let Some(selector) = latest_target.peek().clone() {
82 spawn(async move {
83 focus_selector(selector).await;
84 });
85 }
86 });
87
88 let onclick = props.onclick;
89
90 rsx! {
91 button {
92 class,
93 "data-state": state,
94 "data-ui-back-to-top-reveal": reveal.map(js_number),
95 inert: hidden,
96 r#type: "button",
97 onclick: move |event| {
98 if let Some(handler) = onclick {
99 handler.call(event);
100 }
101
102 if !scrolls {
103 return;
104 }
105
106 scroll_window_to_top();
107
108 if let Some(selector) = focus_target.clone() {
109 spawn(async move {
110 focus_selector(selector).await;
111 });
112 }
113 },
114 onfocus: move |_| focused.set(true),
115 onblur: move |_| focused.set(false),
116 ..props.attributes,
117 {props.children}
118 }
119 }
120}
121
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
124#[non_exhaustive]
125pub enum HeadingAnchorLevel {
126 #[default]
128 H2,
129 H3,
131 H4,
133 H5,
135 H6,
137}
138
139impl HeadingAnchorLevel {
140 pub fn from_number(level: u8) -> Self {
142 match level {
143 3 => Self::H3,
144 4 => Self::H4,
145 5 => Self::H5,
146 6 => Self::H6,
147 _ => Self::H2,
148 }
149 }
150
151 pub fn number(self) -> u8 {
153 match self {
154 Self::H2 => 2,
155 Self::H3 => 3,
156 Self::H4 => 4,
157 Self::H5 => 5,
158 Self::H6 => 6,
159 }
160 }
161}
162
163pub fn heading_anchor_href(id: &str) -> Option<String> {
166 let trimmed = id.trim();
167
168 (!trimmed.is_empty()).then(|| format!("#{}", encode_uri_component(trimmed)))
169}
170
171pub fn heading_anchor_url(id: &str, base: &str) -> Option<String> {
174 let href = heading_anchor_href(id)?;
175 let base = base.split_once('#').map_or(base, |(before, _)| before);
176
177 if base.is_empty() || !base.contains(':') {
178 return None;
179 }
180
181 Some(format!("{base}{href}"))
182}
183
184const LINK_LABEL: &str = "Link to section: {heading}";
186const COPY_LABEL: &str = "Copy link to section: {heading}";
187const COPIED_LABEL: &str = "Link copied";
188const ERROR_LABEL: &str = "Could not copy the link";
189
190fn heading_label(template: Option<&str>, heading: &str, fallback: &str) -> String {
191 let template = template
192 .filter(|value| !value.trim().is_empty())
193 .unwrap_or(fallback);
194
195 format_template(template, &[("heading", heading.trim())])
196}
197
198#[derive(Props, Clone, PartialEq)]
200pub struct HeadingAnchorProps {
201 #[props(into)]
204 pub id: String,
205 #[props(default)]
207 pub level: HeadingAnchorLevel,
208 #[props(into)]
210 pub label: Option<String>,
211 #[props(default = true)]
213 pub copy: bool,
214 #[props(into)]
216 pub link_label: Option<String>,
217 #[props(into)]
219 pub copy_label: Option<String>,
220 #[props(into)]
222 pub copied_label: Option<String>,
223 #[props(into)]
225 pub error_label: Option<String>,
226 #[props(into)]
228 pub class: Option<String>,
229 #[props(extends = GlobalAttributes, extends = div)]
231 pub attributes: Vec<Attribute>,
232 pub children: Element,
234}
235
236fn heading_element(level: HeadingAnchorLevel, id: Option<String>, children: Element) -> Element {
237 match level {
238 HeadingAnchorLevel::H2 => {
239 rsx! { h2 { class: "ui-heading-anchor__heading", id, {children} } }
240 }
241 HeadingAnchorLevel::H3 => {
242 rsx! { h3 { class: "ui-heading-anchor__heading", id, {children} } }
243 }
244 HeadingAnchorLevel::H4 => {
245 rsx! { h4 { class: "ui-heading-anchor__heading", id, {children} } }
246 }
247 HeadingAnchorLevel::H5 => {
248 rsx! { h5 { class: "ui-heading-anchor__heading", id, {children} } }
249 }
250 HeadingAnchorLevel::H6 => {
251 rsx! { h6 { class: "ui-heading-anchor__heading", id, {children} } }
252 }
253 }
254}
255
256#[component]
262pub fn HeadingAnchor(props: HeadingAnchorProps) -> Element {
263 let mut location = use_signal(|| None::<String>);
264 let heading_id = props.id.trim().to_string();
265 let href = heading_anchor_href(&heading_id);
266 let section = optional_text(props.label.as_deref())
267 .unwrap_or_else(|| collapse_whitespace(&element_text(&props.children)));
268 let url = location().and_then(|base| heading_anchor_url(&heading_id, &base));
269 let class = compose([Some("ui-heading-anchor"), props.class.as_deref()]);
270 let refresh = move || {
271 spawn(async move {
272 let next = location_href().await;
273
274 if next.is_some() && *location.peek() != next {
275 location.set(next);
276 }
277 });
278 };
279
280 use_effect(refresh);
281
282 let level = props.level;
283 let link_label = heading_label(props.link_label.as_deref(), §ion, LINK_LABEL);
284 let copy_label = heading_label(props.copy_label.as_deref(), §ion, COPY_LABEL);
285 let copied_label =
286 optional_text(props.copied_label.as_deref()).unwrap_or_else(|| COPIED_LABEL.to_string());
287 let error_label =
288 optional_text(props.error_label.as_deref()).unwrap_or_else(|| ERROR_LABEL.to_string());
289 let copy_value = url.clone().or_else(|| href.clone()).unwrap_or_default();
290
291 rsx! {
292 div {
293 class,
294 "data-level": "{level.number()}",
295 "data-slot": "heading-anchor",
296 "data-ui-heading-anchor": "",
297 "data-ui-owner": "dioxus",
298 ..props.attributes,
299 {heading_element(level, (!heading_id.is_empty()).then(|| heading_id.clone()), props.children)}
300 if let Some(href) = href {
301 span {
302 class: "ui-heading-anchor__actions",
303 "data-slot": "heading-anchor-actions",
304 onfocusin: move |_| refresh(),
306 onpointerenter: move |_| refresh(),
307 a {
308 aria_label: link_label,
309 class: "ui-heading-anchor__link",
310 "data-slot": "heading-anchor-link",
311 href,
312 span { aria_hidden: "true", class: "ui-heading-anchor__hash", "#" }
313 }
314 if props.copy {
315 CopyButton {
316 class: "ui-heading-anchor__copy",
317 copied_content: rsx! { {heading_icon(&lucide::CHECK)} },
318 copied_label,
319 error_content: rsx! { {heading_icon(&lucide::X)} },
320 error_label,
321 hidden: url.is_none(),
322 label: copy_label,
323 size: ButtonSize::Icon,
324 value: copy_value,
325 variant: ButtonVariant::Ghost,
326 {heading_icon(&lucide::COPY)}
327 }
328 }
329 }
330 }
331 }
332 }
333}
334
335fn heading_icon(icon: &'static IconData) -> Element {
337 icon_svg(
338 icon,
339 &format!("{} ui-heading-anchor__icon", icon_svg_class(icon)),
340 )
341}
342
343#[derive(Clone, Debug, Default, PartialEq, Eq)]
345pub struct AnchorLink {
346 pub href: String,
348 pub label: String,
350 pub description: Option<String>,
352 pub depth: Option<u8>,
354 pub index: Option<String>,
356}
357
358impl AnchorLink {
359 pub fn new(href: impl Into<String>, label: impl Into<String>) -> Self {
361 Self {
362 href: href.into(),
363 label: label.into(),
364 ..Self::default()
365 }
366 }
367
368 #[must_use]
370 pub fn depth(mut self, depth: u8) -> Self {
371 self.depth = Some(depth.clamp(1, 6));
372 self
373 }
374}
375
376fn fragment_id(href: &str) -> Option<String> {
378 href.strip_prefix('#')
379 .filter(|fragment| !fragment.is_empty())
380 .map(decode_uri_component)
381}
382
383#[derive(Props, Clone, PartialEq)]
385pub struct AnchorProps {
386 #[props(default)]
388 pub items: Vec<AnchorLink>,
389 #[props(into)]
391 pub value: Option<String>,
392 pub on_value_change: Option<EventHandler<String>>,
394 #[props(default = 96.0)]
397 pub activation_offset: f64,
398 #[props(default = "On this page".to_string(), into)]
400 pub aria_label: String,
401 #[props(into)]
403 pub class: Option<String>,
404 #[props(extends = GlobalAttributes, extends = nav)]
406 pub attributes: Vec<Attribute>,
407 pub children: Element,
409}
410
411#[component]
417pub fn Anchor(props: AnchorProps) -> Element {
418 let first = props
419 .items
420 .first()
421 .map_or_else(String::new, |item| item.href.clone());
422 let active = use_controllable(props.value.clone(), || first, props.on_value_change);
423 let offset = if props.activation_offset.is_finite() {
424 props.activation_offset.max(0.0)
425 } else {
426 0.0
427 };
428 let class = compose([Some("ui-anchor"), props.class.as_deref()]);
429 let current = active.get();
430 let sections: Vec<(String, String)> = props
431 .items
432 .iter()
433 .filter_map(|item| fragment_id(&item.href).map(|id| (id, item.href.clone())))
434 .collect();
435 let mut watcher = use_hook(|| CopyValue::new(None::<Watcher>));
436
437 use_effect(use_reactive(
438 (§ions, &offset),
439 move |(sections, offset)| {
440 if let Some(previous) = watcher.write().take() {
441 previous.stop();
442 }
443
444 if sections.is_empty() {
445 return;
446 }
447
448 let ids = sections.iter().map(|(id, _)| id.clone()).collect();
449 let next = watch_active_section(ids, offset, move |index| {
450 if let Some((_, href)) = sections.get(index) {
451 active.set(href.clone());
452 }
453 });
454 watcher.set(Some(next));
455 },
456 ));
457
458 use_drop(move || {
459 if let Some(previous) = watcher.write().take() {
460 previous.stop();
461 }
462 });
463
464 rsx! {
465 nav {
466 aria_label: props.aria_label,
467 class,
468 "data-ui-anchor": "true",
469 "data-ui-anchor-offset": js_number(offset),
470 "data-ui-owner": "dioxus",
471 ..props.attributes,
472 if !props.items.is_empty() {
473 ol {
474 for item in props.items {
475 {
476 let is_active = item.href == current;
477 let href = item.href.clone();
478
479 rsx! {
480 li { key: "{item.href}",
481 a {
482 aria_current: is_active.then_some("location"),
483 "data-active": if is_active { "true" } else { "false" },
484 "data-depth": item.depth.map(|depth| depth.to_string()),
485 href: item.href.clone(),
486 onclick: move |_| {
487 active.set(href.clone());
488
489 if let Some(id) = fragment_id(&href) {
490 spawn(async move {
491 sleep(Duration::ZERO).await;
493 focus_element_by_id(id, None).await;
494 });
495 }
496 },
497 if let Some(index) = item.index {
498 span { class: "ui-anchor__index", "{index}" }
499 }
500 span { class: "ui-anchor__content",
501 span { class: "ui-anchor__label", "{item.label}" }
502 if let Some(description) = item.description.filter(|text| !text.is_empty()) {
503 span { class: "ui-anchor__description", "{description}" }
504 }
505 }
506 }
507 }
508 }
509 }
510 }
511 }
512 }
513 {props.children}
514 }
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::{
521 HeadingAnchorLevel, fragment_id, heading_anchor_href, heading_anchor_url, heading_label,
522 js_number,
523 };
524
525 #[test]
526 fn heading_hrefs_and_urls_follow_lumen_core() {
527 assert_eq!(
528 heading_anchor_href(" install ").as_deref(),
529 Some("#install")
530 );
531 assert_eq!(heading_anchor_href("a b/c").as_deref(), Some("#a%20b%2Fc"));
532 assert_eq!(heading_anchor_href(" "), None);
533 assert_eq!(
534 heading_anchor_url("install", "https://example.com/docs?x=1#old").as_deref(),
535 Some("https://example.com/docs?x=1#install")
536 );
537 assert_eq!(heading_anchor_url("install", "not a url"), None);
538 assert_eq!(heading_anchor_url("", "https://example.com/"), None);
539 }
540
541 #[test]
542 fn levels_and_labels_normalize() {
543 assert_eq!(HeadingAnchorLevel::from_number(1), HeadingAnchorLevel::H2);
544 assert_eq!(HeadingAnchorLevel::from_number(4).number(), 4);
545 assert_eq!(
546 heading_label(None, " Install ", "Link to section: {heading}"),
547 "Link to section: Install"
548 );
549 assert_eq!(heading_label(Some(" "), "A", "Go {heading}"), "Go A");
550 assert_eq!(heading_label(Some("Ir a {heading}"), "A", "x"), "Ir a A");
551 }
552
553 #[test]
554 fn fragments_decode_and_numbers_format() {
555 assert_eq!(fragment_id("#a%20b").as_deref(), Some("a b"));
556 assert_eq!(fragment_id("#100%").as_deref(), Some("100%"));
557 assert_eq!(fragment_id("/page"), None);
558 assert_eq!(fragment_id("#"), None);
559 assert_eq!(js_number(96.0), "96");
560 assert_eq!(js_number(12.5), "12.5");
561 }
562}