gpui-material-components 0.4.1

Material 3 Expressive desktop components for GPUI
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
use std::{cell::RefCell, f32::consts::TAU, rc::Rc};

use gpui::{
    AnyElement, App, BorderStyle, Bounds, ElementId, Hsla, InteractiveElement, IntoElement,
    ParentElement, PathBuilder, PathStyle, Pixels, Point, SharedString, StrokeOptions, Styled,
    Window, canvas, div, point, px, quad, size,
};
use gpui_base::{TestSupportExt, motion::Easing};
use gpui_material_foundation::{
    LoopClock, current_material_theme, is_bounds_visible, resolve_edges,
};
use gpui_material_theme::{Direction, LogicalEdges, TypographyEmphasis};

use crate::action::icon_slot;
use crate::control_style::finite_length;

use super::types::Metrics;

const MIN_COMPRESSED_HORIZONTAL_PADDING: f32 = 4.;
const EMPHASIZED_DECELERATE: Easing = Easing::CubicBezier {
    x1: 0.05,
    y1: 0.7,
    x2: 0.1,
    y2: 1.0,
};
const STANDARD: Easing = Easing::CubicBezier {
    x1: 0.2,
    y1: 0.0,
    x2: 0.0,
    y2: 1.0,
};
const REDUCED_MOTION_ARC: (f32, f32) = (0.0, 0.72);
const CYCLE_MS: f32 = 6000.;
const SAMPLES_PER_TURN: f32 = 64.;

struct SpinnerClock {
    clock: LoopClock,
    visible: bool,
}

impl Default for SpinnerClock {
    fn default() -> Self {
        Self {
            clock: LoopClock::default(),
            visible: true,
        }
    }
}

fn spinner_arc(elapsed_ms: f32, motionless: bool) -> (f32, f32) {
    if motionless || !elapsed_ms.is_finite() {
        return REDUCED_MOTION_ARC;
    }
    let clock = elapsed_ms.rem_euclid(CYCLE_MS);
    let step = (clock / 1500.).floor();
    let turn = EMPHASIZED_DECELERATE.sample(((clock % 1500.) / 300.).clamp(0., 1.));
    let phase = clock / 3000.;
    let sweep = if phase < 1. {
        0.12 + (0.78 - 0.12) * phase
    } else {
        0.78 - (0.78 - 0.12) * STANDARD.sample((phase - 1.).clamp(0., 1.))
    };
    let start = (clock / CYCLE_MS) * 3. + (step + turn) / 4.;
    (start, sweep)
}

fn arc_point(center: Point<Pixels>, radius: f32, turn: f32) -> Point<Pixels> {
    let angle = turn * TAU - std::f32::consts::FRAC_PI_2;
    let (sin, cos) = angle.sin_cos();
    point(center.x + px(radius * cos), center.y + px(radius * sin))
}

fn paint_round_cap(center: Point<Pixels>, diameter: f32, color: Hsla, window: &mut Window) {
    let half = px(diameter * 0.5);
    let bounds = Bounds::new(
        point(center.x - half, center.y - half),
        size(px(diameter), px(diameter)),
    );
    window.paint_quad(quad(
        bounds,
        half,
        color,
        px(0.),
        gpui::transparent_black(),
        BorderStyle::Solid,
    ));
}

fn render_loading_spinner(
    id: &ElementId,
    diameter: f32,
    tint: Hsla,
    window: &mut Window,
    cx: &mut App,
) -> impl IntoElement {
    let clock = window
        .use_keyed_state((id.clone(), "loading-spinner-clock"), cx, |_, _| {
            Rc::new(RefCell::new(SpinnerClock::default()))
        })
        .read(cx)
        .clone();
    let reduced = cx.reduce_motion();
    let animate_loop = window.is_window_active() && window.is_visible() && !reduced;
    let now = cx.background_executor().now();
    let elapsed = {
        let mut guard = clock.borrow_mut();
        let active = animate_loop && guard.visible;
        guard.clock.advance(now, active, reduced)
    };
    let motionless = reduced || (!animate_loop && elapsed.is_zero());
    let (start, sweep) = spinner_arc(elapsed.as_secs_f32() * 1000., motionless);
    let diameter = diameter.max(12.);

    canvas(
        move |bounds, window, cx| {
            let width = f32::from(bounds.size.width);
            let height = f32::from(bounds.size.height);
            let visible = width.is_finite()
                && height.is_finite()
                && width > 0.
                && height > 0.
                && is_bounds_visible(bounds, window);
            let mut guard = clock.borrow_mut();
            if guard.visible != visible {
                guard.visible = visible;
                if !visible {
                    guard.clock.pause(cx.background_executor().now());
                }
            }
            visible
        },
        move |bounds, visible, window, _| {
            if !visible || tint.a <= 0. {
                return;
            }
            let width = f32::from(bounds.size.width);
            let height = f32::from(bounds.size.height);
            let side = width.min(height);
            let stroke_width = (side * 0.12).clamp(2., 4.).min(side * 0.45);
            let radius = (side - stroke_width) * 0.5;
            if radius <= 0. {
                return;
            }
            let center = bounds.center();
            let steps = ((sweep * SAMPLES_PER_TURN).ceil() as usize).max(4);
            let step = sweep / steps as f32;
            let first = arc_point(center, radius, start);
            let last = arc_point(center, radius, start + sweep);
            let mut path = PathBuilder::default().with_style(PathStyle::Stroke(StrokeOptions {
                line_width: stroke_width,
                miter_limit: 1.,
                ..StrokeOptions::default()
            }));
            path.move_to(first);
            for ix in 1..=steps {
                path.line_to(arc_point(center, radius, start + step * ix as f32));
            }
            if let Ok(path) = path.build() {
                window.paint_path(path, tint);
            }
            paint_round_cap(first, stroke_width, tint, window);
            paint_round_cap(last, stroke_width, tint, window);

            if animate_loop {
                window.request_animation_frame();
            }
        },
    )
    .size(px(diameter))
    .flex_none()
}

pub(super) fn loading_overlay(
    id: &ElementId,
    resting_content: AnyElement,
    icon_size: f32,
    tint: Hsla,
    window: &mut Window,
    cx: &mut App,
) -> AnyElement {
    div()
        .relative()
        .flex()
        .items_center()
        .justify_center()
        .child(div().opacity(0.).child(resting_content))
        .child(
            div()
                .id((id.clone(), "loading-spinner"))
                .test_support()
                .absolute()
                .inset_0()
                .flex()
                .items_center()
                .justify_center()
                .child(render_loading_spinner(id, icon_size, tint, window, cx)),
        )
        .into_any_element()
}

pub(super) fn loading_icon_spinner(
    id: &ElementId,
    icon_size: f32,
    tint: Hsla,
    window: &mut Window,
    cx: &mut App,
) -> AnyElement {
    div()
        .id((id.clone(), "loading-spinner"))
        .test_support()
        .flex()
        .items_center()
        .justify_center()
        .child(render_loading_spinner(id, icon_size, tint, window, cx))
        .into_any_element()
}

fn compress_horizontal_padding(
    left: Pixels,
    right: Pixels,
    width: Pixels,
    icon_extent: Pixels,
    natural_label_width: Pixels,
) -> (Pixels, Pixels, Pixels) {
    let mut left_pad = finite_length(left);
    let mut right_pad = finite_length(right);
    let available = (width - left_pad - right_pad - icon_extent).max(px(0.));
    let deficit = (natural_label_width - available).max(px(0.));
    if deficit > px(0.) {
        let floor_left = left_pad.min(px(MIN_COMPRESSED_HORIZONTAL_PADDING));
        let floor_right = right_pad.min(px(MIN_COMPRESSED_HORIZONTAL_PADDING));
        let slack_left = (left_pad - floor_left).max(px(0.));
        let slack_right = (right_pad - floor_right).max(px(0.));
        let total_slack = slack_left + slack_right;
        let absorb = deficit.min(total_slack);
        if absorb > px(0.) && total_slack > px(0.) {
            let left_cut = absorb * (f32::from(slack_left) / f32::from(total_slack));
            let right_cut = absorb - left_cut;
            left_pad -= left_cut;
            right_pad -= right_cut;
        }
    }
    let label_width = (width - left_pad - right_pad - icon_extent).max(px(0.));
    (left_pad, right_pad, label_width)
}

#[derive(Default)]
pub(super) struct Slots {
    pub(super) leading: Option<AnyElement>,
    pub(super) trailing: Option<AnyElement>,
    pub(super) content: Option<AnyElement>,
    pub(super) padding: Option<LogicalEdges>,
    pub(super) width: Option<Pixels>,
}

impl Slots {
    pub(super) fn render(
        self,
        label: SharedString,
        metrics: Metrics,
        scale: f32,
        window: &Window,
        tint: Hsla,
        cx: &App,
    ) -> AnyElement {
        let theme = current_material_theme(window, cx);
        let direction = theme.layout.direction;
        let typography = metrics.label.style(TypographyEmphasis::Baseline);
        let max_padding = self.width.map_or_else(
            || f32::from(window.viewport_size().width) * 0.125,
            |width| (f32::from(width) - 16.).max(0.) / 2.,
        );
        let horizontal = metrics.padding.min(max_padding);
        let edges = resolve_edges(
            self.padding
                .unwrap_or_else(|| LogicalEdges::symmetric(horizontal, 4.)),
            theme.layout.direction,
        );
        let (mut left_pad, mut right_pad) = (edges.left, edges.right);
        let icons = usize::from(self.leading.is_some()) + usize::from(self.trailing.is_some());
        let icon_extent = px((metrics.icon + metrics.gap) * icons as f32);
        let mut shaped_label = None;
        let label_width = self.width.map(|width| {
            if self.content.is_none()
                && let Some(shaped) = crate::text::shape_single_line(
                    label.clone(),
                    typography,
                    scale,
                    tint,
                    window,
                    cx,
                )
            {
                let natural_width = if scale.is_finite() && scale > 0. {
                    shaped.1.line().width.ceil() / scale
                } else {
                    shaped.1.line().width.ceil()
                };
                let (next_left, next_right, next_label_width) = compress_horizontal_padding(
                    left_pad,
                    right_pad,
                    width,
                    icon_extent,
                    natural_width,
                );
                left_pad = next_left;
                right_pad = next_right;
                shaped_label = Some(shaped);
                next_label_width
            } else {
                (width - left_pad - right_pad - icon_extent).max(px(0.))
            }
        });
        let row_typography = theme.typography.scale_style(typography);
        let mut row = div()
            .flex()
            .items_center()
            .justify_center()
            .min_w_0()
            .max_w_full()
            .gap(px(metrics.gap * scale))
            .pl(left_pad * scale)
            .pr(right_pad * scale)
            .pt(edges.top * scale)
            .pb(edges.bottom * scale)
            .text_size(px(row_typography.size * scale))
            .line_height(px(row_typography.line_height * scale));
        if direction == Direction::Rtl {
            row = row.flex_row_reverse();
        }
        if let Some(width) = self.width {
            row = row.w(width).overflow_hidden();
        }
        row.children(
            self.leading
                .map(|icon| icon_slot(icon, metrics.icon * scale)),
        )
        .child(self.content.unwrap_or_else(|| {
            if let Some(shaped) = shaped_label {
                crate::text::single_line_with_shaped(
                    shaped,
                    typography,
                    scale,
                    tint,
                    (label_width, 1., 1.),
                    window,
                    cx,
                )
            } else {
                crate::text::single_line(
                    label,
                    typography,
                    scale,
                    tint,
                    (label_width, 1., 1.),
                    window,
                    cx,
                )
            }
            .into_any_element()
        }))
        .children(
            self.trailing
                .map(|icon| icon_slot(icon, metrics.icon * scale)),
        )
        .into_any_element()
    }
}

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

    #[test]
    fn spinner_arc_returns_static_fallback_under_reduced_motion_and_cycles_smoothly() {
        assert_eq!(spinner_arc(1234., true), REDUCED_MOTION_ARC);
        assert_eq!(spinner_arc(f32::NAN, false), REDUCED_MOTION_ARC);

        let (s0, l0) = spinner_arc(0., false);
        let (s_mid, l_mid) = spinner_arc(3000., false);
        let (s_wrap, l_wrap) = spinner_arc(CYCLE_MS, false);
        assert!((l0 - 0.12).abs() < 1e-4);
        assert!((l_mid - 0.78).abs() < 1e-4);
        assert!(s_mid > s0);
        assert!((s_wrap - s0).abs() < 1e-4);
        assert!((l_wrap - l0).abs() < 1e-4);
    }

    #[test]
    fn compressed_button_shrinks_horizontal_padding_before_truncating_label() {
        let (left, right, label_width) =
            compress_horizontal_padding(px(16.), px(16.), px(54.), px(0.), px(28.));
        assert_eq!(left, px(13.));
        assert_eq!(right, px(13.));
        assert_eq!(label_width, px(28.));

        let (left, right, label_width) =
            compress_horizontal_padding(px(16.), px(16.), px(72.), px(0.), px(28.));
        assert_eq!(left, px(16.));
        assert_eq!(right, px(16.));
        assert_eq!(label_width, px(40.));

        let (left, right, label_width) =
            compress_horizontal_padding(px(16.), px(16.), px(30.), px(0.), px(28.));
        assert_eq!(left, px(4.));
        assert_eq!(right, px(4.));
        assert_eq!(label_width, px(22.));

        let (left, right, label_width) =
            compress_horizontal_padding(px(2.), px(10.), px(30.), px(0.), px(28.));
        assert_eq!(left, px(2.));
        assert_eq!(right, px(4.));
        assert_eq!(label_width, px(24.));
    }
}