fluidattacks-designs 0.11.0

Fluid Attacks design system, GPUI variant: desktop widgets over the shared tokens
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
//! `Alert` and `AlertDialog` — the web alert: a bordered banner carrying a
//! severity, its glyph, an optional title and a message, closable and able to
//! retire itself after a while.
//!
//! ```ignore
//! Alert::new("lines-empty", "The scan reported no lines.")
//!     .variant(Variant::Warning)
//!     .title("Lines")
//!     .closable(true)
//!     .auto_hide(true)
//! ```
//!
//! The banner is inline, as the web has it: it takes the width its parent gives
//! it and pushes what follows down. Signals shows these same messages as a
//! blocking dialog instead, so [`AlertDialog`] dresses [`Modal`] in this
//! component's variant vocabulary with a single acknowledge button — the pair is
//! what `display_error` and `display_info` become.
//!
//! A banner owns one piece of state, whether it is still up, so a dismissal or a
//! timeout hides it with no flag in the app. The timer is armed once, on the
//! frame the banner first appears: gpui renders a widget many times over, and a
//! timer per frame would be a stampede. A `time` or a handler changed after that
//! frame is not re-read — draw the banner under a new id to re-arm it, which is
//! what remounting does to the web's effect.
//!
//! What the web has and this does not: the `show` prop, since an app that can
//! stop drawing the banner needs no second switch; and the `notification` and
//! `message-banner` components built beside it.

use core::time::Duration;
use std::rc::Rc;

use fluidattacks_designs_domain::alert::{
    colors, dialog_body, message_weight, Colors, IconPosition, Time, Variant, ACKNOWLEDGE_TEXT,
    BORDER_WIDTH, CONTENT_GAP, CONTENT_PADDING_RIGHT, DISMISS_GLYPH, DISMISS_HOVER_ALPHA,
    DISMISS_PADDING, DISMISS_SIZE, DISMISS_STYLE, GLYPH_GAP, GLYPH_SIZE, GLYPH_STYLE, LINE_HEIGHT,
    MIN_WIDTH, PADDING, RADIUS, TEXT_SIZE, TITLE_WEIGHT,
};
use fluidattacks_designs_domain::typography::{Weight, FONT_PRIMARY};
use gpui::prelude::FluentBuilder as _;
use gpui::{
    div, px, rgb, AlignSelf, App, Div, Entity, EntityId, FontWeight, InteractiveElement as _,
    IntoElement, ParentElement as _, RenderOnce, Rgba, SharedString,
    StatefulInteractiveElement as _, Styled as _, Window,
};

use crate::icon::Icon;
use crate::modal::Modal;
use crate::theme::ActiveTheme as _;

/// Shared rather than boxed: the timeout hands its handler to a task that
/// outlives the frame that armed it.
type Handler = Rc<dyn Fn(&mut Window, &mut App)>;

fn font_weight(weight: Weight) -> FontWeight {
    FontWeight(f32::from(weight.value()))
}

fn part(id: &SharedString, name: &str) -> SharedString {
    SharedString::from(format!("{id}-{name}"))
}

/// What a banner holds across frames: whether it is still up, and whether its
/// timeout has been armed — see the module docs for why that is once only.
struct Standing {
    shown: bool,
    armed: bool,
}

impl Standing {
    const fn new() -> Self {
        Self {
            shown: true,
            armed: false,
        }
    }
}

/// What the timeout was configured with, gathered so the arming below reads as
/// one decision rather than a row of flags.
struct Timeout {
    seconds: u64,
    auto_hide: bool,
    handler: Option<Handler>,
}

/// Start the timeout. It reports whatever `auto_hide` says, the way the web
/// fires `onTimeOut` on every alert and only closes the ones that asked.
fn arm(state: &Entity<Standing>, timeout: Timeout, view: EntityId, window: &Window, cx: &mut App) {
    state.update(cx, |standing, _| standing.armed = true);
    let state = state.clone();
    window
        .spawn(cx, async move |task_cx| {
            task_cx
                .background_executor()
                .timer(Duration::from_secs(timeout.seconds))
                .await;
            task_cx
                .update(|task_window, app| {
                    if timeout.auto_hide {
                        state.update(app, |standing, _| standing.shown = false);
                    }
                    if let Some(handler) = &timeout.handler {
                        handler(task_window, app);
                    }
                    app.notify(view);
                })
                .ok();
        })
        .detach();
}

/// The web's `align-items` switch. It has to reach the row the glyph is *in*,
/// not only the outer box: a centered glyph sits against the whole text block,
/// and the nudge [`IconPosition::glyph_margin_top`] carries means nothing on one
/// — a top-positioned glyph has to start at the first line to be nudged onto it.
fn aligned(el: Div, position: IconPosition) -> Div {
    match position {
        IconPosition::Center => el.items_center(),
        IconPosition::Top => el.items_start(),
    }
}

/// The box the text sits in. `min_w_0` is what makes a long message wrap: a
/// flex item never shrinks below the width its content reports, and a text
/// child reports its whole sentence unwrapped, so without it the message runs
/// out of the box instead of growing it downwards.
fn wrapping(text: SharedString) -> Div {
    div().flex_1().min_w_0().child(text)
}

/// One line of the content column: whatever glyph leads it, its text, and the
/// weight that line carries.
fn line(glyph: Option<Div>, text: SharedString, weight: Weight, position: IconPosition) -> Div {
    aligned(div().flex(), position)
        .w_full()
        .pr(px(CONTENT_PADDING_RIGHT))
        .font_weight(font_weight(weight))
        .children(glyph)
        .child(wrapping(text))
}

/// The trailing dismiss control — the web's ghost `IconButton`.
///
/// gpui publishes no `align-self` helper, so the web's `alignSelf: flex-start`
/// goes into the style refinement by hand: the control sits on the first line of
/// a message that wrapped, rather than halfway down it.
fn dismiss_control(id: SharedString, ink: u32, press: Handler) -> impl IntoElement {
    let wash = Rgba {
        alpha: DISMISS_HOVER_ALPHA,
        ..rgb(ink)
    };
    let mut control = div();
    control.style().align_self = Some(AlignSelf::FlexStart);
    control
        .id(id)
        .flex()
        .flex_none()
        .p(px(DISMISS_PADDING))
        .rounded(px(RADIUS))
        .cursor_pointer()
        .hover(move |style| style.bg(wash))
        .on_click(move |_, window, app| {
            app.stop_propagation();
            press(window, app);
        })
        .child(
            Icon::new(DISMISS_GLYPH)
                .style(DISMISS_STYLE)
                .size(DISMISS_SIZE)
                .color(ink),
        )
}

#[derive(IntoElement)]
pub struct Alert {
    id: SharedString,
    message: SharedString,
    title: Option<SharedString>,
    variant: Variant,
    glyph: Option<SharedString>,
    glyph_enabled: bool,
    icon_position: IconPosition,
    closable: bool,
    auto_hide: bool,
    time: Time,
    on_close: Option<Handler>,
    on_timeout: Option<Handler>,
}

impl Alert {
    /// The id keys the banner's own state, so sibling banners stay apart.
    pub fn new(id: impl Into<SharedString>, message: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            message: message.into(),
            title: None,
            variant: Variant::default(),
            glyph: None,
            glyph_enabled: true,
            icon_position: IconPosition::default(),
            closable: false,
            auto_hide: false,
            time: Time::default(),
            on_close: None,
            on_timeout: None,
        }
    }

    #[must_use]
    pub const fn variant(mut self, variant: Variant) -> Self {
        self.variant = variant;
        self
    }

    /// The bold line above the message (web `title`).
    #[must_use]
    pub fn title(mut self, title: impl Into<SharedString>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// A glyph other than the variant's own (web `icon`).
    #[must_use]
    pub fn glyph(mut self, name: impl Into<SharedString>) -> Self {
        self.glyph = Some(name.into());
        self
    }

    /// Whether the leading glyph shows at all (web `iconEnabled`).
    #[must_use]
    pub const fn glyph_enabled(mut self, enabled: bool) -> Self {
        self.glyph_enabled = enabled;
        self
    }

    /// Where the glyph sits against a message that wraps (web `iconPosition`).
    #[must_use]
    pub const fn icon_position(mut self, position: IconPosition) -> Self {
        self.icon_position = position;
        self
    }

    /// Whether it offers a dismiss control (web `closable`).
    #[must_use]
    pub const fn closable(mut self, closable: bool) -> Self {
        self.closable = closable;
        self
    }

    /// Whether the timeout hides it as well as reporting (web `autoHide`).
    #[must_use]
    pub const fn auto_hide(mut self, auto_hide: bool) -> Self {
        self.auto_hide = auto_hide;
        self
    }

    /// How long that timeout is (web `time`).
    #[must_use]
    pub const fn time(mut self, time: Time) -> Self {
        self.time = time;
        self
    }

    /// Reported after the dismiss control hides it (web `onClose`).
    #[must_use]
    pub fn on_close(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_close = Some(Rc::new(handler));
        self
    }

    /// Reported when the time runs out (web `onTimeOut`), whether or not
    /// [`Self::auto_hide`] also hides it.
    #[must_use]
    pub fn on_timeout(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_timeout = Some(Rc::new(handler));
        self
    }

    fn leading_glyph(&self, ink: u32) -> Option<Div> {
        if !self.glyph_enabled {
            return None;
        }
        let name = self
            .glyph
            .clone()
            .unwrap_or_else(|| SharedString::from(self.variant.glyph()));
        Some(
            div()
                .flex_none()
                .mr(px(GLYPH_GAP))
                .mt(px(self.icon_position.glyph_margin_top()))
                .child(
                    Icon::new(name)
                        .style(GLYPH_STYLE)
                        .size(GLYPH_SIZE)
                        .color(ink),
                ),
        )
    }

    /// Hide it, then report — the order the web's `handleClose` has.
    fn closing(&self, state: &Entity<Standing>) -> Handler {
        let state = state.clone();
        let on_close = self.on_close.clone();
        Rc::new(move |press_window: &mut Window, app: &mut App| {
            state.update(app, |standing, _| standing.shown = false);
            if let Some(handler) = &on_close {
                handler(press_window, app);
            }
        })
    }

    /// The box: its variant's colors and the content column inside it.
    fn banner(self, palette: Colors) -> Div {
        // the glyph leads whichever line comes first, as the web moves it into
        // the title row when there is one
        let glyph = self.leading_glyph(palette.fg);
        let position = self.icon_position;
        let has_title = self.title.is_some();
        let (title_glyph, message_glyph) = if has_title {
            (glyph, None)
        } else {
            (None, glyph)
        };
        let column = div()
            .flex()
            .flex_col()
            .flex_1()
            // every box between the banner and the text has to be shrinkable,
            // or the column widens even where the text itself would wrap
            .min_w_0()
            .gap(px(CONTENT_GAP))
            .when_some(self.title, |el, title| {
                el.child(line(title_glyph, title, TITLE_WEIGHT, position))
            })
            .child(line(
                message_glyph,
                self.message,
                message_weight(has_title),
                position,
            ));
        aligned(div().flex(), position)
            .w_full()
            .min_w(px(MIN_WIDTH))
            .p(px(PADDING))
            .rounded(px(RADIUS))
            .border(px(BORDER_WIDTH))
            .border_color(rgb(palette.border))
            .bg(rgb(palette.bg))
            .text_color(rgb(palette.fg))
            .font_family(FONT_PRIMARY)
            .text_size(px(TEXT_SIZE.px()))
            .line_height(px(LINE_HEIGHT))
            .child(column)
    }
}

impl RenderOnce for Alert {
    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let state = window.use_keyed_state(self.id.clone(), cx, |_, _| Standing::new());
        if !state.read(cx).armed {
            let timeout = Timeout {
                seconds: self.time.seconds(),
                auto_hide: self.auto_hide,
                handler: self.on_timeout.clone(),
            };
            arm(&state, timeout, window.current_view(), window, cx);
        }
        if !state.read(cx).shown {
            return div();
        }
        let palette = colors(self.variant, &cx.theme().colors);
        let dismiss = self
            .closable
            .then(|| dismiss_control(part(&self.id, "dismiss"), palette.fg, self.closing(&state)));
        self.banner(palette).children(dismiss)
    }
}

/// The same message as a blocking dialog: a [`Modal`] with the variant's glyph
/// beside its body and one button to acknowledge it.
///
/// The box itself stays the modal's own surface rather than taking the variant's
/// fill — the web has no dialog form of this component, and a tinted dialog is a
/// design decision nobody has made. The glyph carries the severity.
#[derive(IntoElement)]
pub struct AlertDialog {
    id: SharedString,
    title: SharedString,
    message: SharedString,
    variant: Variant,
    acknowledge: SharedString,
    on_acknowledge: Option<Handler>,
}

impl AlertDialog {
    pub fn new(
        id: impl Into<SharedString>,
        title: impl Into<SharedString>,
        message: impl Into<SharedString>,
    ) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            message: message.into(),
            variant: Variant::default(),
            acknowledge: SharedString::from(ACKNOWLEDGE_TEXT),
            on_acknowledge: None,
        }
    }

    #[must_use]
    pub const fn variant(mut self, variant: Variant) -> Self {
        self.variant = variant;
        self
    }

    /// The one button's label (default [`ACKNOWLEDGE_TEXT`]).
    #[must_use]
    pub fn acknowledge_text(mut self, text: impl Into<SharedString>) -> Self {
        self.acknowledge = text.into();
        self
    }

    /// Reported however it closed. A dialog with one button has no second
    /// answer: the button, Escape and the header's control all mean the person
    /// has read it, so the outcome carries no information to hand on.
    #[must_use]
    pub fn on_acknowledge(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        self.on_acknowledge = Some(Rc::new(handler));
        self
    }
}

impl RenderOnce for AlertDialog {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let ink = colors(self.variant, &cx.theme().colors).fg;
        let glyph = SharedString::from(self.variant.glyph());
        let acknowledged = self.on_acknowledge;
        Modal::new(self.id)
            .title(self.title)
            .confirm_text(self.acknowledge)
            // a message is content, and a body no longer sizes itself from it
            .body_height(dialog_body())
            .on_outcome(move |_outcome, window, app| {
                if let Some(handler) = &acknowledged {
                    handler(window, app);
                }
            })
            .child(
                div()
                    .flex()
                    .items_start()
                    .gap(px(GLYPH_GAP))
                    .child(
                        div().flex_none().child(
                            Icon::new(glyph)
                                .style(GLYPH_STYLE)
                                .size(GLYPH_SIZE)
                                .color(ink),
                        ),
                    )
                    .child(wrapping(self.message)),
            )
    }
}

#[cfg(test)]
mod tests {
    use gpui::{px, relative, SharedString, Styled as _};

    use super::wrapping;

    /// The narrowest the text's box may be is nothing at all, and it takes
    /// whatever room the line has. Answering the first with the sentence
    /// instead is what stops a long message from wrapping: the box widens past
    /// the banner rather than growing it downwards.
    #[test]
    fn the_text_box_takes_the_line_and_may_shrink_to_nothing() {
        let mut boxed = wrapping(SharedString::from(
            "The repositories folder is no longer where it was configured",
        ));
        let style = boxed.style();

        assert_eq!(style.min_size.width, Some(px(0.0).into()));
        assert_eq!(style.flex_basis, Some(relative(0.0).into()));
        assert_eq!(style.flex_grow, Some(1.0));
    }
}