hydrolysis-m3 0.3.0

Material 3 widget theme for WaterUI self-drawn backends
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
//! Material Design 3 floating action buttons composed from `WaterUI` primitives.

use core::fmt::{self, Debug};
use core::marker::PhantomData;

use waterui::accessibility::{AccessibilityChildren, AccessibilityRole};
use waterui::color::Color;
use waterui::layout::padding::EdgeInsets;
use waterui::style::FloatingStyle;
use waterui::{Environment, Signal, Str, View, ViewExt as _};
use waterui_controls::label::{IntoLabel, Label};
use waterui_core::handler::{Handler, boxed_action};

use crate::color::{
    OnPrimaryContainer, OnSecondaryContainer, OnTertiaryContainer, Primary, PrimaryContainer,
    SecondaryContainer, SurfaceContainerHigh, TertiaryContainer,
};
use crate::elevation::{MaterialElevationLevel, apply_to_floating_style};
use crate::semantics::interaction_style;
use crate::theme::typography;

/// The geometry of one FAB size.
///
/// Material 3 Expressive offers three, and they differ in corner shape as well
/// as in scale, so a size is a token set rather than a diameter.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FabSizeTokens {
    /// `ContainerWidth` / `ContainerHeight`.
    pub container: f32,
    /// `IconSize`.
    pub icon: f32,
    /// `ContainerShape`, as a corner radius.
    pub corner_radius: f32,
}

impl FabSizeTokens {
    /// The corner radius as a fraction of the container, for clip shapes.
    #[must_use]
    pub fn clip_radius(self) -> f32 {
        self.corner_radius / self.container
    }

    /// The inset that centres the icon in the container.
    #[must_use]
    pub fn icon_padding(self) -> f32 {
        (self.container - self.icon) / 2.0
    }
}

/// How large a floating action button is drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum FabSize {
    /// `FabBaselineTokens`: the standard 56dp FAB.
    #[default]
    Baseline,
    /// `FabMediumTokens`.
    Medium,
    /// `FabLargeTokens`.
    Large,
}

impl FabSize {
    /// The token set for this size.
    #[must_use]
    pub const fn tokens(self) -> FabSizeTokens {
        match self {
            // FabBaselineTokens: CornerLarge
            Self::Baseline => FabSizeTokens {
                container: 56.0,
                icon: 24.0,
                corner_radius: 16.0,
            },
            // FabMediumTokens: CornerLargeIncreased
            Self::Medium => FabSizeTokens {
                container: 80.0,
                icon: 28.0,
                corner_radius: 20.0,
            },
            // FabLargeTokens: CornerExtraLarge. Compose overrides the stale
            // 32dp icon token — FloatingActionButtonDefaults.LargeIconSize is
            // 36.dp ("TODO: FabLargeTokens.IconSize is incorrect").
            Self::Large => FabSizeTokens {
                container: 96.0,
                icon: 36.0,
                corner_radius: 28.0,
            },
        }
    }
}

const EXTENDED_FAB_HEIGHT: f32 = 56.0;
/// Compose wraps the content in `sizeIn(minWidth = ExtendedFabMinimumWidth)`.
const EXTENDED_FAB_MINIMUM_WIDTH: f32 = 80.0;
const EXTENDED_FAB_SHAPE: f32 = 16.0;
const EXTENDED_FAB_CLIP_RADIUS: f32 = EXTENDED_FAB_SHAPE / EXTENDED_FAB_HEIGHT;
const EXTENDED_FAB_LEADING_SPACE_WITHOUT_ICON: f32 = 20.0;
const EXTENDED_FAB_TRAILING_SPACE: f32 = 20.0;

/// Color token set for a FAB variant.
pub trait FabVariantTokens: Default + 'static {
    /// Container color.
    fn container_color() -> Color;

    /// Content color.
    fn content_color() -> Color;
}

/// Surface FAB color tokens.
#[derive(Debug, Clone, Copy, Default)]
pub struct SurfaceFab;

/// Primary FAB color tokens.
#[derive(Debug, Clone, Copy, Default)]
pub struct PrimaryFab;

/// Secondary FAB color tokens.
#[derive(Debug, Clone, Copy, Default)]
pub struct SecondaryFab;

/// Tertiary FAB color tokens.
#[derive(Debug, Clone, Copy, Default)]
pub struct TertiaryFab;

impl FabVariantTokens for SurfaceFab {
    fn container_color() -> Color {
        SurfaceContainerHigh.into()
    }

    fn content_color() -> Color {
        Primary.into()
    }
}

impl FabVariantTokens for PrimaryFab {
    fn container_color() -> Color {
        PrimaryContainer.into()
    }

    fn content_color() -> Color {
        OnPrimaryContainer.into()
    }
}

impl FabVariantTokens for SecondaryFab {
    fn container_color() -> Color {
        SecondaryContainer.into()
    }

    fn content_color() -> Color {
        OnSecondaryContainer.into()
    }
}

impl FabVariantTokens for TertiaryFab {
    fn container_color() -> Color {
        TertiaryContainer.into()
    }

    fn content_color() -> Color {
        OnTertiaryContainer.into()
    }
}

/// A Material Design 3 floating action button.
///
/// The default variant is `PrimaryFab`: `FloatingActionButtonDefaults
/// .containerColor` resolves to `primaryContainer`.
pub struct Fab<Content, Action = fn(&Environment), Tokens = PrimaryFab> {
    accessibility_label: Str,
    content: Content,
    action: Action,
    size: FabSize,
    tokens: PhantomData<Tokens>,
}

impl<Content, Action, Tokens> Debug for Fab<Content, Action, Tokens> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Fab")
            .field("accessibility_label", &self.accessibility_label)
            .finish_non_exhaustive()
    }
}

impl<Content> Fab<Content, fn(&Environment), PrimaryFab> {
    /// Creates a primary FAB with arbitrary visual content.
    #[must_use]
    pub fn new(accessibility_label: impl Into<Str>, content: Content) -> Self {
        Self {
            accessibility_label: accessibility_label.into(),
            content,
            action: noop,
            size: FabSize::default(),
            tokens: PhantomData,
        }
    }
}

impl<Content, Action, Tokens> Fab<Content, Action, Tokens> {
    /// Uses surface FAB color tokens.
    #[must_use]
    pub fn surface(self) -> Fab<Content, Action, SurfaceFab> {
        self.with_variant()
    }

    /// Uses primary FAB color tokens.
    #[must_use]
    pub fn primary(self) -> Fab<Content, Action, PrimaryFab> {
        self.with_variant()
    }

    /// Uses secondary FAB color tokens.
    #[must_use]
    pub fn secondary(self) -> Fab<Content, Action, SecondaryFab> {
        self.with_variant()
    }

    /// Uses tertiary FAB color tokens.
    #[must_use]
    pub fn tertiary(self) -> Fab<Content, Action, TertiaryFab> {
        self.with_variant()
    }

    fn with_variant<NewTokens>(self) -> Fab<Content, Action, NewTokens> {
        Fab {
            accessibility_label: self.accessibility_label,
            content: self.content,
            action: self.action,
            size: self.size,
            tokens: PhantomData,
        }
    }

    /// Sets how large the FAB is drawn.
    #[must_use]
    pub const fn size(mut self, size: FabSize) -> Self {
        self.size = size;
        self
    }

    /// Sets the action performed when the FAB is tapped.
    #[must_use]
    pub fn action<F, Args>(self, action: F) -> Fab<Content, impl FnMut(&Environment), Tokens>
    where
        F: Handler<Args, ()> + 'static,
    {
        Fab {
            accessibility_label: self.accessibility_label,
            content: self.content,
            action: boxed_action(action),
            size: self.size,
            tokens: PhantomData,
        }
    }
}

impl<Content, Action, Tokens> View for Fab<Content, Action, Tokens>
where
    Content: View + 'static,
    Action: FnMut(&Environment) + 'static,
    Tokens: FabVariantTokens,
{
    fn body(self, _env: &Environment) -> impl View {
        let mut action = self.action;
        let size = self.size.tokens();
        let floating_style = floating_style::<Tokens>(
            f64::from(size.container),
            f64::from(size.container),
            size.clip_radius(),
        );

        self.content
            .foreground(Tokens::content_color())
            .size(size.icon, size.icon)
            .padding_with(size.icon_padding())
            .size(size.container, size.container)
            .floating_with(floating_style)
            .on_tap(move |env: Environment| action(&env))
            .a11y_label(self.accessibility_label)
            .a11y_role(AccessibilityRole::Button)
            .a11y_children(AccessibilityChildren::ExcludeDescendants)
            .install(interaction_style(
                Tokens::content_color(),
                f64::from(size.corner_radius),
            ))
    }
}

/// A Material Design 3 extended floating action button.
pub struct ExtendedFab<Action = fn(&Environment), Tokens = PrimaryFab> {
    label: Label,
    accessibility_label: Str,
    action: Action,
    tokens: PhantomData<Tokens>,
}

impl<Action, Tokens> Debug for ExtendedFab<Action, Tokens> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ExtendedFab")
            .field("label", &self.label)
            .finish_non_exhaustive()
    }
}

impl ExtendedFab<fn(&Environment), PrimaryFab> {
    /// Creates a primary extended FAB with a semantic text label.
    #[must_use]
    pub fn new(label: impl IntoLabel) -> Self {
        let label = label.into_label();
        let accessibility_label = label
            .semantic_text()
            .clone()
            .resolve(&Environment::new())
            .content
            .get()
            .to_plain();
        Self {
            label,
            accessibility_label,
            action: noop,
            tokens: PhantomData,
        }
    }
}

impl<Action, Tokens> ExtendedFab<Action, Tokens> {
    /// Uses surface FAB color tokens.
    #[must_use]
    pub fn surface(self) -> ExtendedFab<Action, SurfaceFab> {
        self.with_variant()
    }

    /// Uses secondary FAB color tokens.
    #[must_use]
    pub fn secondary(self) -> ExtendedFab<Action, SecondaryFab> {
        self.with_variant()
    }

    /// Uses tertiary FAB color tokens.
    #[must_use]
    pub fn tertiary(self) -> ExtendedFab<Action, TertiaryFab> {
        self.with_variant()
    }

    fn with_variant<NewTokens>(self) -> ExtendedFab<Action, NewTokens> {
        ExtendedFab {
            label: self.label,
            accessibility_label: self.accessibility_label,
            action: self.action,
            tokens: PhantomData,
        }
    }

    /// Sets the action performed when the extended FAB is tapped.
    #[must_use]
    pub fn action<F, Args>(self, action: F) -> ExtendedFab<impl FnMut(&Environment), Tokens>
    where
        F: Handler<Args, ()> + 'static,
    {
        ExtendedFab {
            label: self.label,
            accessibility_label: self.accessibility_label,
            action: boxed_action(action),
            tokens: PhantomData,
        }
    }
}

impl<Action, Tokens> View for ExtendedFab<Action, Tokens>
where
    Action: FnMut(&Environment) + 'static,
    Tokens: FabVariantTokens,
{
    fn body(self, _env: &Environment) -> impl View {
        let mut action = self.action;
        let floating_style = floating_style::<Tokens>(
            f64::from(EXTENDED_FAB_MINIMUM_WIDTH),
            f64::from(EXTENDED_FAB_HEIGHT),
            EXTENDED_FAB_CLIP_RADIUS,
        );

        self.label
            .font(typography::label_large())
            .foreground(Tokens::content_color())
            .height(EXTENDED_FAB_HEIGHT)
            .padding_with(EdgeInsets::new(
                0.0,
                0.0,
                EXTENDED_FAB_LEADING_SPACE_WITHOUT_ICON,
                EXTENDED_FAB_TRAILING_SPACE,
            ))
            .floating_with(floating_style)
            .on_tap(move |env: Environment| action(&env))
            .a11y_label(self.accessibility_label)
            .a11y_role(AccessibilityRole::Button)
            .a11y_children(AccessibilityChildren::ExcludeDescendants)
            .install(interaction_style(
                Tokens::content_color(),
                f64::from(EXTENDED_FAB_SHAPE),
            ))
    }
}

const fn noop(_env: &Environment) {}

pub(crate) fn theme() -> FloatingStyle {
    let size = FabSize::Baseline.tokens();
    floating_style::<PrimaryFab>(
        f64::from(size.container),
        f64::from(size.container),
        size.clip_radius(),
    )
}

fn floating_style<Tokens>(
    minimum_width: f64,
    minimum_height: f64,
    clip_radius: f32,
) -> FloatingStyle
where
    Tokens: FabVariantTokens,
{
    let mut style = FloatingStyle {
        container_color: Tokens::container_color(),
        content_color: Tokens::content_color(),
        state_layer_color: Tokens::content_color(),
        clip_radius,
        content_inset_x: 0.0,
        content_inset_y: 0.0,
        minimum_width,
        minimum_height,
        disabled_content_opacity: 0.38,
        ..FloatingStyle::default()
    };
    apply_to_floating_style(&mut style, MaterialElevationLevel::LEVEL3);
    style
}

/// Creates a primary FAB with arbitrary visual content.
#[must_use]
pub fn fab<Content>(accessibility_label: impl Into<Str>, content: Content) -> Fab<Content>
where
    Content: View + 'static,
{
    Fab::new(accessibility_label, content)
}

/// Creates a primary extended FAB with a semantic text label.
#[must_use]
pub fn extended_fab(label: impl IntoLabel) -> ExtendedFab {
    ExtendedFab::new(label)
}

#[cfg(test)]
mod tests {
    use super::{
        EXTENDED_FAB_HEIGHT, EXTENDED_FAB_LEADING_SPACE_WITHOUT_ICON, EXTENDED_FAB_MINIMUM_WIDTH,
        EXTENDED_FAB_SHAPE, EXTENDED_FAB_TRAILING_SPACE, FabSize,
    };

    /// `FabBaselineTokens`, `FabMediumTokens` and `FabLargeTokens`. The corner
    /// shape grows with the container — `CornerLarge`, `CornerLargeIncreased`,
    /// `CornerExtraLarge` — so a larger FAB is not simply a scaled-up one.
    #[test]
    fn fab_sizes_match_compose_fab_tokens() {
        let baseline = FabSize::Baseline.tokens();
        assert_eq!(baseline.container, 56.0);
        assert_eq!(baseline.icon, 24.0);
        assert_eq!(baseline.corner_radius, 16.0);

        let medium = FabSize::Medium.tokens();
        assert_eq!(medium.container, 80.0);
        assert_eq!(medium.icon, 28.0);
        assert_eq!(medium.corner_radius, 20.0);

        let large = FabSize::Large.tokens();
        assert_eq!(large.container, 96.0);
        // `FloatingActionButtonDefaults.LargeIconSize` — 36dp, overriding the
        // stale `FabLargeTokens.IconSize` of 32.
        assert_eq!(large.icon, 36.0);
        assert_eq!(large.corner_radius, 28.0);

        // The icon stays centred at every size.
        for size in [baseline, medium, large] {
            assert!((size.icon_padding().mul_add(2.0, size.icon) - size.container).abs() < 1e-6);
            assert!(size.clip_radius() > 0.0 && size.clip_radius() < 0.5);
        }
    }

    #[test]
    fn extended_fab_tokens_match_compose_extended_fab_tokens() {
        assert_eq!(EXTENDED_FAB_HEIGHT, 56.0);
        assert_eq!(EXTENDED_FAB_SHAPE, 16.0);
        assert_eq!(EXTENDED_FAB_MINIMUM_WIDTH, 80.0);
        assert_eq!(EXTENDED_FAB_LEADING_SPACE_WITHOUT_ICON, 20.0);
        assert_eq!(EXTENDED_FAB_TRAILING_SPACE, 20.0);
    }
}