u0ui 0.3.3

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
//! `Frame` / `.cu-pframe`: the anatomy of a Carbon modal drawn in place (not
//! an overlay), so the pattern cards can compare dialog types and button
//! layouts side by side. A real modal is [`crate::components::Dialog`].
//!
//! - **Head** (`.cu-pframe-head`): optional label, title, the ghost close
//!   button in the top-right corner.
//! - **Body** (`.cu-pframe-body`): the caller's children in `body-01`.
//! - **Foot** (`.cu-pframe-foot`): `xl` buttons, full-bleed, sharing the
//!   width by flex weight, after an optional empty lead (`leftGap`), so one
//!   button can take the right half and three buttons a quarter each.
//!
//! ```ignore
//! PatternFrame::new("rename")
//!     .label("Project")
//!     .title("Rename project")
//!     .close_label("Close")
//!     .button(FrameButton::new("Cancel", ButtonVariant::Secondary))
//!     .button(FrameButton::new("Rename", ButtonVariant::Primary))
//!     .child(Input::new("name", &state).label("Project name"))
//! ```
use crate::{
    components::{
        button::{Button, ButtonSize, ButtonVariant},
        overlay::floating_shadow,
    },
    icons::{CarbonIcon, Icon},
    theme::color,
    tokens::{self, ColorRole, REM_PX, TokenLength, TypeStyle},
    typography::TypeStyled as _,
};
use gpui_kit::{
    AnyElement, App, ElementId, InteractiveElement as _, IntoElement, ParentElement, RenderOnce,
    SharedString, Styled, Window, div, prelude::FluentBuilder as _, px, rems,
};
use std::rc::Rc;

/// The frame's box measurements (`src/patterns.css`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameGeometry {
    /// `.cu-pframe-head { padding: var(--spacing-05) 3rem 0 var(--spacing-05) }`: top.
    pub head_top: TokenLength,
    /// … end, clear of the 3rem close button.
    pub head_end: TokenLength,
    /// … start.
    pub head_start: TokenLength,
    /// `.cu-pframe-label { margin-bottom: 2px }`.
    pub label_gap: TokenLength,
    /// `.cu-pframe-body { padding: var(--spacing-05) var(--spacing-05) var(--spacing-07) }`: top and sides.
    pub body_pad: TokenLength,
    /// … bottom.
    pub body_bottom: TokenLength,
    /// `.cu-pframe--danger { border-top: 3px solid var(--support-error) }`, in px.
    pub danger_rule: f32,
    /// `Frame`'s default `width: p.width || 340`, in px.
    pub default_width: f32,
}

impl FrameGeometry {
    /// The reference geometry.
    pub const REFERENCE: Self = Self {
        head_top: tokens::SPACING_05,
        head_end: tokens::SIZE_LG,
        head_start: tokens::SPACING_05,
        label_gap: tokens::SPACING_01,
        body_pad: tokens::SPACING_05,
        body_bottom: tokens::SPACING_07,
        danger_rule: 3.,
        default_width: 340.,
    };
}

/// One foot button: its label, kind and flex weight (`widths[i] || 1`).
#[derive(Clone)]
pub struct FrameButton {
    label: SharedString,
    variant: ButtonVariant,
    weight: f32,
    disabled: bool,
    icon: Option<Icon>,
}

impl FrameButton {
    /// A button reading `label`, of `variant`, weight 1.
    pub fn new(label: impl Into<SharedString>, variant: ButtonVariant) -> Self {
        Self {
            label: label.into(),
            variant,
            weight: 1.,
            disabled: false,
            icon: None,
        }
    }

    /// The flex weight (`style: { flex: widths[i] || 1 }`).
    pub fn weight(mut self, weight: f32) -> Self {
        self.weight = weight;
        self
    }

    /// Disabled (`b.disabled`).
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// A trailing icon (`renderIcon`).
    pub fn icon(mut self, icon: impl Into<Icon>) -> Self {
        self.icon = Some(icon.into());
        self
    }
}

/// The share of the foot each slot takes: the lead gap first (when its
/// weight is positive), then one entry per button.
#[deprecated(note = "ignores each button's padding; use `foot_widths`")]
pub fn foot_shares(lead: f32, weights: &[f32]) -> Vec<f32> {
    let total: f32 = lead.max(0.) + weights.iter().sum::<f32>();
    if total <= 0. {
        return Vec::new();
    }
    std::iter::once(lead)
        .filter(|l| *l > 0.)
        .chain(weights.iter().copied())
        .map(|w| w / total)
        .collect()
}

/// The widths the foot's slots take in a `width`-px frame: the lead gap
/// first (when its weight is positive), then one per `(weight, basis)`
/// button. Each slot is `flex: <weight>`, a zero basis that a button's
/// padding and border floor at `basis` px
/// ([`crate::components::button::Geometry::flex_basis`]); the free space
/// left after the bases goes out by weight.
pub fn foot_widths(width: f32, lead: f32, buttons: &[(f32, f32)]) -> Vec<f32> {
    let lead = (lead > 0.).then_some((lead, 0.));
    let slots: Vec<(f32, f32)> = lead.into_iter().chain(buttons.iter().copied()).collect();
    let weights: f32 = slots.iter().map(|(w, _)| w).sum();
    if weights <= 0. {
        return Vec::new();
    }
    let free = (width - slots.iter().map(|(_, b)| b).sum::<f32>()).max(0.);
    slots
        .iter()
        .map(|(w, basis)| basis + free * w / weights)
        .collect()
}

type ButtonHandler = Rc<dyn Fn(usize, &mut Window, &mut App)>;
type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;

/// A static modal frame. See the module docs.
#[derive(IntoElement)]
pub struct PatternFrame {
    id: ElementId,
    label: Option<SharedString>,
    title: SharedString,
    close_label: SharedString,
    danger: bool,
    width: Option<f32>,
    lead: f32,
    buttons: Vec<FrameButton>,
    children: Vec<AnyElement>,
    on_button: Option<ButtonHandler>,
    on_close: Option<CloseHandler>,
}

impl PatternFrame {
    /// A frame with a stable `id`, 340px wide.
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            label: None,
            title: SharedString::default(),
            close_label: SharedString::default(),
            danger: false,
            width: Some(FrameGeometry::REFERENCE.default_width),
            lead: 0.,
            buttons: Vec::new(),
            children: Vec::new(),
            on_button: None,
            on_close: None,
        }
    }

    /// The small label over the title (`p.label`).
    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
        self.label = Some(label.into());
        self
    }

    /// The title (`p.title`).
    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
        self.title = title.into();
        self
    }

    /// The close button's accessible name and tooltip (`label: 'Close'`).
    pub fn close_label(mut self, label: impl Into<SharedString>) -> Self {
        self.close_label = label.into();
        self
    }

    /// The danger frame: a 3px `support-error` top rule (`p.danger`).
    pub fn danger(mut self, danger: bool) -> Self {
        self.danger = danger;
        self
    }

    /// The width in px (`p.width`); `None` fills the container (`'100%'`).
    pub fn width(mut self, width: Option<f32>) -> Self {
        self.width = width;
        self
    }

    /// An empty lead before the buttons, as a flex weight (`p.leftGap`).
    pub fn lead_gap(mut self, weight: f32) -> Self {
        self.lead = weight;
        self
    }

    /// Append a foot button (`p.buttons`).
    pub fn button(mut self, button: FrameButton) -> Self {
        self.buttons.push(button);
        self
    }

    /// Called with a foot button's index when it is pressed.
    pub fn on_button(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {
        self.on_button = Some(Rc::new(f));
        self
    }

    /// Called when the close button is pressed.
    pub fn on_close(mut self, f: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_close = Some(Rc::new(f));
        self
    }
}

impl ParentElement for PatternFrame {
    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
        self.children.extend(elements);
    }
}

impl RenderOnce for PatternFrame {
    fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
        let g = FrameGeometry::REFERENCE;
        let id = self.id;
        let close = {
            let on_close = self.on_close.clone();
            Button::new((id.clone(), "close"), self.close_label.clone())
                .variant(ButtonVariant::Ghost)
                .size(ButtonSize::Lg)
                .icon_only(true)
                .icon(Icon::carbon(CarbonIcon::Close))
                .on_click(move |_, window, cx| {
                    if let Some(f) = &on_close {
                        f(window, cx)
                    }
                })
        };
        // `.cu-pframe-head` with `.cu-pframe-x { position: absolute; top: 0; right: 0 }`.
        let head = div()
            .relative()
            .flex()
            .flex_col()
            .pt(g.head_top)
            .pr(g.head_end)
            .pl(g.head_start)
            .when_some(self.label, |this, label| {
                this.child(
                    // `.cu-pframe-label`: 0.75rem, 0.32px, text-secondary.
                    div()
                        .mb(g.label_gap)
                        .type_style(TypeStyle::Label01)
                        .text_color(color(ColorRole::TextSecondary))
                        .child(label),
                )
            })
            .child(
                // `.cu-pframe-title { font-size: 1.25rem; line-height: 1.4 }`: heading-03.
                div()
                    .type_style(TypeStyle::Heading03)
                    .text_color(color(ColorRole::TextPrimary))
                    .child(self.title),
            )
            .child(div().absolute().top_0().right_0().child(close));

        // `.cu-pframe-body { font-size: 0.875rem; line-height: 1.42857 }`: body-01.
        let body = div()
            .flex()
            .flex_col()
            .pt(g.body_pad)
            .px(g.body_pad)
            .pb(g.body_bottom)
            .type_style(TypeStyle::Body01)
            .text_color(color(ColorRole::TextPrimary))
            .children(self.children);

        let foot = (!self.buttons.is_empty()).then(|| {
            let buttons = self.buttons.into_iter().enumerate().map(|(i, b)| {
                let on_button = self.on_button.clone();
                let mut button = Button::new((id.clone(), format!("b{i}")), b.label)
                    .variant(b.variant)
                    .size(ButtonSize::Xl)
                    // `style: {flex: widths[i] || 1, maxWidth: 'none'}`.
                    .flex_share(b.weight)
                    .disabled(b.disabled)
                    .on_click(move |_, window, cx| {
                        if let Some(f) = &on_button {
                            f(i, window, cx)
                        }
                    });
                if let Some(icon) = b.icon {
                    button = button.icon(icon);
                }
                button
            });
            // `.cu-pframe-foot { display: flex }`, after the empty
            // `<span style={{flex: leftGap}}>`.
            div()
                .flex()
                .flex_row()
                .w_full()
                .when(self.lead > 0., |this| {
                    this.child(
                        div()
                            .min_w_0()
                            .flex_grow(self.lead)
                            .flex_shrink(1.)
                            .flex_basis(px(0.)),
                    )
                })
                .children(buttons)
        });

        div()
            .id(id.clone())
            .flex()
            .flex_col()
            .max_w_full()
            .map(|this| match self.width {
                Some(w) => this.w(rems(w / REM_PX)),
                None => this.w_full(),
            })
            // `.cu-pframe { background: var(--layer-01); box-shadow: 0 2px 6px var(--shadow) }`.
            .bg(color(ColorRole::Layer01))
            .shadow(floating_shadow())
            .when(self.danger, |this| {
                this.border_t(gpui_kit::px(g.danger_rule))
                    .border_color(color(ColorRole::SupportError))
            })
            .child(head)
            .child(body)
            .children(foot)
    }
}

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

    #[test]
    fn geometry_matches_the_css() {
        let g = FrameGeometry::REFERENCE;
        assert_eq!(
            (
                g.head_top.px_value(),
                g.head_end.px_value(),
                g.head_start.px_value()
            ),
            (16., 48., 16.)
        );
        assert_eq!(g.label_gap.px_value(), 2.);
        assert_eq!(
            (g.body_pad.px_value(), g.body_bottom.px_value()),
            (16., 32.)
        );
        assert_eq!((g.danger_rule, g.default_width), (3., 340.));
    }

    #[test]
    fn button_counts_take_their_dialog_widths() {
        use crate::components::button::{ButtonKind, Geometry};
        use crate::density::Density;
        let basis = |kind| {
            Geometry::for_content(ButtonSize::Xl, Density::Compact, kind, false, false).flex_basis()
        };
        let (ghost, filled) = (basis(ButtonKind::Ghost), basis(ButtonKind::Primary));
        // `.cds--btn` padding 15 / 15 (ghost) or 15 / 16, plus two 1px borders.
        assert_eq!((ghost, filled), (32., 33.));
        // Two buttons: half each (computed `.cu-pframe-foot > *`: 170 / 170).
        assert_eq!(foot_widths(340., 0., &[(1., filled); 2]), vec![170.; 2]);
        // Acknowledgment: the lead gap, then OK at 186.5.
        assert_eq!(foot_widths(340., 1., &[(1., filled)]), vec![153.5, 186.5]);
        // Three buttons after a lead gap: 80.5 / 112.5 / 113.5 / 113.5.
        assert_eq!(
            foot_widths(420., 1., &[(1., ghost), (1., filled), (1., filled)]),
            vec![80.5, 112.5, 113.5, 113.5]
        );
        assert!(foot_widths(340., 0., &[]).is_empty());
    }
}