u0ui 0.3.4

Carbon UI: IBM Carbon v11 visuals with a shadcn-style API for GPUI Kit
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
//! T3 · Pull requests & issues: the discussion parts — [`ReactionBar`],
//! [`PullRequestTimeline`] and [`ReviewForm`] (`src/t3.css` "PR vocabulary").
use super::pr_detail::icon_button;
use super::pull_request::{ReviewDecision, ReviewDecisionBadge};
use crate::{
    components::{AvatarColor, Button, ButtonSize, ButtonVariant, Textarea, TextareaState},
    icons::{CarbonIcon, Icon},
    t3::craft::{self, AvatarTone, focus_handle, focus_visible, press, rem, sans},
    theme::{LayerLevel, color},
    tokens::ColorRole,
};
use gpui_kit::{
    AnyElement, App, AppContext as _, ElementId, FocusHandle, Hsla, InteractiveElement,
    IntoElement, KeyDownEvent, ParentElement, RenderOnce, SharedString,
    StatefulInteractiveElement as _, Styled, Window, div, prelude::FluentBuilder as _, px,
    relative,
};
use std::rc::Rc;

type Handler = Rc<dyn Fn(&mut Window, &mut App)>;
type IndexHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type EventEmojiHandler = Rc<dyn Fn(usize, SharedString, &mut Window, &mut App)>;

/// One reaction (`reactions[]`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Reaction {
    /// `emoji`.
    pub emoji: SharedString,
    /// `count`.
    pub count: usize,
    /// `mine`: the viewer reacted (`aria-pressed`).
    pub mine: bool,
}

impl Reaction {
    /// A reaction.
    pub fn new(emoji: impl Into<SharedString>, count: usize) -> Self {
        Self {
            emoji: emoji.into(),
            count,
            mine: false,
        }
    }

    /// The viewer's own reaction.
    pub fn mine(mut self, mine: bool) -> Self {
        self.mine = mine;
        self
    }
}

type EmojiHandler = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;

/// Emoji reaction pills (`.t3-react`: 24px, 16px radius, `layer-accent-01`;
/// mine = blue tag pair with a 1px `border-interactive` ring) and an Add
/// reaction icon button.
#[derive(IntoElement)]
pub struct ReactionBar {
    id: ElementId,
    reactions: Vec<Reaction>,
    square: bool,
    on_react: Option<EmojiHandler>,
    on_add: Option<Handler>,
    add_label: SharedString,
}

impl ReactionBar {
    /// A reaction bar.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            reactions: Vec::new(),
            square: false,
            on_react: None,
            on_add: None,
            add_label: "Add reaction".into(),
        }
    }

    /// Square reaction chips (`border-radius: 0` on PR detail).
    pub fn square(mut self, square: bool) -> Self {
        self.square = square;
        self
    }

    /// The reactions.
    pub fn reactions(mut self, reactions: impl IntoIterator<Item = Reaction>) -> Self {
        self.reactions = reactions.into_iter().collect();
        self
    }

    /// A pill was pressed (`onReact(emoji)`).
    pub fn on_react(mut self, f: impl Fn(SharedString, &mut Window, &mut App) + 'static) -> Self {
        self.on_react = Some(Rc::new(f));
        self
    }

    /// Add reaction pressed.
    pub fn on_add(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_add = Some(Rc::new(f));
        self
    }

    /// The add button's name (`Add reaction`).
    pub fn add_label(mut self, label: impl Into<SharedString>) -> Self {
        self.add_label = label.into();
        self
    }
}

/// (fill, ink, ring) of a reaction pill.
pub fn reaction_look(mine: bool, hovered: bool) -> (Hsla, Hsla, Option<Hsla>) {
    if mine {
        // `.t3-react--mine` (0,1,0) after `.t3-react:hover` (0,2,0): hover wins the fill.
        (
            color(if hovered {
                ColorRole::LayerAccentHover01
            } else {
                ColorRole::TagBackgroundBlue
            }),
            color(ColorRole::TagColorBlue),
            Some(color(ColorRole::BorderInteractive)),
        )
    } else {
        (
            color(if hovered {
                ColorRole::LayerAccentHover01
            } else {
                ColorRole::LayerAccent01
            }),
            color(ColorRole::TextPrimary),
            None,
        )
    }
}

impl RenderOnce for ReactionBar {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        div()
            .flex()
            .flex_wrap()
            .items_center()
            .gap(rem(4.))
            .children(self.reactions.iter().enumerate().map(|(i, r)| {
                let rid = craft::sub(&id, "r", i);
                let focus = focus_handle(&rid, window, cx);
                let ring = focus_visible(&focus, window);
                let hovered = window
                    .use_keyed_state((rid.clone(), "hover"), cx, |_, _| false)
                    .clone();
                let (fill, ink, edge) = reaction_look(r.mine, *hovered.read(cx));
                let on_react = self.on_react.clone();
                let emoji = r.emoji.clone();
                let pill_radius = if self.square { rem(0.) } else { rem(16.) };
                sans(press(rid, &focus), 12., 400)
                    .gap(rem(4.))
                    .h(rem(24.))
                    .px(rem(8.))
                    .rounded(pill_radius)
                    .bg(fill)
                    .text_color(ink)
                    .when_some(edge, |this, c| this.border_1().border_color(c).px(rem(7.)))
                    .on_hover(move |h, _, cx| {
                        hovered.update(cx, |v, cx| {
                            *v = *h;
                            cx.notify();
                        })
                    })
                    .when_some(on_react, |this, f| {
                        this.on_click(move |_, w, cx| f(emoji.clone(), w, cx))
                    })
                    .child(r.emoji.clone())
                    .child(r.count.to_string())
                    .when(ring, |this| {
                        this.child(
                            div()
                                .absolute()
                                .top(px(-2.))
                                .left(px(-2.))
                                .right(px(-2.))
                                .bottom(px(-2.))
                                .rounded(pill_radius)
                                .border_2()
                                .border_color(color(ColorRole::Focus)),
                        )
                    })
            }))
            .child(icon_button(
                (id, "add"),
                self.add_label.clone(),
                CarbonIcon::FaceAdd,
                self.on_add.clone(),
            ))
    }
}

/// A timeline event kind (`events[].kind`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum EventKind {
    /// `commit`.
    #[default]
    Commit,
    /// `label`.
    Label,
    /// `merged`.
    Merged,
    /// `push`.
    Push,
    /// `ref`.
    Ref,
    /// `comment`: a card.
    Comment,
    /// `review`: a card with a decision.
    Review,
}

impl EventKind {
    /// Every kind.
    pub const ALL: [EventKind; 7] = [
        Self::Commit,
        Self::Label,
        Self::Merged,
        Self::Push,
        Self::Ref,
        Self::Comment,
        Self::Review,
    ];

    /// Comments and reviews render as cards.
    pub const fn is_card(self) -> bool {
        matches!(self, Self::Comment | Self::Review)
    }

    /// The marker icon of a plain event (`Commit`, `Tag`, `Merge`, `Upload`, `Link`).
    pub const fn icon(self) -> CarbonIcon {
        match self {
            Self::Commit => CarbonIcon::Commit,
            Self::Label => CarbonIcon::Tag,
            Self::Merged => CarbonIcon::Merge,
            Self::Push => CarbonIcon::Upload,
            Self::Ref => CarbonIcon::Link,
            Self::Comment | Self::Review => CarbonIcon::CircleFilled,
        }
    }

    /// Marker ink: `icon-secondary`; merged `tag-color-purple`.
    pub fn ink(self) -> Hsla {
        color(match self {
            Self::Merged => ColorRole::TagColorPurple,
            _ => ColorRole::IconSecondary,
        })
    }
}

/// One timeline event.
pub struct TimelineEvent {
    kind: EventKind,
    actor: SharedString,
    text: SharedString,
    body: SharedString,
    review: Option<ReviewDecision>,
    time: SharedString,
    color: Option<AvatarColor>,
    marker: Option<AnyElement>,
    reactions: Option<Vec<Reaction>>,
}

impl TimelineEvent {
    /// An event of `kind` by `actor` at `time`.
    pub fn new(
        kind: EventKind,
        actor: impl Into<SharedString>,
        time: impl Into<SharedString>,
    ) -> Self {
        Self {
            kind,
            actor: actor.into(),
            text: SharedString::default(),
            body: SharedString::default(),
            review: None,
            time: time.into(),
            color: None,
            marker: None,
            reactions: None,
        }
    }

    /// The event kind.
    pub fn kind(&self) -> EventKind {
        self.kind
    }

    /// The event text after the actor (plain events).
    pub fn text(mut self, text: impl Into<SharedString>) -> Self {
        self.text = text.into();
        self
    }

    /// The card body (comments and reviews).
    pub fn body(mut self, body: impl Into<SharedString>) -> Self {
        self.body = body.into();
        self
    }

    /// The review decision.
    pub fn review(mut self, review: ReviewDecision) -> Self {
        self.review = Some(review);
        self
    }

    /// The avatar color (default: a stable tone hashed from the actor).
    pub fn color(mut self, color: AvatarColor) -> Self {
        self.color = Some(color);
        self
    }

    /// A custom card marker in place of the avatar (`provider` →
    /// `ProviderIcon size="sm"` in the reference).
    pub fn marker(mut self, marker: impl IntoElement) -> Self {
        self.marker = Some(marker.into_any_element());
        self
    }

    /// Reactions under the body.
    pub fn reactions(mut self, reactions: impl IntoIterator<Item = Reaction>) -> Self {
        self.reactions = Some(reactions.into_iter().collect());
        self
    }
}

/// The PR event timeline (`.t3-prtl`): a 1px rule at x = 11px joins 24px
/// markers; plain events are one line, comments and reviews are `layer-01`
/// cards with actor, decision, time, Add to thread, body and reactions.
#[derive(IntoElement)]
pub struct PullRequestTimeline {
    id: ElementId,
    events: Vec<TimelineEvent>,
    add_label: SharedString,
    square_reactions: bool,
    on_add_to_thread: Option<IndexHandler>,
    on_react: Option<EventEmojiHandler>,
}

impl PullRequestTimeline {
    /// A timeline.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            events: Vec::new(),
            add_label: "Add to thread".into(),
            square_reactions: false,
            on_add_to_thread: None,
            on_react: None,
        }
    }

    /// Square reaction pills (`true` on PR detail).
    pub fn square_reactions(mut self, square: bool) -> Self {
        self.square_reactions = square;
        self
    }

    /// The events, oldest first.
    pub fn events(mut self, events: impl IntoIterator<Item = TimelineEvent>) -> Self {
        self.events = events.into_iter().collect();
        self
    }

    /// The card action text (`Add to thread`).
    pub fn add_label(mut self, label: impl Into<SharedString>) -> Self {
        self.add_label = label.into();
        self
    }

    /// Add to thread pressed on event `i`.
    pub fn on_add_to_thread(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
        self.on_add_to_thread = Some(Rc::new(f));
        self
    }

    /// A reaction pill on event `i` was pressed.
    pub fn on_react(
        mut self,
        f: impl Fn(usize, SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_react = Some(Rc::new(f));
        self
    }
}

impl RenderOnce for PullRequestTimeline {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let square_reactions = self.square_reactions;
        let secondary = color(ColorRole::TextSecondary);
        let items = self.events.into_iter().enumerate().map(|(i, e)| {
            let marker = if e.kind.is_card() {
                e.marker.unwrap_or_else(|| {
                    let tone = e
                        .color
                        .map(AvatarTone::Avatar)
                        .unwrap_or_else(|| craft::actor_tone(&e.actor));
                    craft::initials(craft::two_letters(&e.actor), tone, 24.).into_any_element()
                })
            } else {
                Icon::carbon(e.kind.icon())
                    .size_length(rem(16.))
                    .color(e.kind.ink())
                    .into_any_element()
            };
            // `.t3-prtl-marker { 24×24; background: var(--background); z-index: 1 }`.
            let marker = div()
                .flex()
                .flex_none()
                .items_center()
                .justify_center()
                .size(rem(24.))
                .bg(color(ColorRole::Background))
                .child(marker);
            let content = if e.kind.is_card() {
                let on_add = self.on_add_to_thread.clone();
                let on_react = self.on_react.clone();
                div()
                    .flex_1()
                    .min_w_0()
                    .bg(color(ColorRole::Layer01))
                    .child(
                        sans(div(), 12., 400)
                            .flex()
                            .items_center()
                            .gap(rem(8.))
                            .min_h(rem(40.))
                            .pl(rem(12.))
                            .pr(rem(4.))
                            .border_b_1()
                            .border_color(color(ColorRole::BorderSubtle01))
                            .text_color(secondary)
                            .child(
                                // `.t3-prtl-head b { color: text-primary; font-size:
                                // 0.875rem }`, no weight: Carbon's `b { font: inherit }`
                                // keeps it 400.
                                sans(div(), 14., 400)
                                    .text_color(color(ColorRole::TextPrimary))
                                    .child(e.actor.clone()),
                            )
                            .when_some(e.review, |this, r| this.child(ReviewDecisionBadge::new(r)))
                            .child(e.time.clone())
                            .child(div().flex_1())
                            .child(
                                Button::new(craft::sub(&id, "add", i), self.add_label.clone())
                                    .variant(ButtonVariant::Ghost)
                                    .size(ButtonSize::Sm)
                                    .icon(CarbonIcon::Chat)
                                    .when_some(on_add, |b, f| {
                                        b.on_click(move |_, w, cx| f(i, w, cx))
                                    }),
                            ),
                    )
                    .child(
                        sans(div(), 14., 400)
                            .p(rem(12.))
                            .line_height(relative(1.42857))
                            .text_color(color(ColorRole::TextPrimary))
                            .child(e.body.clone()),
                    )
                    .when_some(e.reactions, |this, reactions| {
                        this.child(
                            div().px(rem(12.)).pb(rem(12.)).child(
                                ReactionBar::new(craft::sub(&id, "reactions", i))
                                    .square(square_reactions)
                                    .reactions(reactions)
                                    .when_some(on_react, |bar, f| {
                                        bar.on_react(move |emoji, w, cx| f(i, emoji, w, cx))
                                    }),
                            ),
                        )
                    })
                    .into_any_element()
            } else {
                sans(div(), 14., 400)
                    .flex()
                    .flex_wrap()
                    .items_center()
                    .gap_x(rem(8.))
                    .gap_y(rem(4.))
                    .min_h(rem(24.))
                    .text_color(secondary)
                    .child(
                        // `.t3-prtl-event b { color: text-primary }`, no weight:
                        // Carbon's `b { font: inherit }` keeps it 400.
                        sans(div(), 14., 400)
                            .text_color(color(ColorRole::TextPrimary))
                            .child(e.actor.clone()),
                    )
                    .child(e.text.clone())
                    .child(craft::text(e.time.clone(), 12., ColorRole::TextSecondary))
                    .into_any_element()
            };
            div()
                .flex()
                .gap(rem(12.))
                .pb(rem(16.))
                .child(marker)
                .child(content)
        });
        div()
            .relative()
            .flex()
            .flex_col()
            // `.t3-prtl::before { left: 11px; width: 1px; background: border-subtle-01 }`.
            .child(
                div()
                    .absolute()
                    .left(px(11.))
                    .top_0()
                    .bottom_0()
                    .w(px(1.))
                    .bg(color(ColorRole::BorderSubtle01)),
            )
            .children(items)
    }
}

/// A review verdict (`ReviewForm` options).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ReviewVerdict {
    /// `comment`, the default.
    #[default]
    Comment,
    /// `approve`.
    Approve,
    /// `changes`.
    Changes,
}

impl ReviewVerdict {
    /// Every verdict, in order.
    pub const ALL: [ReviewVerdict; 3] = [Self::Comment, Self::Approve, Self::Changes];

    /// The value passed to `onSubmit`.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Comment => "comment",
            Self::Approve => "approve",
            Self::Changes => "changes",
        }
    }
}

/// Texts of a [`ReviewForm`] (hard-coded in the reference).
#[derive(Clone, Debug)]
pub struct ReviewFormTexts {
    /// `Review summary`.
    pub summary: SharedString,
    /// `Leave a comment`.
    pub placeholder: SharedString,
    /// `Review type` (the radio group's name).
    pub group: SharedString,
    /// (title, description) per verdict.
    pub options: [(SharedString, SharedString); 3],
}

impl Default for ReviewFormTexts {
    fn default() -> Self {
        Self {
            summary: "Review summary".into(),
            placeholder: "Leave a comment".into(),
            group: "Review type".into(),
            options: [
                (
                    "Comment".into(),
                    "Submit general feedback without explicit approval.".into(),
                ),
                (
                    "Approve".into(),
                    "Submit feedback and approve merging these changes.".into(),
                ),
                (
                    "Request changes".into(),
                    "Submit feedback that must be addressed before merging.".into(),
                ),
            ],
        }
    }
}

type VerdictHandler = Rc<dyn Fn(ReviewVerdict, &mut Window, &mut App)>;
type ReviewSubmitHandler = Rc<dyn Fn(ReviewVerdict, SharedString, &mut Window, &mut App)>;

/// Submit a review (`.t3-reviewform`, `layer-01`, 30rem): the summary text
/// area on `field-02`, three radio cards (Comment / Approve / Request
/// changes, each with a description) and the submit button.
#[derive(IntoElement)]
pub struct ReviewForm {
    id: ElementId,
    submit_label: SharedString,
    submit_disabled: bool,
    flat: bool,
    hint: Option<SharedString>,
    require_content_unless_approve: bool,
    has_line_comments: bool,
    on_submit: Option<VerdictHandler>,
    on_submit_review: Option<ReviewSubmitHandler>,
    texts: ReviewFormTexts,
}

impl ReviewForm {
    /// A review form.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            submit_label: "Submit review".into(),
            submit_disabled: false,
            flat: false,
            hint: None,
            require_content_unless_approve: false,
            has_line_comments: false,
            on_submit: None,
            on_submit_review: None,
            texts: ReviewFormTexts::default(),
        }
    }

    /// The button text (`Submit review`).
    pub fn submit_label(mut self, label: impl Into<SharedString>) -> Self {
        self.submit_label = label.into();
        self
    }

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

    /// Flat full-width layout on `background` (`PullRequestDetail` board).
    pub fn flat(mut self, flat: bool) -> Self {
        self.flat = flat;
        self
    }

    /// Helper hint placed to the left of `Submit review`.
    pub fn hint(mut self, hint: impl Into<SharedString>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    /// Disable submit for `Comment` / `Changes` when both summary text and line comments are empty.
    pub fn require_content_unless_approve(mut self, require: bool) -> Self {
        self.require_content_unless_approve = require;
        self
    }

    /// Whether pending line comments are attached to this review.
    pub fn has_line_comments(mut self, has: bool) -> Self {
        self.has_line_comments = has;
        self
    }

    /// Submit pressed with the chosen verdict (`onSubmit(type)`).
    pub fn on_submit(mut self, f: impl Fn(ReviewVerdict, &mut Window, &mut App) + 'static) -> Self {
        self.on_submit = Some(Rc::new(f));
        self
    }

    /// Submit pressed with both chosen verdict and summary text, clearing the field.
    pub fn on_submit_review(
        mut self,
        f: impl Fn(ReviewVerdict, SharedString, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_submit_review = Some(Rc::new(f));
        self
    }

    /// Replace the default texts.
    pub fn texts(mut self, texts: ReviewFormTexts) -> Self {
        self.texts = texts;
        self
    }
}

/// The radio circle drawn by `.t3-reviewform .t3-opt::before`: 16px, 1px
/// `icon-primary` ring; checked adds a 7px `icon-primary` dot.
fn radio_circle(checked: bool) -> gpui_kit::Div {
    let ink = color(ColorRole::IconPrimary);
    div()
        .flex()
        .flex_none()
        .items_center()
        .justify_center()
        .mt(px(2.))
        .size(px(16.))
        .rounded_full()
        .border_1()
        .border_color(ink)
        .when(checked, |this| {
            this.child(div().size(px(7.)).rounded_full().bg(ink))
        })
}

impl RenderOnce for ReviewForm {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let id = self.id.clone();
        let flat = self.flat;
        let text = window
            .use_keyed_state((id.clone(), "text"), cx, |window, cx| {
                let ts = cx.new(|cx| TextareaState::new(window, cx));
                cx.observe(&ts, |_, _, cx| cx.notify()).detach();
                ts
            })
            .read(cx)
            .clone();
        let verdict = window
            .use_keyed_state((id.clone(), "verdict"), cx, |_, _| ReviewVerdict::Comment)
            .clone();
        let chosen = *verdict.read(cx);
        let empty_blocked = self.require_content_unless_approve
            && chosen != ReviewVerdict::Approve
            && !self.has_line_comments
            && text.read(cx).value().trim().is_empty();
        let submit_disabled = self.submit_disabled || empty_blocked;
        let handles: Vec<FocusHandle> = (0..3)
            .map(|i| focus_handle(&craft::sub(&id, "opt", i), window, cx))
            .collect();
        let options = ReviewVerdict::ALL.iter().enumerate().map(|(i, v)| {
            let on = *v == chosen;
            let focus = handles[i].clone();
            let ring = focus.is_focused(window);
            let (title, desc) = self.texts.options[i].clone();
            let verdict = verdict.clone();
            let v = *v;
            let hovered = window
                .use_keyed_state(craft::sub(&id, "opt-hover", i), cx, |_, _| false)
                .clone();
            let is_hovered = *hovered.read(cx);
            let card_bg = if flat {
                if is_hovered {
                    ColorRole::LayerHover01
                } else if on {
                    ColorRole::LayerSelected01
                } else {
                    ColorRole::Layer01
                }
            } else if is_hovered {
                ColorRole::LayerHover02
            } else {
                ColorRole::Layer02
            };
            press(craft::sub(&id, "opt", i), &focus)
                .role(gpui_kit::Role::RadioButton)
                .accessibility_label(title.clone())
                // Only the checked radio is a tab stop, like a native group.
                .tab_stop(on)
                .w_full()
                .items_start()
                .gap(rem(12.))
                .py(rem(12.))
                .px(rem(if flat { 16. } else { 12. }))
                .bg(color(card_bg))
                .on_hover(move |h, _, cx| {
                    hovered.update(cx, |x, cx| {
                        *x = *h;
                        cx.notify();
                    })
                })
                .on_click(move |_, _, cx| {
                    verdict.update(cx, |x, cx| {
                        *x = v;
                        cx.notify();
                    })
                })
                .child(radio_circle(on))
                .child(
                    sans(div(), 14., 400)
                        .flex()
                        .flex_col()
                        .text_color(color(ColorRole::TextPrimary))
                        .child(sans(div(), 14., 600).child(title))
                        .child(craft::text(desc, 12., ColorRole::TextSecondary).mt(px(2.))),
                )
                .when(on, |this| {
                    if flat {
                        this.child(super::pull_request::start_bar(color(
                            ColorRole::BorderInteractive,
                        )))
                    } else {
                        // `.t3-opt--on { box-shadow: inset 0 0 0 2px var(--border-interactive) }`.
                        this.child(
                            div()
                                .absolute()
                                .top_0()
                                .left_0()
                                .right_0()
                                .bottom_0()
                                .border_2()
                                .border_color(color(ColorRole::BorderInteractive)),
                        )
                    }
                })
                // `.t3-opt:focus-within { outline: 2px solid var(--focus); outline-offset: -2px }`.
                .when(ring, |this| this.child(craft::focus_ring()))
        });
        let group_keys = {
            let verdict = verdict.clone();
            let handles = handles.clone();
            move |e: &KeyDownEvent, window: &mut Window, cx: &mut App| {
                let current = ReviewVerdict::ALL
                    .iter()
                    .position(|v| *v == *verdict.read(cx))
                    .unwrap_or(0);
                if let Some(next) =
                    crate::t3::base::radio_step(e.keystroke.key.as_str(), 3, Some(current))
                {
                    cx.stop_propagation();
                    verdict.update(cx, |x, cx| {
                        *x = ReviewVerdict::ALL[next];
                        cx.notify();
                    });
                    handles[next].focus(window, cx);
                }
            }
        };
        let on_submit = self.on_submit.clone();
        let on_submit_review = self.on_submit_review.clone();
        let text_for_submit = text.clone();
        let has_submit_cb = on_submit.is_some() || on_submit_review.is_some();
        sans(div(), 14., 400)
            .id(id.clone())
            .flex()
            .flex_col()
            .gap(rem(16.))
            .w_full()
            .when(!flat, |d| {
                d.max_w(rem(480.)).p(rem(16.)).bg(color(ColorRole::Layer01))
            })
            .child(
                Textarea::new((id.clone(), "summary"), &text)
                    .label(self.texts.summary.clone())
                    .placeholder(self.texts.placeholder.clone())
                    .rows(3)
                    .layer(if flat {
                        LayerLevel::One
                    } else {
                        LayerLevel::Two
                    }),
            )
            .child(
                div()
                    .id((id.clone(), "group"))
                    .flex()
                    .flex_col()
                    .map(|d| if flat { d.gap(rem(8.)) } else { d.gap(px(1.)) })
                    .on_key_down(group_keys)
                    .children(options),
            )
            .child(
                div()
                    .flex()
                    .flex_wrap()
                    .justify_end()
                    .items_center()
                    .gap(rem(if flat { 16. } else { 8. }))
                    .when_some(self.hint, |row, hint| {
                        row.child(
                            craft::text(hint, 12., ColorRole::TextHelper)
                                .flex_1()
                                .min_w_0(),
                        )
                    })
                    .child(
                        Button::new((id, "submit"), self.submit_label.clone())
                            .size(ButtonSize::Sm)
                            .disabled(submit_disabled)
                            .when(has_submit_cb, |b| {
                                b.on_click(move |_, w, cx| {
                                    let v = *verdict.read(cx);
                                    if let Some(f) = &on_submit {
                                        f(v, w, cx);
                                    }
                                    if let Some(f) = &on_submit_review {
                                        let body = SharedString::from(
                                            text_for_submit.read(cx).value().to_string(),
                                        );
                                        text_for_submit.update(cx, |s, cx| s.set_value("", w, cx));
                                        f(v, body, w, cx);
                                    }
                                })
                            }),
                    ),
            )
    }
}

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

    #[test]
    fn reaction_and_event_colors() {
        crate::theme::tests_set(crate::tokens::CarbonTheme::White);
        assert_eq!(EventKind::Merged.ink(), color(ColorRole::TagColorPurple));
        let (fill, ink, ring) = reaction_look(true, false);
        assert_eq!(fill, color(ColorRole::TagBackgroundBlue));
        assert_eq!(ink, color(ColorRole::TagColorBlue));
        assert_eq!(ring, Some(color(ColorRole::BorderInteractive)));
        let (fill, _, ring) = reaction_look(false, true);
        assert_eq!(fill, color(ColorRole::LayerAccentHover01));
        assert!(ring.is_none());
        let form = ReviewForm::new("test")
            .flat(true)
            .require_content_unless_approve(true)
            .has_line_comments(true)
            .hint("Hint");
        assert!(form.flat && form.require_content_unless_approve && form.has_line_comments);
    }
}