fluidattacks-designs 0.12.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
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
//! The list widget — a card of rows one of which can be the choice.
//!
//! Split the way [`crate::Select`] is: [`ListState`] is an entity the app owns
//! and calls methods on, [`List`] is the element it renders each frame. The
//! walk and the lookups are the domain's shared
//! [`fluidattacks_designs_domain::navigation`], so a list and a menu answer the
//! arrow keys identically.
//!
//! A list that reports nothing is a list all the same: `SelectionMode::None` stacks
//! rows that only report progress, which is what the reattack assign window
//! does, and it highlights nothing so it never invites a click it will not
//! answer.

use fluidattacks_designs_domain::container::Scroll;
use fluidattacks_designs_domain::icon::Style as IconStyle;
use fluidattacks_designs_domain::list::{
    right_glyph, row_bg, row_text, Item, SelectionMode, BG, BORDER, LEFT_GLYPH, MIN_WIDTH,
    PADDING_Y, RADIUS, RIGHT_GLYPH, ROW_GAP, ROW_LINE_HEIGHT, ROW_MIN_HEIGHT, ROW_PADDING,
    ROW_TEXT_SIZE, ROW_WEIGHT, SHADOW,
};
use fluidattacks_designs_domain::navigation::{choosable, label_of, position_of, step, Step};
use fluidattacks_designs_domain::typography::FONT_PRIMARY;
use gpui::prelude::FluentBuilder as _;
use gpui::{
    div, px, rgb, App, Context, Div, Entity, FocusHandle, Focusable, FontWeight,
    InteractiveElement as _, IntoElement, KeyBinding, MouseButton, ParentElement as _, RenderOnce,
    ScrollHandle, SharedString, Stateful, Styled as _, Window,
};

use crate::container::Container;
use crate::empty_state::EmptyState;
use crate::icon::Icon;
use crate::theme::{ActiveTheme as _, Theme};
use crate::widget::{elevation, report, text, ValueHandler};

const CONTEXT: &str = "DesignsList";

#[allow(
    clippy::derive_partial_eq_without_eq,
    reason = "the actions! expansion derives PartialEq without Eq"
)]
mod action_defs {
    gpui::actions!(designs_list, [Next, Previous, Confirm]);
}

use action_defs::{Confirm, Next, Previous};

/// Bind the list's keymap. [`crate::Theme::init`] calls this; an app that
/// installs the theme needs nothing of its own.
///
/// There is no `escape`: a list is not a floating menu, so there is nothing for
/// it to dismiss.
pub fn bind_keys(cx: &mut App) {
    cx.bind_keys([
        KeyBinding::new("down", Next, Some(CONTEXT)),
        KeyBinding::new("up", Previous, Some(CONTEXT)),
        KeyBinding::new("enter", Confirm, Some(CONTEXT)),
    ]);
}

/// One row of the list — the web's `IListItemProps`.
#[derive(Clone, Debug)]
pub struct ListItem {
    label: SharedString,
    value: SharedString,
    icon: Option<SharedString>,
    right_icon: Option<SharedString>,
    disabled: bool,
}

impl ListItem {
    /// The value is what choosing reports; the label is what the row reads as.
    /// A list whose rows carry no identifier of their own passes the label as
    /// both.
    #[must_use]
    pub fn new(label: impl Into<SharedString>, value: impl Into<SharedString>) -> Self {
        Self {
            label: label.into(),
            value: value.into(),
            icon: None,
            right_icon: None,
            disabled: false,
        }
    }

    /// The glyph beside the label.
    #[must_use]
    pub fn icon(mut self, icon: impl Into<SharedString>) -> Self {
        self.icon = Some(icon.into());
        self
    }

    /// The glyph at the far end. It replaces the tick a chosen row would show,
    /// which is the web's single slot for both.
    #[must_use]
    pub fn right_icon(mut self, icon: impl Into<SharedString>) -> Self {
        self.right_icon = Some(icon.into());
        self
    }

    /// Shown, but not choosable by pointer or keyboard.
    #[must_use]
    pub const fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    fn as_item(&self) -> Item<'_> {
        Item {
            label: &self.label,
            value: &self.value,
            icon: self.icon.as_ref().map(text),
            right_icon: self.right_icon.as_ref().map(text),
            disabled: self.disabled,
        }
    }
}

/// What a list holds: its rows, which one is the choice, and whether it answers
/// a choice at all.
pub struct ListState {
    items: Vec<ListItem>,
    value: Option<SharedString>,
    selection: SelectionMode,
    focus: FocusHandle,
    scroll: ScrollHandle,
}

impl ListState {
    #[must_use]
    pub fn new(cx: &Context<Self>) -> Self {
        Self {
            items: Vec::new(),
            value: None,
            selection: SelectionMode::default(),
            focus: cx.focus_handle(),
            scroll: ScrollHandle::new(),
        }
    }

    /// Whether the list answers a choice. The default is a single choice;
    /// [`SelectionMode::None`] stacks rows that only report.
    #[must_use]
    pub const fn selection(mut self, selection: SelectionMode) -> Self {
        self.selection = selection;
        self
    }

    /// Replace the rows. This is repopulation, not a choice: it reports
    /// nothing, and it keeps the current value so a list that arrives again
    /// with the same row still standing does not lose where the reader was.
    pub fn set_items(&mut self, items: Vec<ListItem>, cx: &mut Context<Self>) {
        self.items = items;
        if self.position().is_none() {
            self.value = None;
        }
        cx.notify();
    }

    /// Set the choice from the app's side, which reports nothing. A value no
    /// row carries clears it, so a caller cannot leave the list standing on a
    /// row that is gone, and a list that answers no choice takes none: it must
    /// highlight nothing, not merely report nothing.
    pub fn set_value(&mut self, value: Option<impl Into<SharedString>>, cx: &mut Context<Self>) {
        self.value = value.map(Into::into).filter(|_| self.selection.choosable());
        if self.position().is_none() {
            self.value = None;
        }
        cx.notify();
    }

    #[must_use]
    pub const fn value(&self) -> Option<&SharedString> {
        self.value.as_ref()
    }

    /// What the chosen row reads as, for a caller that shows it elsewhere.
    #[must_use]
    pub fn label(&self) -> Option<&str> {
        label_of(&self.rows(), self.value.as_ref().map(text)?)
    }

    fn rows(&self) -> Vec<Item<'_>> {
        self.items.iter().map(ListItem::as_item).collect()
    }

    fn position(&self) -> Option<usize> {
        position_of(&self.rows(), self.value.as_ref().map(text)?)
    }

    /// Take the row carrying `value`, or nothing when it cannot be chosen —
    /// which a list that reports nothing never can.
    ///
    /// By value rather than by position, as the select's rows commit: the
    /// position was read when the frame was painted, and a repopulation
    /// between that and the press would land it on a different row.
    fn take(&mut self, value: &SharedString, cx: &mut Context<Self>) -> Option<SharedString> {
        if !self.selection.choosable() {
            return None;
        }
        let rows = self.rows();
        let position = position_of(&rows, value)?;
        if !choosable(&rows, position) {
            return None;
        }
        drop(rows);
        self.value = Some(value.clone());
        cx.notify();
        Some(value.clone())
    }

    /// Move the choice one row, which for a list is the walk and the choice at
    /// once: there is no menu to hold a highlight open until `enter`, so the
    /// row the arrows land on is the row that is chosen.
    fn walk(&mut self, direction: Step, cx: &mut Context<Self>) -> Option<SharedString> {
        if !self.selection.choosable() {
            return None;
        }
        let next = step(&self.rows(), self.position(), direction)?;
        let value = self.items.get(next)?.value.clone();
        self.scroll.scroll_to_item(next);
        self.take(&value, cx)
    }
}

impl Focusable for ListState {
    fn focus_handle(&self, _cx: &App) -> FocusHandle {
        self.focus.clone()
    }
}

#[derive(IntoElement)]
pub struct List {
    state: Entity<ListState>,
    on_change: Option<ValueHandler>,
    on_right_icon: Option<ValueHandler>,
    empty: Option<EmptyState>,
    max_height: Option<f32>,
}

impl List {
    #[must_use]
    pub fn new(state: &Entity<ListState>) -> Self {
        Self {
            state: state.clone(),
            on_change: None,
            on_right_icon: None,
            empty: None,
            max_height: None,
        }
    }

    /// Called with the value a reader chose, and only then — never when
    /// [`ListState::set_items`] or [`ListState::set_value`] moves it.
    #[must_use]
    pub fn on_change(mut self, handler: impl Fn(&str, &mut App) + 'static) -> Self {
        self.on_change = Some(std::rc::Rc::new(handler));
        self
    }

    /// Called with the value of the row whose far glyph was clicked. The row
    /// itself is not chosen by that click: the web separates the two handlers,
    /// and a glyph that both removed a row and selected it would be unusable.
    #[must_use]
    pub fn on_right_icon(mut self, handler: impl Fn(&str, &mut App) + 'static) -> Self {
        self.on_right_icon = Some(std::rc::Rc::new(handler));
        self
    }

    /// What the card shows instead of rows when it has none.
    #[must_use]
    pub fn empty(mut self, empty: EmptyState) -> Self {
        self.empty = Some(empty);
        self
    }

    /// Cap how tall the card stands, past which its rows scroll.
    ///
    /// Uncapped by default, as the web's is: there the page scrolls and the
    /// card just grows. A gpui card in a bounded column has no page under it,
    /// so the height it may not pass has to be said.
    #[must_use]
    pub const fn max_height(mut self, height: f32) -> Self {
        self.max_height = Some(height);
        self
    }
}

impl RenderOnce for List {
    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
        let Self {
            state,
            on_change,
            on_right_icon,
            empty,
            max_height,
        } = self;
        let read = state.read(cx);
        let count = read.items.len();
        let card = card(cx.theme())
            .key_context(CONTEXT)
            // a tab stop, so the keymap below is reachable without the app
            // having to hand the card the keyboard itself
            .tab_index(0)
            .track_focus(&read.focus_handle(cx))
            .when_some(max_height, |el, height| el.max_h(px(height)));
        actions(card, &state, on_change.as_ref()).map(|el| {
            if count == 0 {
                el.child(
                    empty.map_or_else(|| div().into_any_element(), IntoElement::into_any_element),
                )
            } else {
                el.child(rows(
                    &state,
                    (on_change.as_ref(), on_right_icon.as_ref()),
                    cx,
                ))
            }
        })
    }
}

/// The card the rows sit in (`ListItemsWrapper`).
///
/// It takes the width it is given rather than the width of its widest row.
/// The web's is `inline-block` and sizes to content, which on a page is free;
/// here it would mean the card resizing under the reader the moment a tick
/// appeared. The floor is still the web's.
fn card(theme: &Theme) -> Div {
    div()
        .flex()
        .flex_col()
        .w_full()
        .min_w(px(MIN_WIDTH))
        .py(px(PADDING_Y))
        .bg(rgb(theme.shade(BG)))
        .border_1()
        .border_color(rgb(theme.shade(BORDER)))
        .rounded(px(RADIUS))
        .shadow(elevation(SHADOW))
        .font_family(FONT_PRIMARY)
        .text_size(px(ROW_TEXT_SIZE.px()))
        .font_weight(FontWeight(f32::from(ROW_WEIGHT.value())))
}

/// The keyboard. An arrow moves the choice and reports it, as clicking the row
/// it lands on would; `enter` re-reports the row already standing, which is
/// what answers a reader who tabbed in and pressed it.
fn actions(element: Div, state: &Entity<ListState>, on_change: Option<&ValueHandler>) -> Div {
    let (walking, stepping, confirming) = (state.clone(), state.clone(), state.clone());
    let (down, up, enter) = (on_change.cloned(), on_change.cloned(), on_change.cloned());
    element
        .on_action(move |_: &Next, _win, app| {
            let chosen = walking.update(app, |list, inner| list.walk(Step::Next, inner));
            report(chosen, down.as_ref(), app);
        })
        .on_action(move |_: &Previous, _win, app| {
            let chosen = stepping.update(app, |list, inner| list.walk(Step::Previous, inner));
            report(chosen, up.as_ref(), app);
        })
        .on_action(move |_: &Confirm, _win, app| {
            let Some(value) = confirming.read(app).value().cloned() else {
                return;
            };
            let chosen = confirming.update(app, |list, inner| list.take(&value, inner));
            report(chosen, enter.as_ref(), app);
        })
}

/// The rows, in the design system's own scroll box.
///
/// A [`Container`] rather than a flex column, and that is the whole reason the
/// wash on a chosen row reaches both edges: a container is a block box, so a
/// row fills the width it is given. Inside a scrolling *flex* box a fractional
/// width resolves against the content instead, and the wash would stop where
/// the label does.
///
/// The model is read once here and the rows are handed what they need: asking
/// per row would rebuild the whole item list for each of them.
fn rows(
    state: &Entity<ListState>,
    handlers: (Option<&ValueHandler>, Option<&ValueHandler>),
    cx: &App,
) -> gpui::AnyElement {
    let read = state.read(cx);
    let theme = cx.theme();
    let items = read.rows();
    let standing = (read.position(), read.selection.choosable());
    Container::new()
        .scroll("designs-list-rows", Scroll::Y, &read.scroll)
        .flex_grow(1.0)
        .min_h_0()
        .children(
            items
                .iter()
                .enumerate()
                .map(|(position, item)| row(state, (position, item), standing, (handlers, theme))),
        )
        .into_any_element()
}

/// One row: the glyph and the label at one end, the far glyph at the other.
fn row(
    state: &Entity<ListState>,
    (position, item): (usize, &Item<'_>),
    (current, answering): (Option<usize>, bool),
    ((on_change, on_right_icon), theme): ((Option<&ValueHandler>, Option<&ValueHandler>), &Theme),
) -> gpui::AnyElement {
    let chosen = current == Some(position);
    let live = answering && !item.disabled;
    let value = SharedString::from(item.value.to_owned());
    div()
        .id(("designs-list-row", position))
        .flex()
        .flex_none()
        .items_center()
        .justify_between()
        .gap(px(ROW_GAP))
        .min_h(px(ROW_MIN_HEIGHT))
        .py(px(ROW_PADDING.0))
        .px(px(ROW_PADDING.1))
        .line_height(px(ROW_LINE_HEIGHT))
        .map(|el| paint(el, (item.disabled, chosen, live), theme))
        .child(label(item, theme))
        .children(far_glyph(
            item,
            (position, chosen, answering),
            &value,
            (on_right_icon, theme),
        ))
        .when(live, |el| {
            let choosing = state.clone();
            let handler = on_change.cloned();
            el.cursor_pointer()
                .on_mouse_down(MouseButton::Left, move |_, window, app| {
                    // the keyboard follows the pointer, or the arrows would do
                    // nothing until the app focused the card itself
                    choosing.read(app).focus_handle(app).focus(window, app);
                    let picked = choosing.update(app, |list, inner| list.take(&value, inner));
                    report(picked, handler.as_ref(), app);
                })
        })
        .into_any_element()
}

/// The glyph and the label, which read as one and dim together.
///
/// `min_w_0` is what lets a long label wrap instead of widening the row: a flex
/// item will not shrink below its content without it, and the web's row grows
/// downwards rather than clipping.
fn label(item: &Item<'_>, theme: &Theme) -> Div {
    div()
        .flex()
        .items_center()
        .gap(px(ROW_GAP))
        .min_w_0()
        .overflow_hidden()
        .children(item.icon.map(|glyph| {
            Icon::new(glyph.to_owned())
                .style(IconStyle::Light)
                .size(LEFT_GLYPH)
                .color(theme.shade(row_text(item.disabled)))
        }))
        .child(item.label.to_owned())
}

/// The far glyph, and the click that is the row's but not the row's choice.
///
/// The slot is held open on every row a glyph could ever reach — one that names
/// its own, and every row of a list that answers a choice, since choosing paints
/// a tick. Rendering it only when there is something to show would move the
/// label sideways the moment a row was picked.
fn far_glyph(
    item: &Item<'_>,
    (position, chosen, answering): (usize, bool, bool),
    value: &SharedString,
    (on_right_icon, theme): (Option<&ValueHandler>, &Theme),
) -> Option<Stateful<Div>> {
    let glyph = right_glyph(item, chosen);
    if glyph.is_none() && !answering {
        return None;
    }
    let handler = on_right_icon.cloned();
    let clicked = value.clone();
    Some(
        div()
            .id(("designs-list-row-icon", position))
            .flex()
            .flex_none()
            .w(px(RIGHT_GLYPH.px()))
            .items_center()
            .children(glyph.map(|name| {
                Icon::new(name.to_owned())
                    .style(IconStyle::Light)
                    .size(RIGHT_GLYPH)
                    .color(theme.shade(row_text(item.disabled)))
            }))
            .when(
                handler.is_some() && !item.disabled && glyph.is_some(),
                |el| {
                    el.cursor_pointer()
                        // gpui hit-tests every box under the pointer and bubbles
                        // through all of them, so without this the row's own press
                        // runs too and the glyph would choose as well as act
                        .on_mouse_down(MouseButton::Left, move |_, _win, app| {
                            app.stop_propagation();
                            if let Some(handler) = handler.as_ref() {
                                handler(&clicked, app);
                            }
                        })
                },
            ),
    )
}

/// The resting paint comes first, so a row that is both chosen and disabled
/// keeps the chosen wash — on the web both rules apply and the selected one
/// comes last in the cascade.
///
/// The hover is the same model asked a second time: gpui wants the color up
/// front rather than a rule, and being chosen outranking being pointed at is
/// [`row_bg`]'s to decide either way.
fn paint(
    element: Stateful<Div>,
    (disabled, chosen, live): (bool, bool, bool),
    theme: &Theme,
) -> Stateful<Div> {
    let element = element
        .text_color(rgb(theme.shade(row_text(disabled))))
        .when_some(row_bg(chosen, false), |el, bg| el.bg(rgb(theme.shade(bg))));
    if !live {
        return element.when(disabled, |el| {
            el.cursor(gpui::CursorStyle::OperationNotAllowed)
        });
    }
    element.when_some(row_bg(chosen, true), |el, bg| {
        let hovered = rgb(theme.shade(bg));
        el.hover(move |style| style.bg(hovered))
    })
}