blinc_cn 0.5.0

Blinc Component Library - shadcn-style themed components built on blinc_layout primitives
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
481
482
483
484
485
486
487
488
489
490
//! Drawer component for navigation panels
//!
//! A themed navigation drawer that slides in from the left or right edge.
//! Optimized for navigation menus with a simpler API than Sheet.
//!
//! # Example
//!
//! ```ignore
//! use blinc_cn::prelude::*;
//!
//! // Basic navigation drawer
//! cn::drawer()
//!     .title("Menu")
//!     .child(cn::button("Home").variant(ButtonVariant::Ghost))
//!     .child(cn::button("Profile").variant(ButtonVariant::Ghost))
//!     .child(cn::button("Settings").variant(ButtonVariant::Ghost))
//!     .show();
//!
//! // Drawer from the right
//! cn::drawer()
//!     .side(DrawerSide::Right)
//!     .title("Notifications")
//!     .show();
//!
//! // Drawer with header and footer
//! cn::drawer()
//!     .header(|| {
//!         div().flex_row().gap_2()
//!             .child(avatar("JD"))
//!             .child(text("John Doe"))
//!     })
//!     .child(navigation_items())
//!     .footer(|| cn::button("Logout").variant(ButtonVariant::Destructive))
//!     .show();
//! ```

use std::sync::Arc;

use blinc_animation::{AnimationPreset, MultiKeyframeAnimation};
use blinc_core::Color;
use blinc_layout::motion::motion_derived;
use blinc_layout::overlay_state::get_overlay_manager;
use blinc_layout::prelude::*;
use blinc_layout::widgets::overlay::{BackdropConfig, EdgeSide, OverlayHandle, OverlayManagerExt};
use blinc_layout::InstanceKey;
use blinc_theme::{ColorToken, RadiusToken, ThemeState};

/// Drawer side variants
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DrawerSide {
    /// Slide in from the left edge (default, standard for navigation)
    #[default]
    Left,
    /// Slide in from the right edge
    Right,
}

/// Drawer size variants
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DrawerSize {
    /// Narrow drawer (240px)
    Narrow,
    /// Medium drawer (280px)
    #[default]
    Medium,
    /// Wide drawer (320px)
    Wide,
}

impl DrawerSize {
    /// Get the width in pixels
    pub fn width(&self) -> f32 {
        match self {
            DrawerSize::Narrow => 240.0,
            DrawerSize::Medium => 280.0,
            DrawerSize::Wide => 320.0,
        }
    }
}

/// Builder for creating and showing drawers
pub struct DrawerBuilder {
    side: DrawerSide,
    size: DrawerSize,
    title: Option<String>,
    header: Option<Arc<dyn Fn() -> Div + Send + Sync>>,
    children: Vec<Arc<dyn Fn() -> Div + Send + Sync>>,
    footer: Option<Arc<dyn Fn() -> Div + Send + Sync>>,
    show_close: bool,
    on_close: Option<Arc<dyn Fn() + Send + Sync>>,
    /// Animation duration in ms
    animation_duration: u32,
    /// User-added CSS classes
    classes: Vec<String>,
    /// User-set element ID
    user_id: Option<String>,
    /// Unique key for motion animation
    key: InstanceKey,
}

impl DrawerBuilder {
    /// Create a new drawer builder
    #[track_caller]
    pub fn new() -> Self {
        Self {
            side: DrawerSide::Left,
            size: DrawerSize::Medium,
            title: None,
            header: None,
            children: Vec::new(),
            footer: None,
            show_close: true,
            on_close: None,
            animation_duration: 250,
            key: InstanceKey::new("drawer"),
            classes: Vec::new(),
            user_id: None,
        }
    }

    /// Set which side the drawer slides from
    pub fn side(mut self, side: DrawerSide) -> Self {
        self.side = side;
        self
    }

    /// Set the drawer size
    pub fn size(mut self, size: DrawerSize) -> Self {
        self.size = size;
        self
    }

    /// Set the drawer title (shown in header)
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set custom header content (replaces title)
    pub fn header<F>(mut self, header: F) -> Self
    where
        F: Fn() -> Div + Send + Sync + 'static,
    {
        self.header = Some(Arc::new(header));
        self
    }

    /// Add a child element to the drawer body
    pub fn child<F>(mut self, child: F) -> Self
    where
        F: Fn() -> Div + Send + Sync + 'static,
    {
        self.children.push(Arc::new(child));
        self
    }

    /// Add a child element builder directly (for Button, etc.)
    pub fn child_builder<B: ElementBuilder + Clone + Send + Sync + 'static>(
        mut self,
        builder: B,
    ) -> Self {
        self.children
            .push(Arc::new(move || div().child(builder.clone())));
        self
    }

    /// Set custom footer content
    pub fn footer<F>(mut self, footer: F) -> Self
    where
        F: Fn() -> Div + Send + Sync + 'static,
    {
        self.footer = Some(Arc::new(footer));
        self
    }

    /// Show or hide the close button
    pub fn show_close(mut self, show: bool) -> Self {
        self.show_close = show;
        self
    }

    /// Set the callback for when the drawer is closed
    pub fn on_close<F>(mut self, callback: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.on_close = Some(Arc::new(callback));
        self
    }

    /// Set animation duration in milliseconds
    pub fn animation_duration(mut self, duration_ms: u32) -> Self {
        self.animation_duration = duration_ms;
        self
    }

    /// Add a CSS class for selector matching
    pub fn class(mut self, name: impl Into<String>) -> Self {
        self.classes.push(name.into());
        self
    }

    /// Set the element ID for CSS selector matching
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.user_id = Some(id.into());
        self
    }

    /// Get the enter animation for this drawer's side
    fn get_enter_animation(&self) -> MultiKeyframeAnimation {
        let distance = self.size.width();
        match self.side {
            DrawerSide::Left => AnimationPreset::slide_in_left(self.animation_duration, distance),
            DrawerSide::Right => AnimationPreset::slide_in_right(self.animation_duration, distance),
        }
    }

    /// Get the exit animation for this drawer's side
    fn get_exit_animation(&self) -> MultiKeyframeAnimation {
        let exit_duration = (self.animation_duration as f32 * 0.7) as u32;
        let distance = self.size.width();
        match self.side {
            DrawerSide::Left => AnimationPreset::slide_out_left(exit_duration, distance),
            DrawerSide::Right => AnimationPreset::slide_out_right(exit_duration, distance),
        }
    }

    /// Show the drawer
    pub fn show(self) -> OverlayHandle {
        let theme = ThemeState::get();
        let bg = theme.color(ColorToken::Surface);
        let border = theme.color(ColorToken::Border);
        let text_primary = theme.color(ColorToken::TextPrimary);
        let text_secondary = theme.color(ColorToken::TextSecondary);

        // Get animations before moving other fields
        let enter_animation = self.get_enter_animation();
        let exit_animation = self.get_exit_animation();

        let side = self.side;
        let size = self.size;
        let title = self.title;
        let header = self.header;
        let children = self.children;
        let footer = self.footer;
        let show_close = self.show_close;
        let on_close = self.on_close;

        let mgr = get_overlay_manager();

        // Create a unique motion key for this drawer instance
        let motion_key_str = format!("drawer_{}", self.key.get());
        let motion_key_with_child = format!("{}:child:0", motion_key_str);

        // Convert DrawerSide to EdgeSide for overlay positioning
        let edge_side = match side {
            DrawerSide::Left => EdgeSide::Left,
            DrawerSide::Right => EdgeSide::Right,
        };

        // Drawer panel size: width is fixed, height fills viewport
        let drawer_width = size.width();

        mgr.modal()
            .dismiss_on_escape(true)
            .backdrop(BackdropConfig::dark().dismiss_on_click(true))
            .edge_position(edge_side)
            .size(drawer_width, 10000.0) // Large height to fill viewport
            .motion_key(&motion_key_with_child)
            .content(move || {
                build_drawer_content(
                    side,
                    size,
                    &title,
                    &header,
                    &children,
                    &footer,
                    show_close,
                    &on_close,
                    bg,
                    border,
                    text_primary,
                    text_secondary,
                    &enter_animation,
                    &exit_animation,
                    &motion_key_str,
                )
            })
            .show()
    }
}

impl Default for DrawerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Create a new drawer builder
///
/// # Example
///
/// ```ignore
/// cn::drawer()
///     .title("Navigation")
///     .child(|| cn::button("Home").variant(ButtonVariant::Ghost))
///     .child(|| cn::button("Settings").variant(ButtonVariant::Ghost))
///     .show();
/// ```
#[track_caller]
pub fn drawer() -> DrawerBuilder {
    DrawerBuilder::new()
}

/// Build the drawer content
#[allow(clippy::too_many_arguments)]
fn build_drawer_content(
    side: DrawerSide,
    size: DrawerSize,
    title: &Option<String>,
    header: &Option<Arc<dyn Fn() -> Div + Send + Sync>>,
    children: &[Arc<dyn Fn() -> Div + Send + Sync>],
    footer: &Option<Arc<dyn Fn() -> Div + Send + Sync>>,
    show_close: bool,
    on_close: &Option<Arc<dyn Fn() + Send + Sync>>,
    bg: Color,
    border: Color,
    text_primary: Color,
    text_secondary: Color,
    enter_animation: &MultiKeyframeAnimation,
    exit_animation: &MultiKeyframeAnimation,
    motion_key: &str,
) -> Div {
    let theme = ThemeState::get();
    let radius = theme.radius(RadiusToken::Lg);

    // Determine rounded corners based on side
    let border_radius = match side {
        DrawerSide::Left => (0.0, radius, radius, 0.0), // Right corners rounded
        DrawerSide::Right => (radius, 0.0, 0.0, radius), // Left corners rounded
    };

    // Build drawer panel
    let mut drawer = div()
        .class("cn-drawer")
        .w(size.width())
        .h_full()
        .bg(bg)
        .border(1.0, border)
        .shadow_xl()
        .flex_col()
        .overflow_clip();

    // Apply rounded corners
    let (tl, tr, br, bl) = border_radius;
    drawer = drawer.rounded_corners(tl, tr, br, bl);

    // Header section
    let has_header = header.is_some() || title.is_some() || show_close;
    if has_header {
        // padding from CSS: .cn-drawer-header { padding: 16px; }
        let mut header_div = div()
            .class("cn-drawer-header")
            .w_full()
            .flex_row()
            .items_center()
            .justify_between();

        // Custom header or title
        if let Some(ref header_fn) = header {
            header_div = header_div.child(header_fn());
        } else if let Some(ref title_text) = title {
            header_div = header_div.child(
                text(title_text)
                    .size(theme.typography().text_lg)
                    .color(text_primary)
                    .semibold(),
            );
        } else {
            // Empty spacer for alignment when only close button
            header_div = header_div.child(div());
        }

        // Close button
        if show_close {
            let close_icon = r#"<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" x2="6" y1="6" y2="18"/><line x1="6" x2="18" y1="6" y2="18"/></svg>"#;

            let on_close_clone = on_close.clone();
            header_div = header_div.child(
                div()
                    .w(32.0)
                    .h(32.0)
                    .items_center()
                    .rounded(theme.radius(RadiusToken::Sm))
                    .cursor_pointer()
                    .on_click(move |_| {
                        if let Some(ref cb) = on_close_clone {
                            cb();
                        }
                        get_overlay_manager().close_top();
                    })
                    .child(svg(close_icon).size(18.0, 18.0).color(text_secondary)),
            );
        }

        drawer = drawer.child(header_div);

        // Separator under header
        drawer = drawer.child(div().w_full().h(1.0).bg(border));
    }

    // Body section with children (scrollable)
    if !children.is_empty() {
        let mut body = div()
            .flex_1()
            .w_full()
            .flex_col()
            .gap_1()
            .p_2()
            .overflow_scroll();

        for child_fn in children {
            body = body.child(child_fn());
        }

        drawer = drawer.child(body);
    }

    // Footer section
    if let Some(ref footer_fn) = footer {
        // Push footer to bottom with spacer if no children
        if children.is_empty() {
            drawer = drawer.child(div().flex_1());
        }

        drawer = drawer.child(div().w_full().h(1.0).bg(border)); // Separator
                                                                 // padding from CSS: .cn-drawer-footer { padding: 16px; }
        drawer = drawer.child(div().class("cn-drawer-footer").w_full().child(footer_fn()));
    }

    // Wrap drawer panel in motion for slide animations
    // The overlay system handles positioning via Edge position type
    div().child(
        motion_derived(motion_key)
            .enter_animation(enter_animation.clone())
            .exit_animation(exit_animation.clone())
            .child(drawer),
    )
}

/// Convenience function for a left-side drawer (navigation)
#[track_caller]
pub fn drawer_left() -> DrawerBuilder {
    drawer().side(DrawerSide::Left)
}

/// Convenience function for a right-side drawer
#[track_caller]
pub fn drawer_right() -> DrawerBuilder {
    drawer().side(DrawerSide::Right)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_drawer_builder() {
        let builder = drawer()
            .side(DrawerSide::Right)
            .size(DrawerSize::Wide)
            .title("Test");

        assert_eq!(builder.side, DrawerSide::Right);
        assert_eq!(builder.size, DrawerSize::Wide);
        assert_eq!(builder.title, Some("Test".to_string()));
    }

    #[test]
    fn test_drawer_sizes() {
        assert_eq!(DrawerSize::Narrow.width(), 240.0);
        assert_eq!(DrawerSize::Medium.width(), 280.0);
        assert_eq!(DrawerSize::Wide.width(), 320.0);
    }

    #[test]
    fn test_drawer_sides() {
        assert_eq!(DrawerSide::default(), DrawerSide::Left);
    }
}