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
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Radio Group component for single-selection from multiple options
//!
//! A themed radio button group with smooth selection transitions.
//! Uses `State<String>` from context for reactive state management.
//!
//! # Example
//!
//! ```ignore
//! use blinc_cn::prelude::*;
//!
//! fn build_ui(ctx: &WindowedContext) -> impl ElementBuilder {
//!     // Create radio state from context
//!     let selected = ctx.use_state_for("color", "red".to_string());
//!
//!     cn::radio_group(&selected)
//!         .option("red", "Red")
//!         .option("green", "Green")
//!         .option("blue", "Blue")
//!         .on_change(|value| println!("Selected: {}", value))
//! }
//!
//! // Horizontal layout
//! cn::radio_group(&selected)
//!     .horizontal()
//!     .option("yes", "Yes")
//!     .option("no", "No")
//!
//! // With label
//! cn::radio_group(&size)
//!     .label("Select size")
//!     .option("sm", "Small")
//!     .option("md", "Medium")
//!     .option("lg", "Large")
//!
//! // Disabled
//! cn::radio_group(&selected)
//!     .disabled(true)
//!     .option("a", "Option A")
//!     .option("b", "Option B")
//! ```

use blinc_core::{Color, State, Transform};
use blinc_layout::css_parser::{active_stylesheet, ElementState, Stylesheet};
use blinc_layout::div::ElementTypeId;
use blinc_layout::element::RenderProps;
use blinc_layout::element_style::ElementStyle;
use blinc_layout::prelude::*;
use blinc_layout::stateful::{stateful_with_key, ButtonState};
use blinc_layout::tree::{LayoutNodeId, LayoutTree};
use blinc_theme::{ColorToken, SpacingToken, ThemeState};
use std::sync::Arc;

use super::label::{label, LabelSize};

/// Radio button size variants
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RadioSize {
    /// Small radio (14px)
    Small,
    /// Medium radio (18px)
    #[default]
    Medium,
    /// Large radio (22px)
    Large,
}

impl RadioSize {
    fn outer_size(&self) -> f32 {
        match self {
            RadioSize::Small => 14.0,
            RadioSize::Medium => 18.0,
            RadioSize::Large => 22.0,
        }
    }

    fn inner_size(&self) -> f32 {
        match self {
            RadioSize::Small => 6.0,
            RadioSize::Medium => 8.0,
            RadioSize::Large => 10.0,
        }
    }

    fn border_width(&self) -> f32 {
        match self {
            RadioSize::Small => 1.5,
            RadioSize::Medium => 2.0,
            RadioSize::Large => 2.0,
        }
    }
}

/// Layout direction for radio options
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RadioLayout {
    /// Options stacked vertically (default)
    #[default]
    Vertical,
    /// Options arranged horizontally
    Horizontal,
}

/// A radio option with value and label
#[derive(Clone)]
struct RadioOption {
    value: String,
    label: String,
    disabled: bool,
}

/// Radio Group component
///
/// A group of radio buttons where only one can be selected at a time.
/// Uses `State<String>` from context for reactive state management.
pub struct RadioGroup {
    /// The fully-built inner element (Div containing radio buttons and optional label)
    inner: Div,
}

impl RadioGroup {
    /// Create a new radio group with state from context
    ///
    /// # Example
    /// ```ignore
    /// let selected = ctx.use_state_for("choice", "option1".to_string());
    /// cn::radio_group(&selected)
    ///     .option("option1", "First Option")
    ///     .option("option2", "Second Option")
    /// ```
    pub fn new(selected: &State<String>) -> Self {
        Self::with_config(RadioGroupConfig::new(selected.clone()))
    }

    /// Create from a full configuration
    fn with_config(config: RadioGroupConfig) -> Self {
        let theme = ThemeState::get();
        let default_gap = theme.spacing_value(SpacingToken::Space1);
        let gap = config.gap.unwrap_or(default_gap);

        // Build options container
        let mut options_container = match config.layout {
            RadioLayout::Vertical => div().flex_col().gap(gap).h_fit(),
            RadioLayout::Horizontal => div().flex_row().gap(gap).flex_wrap().h_fit(),
        };

        // Add each radio button
        for option in &config.options {
            // Auto-derive per-button CSS ID: "{group_id}-{value}"
            let button_css_id = config.css_group_id.as_ref().map(|group_id| {
                let sanitized = option.value.replace(' ', "-");
                format!("{group_id}-{sanitized}")
            });
            options_container =
                options_container.child(build_radio_button(&config, option, theme, button_css_id));
        }

        // If there's a label, wrap everything
        let mut inner = if let Some(ref label_text) = config.label {
            let spacing = theme.spacing_value(SpacingToken::Space2);
            let mut lbl = label(label_text).size(LabelSize::Medium);
            if config.disabled {
                lbl = lbl.disabled(true);
            }

            div()
                .flex_col()
                .gap(spacing)
                .h_fit()
                .child(lbl)
                .child(options_container)
        } else {
            options_container
        };

        // Apply user classes
        for c in &config.classes {
            inner = inner.class(c);
        }

        Self { inner }
    }
}

/// Build a single radio button
fn build_radio_button(
    config: &RadioGroupConfig,
    option: &RadioOption,
    theme: &ThemeState,
    button_css_id: Option<String>,
) -> Stateful<ButtonState> {
    let outer_size = config.size.outer_size();
    let inner_size = config.size.inner_size();
    let border_width = config.size.border_width();

    // Get colors
    let selected_color = config
        .selected_color
        .unwrap_or_else(|| theme.color(ColorToken::Primary));
    let border = config
        .border_color
        .unwrap_or_else(|| theme.color(ColorToken::BorderSecondary));
    let hover_border = config
        .hover_border_color
        .unwrap_or_else(|| theme.color(ColorToken::Primary));

    let option_value = option.value.clone();
    let option_disabled = option.disabled || config.disabled;
    let option_label = option.label.clone();
    let selected_state = config.selected.clone();
    let selected_state_for_click = config.selected.clone();
    let on_change = config.on_change.clone();
    let value_for_click = option.value.clone();

    let label_color = if option_disabled {
        theme.color(ColorToken::TextTertiary)
    } else {
        theme.color(ColorToken::TextPrimary)
    };

    let css_id_for_state = button_css_id.clone();

    // Unique key per radio button for state isolation
    let stateful_key = button_css_id
        .as_deref()
        .map(|id| format!("radio-{id}"))
        .unwrap_or_else(|| format!("radio-{}", option.value));

    // Build the radio button circle — CSS handles border, scale, opacity via classes
    let has_custom_colors = config.selected_color.is_some()
        || config.border_color.is_some()
        || config.hover_border_color.is_some();

    let mut radio = stateful_with_key::<ButtonState>(&stateful_key)
        .deps([selected_state.signal_id()])
        .on_state(move |ctx| {
            let state = ctx.state();
            let theme = ThemeState::get();
            let is_selected = selected_state.get() == option_value;
            let is_hovered = matches!(state, ButtonState::Hovered | ButtonState::Pressed);

            // Start with builder-configured colors for CSS override resolution
            let mut overrides = RadioStyleOverrides {
                selected_color,
                border_color: border,
                hover_border_color: hover_border,
                label_color,
                opacity: None,
                background: None,
            };

            // Apply CSS overrides if we have an element ID
            if let Some(ref css_id) = css_id_for_state {
                if let Some(stylesheet) = active_stylesheet() {
                    apply_css_overrides_radio(
                        &stylesheet,
                        css_id,
                        is_selected,
                        is_hovered,
                        option_disabled,
                        &mut overrides,
                    );
                }
            }

            // Border color based on state
            let border_color = if is_selected {
                overrides.selected_color
            } else if is_hovered && !option_disabled {
                overrides.hover_border_color
            } else {
                overrides.border_color
            };

            let scale = if is_hovered && !option_disabled {
                1.05
            } else {
                1.0
            };

            let inner_scale = if matches!(state, ButtonState::Pressed) && !option_disabled {
                0.8
            } else {
                1.0
            };

            // Build the radio circle with builder properties + CSS classes
            let mut circle = div()
                .class("cn-radio")
                .w(outer_size)
                .h(outer_size)
                .rounded(outer_size / 2.0)
                .border(border_width, border_color)
                .items_center()
                .justify_center()
                .transform(Transform::scale(scale, scale));

            if is_selected {
                circle = circle.class("cn-radio--selected");
            }

            if option_disabled {
                circle = circle.class("cn-radio--disabled");
            }

            if let Some(bg) = overrides.background {
                circle = circle.bg(bg);
            }

            // Add inner dot if selected
            if is_selected {
                let inner_dot = div()
                    .class("cn-radio-dot")
                    .w(inner_size)
                    .h(inner_size)
                    .rounded(inner_size / 2.0)
                    .bg(overrides.selected_color)
                    .transform(Transform::scale(inner_scale, inner_scale));
                circle = circle.child(inner_dot);
            }

            // Build with label
            let mut visual = div()
                .flex_row()
                .gap_px(theme.spacing_value(SpacingToken::Space4))
                .items_center()
                .cursor_pointer()
                .child(circle)
                .child(text(&option_label).size(14.0).color(overrides.label_color));

            if let Some(opacity) = overrides.opacity {
                visual = visual.opacity(opacity);
            } else if option_disabled {
                visual = visual.opacity(0.5);
            }

            visual
        });

    // Set CSS element ID on the Stateful for element registry matching
    if let Some(ref css_id) = button_css_id {
        radio = radio.id(css_id);
    }

    // Click handler
    radio = radio.on_click(move |_| {
        if option_disabled {
            return;
        }

        let current = selected_state_for_click.get();
        if current != value_for_click {
            selected_state_for_click.set(value_for_click.clone());
            if let Some(ref callback) = on_change {
                callback(&value_for_click);
            }
        }
    });

    radio
}

/// Mutable radio button style overrides, populated by CSS cascade
struct RadioStyleOverrides {
    selected_color: Color,
    border_color: Color,
    hover_border_color: Color,
    label_color: Color,
    opacity: Option<f32>,
    background: Option<Color>,
}

impl RadioStyleOverrides {
    /// Apply a single ElementStyle layer
    fn apply(&mut self, style: &ElementStyle) {
        if let Some(color) = style.accent_color {
            self.selected_color = color;
        }
        if let Some(color) = style.border_color {
            self.border_color = color;
            // border_color also overrides hover_border_color
            self.hover_border_color = color;
        }
        if let Some(color) = style.text_color {
            self.label_color = color;
        }
        if let Some(o) = style.opacity {
            self.opacity = Some(o);
        }
        if let Some(blinc_core::Brush::Solid(color)) = style.background {
            self.background = Some(color);
        }
    }
}

/// Apply CSS style overrides to radio button visual properties
///
/// Cascading order: base → :checked → :hover → :disabled (highest priority)
fn apply_css_overrides_radio(
    stylesheet: &Stylesheet,
    element_id: &str,
    is_selected: bool,
    is_hovered: bool,
    is_disabled: bool,
    overrides: &mut RadioStyleOverrides,
) {
    // 1. Base style
    if let Some(base) = stylesheet.get(element_id) {
        overrides.apply(base);
    }
    // 2. :checked (if selected)
    if is_selected {
        if let Some(s) = stylesheet.get_with_state(element_id, ElementState::Checked) {
            overrides.apply(s);
        }
    }
    // 3. :hover (layered after :checked)
    if is_hovered {
        if let Some(s) = stylesheet.get_with_state(element_id, ElementState::Hover) {
            overrides.apply(s);
        }
    }
    // 4. :disabled (highest priority)
    if is_disabled {
        if let Some(s) = stylesheet.get_with_state(element_id, ElementState::Disabled) {
            overrides.apply(s);
        }
    }
}

/// Internal configuration for building a RadioGroup
#[derive(Clone)]
#[allow(clippy::type_complexity)]
struct RadioGroupConfig {
    selected: State<String>,
    options: Vec<RadioOption>,
    size: RadioSize,
    layout: RadioLayout,
    label: Option<String>,
    disabled: bool,
    gap: Option<f32>,
    selected_color: Option<Color>,
    border_color: Option<Color>,
    hover_border_color: Option<Color>,
    on_change: Option<Arc<dyn Fn(&str) + Send + Sync>>,
    css_group_id: Option<String>,
    /// User-added CSS classes
    classes: Vec<String>,
}

impl RadioGroupConfig {
    fn new(selected: State<String>) -> Self {
        Self {
            selected,
            options: Vec::new(),
            size: RadioSize::default(),
            layout: RadioLayout::default(),
            label: None,
            disabled: false,
            gap: None,
            selected_color: None,
            border_color: None,
            hover_border_color: None,
            on_change: None,
            css_group_id: None,
            classes: Vec::new(),
        }
    }
}

/// Builder for creating RadioGroup components with fluent API
pub struct RadioGroupBuilder {
    config: RadioGroupConfig,
    /// Cached built RadioGroup - built lazily on first access
    built: std::cell::OnceCell<RadioGroup>,
}

impl RadioGroupBuilder {
    /// Create a new radio group builder with state from context
    pub fn new(selected: &State<String>) -> Self {
        Self {
            config: RadioGroupConfig::new(selected.clone()),
            built: std::cell::OnceCell::new(),
        }
    }

    /// Get or build the inner RadioGroup
    fn get_or_build(&self) -> &RadioGroup {
        self.built
            .get_or_init(|| RadioGroup::with_config(self.config.clone()))
    }

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

    /// Set a CSS element ID for the radio group
    ///
    /// Individual radio buttons auto-derive IDs as `"{group_id}-{value}"`.
    /// For example, `.id("theme-radio")` with `.option("light", "Light")` produces
    /// a button with CSS ID `"theme-radio-light"`.
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.config.css_group_id = Some(id.into());
        self
    }

    /// Add an option to the radio group
    pub fn option(mut self, value: impl Into<String>, label: impl Into<String>) -> Self {
        self.config.options.push(RadioOption {
            value: value.into(),
            label: label.into(),
            disabled: false,
        });
        self
    }

    /// Add a disabled option to the radio group
    pub fn option_disabled(mut self, value: impl Into<String>, label: impl Into<String>) -> Self {
        self.config.options.push(RadioOption {
            value: value.into(),
            label: label.into(),
            disabled: true,
        });
        self
    }

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

    /// Set the layout direction
    pub fn layout(mut self, layout: RadioLayout) -> Self {
        self.config.layout = layout;
        self
    }

    /// Use horizontal layout
    pub fn horizontal(mut self) -> Self {
        self.config.layout = RadioLayout::Horizontal;
        self
    }

    /// Use vertical layout (default)
    pub fn vertical(mut self) -> Self {
        self.config.layout = RadioLayout::Vertical;
        self
    }

    /// Add a label above the radio group
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.config.label = Some(label.into());
        self
    }

    /// Disable all options
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.config.disabled = disabled;
        self
    }

    /// Set the gap between options
    pub fn gap(mut self, gap: f32) -> Self {
        self.config.gap = Some(gap);
        self
    }

    /// Set the selected indicator color
    pub fn selected_color(mut self, color: impl Into<Color>) -> Self {
        self.config.selected_color = Some(color.into());
        self
    }

    /// Set the border color
    pub fn border_color(mut self, color: impl Into<Color>) -> Self {
        self.config.border_color = Some(color.into());
        self
    }

    /// Set the hover border color
    pub fn hover_border_color(mut self, color: impl Into<Color>) -> Self {
        self.config.hover_border_color = Some(color.into());
        self
    }

    /// Set the change callback
    ///
    /// Called when a different option is selected, with the new value.
    pub fn on_change<F>(mut self, callback: F) -> Self
    where
        F: Fn(&str) + Send + Sync + 'static,
    {
        self.config.on_change = Some(Arc::new(callback));
        self
    }

    /// Build the final RadioGroup component
    pub fn build_component(self) -> RadioGroup {
        RadioGroup::with_config(self.config)
    }
}

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

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

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

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

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

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

    fn render_props(&self) -> 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) -> ElementTypeId {
        self.get_or_build().element_type_id()
    }

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

/// Create a radio group with state from context
///
/// # Example
///
/// ```ignore
/// use blinc_cn::prelude::*;
///
/// let choice = ctx.use_state_for("choice", "a".to_string());
/// cn::radio_group(&choice)
///     .label("Pick one")
///     .option("a", "Option A")
///     .option("b", "Option B")
///     .option("c", "Option C")
/// ```
pub fn radio_group(selected: &State<String>) -> RadioGroupBuilder {
    RadioGroupBuilder::new(selected)
}

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

    #[test]
    fn test_radio_sizes() {
        assert_eq!(RadioSize::Small.outer_size(), 14.0);
        assert_eq!(RadioSize::Medium.outer_size(), 18.0);
        assert_eq!(RadioSize::Large.outer_size(), 22.0);
    }

    #[test]
    fn test_radio_inner_sizes() {
        assert_eq!(RadioSize::Small.inner_size(), 6.0);
        assert_eq!(RadioSize::Medium.inner_size(), 8.0);
        assert_eq!(RadioSize::Large.inner_size(), 10.0);
    }

    #[test]
    fn test_radio_border_widths() {
        assert_eq!(RadioSize::Small.border_width(), 1.5);
        assert_eq!(RadioSize::Medium.border_width(), 2.0);
        assert_eq!(RadioSize::Large.border_width(), 2.0);
    }

    fn init_theme() {
        let _ = ThemeState::try_get().unwrap_or_else(|| {
            ThemeState::init_default();
            ThemeState::get()
        });
    }

    // Note: RadioGroup builder test requires State which needs context
    // The RadioGroup API is tested through the size/layout tests above
}