Skip to main content

lumen_dioxus/navigation/
links.rs

1//! `Link`, `SkipLink`, `ButtonLink`, and `ButtonGroup`.
2
3use dioxus::prelude::*;
4
5use crate::class::compose;
6
7/// Color treatment of a [`Link`].
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum LinkVariant {
11    /// Brand-colored, underlined link.
12    #[default]
13    Default,
14    /// Inherits the surrounding text color.
15    Inherit,
16}
17
18impl LinkVariant {
19    /// The `data-variant` value.
20    pub fn as_str(self) -> &'static str {
21        match self {
22            Self::Default => "default",
23            Self::Inherit => "inherit",
24        }
25    }
26}
27
28/// `rel` with `noopener noreferrer` added once, keeping the author's tokens first.
29fn new_tab_rel(rel: Option<&str>) -> String {
30    let mut tokens: Vec<&str> = Vec::new();
31
32    for token in rel
33        .unwrap_or_default()
34        .split_whitespace()
35        .chain(["noopener", "noreferrer"])
36    {
37        if !tokens.contains(&token) {
38            tokens.push(token);
39        }
40    }
41
42    tokens.join(" ")
43}
44
45/// Props for [`Link`].
46#[derive(Props, Clone, PartialEq)]
47pub struct LinkProps {
48    /// Opens the destination in a new tab and adds `noopener noreferrer` to `rel`.
49    #[props(default)]
50    pub new_tab: bool,
51    /// Color treatment.
52    #[props(default)]
53    pub variant: LinkVariant,
54    /// Link relationship. `new_tab` adds `noopener noreferrer`.
55    #[props(into)]
56    pub rel: Option<String>,
57    /// Browsing context. `new_tab` sets `_blank`.
58    #[props(into)]
59    pub target: Option<String>,
60    /// Extra classes appended after the Lumen classes.
61    #[props(into)]
62    pub class: Option<String>,
63    /// Click handler. Call `prevent_default` on the event to route inside the app instead.
64    pub onclick: Option<EventHandler<MouseEvent>>,
65    /// Any other `<a>` or global attribute, such as `href`.
66    #[props(extends = GlobalAttributes, extends = a)]
67    pub attributes: Vec<Attribute>,
68    /// Link text.
69    pub children: Element,
70}
71
72/// An inline text link.
73#[component]
74pub fn Link(props: LinkProps) -> Element {
75    let class = compose([
76        Some("ui-link"),
77        (props.variant == LinkVariant::Inherit).then_some("ui-link--inherit"),
78        props.class.as_deref(),
79    ]);
80    let rel = if props.new_tab {
81        Some(new_tab_rel(props.rel.as_deref()))
82    } else {
83        props.rel
84    };
85    let target = if props.new_tab {
86        Some("_blank".to_string())
87    } else {
88        props.target
89    };
90    let onclick = props.onclick;
91
92    rsx! {
93        a {
94            class,
95            "data-slot": "link",
96            "data-variant": props.variant.as_str(),
97            rel,
98            target,
99            onclick: move |event| {
100                if let Some(handler) = onclick {
101                    handler.call(event);
102                }
103            },
104            ..props.attributes,
105            {props.children}
106        }
107    }
108}
109
110/// Props for [`SkipLink`].
111#[derive(Props, Clone, PartialEq)]
112pub struct SkipLinkProps {
113    /// Extra classes appended after the Lumen class.
114    #[props(into)]
115    pub class: Option<String>,
116    /// Any other `<a>` or global attribute. Point `href` at the main content, such as `#main`.
117    #[props(extends = GlobalAttributes, extends = a)]
118    pub attributes: Vec<Attribute>,
119    /// Link text, such as "Skip to content".
120    pub children: Element,
121}
122
123/// A link that stays hidden until it receives keyboard focus, for skipping repeated navigation.
124#[component]
125pub fn SkipLink(props: SkipLinkProps) -> Element {
126    let class = compose([Some("ui-skip-link"), props.class.as_deref()]);
127
128    rsx! {
129        a { class, ..props.attributes, {props.children} }
130    }
131}
132
133/// Visual treatment of a [`ButtonLink`].
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum ButtonLinkVariant {
137    /// Solid brand button.
138    #[default]
139    Primary,
140    /// Quiet filled button.
141    Secondary,
142    /// Bordered button without a fill, like Button's outline variant.
143    Outline,
144    /// Button without a fill or border.
145    Ghost,
146    /// A button-styled inline link.
147    Inline,
148    /// Only the `ui-button-link` hook, for custom styling.
149    Unstyled,
150}
151
152impl ButtonLinkVariant {
153    /// The variant classes, including the radius and border utilities lumen-react adds to styled
154    /// variants. Height comes from the shared Button token.
155    fn class(self) -> &'static str {
156        match self {
157            Self::Unstyled => "ui-button-link--unstyled",
158            Self::Inline => "ui-button ui-button--inline",
159            Self::Primary => {
160                "ui-button ui-button--primary rounded-[var(--ui-button-link-radius,9999px)] border"
161            }
162            Self::Secondary => {
163                "ui-button ui-button--secondary rounded-[var(--ui-button-link-radius,9999px)] border"
164            }
165            Self::Outline => {
166                "ui-button ui-button--outline rounded-[var(--ui-button-link-radius,9999px)] border"
167            }
168            Self::Ghost => {
169                "ui-button ui-button--ghost rounded-[var(--ui-button-link-radius,9999px)] border"
170            }
171        }
172    }
173}
174
175/// Shape of a [`ButtonLink`].
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
177#[non_exhaustive]
178pub enum ButtonLinkShape {
179    /// Text and optional icons.
180    #[default]
181    Default,
182    /// Square icon-only link. Give it an `aria_label`.
183    Icon,
184}
185
186/// Layout utilities lumen-react adds to every styled button link.
187const BUTTON_LINK_LAYOUT: &str = "group inline-flex cursor-pointer items-center justify-center gap-2 text-sm font-semibold tracking-[0.01em]";
188
189/// Props for [`ButtonLink`].
190#[derive(Props, Clone, PartialEq)]
191pub struct ButtonLinkProps {
192    /// Visual treatment.
193    #[props(default)]
194    pub variant: ButtonLinkVariant,
195    /// Text or icon-only shape. Ignored by the inline variant.
196    #[props(default)]
197    pub shape: ButtonLinkShape,
198    /// Extra classes appended after the Lumen classes.
199    #[props(into)]
200    pub class: Option<String>,
201    /// Click handler. Call `prevent_default` on the event to route inside the app instead.
202    pub onclick: Option<EventHandler<MouseEvent>>,
203    /// Any other `<a>` or global attribute, such as `href`.
204    #[props(extends = GlobalAttributes, extends = a)]
205    pub attributes: Vec<Attribute>,
206    /// Link text and icons.
207    pub children: Element,
208}
209
210/// A link styled as a button, for navigation that looks like an action.
211///
212/// lumen-react's `asChild` has no Dioxus equivalent; wrap your router link's content instead, or
213/// pass the same classes to it.
214#[component]
215pub fn ButtonLink(props: ButtonLinkProps) -> Element {
216    let styled = props.variant != ButtonLinkVariant::Unstyled;
217    let icon = props.shape == ButtonLinkShape::Icon && props.variant != ButtonLinkVariant::Inline;
218    let class = compose([
219        Some("ui-button-link"),
220        styled.then_some(BUTTON_LINK_LAYOUT),
221        Some(props.variant.class()),
222        icon.then_some("ui-button-link--icon"),
223        props.class.as_deref(),
224    ]);
225
226    let onclick = props.onclick;
227
228    rsx! {
229        a {
230            class,
231            "data-slot": "button-link",
232            onclick: move |event| {
233                if let Some(handler) = onclick {
234                    handler.call(event);
235                }
236            },
237            ..props.attributes,
238            {props.children}
239        }
240    }
241}
242
243/// Props for [`ButtonGroup`].
244#[derive(Props, Clone, PartialEq)]
245pub struct ButtonGroupProps {
246    /// Extra classes appended after the Lumen class.
247    #[props(into)]
248    pub class: Option<String>,
249    /// Any other `<div>` or global attribute. Name the group with `role: "group"` and
250    /// `aria_label` when the buttons belong together.
251    #[props(extends = GlobalAttributes, extends = div)]
252    pub attributes: Vec<Attribute>,
253    /// The buttons.
254    pub children: Element,
255}
256
257/// Joins related buttons into one segmented control.
258#[component]
259pub fn ButtonGroup(props: ButtonGroupProps) -> Element {
260    let class = compose([Some("ui-button-group"), props.class.as_deref()]);
261
262    rsx! {
263        div { class, ..props.attributes, {props.children} }
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::new_tab_rel;
270
271    #[test]
272    fn new_tab_rel_adds_tokens_once() {
273        assert_eq!(new_tab_rel(None), "noopener noreferrer");
274        assert_eq!(new_tab_rel(Some("me noopener")), "me noopener noreferrer");
275        assert_eq!(new_tab_rel(Some("  ")), "noopener noreferrer");
276    }
277}