Skip to main content

waft_material/
elevation_overlay.rs

1//! Flutter counterpart: material_ui's `elevation_overlay.dart`.
2
3use waft_embedder::{Brightness, Color};
4use waft_foundation::App;
5use waft_widgets::BuildContext;
6
7use crate::colors::Colors;
8use crate::theme::Theme;
9
10/// A utility class for dealing with the overlay color needed
11/// to indicate elevation of surfaces.
12///
13/// Dart's `abstract final class ElevationOverlay`: it is never constructed, its members are
14/// associated functions.
15pub struct ElevationOverlay;
16
17impl ElevationOverlay {
18    /// Applies a surface tint color to a given container color to indicate
19    /// the level of its elevation.
20    ///
21    /// With Material Design 3, some components will use a "surface tint" color
22    /// overlay with an opacity applied to their base color to indicate they are
23    /// elevated. The amount of opacity will vary with the elevation as described
24    /// in: <https://m3.material.io/styles/color/the-color-system/color-roles>.
25    ///
26    /// If `surface_tint` is not null and not completely transparent (`Color::alpha`
27    /// is 0), then the returned color will be the given `color` with the
28    /// `surface_tint` of the appropriate opacity applied to it. Otherwise it will
29    /// just return `color` unmodified.
30    #[allow(deprecated)]
31    pub fn apply_surface_tint(color: Color, surface_tint: Option<Color>, elevation: f64) -> Color {
32        if let Some(surface_tint) = surface_tint
33            && surface_tint != Colors::TRANSPARENT
34        {
35            return Color::alpha_blend(
36                surface_tint.with_opacity(Self::surface_tint_opacity_for_elevation(elevation)),
37                color,
38            );
39        }
40        color
41    }
42
43    // Calculates the opacity of the surface tint color from the elevation by
44    // looking it up in the legacy table of opacities, interpolating
45    // between values as needed. If the elevation is outside the range of values
46    // in the table it will clamp to the smallest or largest opacity.
47    fn surface_tint_opacity_for_elevation(elevation: f64) -> f64 {
48        if elevation < SURFACE_TINT_ELEVATION_OPACITIES[0].elevation {
49            // Elevation less than the first entry, so just clamp it to the first one.
50            return SURFACE_TINT_ELEVATION_OPACITIES[0].opacity;
51        }
52
53        // Walk the opacity list and find the closest match(es) for the elevation.
54        let mut index = 0;
55        while elevation >= SURFACE_TINT_ELEVATION_OPACITIES[index].elevation {
56            // If we found it exactly or walked off the end of the list just return it.
57            if elevation == SURFACE_TINT_ELEVATION_OPACITIES[index].elevation
58                || index + 1 == SURFACE_TINT_ELEVATION_OPACITIES.len()
59            {
60                return SURFACE_TINT_ELEVATION_OPACITIES[index].opacity;
61            }
62            index += 1;
63        }
64
65        // Interpolate between the two opacity values
66        let lower = &SURFACE_TINT_ELEVATION_OPACITIES[index - 1];
67        let upper = &SURFACE_TINT_ELEVATION_OPACITIES[index];
68        let t = (elevation - lower.elevation) / (upper.elevation - lower.elevation);
69        lower.opacity + t * (upper.opacity - lower.opacity)
70    }
71
72    /// Applies an overlay color to a surface color to indicate
73    /// the level of its elevation in a dark theme.
74    ///
75    /// If using Material Design 3, this type of color overlay is no longer used.
76    /// Instead a "surface tint" overlay is used instead. See [`apply_surface_tint`](Self::apply_surface_tint),
77    /// `ThemeData::use_material3` for more information.
78    ///
79    /// Material drop shadows can be difficult to see in a dark theme, so the
80    /// elevation of a surface should be portrayed with an "overlay" in addition
81    /// to the shadow. As the elevation of the component increases, the
82    /// overlay increases in opacity. This function computes and applies this
83    /// overlay to a given color as needed.
84    ///
85    /// If the ambient theme is dark (`ThemeData::brightness` is [`Brightness::Dark`]),
86    /// and `ThemeData::apply_elevation_overlay_color` is true, and the given
87    /// `color` is `ColorScheme::surface` then this will return a version of
88    /// the `color` with a semi-transparent `ColorScheme::on_surface` overlaid
89    /// on top of it. The opacity of the overlay is computed based on the
90    /// `elevation`.
91    ///
92    /// Otherwise it will just return the `color` unmodified.
93    ///
94    /// See also:
95    ///
96    ///  * `ThemeData::apply_elevation_overlay_color` which controls the whether
97    ///    an overlay color will be applied to indicate elevation.
98    ///  * [`overlay_color`](Self::overlay_color) which computes the needed overlay color.
99    ///  * `Material` which uses this to apply an elevation overlay to its surface.
100    ///  * <https://material.io/design/color/dark-theme.html>, which specifies how
101    ///    the overlay should be applied.
102    #[allow(deprecated)]
103    pub fn apply_overlay(
104        app: &mut App,
105        context: BuildContext,
106        color: Color,
107        elevation: f64,
108    ) -> Color {
109        let theme = Theme::of(app, context);
110        if elevation > 0.0
111            && theme.apply_elevation_overlay_color
112            && theme.brightness() == Brightness::Dark
113            && color.with_opacity(1.0) == theme.color_scheme.surface().with_opacity(1.0)
114        {
115            return Self::color_with_overlay(color, theme.color_scheme.on_surface(), elevation);
116        }
117        color
118    }
119
120    /// Computes the appropriate overlay color used to indicate elevation in
121    /// dark themes.
122    ///
123    /// If using Material Design 3, this type of color overlay is no longer used.
124    /// Instead a "surface tint" overlay is used instead. See [`apply_surface_tint`](Self::apply_surface_tint),
125    /// `ThemeData::use_material3` for more information.
126    ///
127    /// See also:
128    ///
129    ///  * <https://material.io/design/color/dark-theme.html#properties> which
130    ///    specifies the exact overlay values for a given elevation.
131    pub fn overlay_color(app: &mut App, context: BuildContext, elevation: f64) -> Color {
132        let theme = Theme::of(app, context);
133        Self::overlay_color_of(theme.color_scheme.on_surface(), elevation)
134    }
135
136    /// Returns a color blended by laying a semi-transparent overlay (using the
137    /// `overlay` color) on top of a surface (using the `surface` color).
138    ///
139    /// If using Material Design 3, this type of color overlay is no longer used.
140    /// Instead a "surface tint" overlay is used instead. See [`apply_surface_tint`](Self::apply_surface_tint),
141    /// `ThemeData::use_material3` for more information.
142    ///
143    /// The opacity of the overlay depends on `elevation`. As `elevation`
144    /// increases, the opacity will also increase.
145    ///
146    /// See <https://material.io/design/color/dark-theme.html#properties>.
147    pub fn color_with_overlay(surface: Color, overlay: Color, elevation: f64) -> Color {
148        Color::alpha_blend(Self::overlay_color_of(overlay, elevation), surface)
149    }
150
151    /// Dart's private `_overlayColor`: applies an opacity to `color` based on `elevation`.
152    #[allow(deprecated)]
153    fn overlay_color_of(color: Color, elevation: f64) -> Color {
154        // Compute the opacity for the given elevation
155        // This formula matches the values in the spec:
156        // https://material.io/design/color/dark-theme.html#properties
157        let opacity = (4.5 * (elevation + 1.0).ln() + 2.0) / 100.0;
158        color.with_opacity(opacity)
159    }
160}
161
162/// Dart's private `_ElevationOpacity`: a data class to hold the opacity at a given elevation.
163struct ElevationOpacity {
164    elevation: f64,
165    opacity: f64,
166}
167
168impl ElevationOpacity {
169    const fn new(elevation: f64, opacity: f64) -> ElevationOpacity {
170        ElevationOpacity { elevation, opacity }
171    }
172}
173
174// Surface tint is no longer recommended by the Material 3 specification, but
175// these values are preserved for backwards compatibility.
176const SURFACE_TINT_ELEVATION_OPACITIES: [ElevationOpacity; 6] = [
177    ElevationOpacity::new(0.0, 0.0),   // Elevation level 0
178    ElevationOpacity::new(1.0, 0.05),  // Elevation level 1
179    ElevationOpacity::new(3.0, 0.08),  // Elevation level 2
180    ElevationOpacity::new(6.0, 0.11),  // Elevation level 3
181    ElevationOpacity::new(8.0, 0.12),  // Elevation level 4
182    ElevationOpacity::new(12.0, 0.14), // Elevation level 5
183];
184
185#[cfg(test)]
186mod tests {
187    use std::rc::Rc;
188
189    use waft_widgets::IntoWidget;
190
191    use waft_widgets::testing::{WidgetTester, test_widgets};
192
193    use super::*;
194    use crate::drawer_theme::tests::probe;
195    use crate::theme_data::ThemeData;
196
197    const BASE_COLOR: Color = Color::new(0xff888888);
198    const SURFACE_TINT_COLOR: Color = Color::new(0xff44ccff);
199
200    #[allow(deprecated)]
201    fn overlay_with_opacity(opacity: f64) -> Color {
202        Color::alpha_blend(SURFACE_TINT_COLOR.with_opacity(opacity), BASE_COLOR)
203    }
204
205    fn tinted(elevation: f64) -> Color {
206        ElevationOverlay::apply_surface_tint(BASE_COLOR, Some(SURFACE_TINT_COLOR), elevation)
207    }
208
209    #[test]
210    fn apply_surface_tint_with_null_surface_tint_returns_given_color() {
211        let result = ElevationOverlay::apply_surface_tint(BASE_COLOR, None, 42.0);
212
213        assert_eq!(result, Color::new(0xFF888888));
214    }
215
216    #[test]
217    fn apply_surface_tint_with_exact_elevation_levels_uses_the_right_opacity_overlay() {
218        // Elevation level 0 (0.0) - should have opacity 0.0.
219        assert_eq!(tinted(0.0), overlay_with_opacity(0.0));
220        // Elevation level 1 (1.0) - should have opacity 0.05.
221        assert_eq!(tinted(1.0), overlay_with_opacity(0.05));
222        // Elevation level 2 (3.0) - should have opacity 0.08.
223        assert_eq!(tinted(3.0), overlay_with_opacity(0.08));
224        // Elevation level 3 (6.0) - should have opacity 0.11`.
225        assert_eq!(tinted(6.0), overlay_with_opacity(0.11));
226        // Elevation level 4 (8.0) - should have opacity 0.12.
227        assert_eq!(tinted(8.0), overlay_with_opacity(0.12));
228        // Elevation level 5 (12.0) - should have opacity 0.14.
229        assert_eq!(tinted(12.0), overlay_with_opacity(0.14));
230    }
231
232    #[test]
233    fn apply_surface_tint_with_elevation_lower_than_level_0_should_have_no_overlay() {
234        assert_eq!(tinted(-42.0), overlay_with_opacity(0.0));
235    }
236
237    #[test]
238    fn apply_surface_tint_with_elevation_higher_than_level_5_should_have_no_level_5_overlay() {
239        // Elevation level 5 (12.0) - should have opacity 0.14.
240        assert_eq!(tinted(42.0), overlay_with_opacity(0.14));
241    }
242
243    #[test]
244    fn apply_surface_tint_with_elevation_between_two_levels_should_interpolate_the_opacity() {
245        // Elevation between level 4 (8.0) and level 5 (12.0) should be interpolated
246        // between the opacities 0.12 and 0.14.
247
248        // One third (0.3): (elevation 9.2) -> (opacity 0.126)
249        assert_eq!(tinted(9.2), overlay_with_opacity(0.126));
250        // Half way (0.5): (elevation 10.0) -> (opacity 0.13)
251        assert_eq!(tinted(10.0), overlay_with_opacity(0.13));
252        // Two thirds (0.6): (elevation 10.4) -> (opacity 0.132)
253        assert_eq!(tinted(10.4), overlay_with_opacity(0.132));
254    }
255
256    #[test]
257    fn apply_surface_tint_with_a_transparent_surface_tint_returns_given_color() {
258        let result =
259            ElevationOverlay::apply_surface_tint(BASE_COLOR, Some(Colors::TRANSPARENT), 6.0);
260
261        assert_eq!(result, BASE_COLOR);
262    }
263
264    fn dark_theme_with_overlay(app: &App) -> ThemeData {
265        ThemeData::builder()
266            .brightness(Brightness::Dark)
267            .use_material3(false)
268            .apply_elevation_overlay_color(true)
269            .build(app)
270    }
271
272    fn overlay_results_under(
273        tester: &mut WidgetTester,
274        theme_of: impl Fn(&App) -> ThemeData + 'static,
275        color_of: impl Fn(&ThemeData) -> Color + 'static,
276        elevation: f64,
277    ) -> (Color, Color, Rc<ThemeData>) {
278        probe(
279            tester,
280            move |app, child| Theme::new(theme_of(app), child).into_widget(),
281            move |app, context| {
282                let theme = Theme::of(app, context);
283                let color = color_of(&theme);
284                (
285                    ElevationOverlay::apply_overlay(app, context, color, elevation),
286                    ElevationOverlay::overlay_color(app, context, elevation),
287                    theme,
288                )
289            },
290        )
291    }
292
293    #[test]
294    fn apply_overlay_overlays_the_surface_color_in_a_dark_theme() {
295        test_widgets(|tester| {
296            let (applied, overlay, theme) = overlay_results_under(
297                tester,
298                dark_theme_with_overlay,
299                |theme| theme.color_scheme.surface(),
300                4.0,
301            );
302
303            let on_surface = theme.color_scheme.on_surface();
304            assert_eq!(
305                applied,
306                ElevationOverlay::color_with_overlay(theme.color_scheme.surface(), on_surface, 4.0)
307            );
308            assert_ne!(applied, theme.color_scheme.surface());
309            assert_eq!(overlay, ElevationOverlay::overlay_color_of(on_surface, 4.0));
310        });
311    }
312
313    #[test]
314    fn apply_overlay_leaves_other_colors_and_light_themes_and_zero_elevation_alone() {
315        test_widgets(|tester| {
316            let (other_color, _, theme) = overlay_results_under(
317                tester,
318                dark_theme_with_overlay,
319                |_| Color::new(0xff123456),
320                4.0,
321            );
322            assert_eq!(other_color, Color::new(0xff123456));
323            assert_eq!(theme.brightness(), Brightness::Dark);
324
325            let (light, _, light_theme) = overlay_results_under(
326                tester,
327                |app| ThemeData::light(app, Some(false)),
328                |theme| theme.color_scheme.surface(),
329                4.0,
330            );
331            assert_eq!(light, light_theme.color_scheme.surface());
332
333            let (flat, _, dark_theme) = overlay_results_under(
334                tester,
335                dark_theme_with_overlay,
336                |theme| theme.color_scheme.surface(),
337                0.0,
338            );
339            assert_eq!(flat, dark_theme.color_scheme.surface());
340        });
341    }
342
343    #[test]
344    #[allow(deprecated)]
345    fn color_with_overlay_uses_the_dark_theme_opacity_curve() {
346        let opacity = (4.5 * 2.0_f64.ln() + 2.0) / 100.0;
347
348        assert_eq!(
349            ElevationOverlay::color_with_overlay(BASE_COLOR, SURFACE_TINT_COLOR, 1.0),
350            Color::alpha_blend(SURFACE_TINT_COLOR.with_opacity(opacity), BASE_COLOR)
351        );
352    }
353}