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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! Toast component for temporary notifications
//!
//! A themed toast notification that appears in a corner and auto-dismisses.
//! Uses the overlay system for proper positioning and timing.
//!
//! # Example
//!
//! ```ignore
//! use blinc_cn::prelude::*;
//!
//! // Simple toast
//! cn::toast("Operation completed successfully").show();
//!
//! // Toast with title and description
//! cn::toast("Saved")
//!     .description("Your changes have been saved.")
//!     .show();
//!
//! // Different variants
//! cn::toast("Error occurred")
//!     .variant(ToastVariant::Destructive)
//!     .description("Please try again later.")
//!     .show();
//!
//! // With custom duration
//! cn::toast("Quick message")
//!     .duration_ms(2000)
//!     .show();
//!
//! // With action button
//! cn::toast("File deleted")
//!     .action("Undo", || {
//!         println!("Undoing...");
//!     })
//!     .show();
//!
//! // In a specific corner
//! cn::toast("Top left toast")
//!     .corner(Corner::TopLeft)
//!     .show();
//!
//! // With custom body content
//! cn::toast("Download Complete")
//!     .body(|| {
//!         div().flex_col().gap_2()
//!             .child(text("Your file has been downloaded."))
//!             .child(
//!                 div().flex_row().gap_2()
//!                     .child(svg(file_icon).size(16.0, 16.0))
//!                     .child(text("report.pdf"))
//!             )
//!     })
//!     .show();
//!
//! // Fully custom toast content
//! cn::toast_custom(|| {
//!     div().flex_row().gap_3().p_4()
//!         .child(avatar("JD").size(40.0))
//!         .child(
//!             div().flex_col()
//!                 .child(text("John Doe").weight(600))
//!                 .child(text("Sent you a message"))
//!         )
//! })
//! .show();
//! ```

use std::sync::Arc;

use blinc_animation::AnimationPreset;
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::{Corner, OverlayHandle, OverlayManagerExt};
use blinc_layout::InstanceKey;
use blinc_theme::{ColorToken, RadiusToken, ThemeState};

use super::button::{button, ButtonSize, ButtonVariant};

/// Toast visual variants
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ToastVariant {
    /// Default toast styling
    #[default]
    Default,
    /// Success toast - green accent
    Success,
    /// Warning toast - yellow accent
    Warning,
    /// Destructive/error toast - red accent
    Destructive,
}

impl ToastVariant {
    /// Get the accent color for this variant
    fn accent_color(&self, theme: &ThemeState) -> Color {
        match self {
            ToastVariant::Default => theme.color(ColorToken::Primary),
            ToastVariant::Success => theme.color(ColorToken::Success),
            ToastVariant::Warning => theme.color(ColorToken::Warning),
            ToastVariant::Destructive => theme.color(ColorToken::Error),
        }
    }

    /// Get the icon SVG for this variant (optional)
    fn icon_svg(&self) -> Option<&'static str> {
        match self {
            ToastVariant::Default => None,
            ToastVariant::Success => Some(
                r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>"#,
            ),
            ToastVariant::Warning => Some(
                r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><line x1="12" x2="12" y1="9" y2="13"/><line x1="12" x2="12.01" y1="17" y2="17"/></svg>"#,
            ),
            ToastVariant::Destructive => Some(
                r#"<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" x2="9" y1="9" y2="15"/><line x1="9" x2="15" y1="9" y2="15"/></svg>"#,
            ),
        }
    }
}

/// Content builder type for custom toast body
pub type ToastBodyFn = Arc<dyn Fn() -> Div + Send + Sync>;

/// Builder for creating and showing toast notifications
pub struct ToastBuilder {
    title: Option<String>,
    description: Option<String>,
    variant: ToastVariant,
    duration_ms: u32,
    corner: Corner,
    action_label: Option<String>,
    action_callback: Option<Arc<dyn Fn() + Send + Sync>>,
    show_close: bool,
    /// Custom body content (replaces title + description)
    body: Option<ToastBodyFn>,
    /// Fully custom content (replaces entire toast layout)
    custom_content: Option<ToastBodyFn>,
}

impl ToastBuilder {
    /// Create a new toast builder with a title
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: Some(title.into()),
            description: None,
            variant: ToastVariant::Default,
            duration_ms: 5000, // 5 seconds default
            corner: Corner::BottomRight,
            action_label: None,
            action_callback: None,
            show_close: true,
            body: None,
            custom_content: None,
        }
    }

    /// Create a toast builder with fully custom content
    pub fn custom<F>(content: F) -> Self
    where
        F: Fn() -> Div + Send + Sync + 'static,
    {
        Self {
            title: None,
            description: None,
            variant: ToastVariant::Default,
            duration_ms: 5000,
            corner: Corner::BottomRight,
            action_label: None,
            action_callback: None,
            show_close: false,
            body: None,
            custom_content: Some(Arc::new(content)),
        }
    }

    /// Set the toast description
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set custom body content (replaces description, keeps title)
    ///
    /// # Example
    ///
    /// ```ignore
    /// cn::toast("Download Complete")
    ///     .body(|| {
    ///         div().flex_row().gap_2()
    ///             .child(svg(file_icon).size(16.0, 16.0))
    ///             .child(text("report.pdf - 2.4 MB"))
    ///     })
    ///     .show();
    /// ```
    pub fn body<F>(mut self, content: F) -> Self
    where
        F: Fn() -> Div + Send + Sync + 'static,
    {
        self.body = Some(Arc::new(content));
        self
    }

    /// Set the toast variant
    pub fn variant(mut self, variant: ToastVariant) -> Self {
        self.variant = variant;
        self
    }

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

    /// Make the toast persistent (no auto-dismiss)
    pub fn persistent(mut self) -> Self {
        self.duration_ms = 0; // 0 = no auto-dismiss
        self
    }

    /// Set the corner position
    pub fn corner(mut self, corner: Corner) -> Self {
        self.corner = corner;
        self
    }

    /// Add an action button
    pub fn action<F>(mut self, label: impl Into<String>, callback: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.action_label = Some(label.into());
        self.action_callback = Some(Arc::new(callback));
        self
    }

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

    /// Show the toast
    #[track_caller]
    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);
        let radius = theme.radius(RadiusToken::Lg);

        let title = self.title;
        let description = self.description;
        let variant = self.variant;
        let accent_color = variant.accent_color(theme);
        let icon_svg = variant.icon_svg().map(|s| s.to_string());
        let action_label = self.action_label;
        let action_callback = self.action_callback;
        let show_close = self.show_close;
        let corner = self.corner;
        let duration_ms = self.duration_ms;
        let body = self.body;
        let custom_content = self.custom_content;

        let mgr = get_overlay_manager();

        // Create a unique motion key for this toast instance
        let key = InstanceKey::new("toast");
        let motion_key_str = format!("toast_{}", key.get());
        let motion_key_with_child = format!("{}:child:0", motion_key_str);

        let mut toast_builder = mgr
            .toast()
            .corner(corner)
            .motion_key(&motion_key_with_child)
            .content(move || {
                build_toast_content(
                    &title,
                    &description,
                    &icon_svg,
                    accent_color,
                    variant,
                    bg,
                    border,
                    text_primary,
                    text_secondary,
                    radius,
                    &action_label,
                    &action_callback,
                    show_close,
                    &body,
                    &custom_content,
                    corner,
                    &motion_key_str,
                )
            });

        // Set duration if not persistent
        if duration_ms > 0 {
            toast_builder = toast_builder.duration_ms(duration_ms);
        }

        toast_builder.show()
    }
}

/// Get enter animation based on corner
fn get_enter_animation(corner: Corner) -> blinc_animation::MultiKeyframeAnimation {
    const SLIDE_DISTANCE: f32 = 200.0;
    match corner {
        Corner::TopLeft | Corner::BottomLeft => AnimationPreset::slide_in_left(200, SLIDE_DISTANCE),
        Corner::TopRight | Corner::BottomRight => {
            AnimationPreset::slide_in_right(200, SLIDE_DISTANCE)
        }
    }
}

/// Get exit animation based on corner
fn get_exit_animation(corner: Corner) -> blinc_animation::MultiKeyframeAnimation {
    const SLIDE_DISTANCE: f32 = 200.0;
    match corner {
        Corner::TopLeft | Corner::BottomLeft => {
            AnimationPreset::slide_out_left(150, SLIDE_DISTANCE)
        }
        Corner::TopRight | Corner::BottomRight => {
            AnimationPreset::slide_out_right(150, SLIDE_DISTANCE)
        }
    }
}

/// Build the toast content
#[allow(clippy::too_many_arguments)]
fn build_toast_content(
    title: &Option<String>,
    description: &Option<String>,
    icon_svg: &Option<String>,
    accent_color: Color,
    variant: ToastVariant,
    bg: Color,
    border: Color,
    text_primary: Color,
    text_secondary: Color,
    radius: f32,
    action_label: &Option<String>,
    action_callback: &Option<Arc<dyn Fn() + Send + Sync>>,
    show_close: bool,
    body: &Option<ToastBodyFn>,
    custom_content: &Option<ToastBodyFn>,
    corner: Corner,
    motion_key: &str,
) -> Div {
    let theme = ThemeState::get();
    let enter_anim = get_enter_animation(corner);
    let exit_anim = get_exit_animation(corner);

    // If fully custom content is provided, use that directly
    if let Some(ref custom_fn) = custom_content {
        let toast = custom_fn()
            .class("cn-toast")
            .w(360.0)
            .bg(bg)
            .border(1.0, border)
            .rounded(radius)
            .shadow_lg();

        return div().child(
            motion_derived(motion_key)
                .enter_animation(enter_anim)
                .exit_animation(exit_anim)
                .child(toast),
        );
    }

    // Check if this is a variant toast (has icon/accent)
    let has_accent = icon_svg.is_some();

    // Main toast container - use left border for accent
    let mut toast = div()
        .class("cn-toast")
        .w(360.0)
        .bg(bg)
        .border(1.0, border)
        .rounded(radius)
        .shadow_lg();

    // Add variant-specific class
    match variant {
        ToastVariant::Success => toast = toast.class("cn-toast--success"),
        ToastVariant::Warning => toast = toast.class("cn-toast--warning"),
        ToastVariant::Destructive => toast = toast.class("cn-toast--error"),
        ToastVariant::Default => toast = toast.class("cn-toast--info"),
    }

    // Add left border accent for variant toasts
    if has_accent {
        toast = toast.border_left(4.0, accent_color);
    }

    // Inner content container
    let mut inner = div().w_full().flex_row().items_start().gap_3().p_4();

    // Icon (if variant has one)
    if let Some(ref svg_str) = icon_svg {
        inner = inner.child(
            div()
                .flex_shrink_0()
                .child(svg(svg_str).size(20.0, 20.0).color(accent_color)),
        );
    }

    // Content area
    let mut content = div().flex_1().flex_col().gap_1();

    // Title (if present)
    if let Some(ref title_text) = title {
        content = content.child(
            text(title_text)
                .size(theme.typography().text_sm)
                .color(text_primary)
                .medium(),
        );
    }

    // Custom body content OR description
    if let Some(ref body_fn) = body {
        content = content.child(body_fn());
    } else if let Some(ref desc) = description {
        content = content.child(
            text(desc)
                .size(theme.typography().text_sm)
                .color(text_secondary),
        );
    }

    inner = inner.child(content);

    // Action button (if provided)
    if let Some(ref label) = action_label {
        let callback = action_callback.clone();
        inner = inner.child(
            button(label)
                .variant(ButtonVariant::Outline)
                .size(ButtonSize::Small)
                .on_click(move |_| {
                    if let Some(ref cb) = callback {
                        cb();
                    }
                    // Close the toast after action
                    get_overlay_manager().close_top();
                }),
        );
    }

    // Close button
    if show_close {
        let close_icon = r#"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" 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>"#;

        inner = inner.child(
            div()
                .flex_shrink_0()
                .w(24.0)
                .h(24.0)
                .items_center()
                .rounded(theme.radius(RadiusToken::Sm))
                .cursor_pointer()
                .on_click(|_| {
                    get_overlay_manager().close_top();
                })
                .child(svg(close_icon).size(16.0, 16.0).color(text_secondary)),
        );
    }

    toast = toast.child(inner);

    // Wrap in motion for animations
    div().child(
        motion_derived(motion_key)
            .enter_animation(enter_anim)
            .exit_animation(exit_anim)
            .child(toast),
    )
}

/// Create a toast notification
///
/// # Example
///
/// ```ignore
/// cn::toast("Success!")
///     .description("Your file has been uploaded.")
///     .variant(ToastVariant::Success)
///     .show();
/// ```
pub fn toast(title: impl Into<String>) -> ToastBuilder {
    ToastBuilder::new(title)
}

/// Convenience function for success toasts
pub fn toast_success(title: impl Into<String>) -> ToastBuilder {
    ToastBuilder::new(title).variant(ToastVariant::Success)
}

/// Convenience function for warning toasts
pub fn toast_warning(title: impl Into<String>) -> ToastBuilder {
    ToastBuilder::new(title).variant(ToastVariant::Warning)
}

/// Convenience function for error toasts
pub fn toast_error(title: impl Into<String>) -> ToastBuilder {
    ToastBuilder::new(title).variant(ToastVariant::Destructive)
}

/// Create a toast with fully custom content
///
/// # Example
///
/// ```ignore
/// cn::toast_custom(|| {
///     div().flex_row().gap_3().p_4()
///         .child(avatar("JD").size(40.0))
///         .child(
///             div().flex_col()
///                 .child(text("John Doe").weight(600))
///                 .child(text("Sent you a message"))
///         )
/// })
/// .show();
/// ```
pub fn toast_custom<F>(content: F) -> ToastBuilder
where
    F: Fn() -> Div + Send + Sync + 'static,
{
    ToastBuilder::custom(content)
}

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

    #[test]
    fn test_toast_builder() {
        let toast = ToastBuilder::new("Test");
        assert_eq!(toast.title, Some("Test".to_string()));
        assert_eq!(toast.duration_ms, 5000);
    }

    #[test]
    fn test_toast_with_description() {
        let toast = ToastBuilder::new("Title").description("Description");
        assert_eq!(toast.description, Some("Description".to_string()));
    }

    #[test]
    fn test_toast_persistent() {
        let toast = ToastBuilder::new("Persistent").persistent();
        assert_eq!(toast.duration_ms, 0);
    }

    #[test]
    fn test_toast_variants() {
        assert!(ToastVariant::Default.icon_svg().is_none());
        assert!(ToastVariant::Success.icon_svg().is_some());
        assert!(ToastVariant::Warning.icon_svg().is_some());
        assert!(ToastVariant::Destructive.icon_svg().is_some());
    }
}