herogpui-components 0.12.0

HeroUI-style component library for GPUI
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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! RadioGroup — port of `@heroui/radio`.

use std::{cell::RefCell, rc::Rc};

use gpui::{prelude::*, px, App, IntoElement, Pixels, RenderOnce, SharedString, Styled, Window};
use herogpui_core::{element_id, Color, FieldVariant, Orientation};
use herogpui_theme::ActiveTheme;

use crate::a11y::{self, A11y as _};

/// One radio's visible label, submitted value, and local disabled state.
#[derive(Clone)]
pub struct RadioOption {
    label: SharedString,
    value: SharedString,
    is_disabled: bool,
    description: Option<SharedString>,
    error_message: Option<SharedString>,
}

impl RadioOption {
    pub fn new(label: impl Into<SharedString>) -> Self {
        let label = label.into();
        Self {
            value: label.clone(),
            label,
            is_disabled: false,
            description: None,
            error_message: None,
        }
    }

    /// `value` — submitted and reported independently of the visible label.
    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
        self.value = value.into();
        self
    }

    /// `isDisabled` — disables this option only.
    pub fn is_disabled(mut self, value: bool) -> Self {
        self.is_disabled = value;
        self
    }

    /// `Description` — help text below this option's clickable content.
    pub fn description(mut self, text: impl Into<SharedString>) -> Self {
        self.description = Some(text.into());
        self
    }

    /// `FieldError` — validation text below this option's clickable content.
    pub fn error_message(mut self, text: impl Into<SharedString>) -> Self {
        self.error_message = Some(text.into());
        self
    }
}

impl From<SharedString> for RadioOption {
    fn from(label: SharedString) -> Self {
        Self::new(label)
    }
}

impl From<String> for RadioOption {
    fn from(label: String) -> Self {
        Self::new(label)
    }
}

impl From<&str> for RadioOption {
    fn from(label: &str) -> Self {
        Self::new(label.to_owned())
    }
}

/// Field state handed to the root `Radio` and `Radio.Indicator` renderers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RadioOptionState {
    pub is_selected: bool,
    pub is_disabled: bool,
    pub is_read_only: bool,
    pub is_invalid: bool,
    pub is_required: bool,
}

/// HeroGPUI-only compact size for a [`RadioGroup`].
///
/// | Metric (pixels) | Sm | Md (pinned default) |
/// | --- | --- | --- |
/// | Control / selected dot / pressed dot | 14 / 5 / 8 | 16 / 6 / 8 |
/// | Label text / line height | 12 / 16 | 14 / 20 |
/// | Control-to-label gap / supporting-text indent | 10 / 24 | 12 / 28 |
///
/// Both steps have zero row padding and no extra minimum hitbox: each clickable
/// row includes its control and label and grows with caller content. Options
/// remain 16px apart in either orientation; horizontal groups wrap. Supporting
/// text remains 12/16 with a 4px vertical gap. Control and dot keep `key_radius`;
/// `radius` overrides only the control. Press scales the control by 0.95 when
/// motion is enabled; the selected dot's pressed size remains 8px in both steps.
///
/// v3.2.4 removed the field `size` prop, so this is additive: `Md` is
/// byte-identical to the pinned default and `Sm` is HeroGPUI's own 14px step.
/// Not a v3 prop.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RadioSize {
    Sm,
    #[default]
    Md,
}

impl RadioSize {
    pub const ALL: [RadioSize; 2] = [Self::Sm, Self::Md];

    /// `(control, dot, label text, row gap)` for this step.
    fn metrics(self) -> (Pixels, Pixels, Pixels, Pixels) {
        match self {
            Self::Sm => (px(14.), px(5.), px(12.), px(10.)),
            Self::Md => (px(16.), px(6.), px(14.), px(12.)),
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Sm => "Small",
            Self::Md => "Medium",
        }
    }
}

/// HeroUI RadioGroup.
#[derive(IntoElement)]
pub struct RadioGroup {
    /// `name` — the name this control submits under; read back by
    /// [`Self::form_field`].
    name: Option<SharedString>,
    id: gpui::ElementId,
    options: Vec<RadioOption>,
    /// Mirrors the current value, validity, successful state, focus and reset
    /// behavior for a live [`crate::form::FormField`].
    form_state: Rc<RefCell<crate::form::LiveFormFieldState>>,
    /// `Radio`'s `children`-as-a-function: handed the option and its state.
    option_content:
        Option<std::sync::Arc<dyn Fn(&SharedString, RadioOptionState) -> gpui::AnyElement>>,
    /// `Radio.Indicator` children — replaces the built-in dot per option.
    indicator: Option<std::sync::Arc<dyn Fn(&SharedString, RadioOptionState) -> gpui::AnyElement>>,
    /// The `<Description>` v3 composes inside a `<Radio>`, per option and in the
    /// same order. `.radio` is `flex flex-col gap-1` around its content and this
    /// text, indented under the label by `ps-7`.
    descriptions: Vec<Option<SharedString>>,
    /// The group's own `<Label>`, `<Description>` and `<FieldError>`. v3
    /// composes all three inside `<RadioGroup>` -- every documented example
    /// opens with `<Label>Plan selection</Label>` -- and a monolithic group takes
    /// them as props, the way `CheckboxGroup` does.
    label: Option<SharedString>,
    description: Option<SharedString>,
    error_message: Option<SharedString>,
    selected: Option<usize>,
    /// Whether `value` was supplied. `Option<usize>` cannot distinguish
    /// "controlled, nothing selected" from "uncontrolled" on its own.
    is_controlled: bool,
    default_value: Option<usize>,
    orientation: Orientation,
    is_disabled: bool,
    variant: FieldVariant,
    is_invalid: bool,
    is_required: bool,
    is_read_only: bool,
    on_change: Option<std::sync::Arc<dyn Fn(&SharedString, &mut Window, &mut App) + 'static>>,
    /// The compact step; `Md` is the pinned default.
    size: RadioSize,
    /// The control circle's corner radius, in place of the owning `key_radius`
    /// helper. The control's pressed box follows it; the selected dot inside
    /// keeps its own.
    radius: Option<Pixels>,
    /// Expands the root to the available width.
    full_width: bool,
    /// The `sx` slot, refined over the root style at the end of render.
    sx: Option<Box<gpui::StyleRefinement>>,
}

impl RadioGroup {
    pub fn variant(mut self, variant: FieldVariant) -> Self {
        self.variant = variant;
        self
    }

    pub fn is_invalid(mut self, v: bool) -> Self {
        self.is_invalid = v;
        self
    }

    pub fn is_required(mut self, v: bool) -> Self {
        self.is_required = v;
        self
    }

    /// `isReadOnly` — the value is shown but cannot be changed.
    pub fn is_read_only(mut self, v: bool) -> Self {
        self.is_read_only = v;
        self
    }

    /// `Radio`'s root render function — handed the option's label and v3's
    /// field state: selected, disabled, read-only, invalid and required.
    pub fn option_content(
        mut self,
        render: impl Fn(&SharedString, RadioOptionState) -> gpui::AnyElement + 'static,
    ) -> Self {
        self.option_content = Some(std::sync::Arc::new(render));
        self
    }

    /// `Radio.Indicator` — draws each option's indicator from its field state.
    pub fn indicator(
        mut self,
        render: impl Fn(&SharedString, RadioOptionState) -> gpui::AnyElement + 'static,
    ) -> Self {
        self.indicator = Some(std::sync::Arc::new(render));
        self
    }

    /// The per-option descriptions, in the order the options were given. v3
    /// writes one `<Description>` inside each `<Radio>`; a monolithic group
    /// takes the column instead.
    pub fn descriptions<T: Into<SharedString>>(
        mut self,
        text: impl IntoIterator<Item = Option<T>>,
    ) -> Self {
        self.descriptions = text.into_iter().map(|opt| opt.map(Into::into)).collect();
        self
    }

    pub fn new(id: impl Into<gpui::ElementId>, options: Vec<RadioOption>) -> Self {
        Self {
            name: None,
            id: id.into(),
            options,
            form_state: Rc::new(RefCell::new(crate::form::LiveFormFieldState {
                value: crate::form::FormValue::Text(SharedString::default()),
                is_invalid: false,
                is_successful: true,
                focus: None,
                restore: None,
            })),
            option_content: None,
            indicator: None,
            descriptions: Vec::new(),
            label: None,
            description: None,
            error_message: None,
            selected: None,
            is_controlled: false,
            default_value: None,
            orientation: Orientation::Vertical,
            is_disabled: false,
            variant: FieldVariant::Primary,
            is_invalid: false,
            is_required: false,
            is_read_only: false,
            on_change: None,
            size: RadioSize::default(),
            radius: None,
            full_width: false,
            sx: None,
        }
    }

    /// The `<Label>` v3 composes inside the group.
    pub fn label(mut self, text: impl Into<SharedString>) -> Self {
        self.label = Some(text.into());
        self
    }

    /// The `<Description>` v3 composes inside the group, below its options.
    pub fn description(mut self, text: impl Into<SharedString>) -> Self {
        self.description = Some(text.into());
        self
    }

    /// The `<FieldError>` v3 composes inside the group; supplying it also marks
    /// the group invalid, as every other field in this port does.
    pub fn error_message(mut self, text: impl Into<SharedString>) -> Self {
        self.error_message = Some(text.into());
        self
    }

    /// `name` — the name this control submits under.
    pub fn name(mut self, name: impl Into<SharedString>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// The `Form` field this control submits, when it has a `name`.
    ///
    /// v3 discovers a field through the DOM; gpui gives a child no way to reach
    /// its ancestor, so the control hands the pair over instead. Borrows, so the
    /// control is still yours to place:
    ///
    /// ```
    /// # use gpui::{prelude::*, Window};
    /// # use herogpui_components::{Form, RadioGroup, RadioOption};
    /// # struct Demo;
    /// # impl Render for Demo {
    /// #     fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
    /// #         let form = Form::new();
    /// #         let control = RadioGroup::new("plan", vec![RadioOption::new("Pro")]).name("plan");
    /// let field = control.form_field();
    /// form.field(field.unwrap()).child(control)
    /// #     }
    /// # }
    /// # let mut tcx = gpui::TestAppContext::single();
    /// # tcx.update(herogpui_theme::ThemeProvider::init);
    /// # let _ = tcx.add_window_view(|_, _| Demo);
    /// ```
    pub fn form_field(&self) -> Option<crate::form::FormField> {
        let name = self.name.clone()?;
        let selected = if self.is_controlled {
            self.selected
        } else {
            self.default_value
        };
        {
            let mut state = self.form_state.borrow_mut();
            state.value = crate::form::FormValue::Text(
                selected
                    .and_then(|index| self.options.get(index))
                    .map(|option| option.value.clone())
                    .unwrap_or_default(),
            );
            state.is_invalid = self.is_invalid
                || self.error_message.is_some()
                || self
                    .options
                    .iter()
                    .any(|option| option.error_message.is_some());
            state.is_successful = !self.is_disabled;
        }
        Some(
            crate::form::FormField::live(name, self.form_state.clone())
                .is_required(self.is_required),
        )
    }

    /// `value` — the selected option's value. Supplying it makes the group controlled.
    pub fn value(mut self, value: impl AsRef<str>) -> Self {
        self.selected = self
            .options
            .iter()
            .position(|option| option.value == value.as_ref());
        self.form_state.borrow_mut().value = crate::form::FormValue::Text(
            self.selected
                .and_then(|index| self.options.get(index))
                .map(|option| option.value.clone())
                .unwrap_or_default(),
        );
        self.is_controlled = true;
        self
    }

    /// `defaultValue` — the uncontrolled initial selection.
    ///
    /// Only consulted when `value` is not supplied; the group then owns the
    /// selection and a press moves it.
    pub fn default_value(mut self, value: impl AsRef<str>) -> Self {
        self.default_value = self
            .options
            .iter()
            .position(|option| option.value == value.as_ref());
        if !self.is_controlled {
            self.form_state.borrow_mut().value = crate::form::FormValue::Text(
                self.default_value
                    .and_then(|index| self.options.get(index))
                    .map(|option| option.value.clone())
                    .unwrap_or_default(),
            );
        }
        self
    }

    pub fn orientation(mut self, o: Orientation) -> Self {
        self.orientation = o;
        self
    }

    pub fn is_disabled(mut self, v: bool) -> Self {
        self.is_disabled = v;
        self
    }

    pub fn on_change(mut self, f: impl Fn(&SharedString, &mut Window, &mut App) + 'static) -> Self {
        self.on_change = Some(std::sync::Arc::new(f));
        self
    }

    /// Sets the compact step. `Md` is the default and byte-identical to the
    /// pinned control; `Sm` is a 14px control with a 5px dot, 12px label text
    /// (16px leading) and a 10px row gap. Not a v3 prop.
    pub fn size(mut self, size: RadioSize) -> Self {
        self.size = size;
        self
    }

    /// The radio control's corner radius, in place of the owning `key_radius`
    /// helper: the control circle takes it and its pressed box scales the same
    /// value instead of snapping back to the helper, while the selected dot
    /// inside is an inner part and keeps its own. Not a v3 prop; the removed
    /// v2 `radius` prop is prohibited and this is a per-component repository
    /// extension.
    pub fn radius(mut self, radius: impl Into<Pixels>) -> Self {
        self.radius = Some(radius.into());
        self
    }

    /// `fullWidth` — expands the root to the available width without
    /// redistributing the children.
    pub fn full_width(mut self, v: bool) -> Self {
        self.full_width = v;
        self
    }

    /// The one slot for caller-owned low-level styling: GPUI's styling methods
    /// (`bg`, `text_color`, `w`, `h`, `p`, `rounded`, `border_color`, …)
    /// applied to the radio group's root element after every value the
    /// orientation and the active theme chose, so they win.
    pub fn sx(mut self, style: impl FnOnce(gpui::Div) -> gpui::Div) -> Self {
        self.sx = Some(crate::util::capture_sx(style));
        self
    }
}

impl RenderOnce for RadioGroup {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        // `controlled` takes `cx` mutably, so it precedes the theme tokens.
        let (selected, own) = crate::util::controlled(
            window,
            cx,
            element_id::scoped(&self.id, "value"),
            self.is_controlled.then_some(self.selected),
            self.default_value,
        );
        let is_invalid = self.is_invalid
            || self.error_message.is_some()
            || self
                .options
                .iter()
                .any(|option| option.error_message.is_some());
        let selected_value = selected
            .and_then(|index| self.options.get(index))
            .map(|option| option.value.clone())
            .unwrap_or_default();
        {
            let mut state = self.form_state.borrow_mut();
            state.value = crate::form::FormValue::Text(selected_value);
            state.is_invalid = is_invalid;
            state.is_successful = !self.is_disabled;
        }

        let reset_own = own.clone();
        let reset_state = Rc::downgrade(&self.form_state);
        let reset_change = self.is_controlled.then(|| self.on_change.clone()).flatten();
        let reset_index = self.default_value;
        let reset_value = reset_index
            .and_then(|index| self.options.get(index))
            .map(|option| option.value.clone())
            .unwrap_or_default();
        self.form_state.borrow_mut().restore = (reset_own.is_some() || reset_change.is_some())
            .then(|| {
                crate::util::shared(move |window: &mut Window, cx: &mut App| {
                    if let Some(state) = reset_state.upgrade() {
                        state.borrow_mut().value =
                            crate::form::FormValue::Text(reset_value.clone());
                    }
                    if let Some(held) = &reset_own {
                        held.update(cx, |selected, cx| {
                            *selected = reset_index;
                            cx.notify();
                        });
                    }
                    if let Some(on_change) = &reset_change {
                        on_change(&reset_value, window, cx);
                    }
                }) as std::sync::Arc<dyn Fn(&mut Window, &mut App)>
            });

        // *One* handle for the whole group, because a radio group is one tab
        // stop. Which row claims it is what moves: a roving tab stop cannot be
        // done by flipping a handle's `tab_stop`, since that is fixed where the
        // handle is made. `use_keyed_state` takes `cx` mutably, so it precedes
        // the theme.
        // Every per-option id hangs off the group id as structure, so a
        // per-option key costs an `Arc` clone rather than a fresh `String`.
        let id_prefix = self.id.clone();
        let group_focus =
            crate::util::tab_stop_handle(element_id::scoped(&id_prefix, "focus"), window, cx);
        self.form_state.borrow_mut().focus = Some(group_focus.clone());

        // A radio group is *one* tab stop: Tab moves past the whole group and
        // the arrows choose within it, which is the ARIA radio-group pattern
        // React Aria implements. The stop is the selected option, or the first
        // when nothing is selected yet.
        //
        // `Radio.isDisabled` options are left out of `stops` -- the list the
        // arrows and Home/End walk -- so the cursor never lands on one. The
        // tab stop skips them too: a stop resting on a disabled option has no
        // row to claim the group's handle (AGENTS.md's roving tab stop), which
        // would take the whole group out of the tab order. So with nothing
        // selected and the first option disabled, the group is still reachable
        // by Tab, on the first *enabled* option. With every option disabled
        // `stops` is empty, no row tracks the handle, and the group leaves the
        // tab order exactly as the group-wide `is_disabled` does.
        // `Arc` because every enabled option's key handler captures the whole
        // list: a plain clone per option was O(n^2) per frame.
        let stops: std::sync::Arc<Vec<usize>> = std::sync::Arc::new(
            (0..self.options.len())
                .filter(|i| !self.options[*i].is_disabled)
                .collect(),
        );
        let initial_focus_index = selected
            .filter(|i| stops.contains(i))
            .or_else(|| stops.first().copied())
            .unwrap_or(0);
        // Actual focus and selection diverge in a read-only group: React
        // Aria's arrow handler focuses the next input first, then its stately
        // setter rejects the value change. Keep that roving cursor separately
        // from `selected`, keyed by the component id so two groups cannot
        // share it.
        let cursor =
            window.use_keyed_state(element_id::scoped(&id_prefix, "cursor"), cx, move |_, _| {
                initial_focus_index
            });
        let held_cursor = *cursor.read(cx);
        let cursor_index = if group_focus.is_focused(window) && stops.contains(&held_cursor) {
            held_cursor
        } else {
            initial_focus_index
        };

        // One hover/press slot per option. The row's press grows the selected
        // indicator from 6px to 8px.
        let interaction: Vec<crate::util::Interaction> = (0..self.options.len())
            .map(|i| {
                crate::util::interaction(
                    element_id::scoped(&element_id::indexed(&id_prefix, "opt", i), "interaction"),
                    window,
                    cx,
                )
            })
            .collect();

        let sem = cx.role(Color::Accent);
        let colors = cx.colors();
        let layout = cx.layout();
        // `.radio__control` is `size-4 rounded-lg` — a rounded square, not a
        // circle — and `.radio__indicator` fills it at `rounded-lg` too.
        // The selected dot is the indicator scaled to `0.4286` of the 16px
        // control, which v3's own comment rounds to 6px. (8px is its *pressed*
        // size, `scale: 0.5714`.)
        let (circle, dot, text, gap) = self.size.metrics();

        // `.radio-group` spaces its options with `mt-4` when vertical and
        // `gap-4` when horizontal — 16px either way.
        let mut group = match self.orientation {
            Orientation::Horizontal => gpui::div().flex().items_center().flex_wrap().gap(px(16.)),
            Orientation::Vertical => gpui::div().flex().flex_col().gap(px(16.)),
        };
        // `.radio-group--secondary` is not a panel: it only repaints the
        // *control* with `--default` and drops its shadow. This used to wrap the
        // whole group in a padded `surface_secondary` card, which v3 has no rule
        // for.
        let control_bg = match self.variant {
            FieldVariant::Primary => colors.field.background,
            FieldVariant::Secondary => colors.default.color,
        };
        let control_shadow = (self.variant == FieldVariant::Primary
            && !layout.field_shadow.is_empty())
        .then(|| layout.field_shadow.clone());

        // The control circle's radius, resolved once: the pressed box below
        // scales the same value instead of snapping back to the helper.
        let control_radius = self.radius.unwrap_or_else(|| crate::util::key_radius(cx));

        let option_values: std::sync::Arc<Vec<SharedString>> = std::sync::Arc::new(
            self.options
                .iter()
                .map(|option| option.value.clone())
                .collect(),
        );
        for (i, option) in self.options.into_iter().enumerate() {
            let label = option.label;
            let value = option.value;
            let description = option
                .description
                .or_else(|| self.descriptions.get(i).and_then(|text| text.clone()));
            let error_message = option.error_message;
            let is_selected = selected == Some(i);
            let option_invalid =
                self.is_invalid || self.error_message.is_some() || error_message.is_some();
            // `Radio.isDisabled` — the option's own switch, beside the
            // group-wide `is_disabled`: dimmed (`status-disabled`'s opacity,
            // v3's "reduced opacity, no pointer events"), no pointer
            // affordance, no click handler and no place in the tab order or
            // the arrow navigation.
            let row_disabled = self.is_disabled || option.is_disabled;
            let (is_hovered, is_pressed) = interaction
                .get(i)
                .map(|slot| *slot.read(cx))
                .unwrap_or_default();
            let option_state = RadioOptionState {
                is_selected,
                is_disabled: row_disabled,
                is_read_only: self.is_read_only,
                is_invalid: option_invalid,
                is_required: self.is_required,
            };
            // `.radio__control` uses the field border width and shadow from the
            // active theme. Unselected hover changes its fill; selected hover
            // keeps `bg-accent` and only changes the border, matching
            // `radio.css` where `bg-accent-hover` is reserved for press.
            let hover_bg = match self.variant {
                FieldVariant::Primary => colors.field.hover(),
                FieldVariant::Secondary => colors.default.hover(),
            };
            let mut circle_el = gpui::div()
                .id(element_id::scoped(
                    &element_id::indexed(&id_prefix, "opt", i),
                    "control",
                ))
                .flex()
                .items_center()
                .justify_center()
                .size(circle)
                .rounded(control_radius)
                .flex_shrink_0()
                .border(layout.field_border_width)
                // HeroUI removes the field border from the selected control;
                // the accent fill owns that edge. An enabled custom theme can
                // expose a nonzero field border, so keep the selected state
                // transparent instead of letting the base border show through.
                .border_color(if is_selected {
                    gpui::transparent_black()
                } else {
                    colors.field.border
                })
                .bg(if is_selected { sem.color } else { control_bg })
                .when(is_hovered && !row_disabled, |el| {
                    el.border_color(colors.field.border_hover())
                        .when(!is_selected, |el| el.bg(hover_bg))
                })
                .when_some(control_shadow.clone(), |el, shadows| el.shadow(shadows));

            if let Some(render) = &self.indicator {
                circle_el = circle_el.child(render(&label, option_state));
            } else if is_selected {
                circle_el = circle_el.child(
                    gpui::div()
                        .size(if is_pressed { px(8.) } else { dot })
                        .rounded(crate::util::key_radius(cx))
                        .bg(sem.foreground),
                );
            }
            // `status-invalid-field` is a 1px danger outline over whatever the
            // control already paints — it does not replace the fill, and v3
            // applies it whether or not the option is selected.
            if option_invalid {
                circle_el = circle_el.border_1().border_color(colors.danger.color);
            }

            // v3 focuses the radio and rings `.radio__control`: the row takes the
            // focus, the control shows it.
            let focused = i == cursor_index
                && group_focus.is_focused(window)
                && crate::util::focus_visible(cx);
            // The ring is an overlay child on the control itself, not on the
            // press skin `anim::pressed_with_background` builds below: the
            // control is the element that carries `control_radius` and the one
            // v3 rings, and the press refinement lands on that same element, so
            // the overlay scales with it. Concentric by construction, where the
            // spread shadow repeated the control's radius two pixels out.
            let circle_el = crate::util::with_focus_ring_overlay(
                circle_el,
                focused && !row_disabled,
                true,
                control_radius,
                control_shadow.clone().unwrap_or_default(),
                cx,
            );

            // `.radio__control[data-pressed]` is `scale-95`, and a checked one
            // also fills with `bg-accent-hover`. A disabled option cannot be
            // pressed, so it skips the animation like a read-only one.
            let circle_el = if row_disabled || self.is_read_only {
                circle_el
            } else {
                // The pressed fill rides inside the press refinement, which
                // owns the scale; a chained `.active` would replace it.
                let pressed_fill = sem.hover();
                if is_selected {
                    crate::anim::pressed_with_background(
                        circle_el,
                        crate::anim::PressBox {
                            height: circle,
                            padding_x: None,
                            width: Some(circle),
                            min_width: None,
                            text_size: text,
                            line_height: text,
                            gap: px(0.),
                            radius: control_radius,
                            shrink_x: true,
                            scale: crate::anim::PRESSED_SCALE_DEEP,
                        },
                        pressed_fill,
                        cx,
                    )
                } else {
                    crate::anim::pressed(
                        circle_el,
                        crate::anim::PressBox {
                            height: circle,
                            padding_x: None,
                            width: Some(circle),
                            min_width: None,
                            text_size: text,
                            line_height: text,
                            gap: px(0.),
                            radius: control_radius,
                            shrink_x: true,
                            scale: crate::anim::PRESSED_SCALE_DEEP,
                        },
                        cx,
                    )
                }
            };

            // Each option is a native `<input type="radio">` upstream, so its
            // role is `radio` and `aria-checked` follows the selection.
            let option_name = a11y::Name::field(
                Some(&label),
                description.as_ref(),
                &crate::validation::resolve(option_invalid, &[], None, error_message.clone()),
            );
            let mut row = gpui::div()
                .id(element_id::indexed(&id_prefix, "opt", i))
                .a11y_named(a11y::Role::RadioButton, &option_name)
                .a11y_checked(is_selected, false)
                .when(!row_disabled && i == cursor_index, |r| {
                    r.track_focus(&group_focus)
                })
                .flex()
                .items_center()
                .gap(gap)
                .text_size(text)
                .line_height(crate::util::leading_for(text).unwrap_or(px(20.)))
                .font_weight(gpui::FontWeight::MEDIUM)
                .text_color(colors.foreground)
                .when(!row_disabled && !self.is_read_only, |r| {
                    r.cursor(crate::util::interactive_cursor(cx))
                })
                .when(row_disabled, |r| r.opacity(layout.disabled_opacity))
                .child(circle_el)
                .child(match &self.option_content {
                    Some(render) => render(&label, option_state),
                    None => label.into_any_element(),
                });
            if !row_disabled && !self.is_read_only {
                if let Some(slot) = interaction.get(i) {
                    row = crate::util::track_interaction(row, slot);
                }
            }

            if !row_disabled {
                let on_change = self.on_change.clone();
                let own = own.clone();
                let read_only = self.is_read_only;
                // The arrows always take focus with them. In a mutable group
                // they also select; read-only keeps the cursor movement and
                // rejects only that second step, matching the pinned hooks.
                let key_change = on_change.clone();
                let key_own = own.clone();
                let key_stops = stops.clone();
                let key_cursor = cursor.clone();
                let key_values = option_values.clone();
                let key_form_state = self.form_state.clone();
                row = row.on_key_down(move |event, window, cx| {
                    let key = match event.keystroke.key.as_str() {
                        "down" | "right" => "down",
                        "up" | "left" => "up",
                        _ => return,
                    };
                    // `useRadioGroup` owns all four arrows, but has no Home or
                    // End shortcut. Leave those and every other key available
                    // to the enclosing surface.
                    cx.stop_propagation();
                    let crate::list_nav::Move::To(next) =
                        crate::list_nav::resolve(&key_stops, Some(i), key, true)
                    else {
                        return;
                    };
                    key_cursor.update(cx, |v, cx| {
                        *v = next;
                        cx.notify();
                    });
                    if !read_only {
                        if let Some(held) = &key_own {
                            key_form_state.borrow_mut().value =
                                crate::form::FormValue::Text(key_values[next].clone());
                            held.update(cx, |v, cx| {
                                *v = Some(next);
                                cx.notify();
                            });
                        }
                        if let Some(f) = &key_change {
                            f(&key_values[next], window, cx);
                        }
                    }
                });
                let click_cursor = cursor.clone();
                let click_focus = group_focus.clone();
                let click_form_state = self.form_state.clone();
                row = row.on_click(move |_, window, cx| {
                    window.focus(&click_focus, cx);
                    click_cursor.update(cx, |v, cx| {
                        *v = i;
                        cx.notify();
                    });
                    if !read_only {
                        // Uncontrolled: move our own selection, or pressing a
                        // radio would do nothing.
                        if let Some(held) = &own {
                            click_form_state.borrow_mut().value =
                                crate::form::FormValue::Text(value.clone());
                            held.update(cx, |v, cx| {
                                *v = Some(i);
                                cx.notify();
                            });
                        }
                        if let Some(f) = &on_change {
                            f(&value, window, cx);
                        }
                    }
                });
            }

            // `.radio` is `flex flex-col gap-1` around its content and the
            // description, which `ps-7` indents under the label -- the control
            // plus the content gap.
            match (error_message, description) {
                (Some(message), _) => {
                    group = group.child(
                        gpui::div().flex().flex_col().gap(px(4.)).child(row).child(
                            gpui::div()
                                .pl(circle + gap)
                                .child(crate::field::ErrorMessage::new(message)),
                        ),
                    );
                }
                (None, Some(text)) => {
                    group = group.child(
                        gpui::div().flex().flex_col().gap(px(4.)).child(row).child(
                            gpui::div()
                                .pl(circle + gap)
                                .child(crate::field::Description::new(text)),
                        ),
                    );
                }
                (None, None) => group = group.child(row),
            }
        }

        // `.radio` is `flex flex-col gap-1`, and the group's own label,
        // description and error are its siblings. v3 marks `isRequired` on the
        // Label rather than adding a line of its own, which is what
        // `field::Label` draws.
        // `useRadioGroup` is `role="radiogroup"` with `aria-orientation`
        // always present (it defaults to `vertical`), named and described
        // through `useField`.
        let group_name = a11y::Name::field(
            self.label.as_ref(),
            self.description.as_ref(),
            &crate::validation::resolve(is_invalid, &[], None, self.error_message.clone()),
        );
        let mut root = gpui::div()
            .id(self.id.clone())
            .a11y_named(a11y::Role::RadioGroup, &group_name)
            .a11y_orientation(self.orientation)
            .flex()
            .flex_col()
            .gap(px(4.));
        if self.full_width {
            root = root.w_full();
        }
        if let Some(label) = &self.label {
            root = root.child(
                crate::field::Label::new(label.clone())
                    .is_required(self.is_required)
                    .is_disabled(self.is_disabled)
                    .is_invalid(is_invalid),
            );
        }
        // v3's order, from its own examples: the group's `<Description>` sits
        // between the label and the options, and its `<FieldError>` after them.
        // (A *field*'s description is replaced by its error; `radio-group.css`
        // has no rule hiding this one, so both can show.)
        if let Some(description) = &self.description {
            root = root.child(crate::field::Description::new(description.clone()));
        }
        root = root.child(group);
        let error = is_invalid.then(|| self.error_message.clone()).flatten();
        if let Some(error) = crate::anim::field_error_panel(&self.id, error, window, cx) {
            root = root.child(error);
        }
        root = crate::util::apply_sx(root, &self.sx);
        root
    }
}

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

    /// Render wraps the walk list and the value list in `Arc` so every enabled
    /// option's key handler clones the pointer, not the Vec.
    #[test]
    fn option_key_handlers_share_walk_and_value_lists() {
        let source = include_str!("radio_group.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(
            source.contains("let stops: std::sync::Arc<Vec<usize>> = std::sync::Arc::new("),
            "the walk list must be one Arc shared by every enabled option"
        );
        assert!(
            source.contains(
                "let option_values: std::sync::Arc<Vec<SharedString>> = std::sync::Arc::new("
            ),
            "the value list must be one Arc shared by every enabled option"
        );
        assert!(
            source.contains("let key_stops = stops.clone();"),
            "each enabled option must clone the shared walk list"
        );
        assert!(
            source.contains("let key_values = option_values.clone();"),
            "each enabled option must clone the shared value list"
        );

        // The clones above are `Arc::clone`: two handles to one allocation.
        let stops: std::sync::Arc<Vec<usize>> = std::sync::Arc::new(vec![0, 1, 2]);
        let values: std::sync::Arc<Vec<SharedString>> =
            std::sync::Arc::new(vec![SharedString::from("v0")]);
        let walk = std::sync::Arc::clone(&stops);
        let list = std::sync::Arc::clone(&values);
        assert!(
            std::sync::Arc::ptr_eq(&walk, &stops) && std::sync::Arc::ptr_eq(&list, &values),
            "Arc clones of the walk and value lists must share pointer identity"
        );
    }

    #[test]
    fn hover_background_respects_selection_and_variant() {
        let source = include_str!("radio_group.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("the implementation section is always present");
        assert!(source.contains("let hover_bg = match self.variant"));
        assert!(source.contains("FieldVariant::Primary => colors.field.hover()"));
        assert!(source.contains("FieldVariant::Secondary => colors.default.hover()"));
        assert!(source.contains(".when(is_hovered && !row_disabled"));
        assert!(source.contains(".when(!is_selected, |el| el.bg(hover_bg))"));
        assert!(source.contains("colors.field.border_hover()"));
        assert!(source.contains("if is_selected {\n                    gpui::transparent_black()"));
    }
}

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

    #[test]
    fn md_is_the_pinned_geometry_and_sm_scales_together() {
        assert_eq!(RadioSize::default(), RadioSize::Md);
        assert_eq!(RadioSize::Md.metrics(), (px(16.), px(6.), px(14.), px(12.)));
        assert_eq!(RadioSize::Sm.metrics(), (px(14.), px(5.), px(12.), px(10.)));
        assert_eq!(
            crate::util::leading_for(RadioSize::Sm.metrics().2),
            Some(px(16.))
        );
    }
}