dioxus_components 0.1.2

A comprehensive collection of reusable Dioxus 0.7 components built with Tailwind CSS v4
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use crate::components::portal::Portal;
use dioxus::prelude::*;
use wasm_bindgen::JsCast;

/* -------------------------------------------------------------------------------------------------
 * Dialog Context
 * -----------------------------------------------------------------------------------------------*/

#[derive(Clone)]
struct DialogContext {
    open: Signal<bool>,
    modal: bool,
    content_id: String,
    title_id: String,
    description_id: String,
    on_open_change: Option<EventHandler<bool>>,
}

/* -------------------------------------------------------------------------------------------------
 * Dialog (Root)
 * -----------------------------------------------------------------------------------------------*/

#[component]
pub fn Dialog(
    /// Controlled open state
    open: Option<bool>,
    /// Whether the dialog is open by default (uncontrolled)
    #[props(default = false)]
    default_open: bool,
    /// Callback when open state changes (for controlled mode)
    on_open_change: Option<EventHandler<bool>>,
    /// Whether the dialog is modal (blocks interaction with content behind it)
    #[props(default = true)]
    modal: bool,
    children: Element,
) -> Element {
    // Controlled vs Uncontrolled state
    let mut internal_open = use_signal(|| open.unwrap_or(default_open));

    // Sync controlled state if provided
    use_effect(move || {
        if let Some(controlled_open) = open {
            internal_open.set(controlled_open);
        }
    });

    // Generate unique IDs for accessibility
    let content_id = use_memo(move || {
        format!(
            "dialog-content-{}",
            (js_sys::Math::random() * 1_000_000_000.0) as u64
        )
    });
    let title_id = use_memo(move || {
        format!(
            "dialog-title-{}",
            (js_sys::Math::random() * 1_000_000_000.0) as u64
        )
    });
    let description_id = use_memo(move || {
        format!(
            "dialog-description-{}",
            (js_sys::Math::random() * 1_000_000_000.0) as u64
        )
    });

    let context = DialogContext {
        open: internal_open,
        modal,
        content_id: content_id().to_string(),
        title_id: title_id().to_string(),
        description_id: description_id().to_string(),
        on_open_change,
    };

    use_context_provider(|| context);

    rsx! { {children} }
}

/* -------------------------------------------------------------------------------------------------
 * DialogTrigger
 * -----------------------------------------------------------------------------------------------*/

#[component]
pub fn DialogTrigger(
    #[props(extends = GlobalAttributes)] attributes: Vec<Attribute>,
    children: Element,
) -> Element {
    let context = use_context::<DialogContext>();
    let mut open = context.open;

    let onclick = move |_event: Event<MouseData>| {
        let new_state = !open();
        open.set(new_state);

        // Call on_open_change callback if provided
        if let Some(handler) = &context.on_open_change {
            handler.call(new_state);
        }
    };

    rsx! {
        button {
            r#type: "button",
            "aria-haspopup": "dialog",
            "aria-expanded": if open() { "true" } else { "false" },
            "aria-controls": context.content_id,
            "data-state": if open() { "open" } else { "closed" },
            onclick: onclick,
            ..attributes,
            {children}
        }
    }
}

/* -------------------------------------------------------------------------------------------------
 * DialogOverlay
 * -----------------------------------------------------------------------------------------------*/

#[component]
pub fn DialogOverlay(
    #[props(extends = GlobalAttributes)] attributes: Vec<Attribute>,
    #[props(default = String::new())] class: String,
    children: Element,
) -> Element {
    let context = use_context::<DialogContext>();
    let open = context.open;

    if !context.modal {
        return rsx! { {children} };
    }

    if !open() {
        return rsx! {};
    }

    let combined_class = if class.is_empty() {
        "dialog-overlay".to_string()
    } else {
        format!("dialog-overlay {}", class)
    };

    rsx! {
        div {
            class: combined_class,
            "data-state": if open() { "open" } else { "closed" },
            style: "position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); z-index: 9998; pointer-events: auto;",
            ..attributes,
            {children}
        }
    }
}

/* -------------------------------------------------------------------------------------------------
 * DialogContent
 * -----------------------------------------------------------------------------------------------*/

#[component]
pub fn DialogContent(
    #[props(extends = GlobalAttributes)] attributes: Vec<Attribute>,
    #[props(default = String::new())] class: String,
    /// Container element selector for the portal (default: "body")
    #[props(default = "body".to_string())]
    container: String,
    /// Whether clicking outside should close the dialog
    #[props(default = true)]
    close_on_outside_click: bool,
    /// Whether pressing Escape should close the dialog
    #[props(default = true)]
    close_on_escape: bool,
    children: Element,
) -> Element {
    let context = use_context::<DialogContext>();
    let mut open = context.open;
    let content_id = context.content_id.clone();
    let is_modal = context.modal;

    if !open() {
        return rsx! {};
    }

    let combined_class = if class.is_empty() {
        "dialog-content".to_string()
    } else {
        format!("dialog-content {}", class)
    };

    // Clone context fields we need for the JSX
    let modal = context.modal;
    let content_id_for_jsx = context.content_id.clone();
    let title_id_for_jsx = context.title_id.clone();
    let description_id_for_jsx = context.description_id.clone();
    let on_open_change = context.on_open_change.clone();

    // Body scroll lock for modal dialogs (with layout shift prevention)
    use_effect(move || {
        if open() && is_modal {
            // Lock body scroll using JavaScript with scrollbar width compensation
            let lock_scroll_js = r#"
                (function() {
                    if (!document.body) return;
                    
                    // Calculate scrollbar width before hiding it
                    const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
                    
                    // Store original values for restoration
                    window._originalOverflow = document.body.style.overflow;
                    window._originalPaddingRight = document.body.style.paddingRight;
                    
                    // Lock scroll and compensate for scrollbar width
                    document.body.style.overflow = 'hidden';
                    if (scrollbarWidth > 0) {
                        document.body.style.paddingRight = scrollbarWidth + 'px';
                    }
                })();
            "#;

            if let Ok(_) = js_sys::eval(lock_scroll_js) {
                // Scroll is locked with layout shift prevention
            }
        } else {
            // Unlock scroll and restore original padding
            let unlock_scroll_js = r#"
                (function() {
                    if (!document.body) return;
                    
                    // Restore original values
                    document.body.style.overflow = window._originalOverflow || '';
                    document.body.style.paddingRight = window._originalPaddingRight || '';
                    
                    // Clean up stored values
                    delete window._originalOverflow;
                    delete window._originalPaddingRight;
                })();
            "#;

            let _ = js_sys::eval(unlock_scroll_js);
        }
    });

    // Focus trap for modal dialogs
    use_effect(move || {
        if !open() || !is_modal {
            return;
        }

        let dialog_id = content_id.clone();

        // Set up focus trap using JavaScript
        let trap_js = format!(
            r#"
            (function() {{
                const dialog = document.getElementById('{}');
                if (!dialog) return;
                
                // Focus first focusable element
                const focusableElements = dialog.querySelectorAll(
                    'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
                );
                if (focusableElements.length > 0) {{
                    focusableElements[0].focus();
                }}
                
                // Set up focus trap
                const handleTab = (e) => {{
                    if (e.key !== 'Tab') return;
                    
                    const focusable = Array.from(focusableElements);
                    const firstFocusable = focusable[0];
                    const lastFocusable = focusable[focusable.length - 1];
                    
                    if (e.shiftKey) {{
                        if (document.activeElement === firstFocusable) {{
                            lastFocusable.focus();
                            e.preventDefault();
                        }}
                    }} else {{
                        if (document.activeElement === lastFocusable) {{
                            firstFocusable.focus();
                            e.preventDefault();
                        }}
                    }}
                }};
                
                dialog.addEventListener('keydown', handleTab);
                
                // Store cleanup function
                window._dialogFocusTrapCleanup = () => {{
                    dialog.removeEventListener('keydown', handleTab);
                }};
            }})();
            "#,
            dialog_id
        );

        let _ = js_sys::eval(&trap_js);
    });

    // Enhanced Escape key handler
    use_effect(move || {
        if !close_on_escape || !open() {
            return;
        }

        let escape_handler_js = format!(
            r#"
            (function() {{
                const handleEscape = (e) => {{
                    if (e.key === 'Escape') {{
                        e.preventDefault();
                        e.stopPropagation();
                        // This will be handled by the Dialog state
                    }}
                }};
                
                document.addEventListener('keydown', handleEscape);
                
                window._dialogEscapeCleanup = () => {{
                    document.removeEventListener('keydown', handleEscape);
                }};
            }})();
            "#
        );

        let _ = js_sys::eval(&escape_handler_js);

        // Also set up Dioxus event handler
        let ctx_for_handler = context.clone();
        let closure =
            wasm_bindgen::closure::Closure::wrap(Box::new(move |e: web_sys::KeyboardEvent| {
                if e.key() == "Escape" {
                    e.prevent_default();
                    e.stop_propagation();
                    open.set(false);

                    // Call on_open_change callback if provided
                    if let Some(handler) = &ctx_for_handler.on_open_change {
                        handler.call(false);
                    }
                }
            }) as Box<dyn FnMut(_)>);

        if let Some(window) = web_sys::window() {
            if let Some(document) = window.document() {
                let _ = document
                    .add_event_listener_with_callback("keydown", closure.as_ref().unchecked_ref());
            }
        }

        closure.forget();
    });

    // Handle backdrop click
    let on_backdrop_click = move |_event: Event<MouseData>| {
        if close_on_outside_click {
            open.set(false);

            // Call on_open_change callback if provided
            if let Some(handler) = &on_open_change {
                handler.call(false);
            }
        }
    };

    rsx! {
        Portal {
            container,
            // Backdrop overlay
            if modal {
                div {
                    class: "dialog-backdrop",
                    style: "position: fixed; inset: 0; z-index: 9998;",
                    onclick: on_backdrop_click,
                }
            }
            // Dialog content
            div {
                role: "dialog",
                id: content_id_for_jsx,
                "aria-labelledby": title_id_for_jsx,
                "aria-describedby": description_id_for_jsx,
                "aria-modal": if modal { "true" } else { "false" },
                "data-state": if open() { "open" } else { "closed" },
                class: combined_class,
                style: "position: fixed; z-index: 9999;",
                tabindex: "-1",
                ..attributes,
                {children}
            }
        }
    }
}

/* -------------------------------------------------------------------------------------------------
 * DialogTitle
 * -----------------------------------------------------------------------------------------------*/

#[component]
pub fn DialogTitle(
    #[props(extends = GlobalAttributes)] attributes: Vec<Attribute>,
    #[props(default = String::new())] class: String,
    children: Element,
) -> Element {
    let context = use_context::<DialogContext>();

    let combined_class = if class.is_empty() {
        "dialog-title".to_string()
    } else {
        format!("dialog-title {}", class)
    };

    rsx! {
        h2 {
            id: context.title_id,
            class: combined_class,
            ..attributes,
            {children}
        }
    }
}

/* -------------------------------------------------------------------------------------------------
 * DialogDescription
 * -----------------------------------------------------------------------------------------------*/

#[component]
pub fn DialogDescription(
    #[props(extends = GlobalAttributes)] attributes: Vec<Attribute>,
    #[props(default = String::new())] class: String,
    children: Element,
) -> Element {
    let context = use_context::<DialogContext>();

    let combined_class = if class.is_empty() {
        "dialog-description".to_string()
    } else {
        format!("dialog-description {}", class)
    };

    rsx! {
        p {
            id: context.description_id,
            class: combined_class,
            ..attributes,
            {children}
        }
    }
}

/* -------------------------------------------------------------------------------------------------
 * DialogClose
 * -----------------------------------------------------------------------------------------------*/

#[component]
pub fn DialogClose(
    #[props(extends = GlobalAttributes)] attributes: Vec<Attribute>,
    children: Element,
) -> Element {
    let context = use_context::<DialogContext>();
    let mut open = context.open;

    let onclick = move |_event: Event<MouseData>| {
        open.set(false);

        // Call on_open_change callback if provided
        if let Some(handler) = &context.on_open_change {
            handler.call(false);
        }
    };

    rsx! {
        button {
            r#type: "button",
            onclick: onclick,
            ..attributes,
            {children}
        }
    }
}