gpui-material-foundation 0.4.1

GPUI adapters and drawing primitives for GPUI Material
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
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
mod control;
mod elevation;
mod passive;

use std::rc::Rc;

use gpui::{
    AnyElement, App, Bounds, ElementId, Entity, FocusHandle, Hsla, IntoElement, ParentElement,
    Pixels, RenderOnce, SharedString, StyleRefinement, Styled, Window, px,
};
use gpui_material_theme::{ColorRole, CornerShape, Direction, Elevation, MaterialTheme};

use crate::{InteractionSource, Shape, ShapeFit, ShapePolygon, current_material_theme};

pub use elevation::{
    color, elevation_shadow_pair, elevation_shadows, resolve_color_spec, resolve_edges, scrim_color,
};

/// An outline in logical pixels, drawn around the surface's shape.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SurfaceBorder {
    /// Stroke width in logical pixels.
    pub width: Pixels,
    /// Stroke color in HSLA.
    pub color: Hsla,
}

/// Customizes the Material feedback painted by one interactive surface.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SurfaceFeedback {
    /// Whether to paint hover, focus, and pressed state-layer tints (defaults to `true`).
    pub state_layer: bool,
    /// Whether to paint pointer-originated ink ripples on press (defaults to `true`).
    pub ripple: bool,
    /// Whether to paint a Material keyboard focus ring (defaults to `true`).
    pub focus_ring: bool,
    /// Optional explicit ink color for state layers and ripples; defaults to the resolved content color.
    pub ink: Option<Hsla>,
    /// Optional explicit focus ring color; defaults to the theme's secondary/focus token.
    pub focus_color: Option<Hsla>,
}

impl Default for SurfaceFeedback {
    fn default() -> Self {
        Self {
            state_layer: true,
            ripple: true,
            focus_ring: true,
            ink: None,
            focus_color: None,
        }
    }
}

#[derive(Clone, Copy)]
enum SurfaceAction {
    Activate,
    Select(bool),
    Check(bool),
}

type Activate = Rc<dyn Fn(&mut Window, &mut App)>;

struct Control {
    id: ElementId,
    label: SharedString,
    action: SurfaceAction,
    activate: Option<Activate>,
}

/// A passive Material background or an interactive surface with arbitrary children.
#[derive(IntoElement)]
pub struct Surface {
    style: StyleRefinement,
    children: Vec<AnyElement>,
    role: ColorRole,
    container_color: Option<Hsla>,
    content_color: Option<Hsla>,
    inherit_content_color: bool,
    shape: Option<CornerShape>,
    polygon: Option<ShapePolygon>,
    shape_fit: ShapeFit,
    clip_backdrop: Option<Hsla>,
    shape_hit_test: Option<bool>,
    border: Option<SurfaceBorder>,
    tonal_elevation: Elevation,
    shadow_elevation: Elevation,
    shadow_scale: f32,
    theme: Option<Rc<MaterialTheme>>,
    control: Option<Control>,
    disabled: bool,
    focus: Option<FocusHandle>,
    feedback: SurfaceFeedback,
    interaction_source: Option<Entity<InteractionSource>>,
}

impl Surface {
    /// Creates a passive (non-interactive) Material surface filled with `role`.
    pub fn new(role: ColorRole) -> Self {
        Self {
            style: StyleRefinement::default(),
            children: Vec::new(),
            role,
            container_color: None,
            content_color: None,
            inherit_content_color: false,
            shape: None,
            polygon: None,
            shape_fit: ShapeFit::Contain,
            clip_backdrop: None,
            shape_hit_test: None,
            border: None,
            tonal_elevation: Elevation::Level0,
            shadow_elevation: Elevation::Level0,
            shadow_scale: 1.,
            theme: None,
            control: None,
            disabled: false,
            focus: None,
            feedback: SurfaceFeedback::default(),
            interaction_source: None,
        }
    }

    /// Creates an interactive clickable surface with button semantics and `on_activate` support.
    pub fn clickable(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        role: ColorRole,
    ) -> Self {
        Self::interactive(id, label, role, SurfaceAction::Activate)
    }

    /// Renders the caller's selection and requests activation through `on_activate`.
    pub fn selectable(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        role: ColorRole,
        selected: bool,
    ) -> Self {
        Self::interactive(id, label, role, SurfaceAction::Select(selected))
    }

    /// Renders the caller's check state and requests the next value through `on_checked_change`.
    pub fn toggleable(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        role: ColorRole,
        checked: bool,
    ) -> Self {
        Self::interactive(id, label, role, SurfaceAction::Check(checked))
    }

    fn interactive(
        id: impl Into<ElementId>,
        label: impl Into<SharedString>,
        role: ColorRole,
        action: SurfaceAction,
    ) -> Self {
        Self {
            control: Some(Control {
                id: id.into(),
                label: label.into(),
                action,
                activate: None,
            }),
            ..Self::new(role)
        }
    }

    /// Registers the activation callback for clickable and selectable surfaces.
    pub fn on_activate(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
        if let Some(control) = &mut self.control {
            control.activate = Some(Rc::new(handler));
        }
        self
    }

    /// Registers the toggled callback for surfaces constructed with [`Self::toggleable`],
    /// passing the requested next checked state (`!checked`).
    pub fn on_checked_change(
        mut self,
        handler: impl Fn(bool, &mut Window, &mut App) + 'static,
    ) -> Self {
        if let Some(control) = &mut self.control
            && let SurfaceAction::Check(checked) = control.action
        {
            control.activate = Some(Rc::new(move |window, cx| handler(!checked, window, cx)));
        }
        self
    }

    /// Disables pointer and keyboard interaction when `true`.
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    /// Associates a caller-owned GPUI [`FocusHandle`] with this interactive surface.
    pub fn track_focus(mut self, focus: &FocusHandle) -> Self {
        self.focus = Some(focus.clone());
        self
    }

    /// Configures state-layer, ripple, and focus-ring feedback for this surface.
    pub fn feedback(mut self, feedback: SurfaceFeedback) -> Self {
        self.feedback = feedback;
        self
    }

    /// Connects a shared [`InteractionSource`] entity so external views can observe
    /// hover, focus, press, and drag states.
    pub fn interaction_source(mut self, source: &Entity<InteractionSource>) -> Self {
        self.interaction_source = Some(source.clone());
        self
    }

    /// Uses an explicit fill and inherits the foreground unless one is supplied.
    pub fn container_color(mut self, color: Hsla) -> Self {
        self.container_color = Some(color);
        self
    }

    /// Sets the inherited foreground for this surface's children.
    pub fn content_color(mut self, color: Hsla) -> Self {
        self.content_color = Some(color);
        self
    }

    /// Uses the ancestor text color unless this surface supplies an explicit foreground.
    pub fn inherit_content_color(mut self, inherit: bool) -> Self {
        self.inherit_content_color = inherit;
        self
    }

    /// Applies a rounded-rectangle [`CornerShape`] to the surface, clearing any polygon shape.
    pub fn shape(mut self, shape: CornerShape) -> Self {
        self.shape = Some(shape);
        self.polygon = None;
        self
    }

    /// Uses any [`ShapePolygon`] (including [`MaterialShape`](gpui_material_theme::MaterialShape),
    /// [`PolygonRole`](gpui_material_theme::PolygonRole), or sampled [`ShapeMorph`](crate::ShapeMorph)
    /// outlines) for background painting, border stroke, shadow, clipping, and feedback.
    ///
    /// Interactive polygon surfaces default to shape-aware pointer hit testing unless
    /// overridden with [`Self::shape_hit_test`].
    pub fn polygon_shape(mut self, polygon: impl Into<ShapePolygon>) -> Self {
        self.polygon = Some(polygon.into());
        self.shape = None;
        self
    }

    /// Chooses how a [`Self::polygon_shape`] maps into the laid-out surface bounds.
    pub fn shape_fit(mut self, fit: ShapeFit) -> Self {
        self.shape_fit = fit;
        self
    }

    /// Visually clips overflowing children to the resolved shape contour by applying a
    /// rectangular content mask and painting an EvenOdd exterior mask in `backdrop`.
    /// Match `backdrop` to the uniform background behind this surface.
    pub fn shape_clip_backdrop(mut self, backdrop: Hsla) -> Self {
        self.clip_backdrop = Some(backdrop);
        self
    }

    /// Controls whether pointer hover, press, and click activation require the cursor to
    /// lie inside the resolved shape contour. Defaults to `true` for [`Self::polygon_shape`]
    /// and `false` for rectangular or [`CornerShape`] surfaces. Keyboard and accessibility
    /// activation remain available regardless of this setting.
    pub fn shape_hit_test(mut self, enabled: bool) -> Self {
        self.shape_hit_test = Some(enabled);
        self
    }

    /// Draws an outline border around the resolved surface shape.
    pub fn border(mut self, border: SurfaceBorder) -> Self {
        self.border = Some(border);
        self
    }

    /// Applies tonal surface-tint elevation (defaults to [`Elevation::Level0`]).
    pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
        self.tonal_elevation = elevation;
        self
    }

    /// Applies drop-shadow elevation (defaults to [`Elevation::Level0`]).
    pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
        self.shadow_elevation = elevation;
        self
    }

    /// Scales the offset and blur radius with an animated surface.
    pub fn shadow_scale(mut self, scale: f32) -> Self {
        self.shadow_scale = scale;
        self
    }

    /// Uses an explicit window or subtree theme for this surface.
    pub fn theme(mut self, theme: MaterialTheme) -> Self {
        self.theme = Some(Rc::new(theme));
        self
    }
}

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

impl Styled for Surface {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

#[derive(Clone)]
pub(super) enum ResolvedShape {
    Corners(CornerShape, Direction),
    Polygon(ShapePolygon, ShapeFit),
}

impl ResolvedShape {
    pub(super) fn build(&self, bounds: Bounds<Pixels>) -> Option<Shape> {
        match self {
            Self::Corners(shape, direction) => Shape::rounded(bounds, *shape, *direction),
            Self::Polygon(polygon, fit) => Shape::polygon(bounds, polygon, *fit),
        }
    }
}

pub(super) struct PolygonPaint {
    pub(super) background: Hsla,
    pub(super) shadow_elevation: f32,
    pub(super) shadow_scale: f32,
    pub(super) shadow_color: Hsla,
    pub(super) border: Option<(Pixels, Hsla)>,
}

impl RenderOnce for Surface {
    fn render(mut self, window: &mut Window, cx: &mut App) -> impl IntoElement {
        let current;
        let theme = match &self.theme {
            Some(theme) => theme.as_ref(),
            None => {
                current = current_material_theme(window, cx);
                &*current
            }
        };
        let scheme = &theme.colors;
        let default_focus = color(scheme.color(ColorRole::Secondary));
        let shadow_color = color(scheme.color(ColorRole::Shadow));
        let background = if self.role == ColorRole::Surface {
            scheme.surface_at_elevation(self.tonal_elevation)
        } else {
            scheme.color(self.role)
        };
        let direction = theme.layout.direction;
        let background = self.container_color.unwrap_or_else(|| color(background));
        let foreground = self.content_color.or_else(|| {
            if self.inherit_content_color || self.container_color.is_some() {
                return None;
            }
            scheme.pair(self.role).map(|pair| color(pair.foreground))
        });
        if let Some(foreground) = foreground {
            self.style.text.color = Some(foreground);
        }
        let border = self.border.map(|border| {
            let border_width = if f32::from(border.width).is_finite() {
                border.width.max(px(0.))
            } else {
                px(0.)
            };
            (border_width, border.color)
        });
        let polygon_paint = if self.polygon.is_some() {
            Some(PolygonPaint {
                background,
                shadow_elevation: self.shadow_elevation.dp(),
                shadow_scale: self.shadow_scale,
                shadow_color,
                border: border.filter(|(width, _)| *width > px(0.)),
            })
        } else {
            self.style.background = Some(background.into());
            let shadows =
                elevation_shadows(self.shadow_elevation.dp(), self.shadow_scale, shadow_color);
            if !shadows.is_empty() {
                self.style.box_shadow = Some(shadows);
            }
            if let Some(shape) = self.shape {
                if shape == CornerShape::Full {
                    self = self.rounded_full();
                } else {
                    let [tl, tr, br, bl] = shape.radii(f32::MAX, f32::MAX, direction);
                    self = self
                        .rounded_tl(px(tl))
                        .rounded_tr(px(tr))
                        .rounded_br(px(br))
                        .rounded_bl(px(bl));
                }
            }
            if let Some((border_width, border_color)) = border {
                let width = Some(border_width.into());
                self.style.border_widths.top = width;
                self.style.border_widths.right = width;
                self.style.border_widths.bottom = width;
                self.style.border_widths.left = width;
                self.style.border_color = Some(if border_width > px(0.) {
                    border_color
                } else {
                    gpui::transparent_black()
                });
            }
            None
        };
        let resolved_shape = self.resolve_shape(direction, window);
        let Some(control) = self.control.take() else {
            return self.render_passive(resolved_shape, polygon_paint);
        };
        self.render_control(
            control,
            resolved_shape,
            polygon_paint,
            default_focus,
            window,
            cx,
        )
    }
}

impl Surface {
    fn resolve_shape(&self, direction: Direction, window: &Window) -> ResolvedShape {
        if let Some(polygon) = &self.polygon {
            ResolvedShape::Polygon(polygon.clone(), self.shape_fit)
        } else if let Some(shape) = self.shape {
            ResolvedShape::Corners(shape, direction)
        } else {
            let radii = &self.style.corner_radii;
            let radius = |value: Option<gpui::AbsoluteLength>| {
                value.map_or(0., |value| value.to_pixels(window.rem_size()).into())
            };
            ResolvedShape::Corners(
                CornerShape::Radii([
                    radius(radii.top_left),
                    radius(radii.top_right),
                    radius(radii.bottom_right),
                    radius(radii.bottom_left),
                ]),
                Direction::Ltr,
            )
        }
    }
}