gpui_material_foundation/
surface.rs1use gpui::{
2 AnyElement, App, Hsla, IntoElement, ParentElement, RenderOnce, Rgba, Styled, Window, div,
3};
4use gpui_material_theme::{Argb, ColorRole, Elevation, MaterialTheme};
5
6use crate::window_material_theme;
7
8pub fn color(argb: Argb) -> Hsla {
10 let [a, r, g, b] = argb.channels().map(|channel| f32::from(channel) / 255.);
11 Rgba { r, g, b, a }.into()
12}
13
14pub fn scrim_color(theme: &MaterialTheme, opacity: f32) -> Hsla {
16 color(theme.colors.color(ColorRole::Scrim)).opacity(opacity.clamp(0., 1.))
17}
18
19pub fn elevation_shadows(elevation: f32, scale: f32, shadow: Hsla) -> Vec<gpui::BoxShadow> {
23 let dp = elevation * scale;
24 if !dp.is_finite() || dp <= 0. || !scale.is_finite() || scale <= 0. {
25 return Vec::new();
26 }
27 vec![
28 gpui_base::box_shadow(0., dp * 0.4, dp, 0., shadow.opacity(0.18)),
29 gpui_base::box_shadow(0., scale, dp * 0.5, 0., shadow.opacity(0.13)),
30 ]
31}
32
33#[derive(IntoElement)]
35pub struct Surface {
36 element: gpui::Div,
37 role: ColorRole,
38 tonal_elevation: Elevation,
39 shadow_elevation: Elevation,
40 shadow_scale: f32,
41 theme: Option<MaterialTheme>,
42}
43
44impl Surface {
45 pub fn new(role: ColorRole) -> Self {
46 Self {
47 element: div(),
48 role,
49 tonal_elevation: Elevation::Level0,
50 shadow_elevation: Elevation::Level0,
51 shadow_scale: 1.,
52 theme: None,
53 }
54 }
55
56 pub fn tonal_elevation(mut self, elevation: Elevation) -> Self {
57 self.tonal_elevation = elevation;
58 self
59 }
60
61 pub fn shadow_elevation(mut self, elevation: Elevation) -> Self {
62 self.shadow_elevation = elevation;
63 self
64 }
65
66 pub fn shadow_scale(mut self, scale: f32) -> Self {
68 self.shadow_scale = scale;
69 self
70 }
71
72 pub fn with_theme(mut self, theme: MaterialTheme) -> Self {
74 self.theme = Some(theme);
75 self
76 }
77}
78
79impl ParentElement for Surface {
80 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
81 self.element.extend(elements);
82 }
83}
84
85impl Styled for Surface {
86 fn style(&mut self) -> &mut gpui::StyleRefinement {
87 self.element.style()
88 }
89}
90
91impl RenderOnce for Surface {
92 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
93 let theme = self
94 .theme
95 .as_ref()
96 .unwrap_or_else(|| window_material_theme(window, cx));
97 let scheme = &theme.colors;
98 let background = if self.role == ColorRole::Surface {
99 scheme.surface_at_elevation(self.tonal_elevation)
100 } else {
101 scheme.color(self.role)
102 };
103 let mut element = self.element.bg(color(background));
104 if let Some(pair) = scheme.pair(self.role) {
105 element = element.text_color(color(pair.foreground));
106 }
107 let shadows = elevation_shadows(
108 self.shadow_elevation.dp(),
109 self.shadow_scale,
110 color(scheme.color(ColorRole::Shadow)),
111 );
112 if !shadows.is_empty() {
113 element = element.shadow(shadows);
114 }
115 element
116 }
117}