Skip to main content

dioxus_bootstrap_css/
dropdown.rs

1use dioxus::prelude::*;
2
3/// Bootstrap Dropdown component — signal-driven, no JavaScript.
4///
5/// Replaces Bootstrap's dropdown JavaScript plugin with signal-controlled open/close.
6/// Supports split buttons, drop directions, and auto-closes on outside click.
7///
8/// # Bootstrap HTML → Dioxus
9///
10/// ```html
11/// <!-- Bootstrap HTML (requires JavaScript) -->
12/// <div class="dropdown">
13///   <button class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown">Menu</button>
14///   <ul class="dropdown-menu">
15///     <li><button class="dropdown-item">Action</button></li>
16///     <li><hr class="dropdown-divider"></li>
17///     <li><button class="dropdown-item">Other</button></li>
18///   </ul>
19/// </div>
20/// ```
21///
22/// ```rust,no_run
23/// # use dioxus::prelude::*;
24/// # use dioxus_bootstrap_css::prelude::*;
25/// # fn _doctest() -> Element {
26/// // Dioxus equivalent
27/// let open = use_signal(|| false);
28/// rsx! {
29///     Dropdown { open: open,
30///         toggle: rsx! { "Menu" },
31///         menu: rsx! {
32///             DropdownItem { "Action" }
33///             DropdownDivider {}
34///             DropdownItem { "Other" }
35///         },
36///     }
37///     // Split button variant
38///     Dropdown { open: open, split: true, color: Color::Danger,
39///         toggle: rsx! { "Delete" },
40///         menu: rsx! { DropdownItem { "Confirm Delete" } },
41///     }
42/// }
43/// # }
44/// ```
45///
46/// # Props
47///
48/// - `open` — `Signal<bool>` controlling open state
49/// - `toggle` — toggle button content (Element)
50/// - `menu` — dropdown menu content (Element)
51/// - `split` — split button mode (separate action button + caret toggle)
52/// - `color` — button color in split mode
53/// - `direction` — `DropDirection::Down`, `Up`, `Start`, `End`
54/// - `align_end` — align menu's right edge to the toggle (works JS-free)
55#[derive(Clone, PartialEq, Props)]
56pub struct DropdownProps {
57    /// Signal controlling dropdown open state.
58    pub open: Signal<bool>,
59    /// Toggle button content.
60    pub toggle: Element,
61    /// Dropdown menu content (DropdownItem components).
62    pub menu: Element,
63    /// Additional CSS classes for the dropdown container.
64    #[props(default)]
65    pub class: String,
66    /// Additional CSS classes for the toggle button.
67    #[props(default)]
68    pub toggle_class: String,
69    /// Drop direction.
70    #[props(default)]
71    pub direction: DropDirection,
72    /// Align menu to the end (right).
73    #[props(default)]
74    pub align_end: bool,
75    /// Split button mode — toggle is a separate caret-only button.
76    #[props(default)]
77    pub split: bool,
78    /// Color for split button mode (used for the main button).
79    #[props(default)]
80    pub color: Option<crate::types::Color>,
81    /// Any additional HTML attributes.
82    #[props(extends = GlobalAttributes)]
83    attributes: Vec<Attribute>,
84}
85
86/// Dropdown direction.
87#[derive(Clone, Copy, Debug, Default, PartialEq)]
88pub enum DropDirection {
89    #[default]
90    Down,
91    Up,
92    Start,
93    End,
94}
95
96#[component]
97pub fn Dropdown(props: DropdownProps) -> Element {
98    let is_open = *props.open.read();
99    let mut open_signal = props.open;
100
101    let dir_class = match props.direction {
102        DropDirection::Down => "dropdown",
103        DropDirection::Up => "dropup",
104        DropDirection::Start => "dropstart",
105        DropDirection::End => "dropend",
106    };
107
108    let container_class = if props.class.is_empty() {
109        dir_class.to_string()
110    } else {
111        format!("{dir_class} {}", props.class)
112    };
113
114    let color_name = match &props.color {
115        Some(c) => format!("{c}"),
116        None => "secondary".to_string(),
117    };
118
119    let toggle_class = if props.split {
120        format!("btn btn-{color_name} dropdown-toggle dropdown-toggle-split")
121    } else if props.toggle_class.is_empty() {
122        format!("btn btn-{color_name} dropdown-toggle")
123    } else {
124        format!("btn dropdown-toggle {}", props.toggle_class)
125    };
126
127    let menu_class = if is_open {
128        if props.align_end {
129            "dropdown-menu dropdown-menu-end show"
130        } else {
131            "dropdown-menu show"
132        }
133    } else if props.align_end {
134        "dropdown-menu dropdown-menu-end"
135    } else {
136        "dropdown-menu"
137    };
138
139    // Bootstrap offsets the menu from the toggle by `--bs-dropdown-spacer` (0.125rem);
140    // in stock Bootstrap that offset is applied by Popper. JS-free, we set it directly
141    // so the menu clears the toggle by the same 2px instead of sitting flush against it.
142    let spacer = match props.direction {
143        DropDirection::Down => "margin-top: var(--bs-dropdown-spacer, 0.125rem);",
144        DropDirection::Up => "margin-bottom: var(--bs-dropdown-spacer, 0.125rem);",
145        DropDirection::Start | DropDirection::End => "",
146    };
147    // JS-free end-alignment: Bootstrap gates .dropdown-menu-end{right:0;left:auto} on
148    // [data-bs-popper] (set only by its JS), so apply the end values directly.
149    let menu_style = if props.align_end {
150        format!("{spacer} right: 0; left: auto;")
151    } else {
152        spacer.to_string()
153    };
154
155    rsx! {
156        // Invisible overlay to close on outside click (only when open)
157        if is_open {
158            div {
159                style: "position: fixed; inset: 0; z-index: 990;",
160                onclick: move |_| open_signal.set(false),
161            }
162        }
163        div { class: "{container_class}",
164            style: if is_open { "position: relative; z-index: 991;" } else { "" },
165            ..props.attributes,
166            // Split mode: main button + separate toggle caret
167            if props.split {
168                button {
169                    class: "btn btn-{color_name}",
170                    r#type: "button",
171                    {props.toggle.clone()}
172                }
173            }
174            button {
175                class: "{toggle_class}",
176                r#type: "button",
177                "aria-expanded": if is_open { "true" } else { "false" },
178                onclick: move |evt| {
179                    evt.stop_propagation();
180                    open_signal.set(!is_open);
181                },
182                if !props.split {
183                    {props.toggle}
184                }
185                if props.split {
186                    span { class: "visually-hidden", "Toggle Dropdown" }
187                }
188            }
189            ul { class: "{menu_class}",
190                style: "{menu_style}",
191                // Close dropdown when clicking an item
192                onclick: move |_| open_signal.set(false),
193                {props.menu}
194            }
195        }
196    }
197}
198
199/// Standalone Bootstrap dropdown menu.
200///
201/// Use this when open/position behavior is owned by a surrounding component
202/// but the menu and items should still use Bootstrap dropdown structure.
203#[derive(Clone, PartialEq, Props)]
204pub struct DropdownMenuProps {
205    /// Whether to show the menu.
206    #[props(default)]
207    pub show: bool,
208    /// Align menu to the end side.
209    #[props(default)]
210    pub align_end: bool,
211    /// Additional CSS classes.
212    #[props(default)]
213    pub class: String,
214    /// Any additional HTML attributes.
215    #[props(extends = GlobalAttributes)]
216    attributes: Vec<Attribute>,
217    /// Child menu items.
218    pub children: Element,
219}
220
221#[component]
222pub fn DropdownMenu(props: DropdownMenuProps) -> Element {
223    let mut classes = vec!["dropdown-menu".to_string()];
224    if props.align_end {
225        classes.push("dropdown-menu-end".to_string());
226    }
227    if props.show {
228        classes.push("show".to_string());
229    }
230    if !props.class.is_empty() {
231        classes.push(props.class.clone());
232    }
233    let full_class = classes.join(" ");
234    // JS-free end-alignment: Bootstrap gates .dropdown-menu-end{right:0;left:auto}
235    // on [data-bs-popper] (set only by its JS), so apply the values directly.
236    let align_style = if props.align_end {
237        "right: 0; left: auto;"
238    } else {
239        ""
240    };
241    rsx! {
242    ul { class: "{full_class}", style: "{align_style}", ..props.attributes, {props.children} }
243    }
244}
245
246/// A single item in a Dropdown menu.
247///
248/// Renders a `<button class="dropdown-item">` by default. Set `href` to render a
249/// real `<a class="dropdown-item" href=...>` instead — use this for menu entries
250/// that navigate to a URL so the browser's link behaviours work (middle-click /
251/// ctrl-click to open in a background tab, copy-link and open-in-new-window
252/// context actions, and a visible target URL on hover). Add `target` (e.g.
253/// `"_blank"`) to open in a new tab. The same `active`, `disabled`, `class`, and
254/// `onclick` props apply to both forms.
255///
256/// ```rust,no_run
257/// # use dioxus::prelude::*;
258/// # use dioxus_bootstrap_css::prelude::*;
259/// # fn _doctest() -> Element {
260/// rsx! {
261///     DropdownItem { "Action" }                                  // <button>
262///     DropdownItem { href: "/settings", "Settings" }             // <a href="/settings">
263///     DropdownItem { href: "https://example.com", target: "_blank", "Docs" }
264/// }
265/// # }
266/// ```
267#[derive(Clone, PartialEq, Props)]
268pub struct DropdownItemProps {
269    /// Active state.
270    #[props(default)]
271    pub active: bool,
272    /// Disabled state.
273    #[props(default)]
274    pub disabled: bool,
275    /// When set, render an `<a class="dropdown-item" href=...>` anchor instead of
276    /// a `<button>` so the item behaves as a real hyperlink. Anchors cannot be
277    /// HTML-`disabled`, so a disabled anchor item carries the `.disabled` class,
278    /// `aria-disabled="true"`, and `tabindex="-1"` (matching `NavLink`).
279    #[props(default)]
280    pub href: Option<String>,
281    /// Anchor `target` (e.g. `"_blank"` to open in a new tab). Only applies when
282    /// `href` is set.
283    #[props(default)]
284    pub target: Option<String>,
285    /// Click event handler.
286    #[props(default)]
287    pub onclick: Option<EventHandler<MouseEvent>>,
288    /// Additional CSS classes.
289    #[props(default)]
290    pub class: String,
291    /// Any additional HTML attributes.
292    #[props(extends = GlobalAttributes)]
293    attributes: Vec<Attribute>,
294    /// Child elements.
295    pub children: Element,
296}
297
298/// Build the class string for a dropdown item (`dropdown-item` + optional
299/// `active`/`disabled` + caller classes). Shared by the `<button>` and `<a>`
300/// render paths so both carry identical classes.
301fn dropdown_item_class(active: bool, disabled: bool, class: &str) -> String {
302    let mut classes = vec!["dropdown-item".to_string()];
303    if active {
304        classes.push("active".to_string());
305    }
306    if disabled {
307        classes.push("disabled".to_string());
308    }
309    if !class.is_empty() {
310        classes.push(class.to_string());
311    }
312    classes.join(" ")
313}
314
315#[component]
316pub fn DropdownItem(props: DropdownItemProps) -> Element {
317    let full_class = dropdown_item_class(props.active, props.disabled, &props.class);
318
319    // Anchor form: a real hyperlink so browser link behaviours work. Anchors
320    // can't be HTML-`disabled`, so disabled state is conveyed by the `.disabled`
321    // class plus `aria-disabled`/`tabindex="-1"` (matching NavLink).
322    if let Some(href) = props.href.clone() {
323        let target = props.target.clone();
324        return rsx! {
325            li {
326                a {
327                    class: "{full_class}",
328                    href: "{href}",
329                    target: target,
330                    "aria-disabled": if props.disabled { "true" } else { "" },
331                    tabindex: if props.disabled { "-1" } else { "" },
332                    onclick: move |evt| {
333                        if let Some(handler) = &props.onclick {
334                            handler.call(evt);
335                        }
336                    },
337                    ..props.attributes,
338                    {props.children}
339                }
340            }
341        };
342    }
343
344    rsx! {
345        li {
346            button {
347                class: "{full_class}",
348                r#type: "button",
349                disabled: props.disabled,
350                onclick: move |evt| {
351                    if let Some(handler) = &props.onclick {
352                        handler.call(evt);
353                    }
354                },
355                ..props.attributes,
356                {props.children}
357            }
358        }
359    }
360}
361
362/// Dropdown menu divider.
363#[component]
364pub fn DropdownDivider() -> Element {
365    rsx! {
366        li { hr { class: "dropdown-divider" } }
367    }
368}
369
370/// Dropdown menu header text.
371#[derive(Clone, PartialEq, Props)]
372pub struct DropdownHeaderProps {
373    /// Any additional HTML attributes.
374    #[props(extends = GlobalAttributes)]
375    attributes: Vec<Attribute>,
376    pub children: Element,
377}
378
379#[component]
380pub fn DropdownHeader(props: DropdownHeaderProps) -> Element {
381    rsx! {
382        li { h6 { class: "dropdown-header", ..props.attributes, {props.children} } }
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn dropdown_item_class_base() {
392        assert_eq!(dropdown_item_class(false, false, ""), "dropdown-item");
393    }
394
395    #[test]
396    fn dropdown_item_class_active_disabled_and_extra() {
397        // Identical class output for the `<button>` and `<a>` render paths.
398        assert_eq!(
399            dropdown_item_class(true, true, "text-danger"),
400            "dropdown-item active disabled text-danger"
401        );
402    }
403
404    #[test]
405    fn dropdown_item_class_active_only() {
406        assert_eq!(dropdown_item_class(true, false, ""), "dropdown-item active");
407    }
408}