blinc_cn 0.4.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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
//! Button component with shadcn-style variants
//!
//! A themed button component using CSS `:hover`/`:active` for visual feedback.
//! All styling is CSS-driven via `.cn-button` classes, making it fully overridable.
//!
//! # Example
//!
//! ```ignore
//! use blinc_cn::prelude::*;
//!
//! // Primary button (default)
//! cn::button("Click me")
//!
//! // Destructive button
//! cn::button("Delete")
//!     .variant(ButtonVariant::Destructive)
//!
//! // Outline button with custom size
//! cn::button("Cancel")
//!     .variant(ButtonVariant::Outline)
//!     .size(ButtonSize::Small)
//!
//! // Button with click handler
//! cn::button("Submit")
//!     .on_click(|_| println!("Submitted!"))
//! ```

use blinc_core::Color;
use blinc_layout::div::ElementBuilder;
use blinc_layout::prelude::*;
use blinc_layout::stateful::{use_shared_state, ButtonState, SharedState};
use blinc_layout::tree::{LayoutNodeId, LayoutTree};
use blinc_layout::widgets::button as layout_button;
use blinc_layout::InstanceKey;
use blinc_theme::{ColorToken, ThemeState};
use std::sync::Arc;

/// Button visual variants (like shadcn)
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonVariant {
    /// Primary action button - filled with primary color
    #[default]
    Primary,
    /// Secondary action - muted background
    Secondary,
    /// Destructive action - red/danger styling
    Destructive,
    /// Outline button - border only, transparent background
    Outline,
    /// Ghost button - no background, minimal styling
    Ghost,
    /// Link button - appears as a link, no button styling
    Link,
}

impl ButtonVariant {
    /// Get the CSS class suffix for this variant
    fn css_class(&self) -> &'static str {
        match self {
            ButtonVariant::Primary => "cn-button--primary",
            ButtonVariant::Secondary => "cn-button--secondary",
            ButtonVariant::Destructive => "cn-button--destructive",
            ButtonVariant::Outline => "cn-button--outline",
            ButtonVariant::Ghost => "cn-button--ghost",
            ButtonVariant::Link => "cn-button--link",
        }
    }

    /// Get the background color for this variant and state.
    ///
    /// Used by components that still use `Stateful<ButtonState>` (dropdown menu, select).
    pub(crate) fn background(&self, theme: &ThemeState, state: ButtonState) -> Color {
        match (self, state) {
            (_, ButtonState::Disabled) => self.base_background(theme).with_alpha(0.5),
            (ButtonVariant::Primary, ButtonState::Pressed) => {
                theme.color(ColorToken::PrimaryActive)
            }
            (ButtonVariant::Secondary, ButtonState::Pressed) => {
                theme.color(ColorToken::SecondaryActive)
            }
            (ButtonVariant::Destructive, ButtonState::Pressed) => {
                darken(theme.color(ColorToken::Error), 0.15)
            }
            (ButtonVariant::Outline | ButtonVariant::Ghost, ButtonState::Pressed) => {
                theme.color(ColorToken::TextPrimary).with_alpha(0.1)
            }
            (ButtonVariant::Link, ButtonState::Pressed) => Color::TRANSPARENT,
            (ButtonVariant::Primary, ButtonState::Hovered) => theme.color(ColorToken::PrimaryHover),
            (ButtonVariant::Secondary, ButtonState::Hovered) => {
                theme.color(ColorToken::SecondaryHover)
            }
            (ButtonVariant::Destructive, ButtonState::Hovered) => {
                darken(theme.color(ColorToken::Error), 0.1)
            }
            (ButtonVariant::Outline | ButtonVariant::Ghost, ButtonState::Hovered) => {
                theme.color(ColorToken::TextPrimary).with_alpha(0.05)
            }
            (ButtonVariant::Link, ButtonState::Hovered) => Color::TRANSPARENT,
            _ => self.base_background(theme),
        }
    }

    fn base_background(&self, theme: &ThemeState) -> Color {
        match self {
            ButtonVariant::Primary => theme.color(ColorToken::Primary),
            ButtonVariant::Secondary => theme.color(ColorToken::Secondary),
            ButtonVariant::Destructive => theme.color(ColorToken::Error),
            ButtonVariant::Outline | ButtonVariant::Ghost | ButtonVariant::Link => {
                Color::TRANSPARENT
            }
        }
    }

    /// Get the foreground (text) color for this variant
    pub(crate) fn foreground(&self, theme: &ThemeState) -> Color {
        match self {
            ButtonVariant::Primary | ButtonVariant::Destructive => {
                theme.color(ColorToken::TextInverse)
            }
            ButtonVariant::Secondary | ButtonVariant::Outline | ButtonVariant::Ghost => {
                theme.color(ColorToken::TextPrimary)
            }
            ButtonVariant::Link => theme.color(ColorToken::Primary),
        }
    }

    /// Get the border color for this variant (if any)
    pub(crate) fn border(&self, theme: &ThemeState) -> Option<Color> {
        match self {
            ButtonVariant::Outline => Some(theme.color(ColorToken::Border)),
            _ => None,
        }
    }
}

/// Helper to darken a color
fn darken(color: Color, amount: f32) -> Color {
    Color::rgba(
        (color.r * (1.0 - amount)).max(0.0),
        (color.g * (1.0 - amount)).max(0.0),
        (color.b * (1.0 - amount)).max(0.0),
        color.a,
    )
}

/// Button size variants
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ButtonSize {
    /// Small button
    Small,
    /// Default size
    #[default]
    Medium,
    /// Large button
    Large,
    /// Icon-only button (square)
    Icon,
}

impl ButtonSize {
    /// Get the CSS class suffix for this size
    fn css_class(&self) -> &'static str {
        match self {
            ButtonSize::Small => "cn-button--sm",
            ButtonSize::Medium => "cn-button--md",
            ButtonSize::Large => "cn-button--lg",
            ButtonSize::Icon => "cn-button--icon",
        }
    }

    /// Get height
    fn height(&self) -> f32 {
        match self {
            ButtonSize::Small => 32.0,
            ButtonSize::Medium => 40.0,
            ButtonSize::Large => 44.0,
            ButtonSize::Icon => 40.0,
        }
    }

    /// Get horizontal padding (raw pixels)
    fn padding_x(&self) -> f32 {
        match self {
            ButtonSize::Small => 12.0,
            ButtonSize::Medium => 16.0,
            ButtonSize::Large => 24.0,
            ButtonSize::Icon => 8.0,
        }
    }

    /// Get vertical padding (raw pixels)
    fn padding_y(&self) -> f32 {
        match self {
            ButtonSize::Small => 4.0,
            ButtonSize::Medium => 8.0,
            ButtonSize::Large => 12.0,
            ButtonSize::Icon => 8.0,
        }
    }

    /// Get font size for text/icon sizing
    fn font_size(&self) -> f32 {
        match self {
            ButtonSize::Small => 13.0,
            ButtonSize::Medium => 14.0,
            ButtonSize::Large => 16.0,
            ButtonSize::Icon => 14.0,
        }
    }

    /// Get default border radius (inline fallback — CSS overrides this)
    fn border_radius(&self) -> f32 {
        match self {
            ButtonSize::Small => 4.0,
            ButtonSize::Medium => 6.0,
            ButtonSize::Large => 8.0,
            ButtonSize::Icon => 6.0,
        }
    }
}

/// Icon position within the button
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum IconPosition {
    /// Icon appears before the label (left in LTR)
    #[default]
    Start,
    /// Icon appears after the label (right in LTR)
    End,
}

/// Get or create a persistent SharedState<ButtonState> for the given key
///
/// This is a convenience wrapper around `use_shared_state::<ButtonState>`.
/// Used by dropdown menus, menubars, and navigation menus.
pub(crate) fn use_button_state(key: &str) -> SharedState<ButtonState> {
    use_shared_state::<ButtonState>(key)
}

/// Reset a button state to Idle
///
/// Call this when an overlay closes to clear any lingering hover/pressed states.
pub(crate) fn reset_button_state(key: &str) {
    let state = use_button_state(key);
    let mut inner = state.lock().unwrap();
    inner.state = ButtonState::Idle;
}

/// Create a button with a label
///
/// Uses `#[track_caller]` with UUID to generate a unique instance key.
/// CSS handles all visual states (`:hover`, `:active`) automatically.
///
/// # Example
///
/// ```ignore
/// use blinc_cn::prelude::*;
///
/// cn::button("OK")
///     .variant(ButtonVariant::Primary)
///     .on_click(|_| println!("Confirmed!"))
///
/// // Safe in loops - each button gets unique state
/// for item in items {
///     cn::button(&item.name)
/// }
/// ```
#[track_caller]
pub fn button(label: impl Into<String>) -> ButtonBuilder {
    ButtonBuilder {
        key: InstanceKey::new("button"),
        config: ButtonConfig {
            label: label.into(),
            variant: ButtonVariant::default(),
            btn_size: ButtonSize::default(),
            disabled: false,
            icon: None,
            icon_position: IconPosition::default(),
            icon_size: None,
            text_color: None,
            on_click: None,
        },
        built: std::cell::OnceCell::new(),
    }
}

/// Internal configuration for ButtonBuilder
#[derive(Clone)]
#[allow(clippy::type_complexity)]
struct ButtonConfig {
    label: String,
    variant: ButtonVariant,
    btn_size: ButtonSize,
    disabled: bool,
    icon: Option<String>,
    icon_position: IconPosition,
    icon_size: Option<f32>,
    text_color: Option<Color>,
    on_click: Option<Arc<dyn Fn(&blinc_layout::event_handler::EventContext) + Send + Sync>>,
}

/// The built button element — wraps `blinc_layout::widgets::button::Button`
/// which provides `Stateful<ButtonState>` FSM for hover/press behavior.
pub struct Button {
    inner: layout_button::Button,
}

impl Button {
    /// Build from a config with the instance key
    fn from_config(instance_key: &str, config: ButtonConfig) -> Self {
        let theme = ThemeState::get();
        let font_size = config.btn_size.font_size();
        let variant = config.variant;
        let disabled = config.disabled;

        // Get persistent state for this button
        let state_key = format!("_cn_btn_{}", instance_key);
        let btn_state = use_button_state(&state_key);
        if disabled {
            let mut inner = btn_state.lock().unwrap();
            inner.state = ButtonState::Disabled;
        }

        // Variant colors for the layout button's FSM
        let bg = variant.base_background(theme);
        let hover_bg = variant.background(theme, ButtonState::Hovered);
        let pressed_bg = variant.background(theme, ButtonState::Pressed);

        // Content closure — returns ONLY the text/icon content.
        // The layout button handles bg, rounded, padding, etc.
        let label = config.label.clone();
        let icon = config.icon.clone();
        let icon_position = config.icon_position;
        let custom_icon_size = config.icon_size;

        let btn_size = config.btn_size;
        let default_fg = config
            .text_color
            .unwrap_or_else(|| variant.foreground(theme));

        // Determine icon-only mode at construction time (needed for sizing)
        let is_icon_only = config.icon.is_some() && config.label.is_empty();
        let resolved_icon_size = config.icon_size.unwrap_or(font_size + 2.0);

        // Create button with empty content — we'll set up on_state below
        // to read CSS-resolved text_color for both label and icon.
        let mut btn = layout_button::Button::with_content(btn_state, |_state| div())
            .text_color(default_fg)
            .bg_color(bg)
            .hover_color(hover_bg)
            .pressed_color(pressed_bg)
            .rounded(config.btn_size.border_radius())
            .items_center()
            .justify_center()
            // CSS classes for user overrides
            .class("cn-button")
            .class(variant.css_class())
            .class(config.btn_size.css_class());

        // Icon-only: explicit square dimensions so items_center/justify_center
        // can center the icon. With-label: shrink-wrap to content.
        if is_icon_only {
            let pad = config.btn_size.padding_y();
            let dim = resolved_icon_size + pad * 2.0;
            btn = btn.w(dim).h(dim);
        } else {
            btn = btn.w_fit();
        }

        // Capture config arc so the on_state callback can read CSS-resolved text_color
        let cfg_arc = btn.config_arc();
        btn = btn.on_state(move |_state, container| {
            // Read CSS-resolved text_color — apply_css_overrides_button has already run
            let fg = cfg_arc.lock().unwrap().text_color;

            if is_icon_only {
                // Icon-only: place SVG directly as child of the Stateful container.
                // The container's items_center + justify_center + explicit w/h
                // handles centering — no content wrapper needed.
                if let Some(ref icon_str) = icon {
                    let icon_size = custom_icon_size.unwrap_or(font_size + 2.0);
                    let svg_str = blinc_icons::to_svg(icon_str, icon_size);
                    let icon_svg = svg(&svg_str).size(icon_size, icon_size).color(fg);
                    container.merge(div().child(icon_svg));
                }
            } else {
                // With label: use content wrapper for flex_row layout
                let label_text = text(&label)
                    .size(font_size)
                    .color(fg)
                    .no_wrap()
                    .v_center()
                    .pointer_events_none()
                    .no_cursor();

                let pad_x = btn_size.padding_x();
                let pad_y = btn_size.padding_y();
                let mut content = div()
                    .flex_row()
                    .items_center()
                    .justify_center()
                    .gap_px(6.0)
                    .padding_x_px(pad_x)
                    .padding_y_px(pad_y)
                    .pointer_events_none();

                if let Some(ref icon_str) = icon {
                    let icon_size = custom_icon_size.unwrap_or(font_size + 2.0);
                    let svg_str = blinc_icons::to_svg(icon_str, icon_size);
                    let icon_svg = svg(&svg_str).size(icon_size, icon_size).color(fg);

                    match icon_position {
                        IconPosition::Start => {
                            content = content.child(icon_svg).child(label_text);
                        }
                        IconPosition::End => {
                            content = content.child(label_text).child(icon_svg);
                        }
                    }
                } else {
                    content = content.child(label_text);
                }

                container.merge(div().child(content));
            }
        });

        if disabled {
            btn = btn.class("cn-button--disabled").opacity(0.5).disabled(true);
        }

        // Shadow
        if variant != ButtonVariant::Link && variant != ButtonVariant::Ghost {
            btn = btn.shadow_md();
        }
        if variant == ButtonVariant::Outline {
            btn = btn.shadow_sm();
        }

        // Border for outline variant
        if let Some(border_color) = variant.border(theme) {
            btn = btn.border(1.0, border_color);
        }

        // Click handler
        if let Some(handler) = config.on_click {
            btn = btn.on_click(move |ctx| handler(ctx));
        }

        Self { inner: btn }
    }

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

    /// Set the element ID for CSS selector matching
    pub fn id(mut self, id: &str) -> Self {
        self.inner = self.inner.id(id);
        self
    }
}

impl ElementBuilder for Button {
    fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId {
        self.inner.build(tree)
    }

    fn render_props(&self) -> blinc_layout::element::RenderProps {
        self.inner.render_props()
    }

    fn children_builders(&self) -> &[Box<dyn ElementBuilder>] {
        self.inner.children_builders()
    }

    fn element_type_id(&self) -> blinc_layout::div::ElementTypeId {
        self.inner.element_type_id()
    }

    fn event_handlers(&self) -> Option<&blinc_layout::event_handler::EventHandlers> {
        self.inner.event_handlers()
    }

    fn layout_style(&self) -> Option<&taffy::Style> {
        self.inner.layout_style()
    }

    fn element_classes(&self) -> &[String] {
        self.inner.element_classes()
    }

    fn element_id(&self) -> Option<&str> {
        self.inner.element_id()
    }
}

/// Button configuration for building buttons
pub struct ButtonBuilder {
    /// Unique instance key (UUID-based for loop/closure safety)
    key: InstanceKey,
    config: ButtonConfig,
    /// Cached built Button - built lazily on first access
    built: std::cell::OnceCell<Button>,
}

impl ButtonBuilder {
    /// Create a new button builder with explicit key
    ///
    /// For most use cases, prefer `button()` which auto-generates a unique key.
    /// Use this when you need a deterministic key for programmatic access.
    pub fn with_key(key: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            key: InstanceKey::explicit(key),
            config: ButtonConfig {
                label: label.into(),
                variant: ButtonVariant::default(),
                btn_size: ButtonSize::default(),
                disabled: false,
                icon: None,
                icon_position: IconPosition::Start,
                icon_size: None,
                text_color: None,
                on_click: None,
            },
            built: std::cell::OnceCell::new(),
        }
    }

    /// Get or build the inner Button
    fn get_or_build(&self) -> &Button {
        self.built
            .get_or_init(|| Button::from_config(self.key.get(), self.config.clone()))
    }

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

    /// Set the button size
    pub fn size(mut self, size: ButtonSize) -> Self {
        self.config.btn_size = size;
        self
    }

    /// Make the button disabled
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.config.disabled = disabled;
        self
    }

    /// Set an icon for the button
    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.config.icon = Some(icon.into());
        self
    }

    /// Set the icon position
    pub fn icon_position(mut self, position: IconPosition) -> Self {
        self.config.icon_position = position;
        self
    }

    /// Set the icon size in pixels (overrides the default derived from font size)
    pub fn icon_size(mut self, size: f32) -> Self {
        self.config.icon_size = Some(size);
        self
    }

    /// Set the text/icon color (overrides variant default)
    pub fn color(mut self, color: impl Into<Color>) -> Self {
        self.config.text_color = Some(color.into());
        self
    }

    /// Set the click handler
    pub fn on_click<F>(mut self, handler: F) -> Self
    where
        F: Fn(&blinc_layout::event_handler::EventContext) + Send + Sync + 'static,
    {
        self.config.on_click = Some(Arc::new(handler));
        self
    }

    /// Build the final Button component
    pub fn build_component(self) -> Button {
        Button::from_config(self.key.get(), self.config)
    }
}

impl ElementBuilder for ButtonBuilder {
    fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId {
        self.get_or_build().build(tree)
    }

    fn render_props(&self) -> blinc_layout::element::RenderProps {
        self.get_or_build().render_props()
    }

    fn children_builders(&self) -> &[Box<dyn ElementBuilder>] {
        self.get_or_build().children_builders()
    }

    fn element_type_id(&self) -> blinc_layout::div::ElementTypeId {
        self.get_or_build().element_type_id()
    }

    fn event_handlers(&self) -> Option<&blinc_layout::event_handler::EventHandlers> {
        self.get_or_build().event_handlers()
    }

    fn layout_style(&self) -> Option<&taffy::Style> {
        self.get_or_build().layout_style()
    }

    fn element_classes(&self) -> &[String] {
        self.get_or_build().element_classes()
    }

    fn element_id(&self) -> Option<&str> {
        self.get_or_build().element_id()
    }
}