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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! `Button` — the web button's five variants with their hover and disabled
//! states. Variants compose theme roles in the domain; this file resolves
//! them against the active theme, paints, and wires the click.
//!
//! Hover drives tracked state rather than gpui's `.hover()` refinement, which
//! applies at paint time — after child text has captured its color at layout,
//! so it can restyle the box but never the label. The web's `transition: all`
//! needs the palette interpolated over time in any case.

use std::time::Instant;

use crate::icon::Icon;
use crate::notification_sign::NotificationSign;
use crate::tag::Tag;
use crate::theme::ActiveTheme as _;
use crate::tooltip::Tooltip;
use fluidattacks_designs_domain::button::{
    colors, padding, spacing, Justify, State, Variant, DOT_LEFT, DOT_LEFT_WITH_ICON, DOT_TOP,
    ICON_SIZE, TEXT_SIZE,
};
use fluidattacks_designs_domain::icon::{Size as IconSize, Style as IconStyle};
use fluidattacks_designs_domain::tooltip::Place;
use fluidattacks_designs_domain::typography::FONT_PRIMARY;
use fluidattacks_designs_domain::{button, motion};
use gpui::prelude::FluentBuilder as _;
use gpui::{
    div, px, relative, rgb, App, ClickEvent, ElementId, Entity, InteractiveElement as _,
    IntoElement, ParentElement as _, RenderOnce, Rgba, SharedString,
    StatefulInteractiveElement as _, Styled as _, Window,
};

type ClickHandler = Box<dyn Fn(&ClickEvent, &mut Window, &mut App) + 'static>;

/// The link-variant destination (web `href` + `external`).
#[derive(Default)]
struct LinkTarget {
    url: Option<SharedString>,
    external: bool,
}

/// A resolved frame of button colors, alpha included so transitions can fade
/// surfaces in and out.
#[derive(Clone, Copy)]
struct Paint {
    bg: Option<Rgba>,
    fg: Rgba,
    border: Option<Rgba>,
}

impl From<button::Colors> for Paint {
    fn from(palette: button::Colors) -> Self {
        Self {
            bg: palette.bg.map(opaque),
            fg: opaque(palette.fg),
            border: palette.border.map(opaque),
        }
    }
}

fn opaque(color: u32) -> Rgba {
    rgb(color)
}

const fn faded(color: Rgba) -> Rgba {
    Rgba {
        alpha: 0.0,
        ..color
    }
}

fn mix(from: Rgba, to: Rgba, amount: f32) -> Rgba {
    let channel = |a: f32, b: f32| (b - a).mul_add(amount, a);
    Rgba::new(
        channel(from.color.red, to.color.red),
        channel(from.color.green, to.color.green),
        channel(from.color.blue, to.color.blue),
        channel(from.alpha, to.alpha),
    )
}

/// An absent surface fades through its counterpart's color at zero alpha, the
/// way css transitions treat `transparent`.
fn mix_surface(from: Option<Rgba>, to: Option<Rgba>, amount: f32) -> Option<Rgba> {
    match (from, to) {
        (None, None) => None,
        (Some(from_color), Some(to_color)) => Some(mix(from_color, to_color, amount)),
        (None, Some(to_color)) => Some(mix(faded(to_color), to_color, amount)),
        (Some(from_color), None) => Some(mix(from_color, faded(from_color), amount)),
    }
}

fn mix_paint(from: Paint, to: Paint, amount: f32) -> Paint {
    Paint {
        bg: mix_surface(from.bg, to.bg, amount),
        fg: mix(from.fg, to.fg, amount),
        border: mix_surface(from.border, to.border, amount),
    }
}

#[derive(Clone, Copy)]
struct HoverAnimation {
    hovered: bool,
    /// The state whose colors the transition is heading to; any change —
    /// hover or a disabled flip — retargets from the colors on screen,
    /// like the web's `transition: all`.
    shown: State,
    /// The moment of the last retarget and the colors on screen right then
    /// — transitions resume from wherever a reversal caught them, like css.
    transition: Option<(Instant, Paint)>,
}

impl Default for HoverAnimation {
    fn default() -> Self {
        Self {
            hovered: false,
            shown: State::Idle,
            transition: None,
        }
    }
}

/// Restart the transition from whatever colors the change caught on screen.
fn retarget(
    animation_state: &Entity<HoverAnimation>,
    variant: Variant,
    state: State,
    cx: &mut App,
) {
    let theme = cx.theme().colors;
    animation_state.update(cx, |animation, _cx| {
        let previous_target = Paint::from(colors(variant, animation.shown, &theme));
        let (current, _) = displayed(animation, previous_target);
        animation.transition = Some((Instant::now(), current));
        animation.shown = state;
    });
}

/// The colors currently on screen, and whether the transition is still going.
fn displayed(animation: &HoverAnimation, target: Paint) -> (Paint, bool) {
    match animation.transition {
        None => (target, false),
        Some((started, from)) => {
            let progress = started.elapsed().as_secs_f32() * 1000.0 / motion::DURATION_MS;
            if progress >= 1.0 {
                (target, false)
            } else {
                (mix_paint(from, target, motion::ease(progress)), true)
            }
        }
    }
}

#[derive(IntoElement)]
pub struct Button {
    id: ElementId,
    label: SharedString,
    variant: Variant,
    disabled: bool,
    icon: Option<SharedString>,
    icon_color: Option<u32>,
    icon_style: IconStyle,
    icon_size: IconSize,
    right_icon: Option<SharedString>,
    tag: Option<SharedString>,
    notification: Option<u32>,
    dot_notification: bool,
    underline: bool,
    link_target: LinkTarget,
    width: Option<f32>,
    justify: Justify,
    tooltip: Option<(ElementId, SharedString)>,
    tooltip_place: Place,
    on_click: Option<ClickHandler>,
}

impl Button {
    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            variant: Variant::default(),
            disabled: false,
            icon: None,
            icon_color: None,
            icon_style: IconStyle::Light,
            icon_size: ICON_SIZE,
            right_icon: None,
            tag: None,
            notification: None,
            dot_notification: false,
            underline: false,
            link_target: LinkTarget::default(),
            width: None,
            justify: Justify::Center,
            tooltip: None,
            tooltip_place: Place::Bottom,
            on_click: None,
        }
    }

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

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

    /// A leading icon (web defaults: fa-light at lg, the label's color).
    #[must_use]
    pub fn icon(mut self, name: impl Into<SharedString>) -> Self {
        self.icon = Some(name.into());
        self
    }

    #[must_use]
    pub const fn icon_color(mut self, color: u32) -> Self {
        self.icon_color = Some(color);
        self
    }

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

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

    /// A trailing icon; link buttons always show one (arrow-right unless
    /// overridden), like the web.
    #[must_use]
    pub fn right_icon(mut self, name: impl Into<SharedString>) -> Self {
        self.right_icon = Some(name.into());
        self
    }

    /// A default-variant tag after the label, hidden while disabled.
    #[must_use]
    pub fn tag(mut self, tag: impl Into<SharedString>) -> Self {
        self.tag = Some(tag.into());
        self
    }

    /// The trailing error count pill; ghost-only on the web.
    #[must_use]
    pub const fn notification(mut self, count: u32) -> Self {
        self.notification = Some(count);
        self
    }

    /// The error dot pinned over the button; ghost-only on the web.
    #[must_use]
    pub const fn dot_notification(mut self, dot: bool) -> Self {
        self.dot_notification = dot;
        self
    }

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

    /// Link-variant destination: clicking opens it in the default browser
    /// and replaces `on_click`, exactly like the web wires it.
    #[must_use]
    pub fn href(mut self, href: impl Into<SharedString>) -> Self {
        self.link_target.url = Some(href.into());
        self
    }

    /// The web opens external hrefs in a new tab; every desktop href opens
    /// the default browser, so this is accepted for API parity only.
    #[must_use]
    pub const fn external(mut self, external: bool) -> Self {
        self.link_target.external = external;
        self
    }

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

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

    /// Wrap the button in a tooltip (web `tooltip`); the id keeps sibling
    /// tooltips apart, like the web's derived `id-tooltip`.
    #[must_use]
    pub fn tooltip(mut self, id: impl Into<ElementId>, tip: impl Into<SharedString>) -> Self {
        self.tooltip = Some((id.into(), tip.into()));
        self
    }

    /// The web `tooltipPlace` (default bottom).
    #[must_use]
    pub const fn tooltip_place(mut self, place: Place) -> Self {
        self.tooltip_place = place;
        self
    }

    #[must_use]
    pub fn on_click(
        mut self,
        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.on_click = Some(Box::new(handler));
        self
    }

    /// The web replaces `onClick` with the href opener on link buttons; a
    /// link without an href does nothing, faithfully.
    fn effective_handler(&mut self) -> Option<ClickHandler> {
        if !matches!(self.variant, Variant::Link) {
            return self.on_click.take();
        }
        self.link_target.url.take().map(|href| {
            let opener: ClickHandler =
                Box::new(move |_: &ClickEvent, _: &mut Window, cx: &mut App| {
                    cx.open_url(&href);
                });
            opener
        })
    }
}

/// One frame of the color transition: retargets on any state change and
/// keeps animating until the target is reached.
fn transition_frame(
    animation_state: &Entity<HoverAnimation>,
    variant: Variant,
    disabled: bool,
    window: &Window,
    cx: &mut App,
) -> Paint {
    let animation = *animation_state.read(cx);
    let state = if disabled {
        State::Disabled
    } else if animation.hovered {
        State::Hover
    } else {
        State::Idle
    };
    // any state change retargets, so disabled flips also transition
    if animation.shown != state {
        retarget(animation_state, variant, state, cx);
    }
    let refreshed = *animation_state.read(cx);
    let theme = cx.theme().colors;
    let target = Paint::from(colors(variant, state, &theme));
    let (painted, animating) = displayed(&refreshed, target);
    if animating {
        window.request_animation_frame();
    }
    painted
}

fn set_hovered(animation_state: &Entity<HoverAnimation>, hovered: bool, cx: &mut App) {
    animation_state.update(cx, |animation, _| animation.hovered = hovered);
}

#[must_use]
fn with_tooltip(
    button: gpui::Stateful<gpui::Div>,
    tooltip: Option<(ElementId, SharedString)>,
    place: Place,
) -> gpui::AnyElement {
    match tooltip {
        Some((tooltip_id, tip)) => Tooltip::new(tooltip_id, tip)
            .place(place)
            .child(button)
            .into_any_element(),
        None => button.into_any_element(),
    }
}

#[must_use]
fn justified<E: gpui::Styled>(el: E, justify: Justify) -> E {
    match justify {
        Justify::Center => el.justify_center(),
        Justify::Start => el.justify_start(),
        Justify::End => el.justify_end(),
        Justify::Between => el.justify_between(),
    }
}

/// The children between the box edges: dot, leading icon, label, trailing
/// icon, tag chip and count pill, tinted with the transition frame.
fn content(button: Button, painted: Paint) -> Vec<gpui::AnyElement> {
    let mut children: Vec<gpui::AnyElement> = Vec::new();
    let is_ghost = matches!(button.variant, Variant::Ghost);
    if button.dot_notification && is_ghost && !button.disabled {
        let left = if button.icon.is_some() {
            DOT_LEFT_WITH_ICON
        } else {
            DOT_LEFT
        };
        children.push(
            div()
                .absolute()
                .top(relative(DOT_TOP))
                .left(relative(left))
                .child(NotificationSign::new())
                .into_any_element(),
        );
    }
    if let Some(name) = button.icon {
        let icon = Icon::new(name)
            .style(button.icon_style)
            .size(button.icon_size);
        children.push(
            match button.icon_color {
                Some(color) => icon.color(color),
                None => icon.color_rgba(painted.fg),
            }
            .into_any_element(),
        );
    }
    children.push(button.label.into_any_element());
    let arrow = matches!(button.variant, Variant::Link);
    if button.right_icon.is_some() || arrow {
        let name = button
            .right_icon
            .unwrap_or_else(|| SharedString::from("arrow-right"));
        children.push(
            Icon::new(name)
                .style(IconStyle::Light)
                .size(button.icon_size)
                .color_rgba(painted.fg)
                .into_any_element(),
        );
    }
    if let Some(tag) = button.tag.filter(|_| !button.disabled) {
        children.push(Tag::new(tag).into_any_element());
    }
    if let Some(count) = button.notification.filter(|_| is_ghost && !button.disabled) {
        children.push(NotificationSign::new().count(count).into_any_element());
    }
    children
}

impl RenderOnce for Button {
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let animation_state =
            window.use_keyed_state(self.id.clone(), cx, |_, _| HoverAnimation::default());
        let variant = self.variant;
        let painted = transition_frame(&animation_state, variant, self.disabled, window, cx);
        let (pad_y, pad_x) = padding(variant);
        let box_spacing = spacing(variant);
        let handler = self.effective_handler().filter(|_| !self.disabled);
        let tooltip = self.tooltip.take();
        let tooltip_place = self.tooltip_place;
        let id = self.id.clone();
        let disabled = self.disabled;
        let underline = self.underline;
        let width = self.width;
        let justify = self.justify;
        let has_dot = self.dot_notification;
        let children = content(self, painted);
        let button = div()
            .id(id)
            .flex()
            .items_center()
            .map(|el| justified(el, justify))
            .when(has_dot, gpui::Styled::relative)
            .gap(px(box_spacing))
            .rounded(px(box_spacing))
            .py(px(pad_y))
            .px(px(pad_x))
            .when_some(width, |el, width| el.w(px(width)))
            .font_family(FONT_PRIMARY)
            .text_size(px(TEXT_SIZE.px()))
            .line_height(px(TEXT_SIZE.line_height_px()))
            .when(underline, gpui::Styled::underline)
            .whitespace_nowrap()
            .text_color(painted.fg)
            .when_some(painted.bg, gpui::Styled::bg)
            .when_some(painted.border, |el, border| {
                el.border_1().border_color(border)
            })
            .when(disabled, gpui::Styled::cursor_not_allowed)
            .when(!disabled, |el| {
                el.cursor_pointer()
                    .on_hover(move |is_hovered, hover_window, hover_cx| {
                        set_hovered(&animation_state, *is_hovered, hover_cx);
                        hover_window.refresh();
                    })
            })
            .when_some(handler, |el, handler| el.on_click(handler))
            .children(children);
        with_tooltip(button, tooltip, tooltip_place)
    }
}