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
//! Material Design 3 segmented buttons composed from `WaterUI` primitives.

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

use vello::kurbo::RoundedRectRadii;
use waterui::accessibility::{AccessibilityChildren, AccessibilityRole, AccessibilityState};
use waterui::border::Border;
use waterui::component::hstack;
use waterui::layout::padding::EdgeInsets;
use waterui::reactive::SignalExt as _;
use waterui::shape::{Rectangle, ShapeExt as _, UnevenRoundedRectangle};
use waterui::{AnyView, Binding, Computed, Environment, Str, View, ViewExt as _};
use waterui_controls::label::{IntoLabel, Label};
use waterui_core::handler::{Handler, SharedAction, boxed_action};
use waterui_core::interaction::Disabled;
use waterui_core::view::TupleViews;

use crate::color::{OnSecondaryContainer, OnSurface, Outline, SecondaryContainer, Surface};
use crate::icons::CheckmarkIcon;
use crate::semantics::{conditional_color, interaction_style_with_radii, label_plain_text};
use crate::theme::typography;

const OUTLINED_SEGMENTED_BUTTON_CONTAINER_HEIGHT: f32 = 40.0;
const OUTLINED_SEGMENTED_BUTTON_CONTAINER_SHAPE: f32 = 20.0;
const OUTLINED_SEGMENTED_BUTTON_CONTAINER_CLIP_RADIUS: f32 =
    OUTLINED_SEGMENTED_BUTTON_CONTAINER_SHAPE / OUTLINED_SEGMENTED_BUTTON_CONTAINER_HEIGHT;
const OUTLINED_SEGMENTED_BUTTON_OUTLINE_WIDTH: f32 = 1.0;
const OUTLINED_SEGMENTED_BUTTON_LEADING_SPACE: f32 = 12.0;
const OUTLINED_SEGMENTED_BUTTON_TRAILING_SPACE: f32 = 12.0;
const OUTLINED_SEGMENTED_BUTTON_ICON_SIZE: f32 = 18.0;
const OUTLINED_SEGMENTED_BUTTON_CHECKMARK_LINE_WIDTH: f32 = 2.0;
const OUTLINED_SEGMENTED_BUTTON_ICON_LABEL_SPACE: f32 = 8.0;
/// `ButtonDefaults.MinWidth` — each segment is at least this wide.
const OUTLINED_SEGMENTED_BUTTON_MIN_WIDTH: f32 = 58.0;
/// With no unchecked icon, `SegmentedButtonContentMeasurePolicy` still reserves
/// the icon slot and shifts the label `-half` of it, recentering the label over
/// the icon-plus-label span.
const OUTLINED_SEGMENTED_BUTTON_LABEL_OFFSET_UNSELECTED: f32 =
    -(OUTLINED_SEGMENTED_BUTTON_ICON_SIZE + OUTLINED_SEGMENTED_BUTTON_ICON_LABEL_SPACE) * 0.5;
/// Disabled labels and icons: `onSurface` at the M3 disabled-content alpha.
const OUTLINED_SEGMENTED_BUTTON_DISABLED_CONTENT_OPACITY: f32 = 0.38;
/// Disabled borders and separators: `onSurface` at the M3 disabled-outline alpha.
const OUTLINED_SEGMENTED_BUTTON_DISABLED_OUTLINE_OPACITY: f32 = 0.12;

/// Logical corner treatment for a segmented button inside a set.
#[derive(Debug, Clone, Copy)]
pub struct SegmentedButtonShape {
    top_leading: f32,
    top_trailing: f32,
    bottom_leading: f32,
    bottom_trailing: f32,
}

impl SegmentedButtonShape {
    /// Shape for a single standalone segmented button.
    #[must_use]
    pub const fn single() -> Self {
        Self::all(OUTLINED_SEGMENTED_BUTTON_CONTAINER_CLIP_RADIUS)
    }

    /// Shape for the leading segment in a horizontal set.
    #[must_use]
    pub const fn start() -> Self {
        Self::new(
            OUTLINED_SEGMENTED_BUTTON_CONTAINER_CLIP_RADIUS,
            0.0,
            OUTLINED_SEGMENTED_BUTTON_CONTAINER_CLIP_RADIUS,
            0.0,
        )
    }

    /// Shape for a middle segment in a horizontal set.
    #[must_use]
    pub const fn middle() -> Self {
        Self::all(0.0)
    }

    /// Shape for the trailing segment in a horizontal set.
    #[must_use]
    pub const fn end() -> Self {
        Self::new(
            0.0,
            OUTLINED_SEGMENTED_BUTTON_CONTAINER_CLIP_RADIUS,
            0.0,
            OUTLINED_SEGMENTED_BUTTON_CONTAINER_CLIP_RADIUS,
        )
    }

    const fn all(radius: f32) -> Self {
        Self::new(radius, radius, radius, radius)
    }

    const fn new(
        top_leading: f32,
        top_trailing: f32,
        bottom_leading: f32,
        bottom_trailing: f32,
    ) -> Self {
        Self {
            top_leading,
            top_trailing,
            bottom_leading,
            bottom_trailing,
        }
    }

    const fn shape(self) -> UnevenRoundedRectangle {
        UnevenRoundedRectangle::new(
            self.top_leading,
            self.top_trailing,
            self.bottom_leading,
            self.bottom_trailing,
        )
    }

    const fn has_leading_separator(self) -> bool {
        self.top_leading == 0.0 && self.bottom_leading == 0.0
    }

    fn interaction_radii(self) -> RoundedRectRadii {
        let scale = f64::from(OUTLINED_SEGMENTED_BUTTON_CONTAINER_HEIGHT);
        RoundedRectRadii::new(
            f64::from(self.top_leading) * scale,
            f64::from(self.top_trailing) * scale,
            f64::from(self.bottom_trailing) * scale,
            f64::from(self.bottom_leading) * scale,
        )
    }
}

/// A Material Design 3 outlined segmented button.
pub struct OutlinedSegmentedButton<Action = fn(&Environment)> {
    label: Label,
    accessibility_label: Str,
    selected: Binding<bool>,
    shape: SegmentedButtonShape,
    action: Action,
}

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

impl OutlinedSegmentedButton<fn(&Environment)> {
    /// Creates an outlined segmented button bound to the provided selected state.
    #[must_use]
    pub fn new(label: impl IntoLabel, selected: &Binding<bool>) -> Self {
        let label = label.into_label();
        let accessibility_label = label_plain_text(&label);
        Self {
            label,
            accessibility_label,
            selected: selected.clone(),
            shape: SegmentedButtonShape::single(),
            action: noop,
        }
    }
}

impl<Action> OutlinedSegmentedButton<Action> {
    /// Uses the leading-segment shape.
    #[must_use]
    pub const fn start(mut self) -> Self {
        self.shape = SegmentedButtonShape::start();
        self
    }

    /// Uses the middle-segment shape.
    #[must_use]
    pub const fn middle(mut self) -> Self {
        self.shape = SegmentedButtonShape::middle();
        self
    }

    /// Uses the trailing-segment shape.
    #[must_use]
    pub const fn end(mut self) -> Self {
        self.shape = SegmentedButtonShape::end();
        self
    }

    /// Sets the action performed after this button toggles its selected state.
    #[must_use]
    pub fn action<F, Args>(self, action: F) -> OutlinedSegmentedButton<impl FnMut(&Environment)>
    where
        F: Handler<Args, ()> + 'static,
    {
        OutlinedSegmentedButton {
            label: self.label,
            accessibility_label: self.accessibility_label,
            selected: self.selected,
            shape: self.shape,
            action: boxed_action(action),
        }
    }
}

impl<Action> View for OutlinedSegmentedButton<Action>
where
    Action: FnMut(&Environment) + 'static,
{
    fn body(self, env: &Environment) -> impl View {
        let mut action = self.action;
        let action = SharedAction::new(move |env: Environment| action(&env));
        let selected_for_view = self.selected.clone();
        let accessibility_state = self
            .selected
            .map(|selected| AccessibilityState::new().selected(selected));
        let disabled = Disabled::resolve(env, false);

        segmented_button_view(
            self.label,
            self.shape,
            self.accessibility_label,
            selected_for_view,
            action,
            &disabled,
        )
        .a11y_state_signal(accessibility_state)
    }
}

/// A Material Design 3 outlined segmented button set.
pub struct OutlinedSegmentedButtonSet<Content> {
    content: Content,
    accessibility_label: Str,
}

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

impl<Content> OutlinedSegmentedButtonSet<Content> {
    /// Creates an outlined segmented button set with two or more button children.
    #[must_use]
    pub fn new(content: Content) -> Self {
        Self {
            content,
            accessibility_label: "Segmented buttons".into(),
        }
    }

    /// Sets the set accessibility label.
    #[must_use]
    pub fn label(mut self, label: impl Into<Str>) -> Self {
        self.accessibility_label = label.into();
        self
    }
}

impl<Content> View for OutlinedSegmentedButtonSet<Content>
where
    Content: TupleViews + 'static,
{
    fn body(self, env: &Environment) -> impl View {
        let disabled = Disabled::resolve(env, false);
        hstack(self.content)
            .spacing(0.0)
            .border_with(
                Border::new(
                    conditional_color(
                        disabled,
                        OnSurface.with_opacity(OUTLINED_SEGMENTED_BUTTON_DISABLED_OUTLINE_OPACITY),
                        Outline,
                    ),
                    OUTLINED_SEGMENTED_BUTTON_OUTLINE_WIDTH,
                )
                .corner_radius(OUTLINED_SEGMENTED_BUTTON_CONTAINER_SHAPE),
            )
            .a11y_label(self.accessibility_label)
            .a11y_role(AccessibilityRole::Group)
    }
}

/// Creates a Material Design 3 outlined segmented button.
#[must_use]
pub fn outlined_segmented_button(
    label: impl IntoLabel,
    selected: &Binding<bool>,
) -> OutlinedSegmentedButton {
    OutlinedSegmentedButton::new(label, selected)
}

/// Creates a Material Design 3 outlined segmented button set.
#[must_use]
pub fn outlined_segmented_button_set<Content>(
    content: Content,
) -> OutlinedSegmentedButtonSet<Content> {
    OutlinedSegmentedButtonSet::new(content)
}

fn segmented_button_view(
    label: Label,
    shape: SegmentedButtonShape,
    accessibility_label: Str,
    selected_state: Binding<bool>,
    action: SharedAction,
    disabled: &Computed<bool>,
) -> impl View {
    let foreground = conditional_color(
        disabled.clone(),
        OnSurface.with_opacity(OUTLINED_SEGMENTED_BUTTON_DISABLED_CONTENT_OPACITY),
        conditional_color(selected_state.clone(), OnSecondaryContainer, OnSurface),
    );
    let background = conditional_color(
        selected_state.clone(),
        SecondaryContainer,
        Surface.with_opacity(0.0),
    );
    let state_layer_color =
        conditional_color(selected_state.clone(), OnSecondaryContainer, OnSurface);
    let checkmark_opacity = selected_state
        .with(crate::theme::motion::default_effects())
        .map(|selected| if selected { 1.0 } else { 0.0 });
    let label_offset = selected_state
        .with(crate::theme::motion::fast_spatial())
        .map(|selected| {
            if selected {
                0.0
            } else {
                OUTLINED_SEGMENTED_BUTTON_LABEL_OFFSET_UNSELECTED
            }
        });
    let label = label
        .font(typography::label_large())
        .foreground(foreground)
        .offset(label_offset, 0.0);
    let checkmark = CheckmarkIcon::new(
        conditional_color(
            disabled.clone(),
            OnSurface.with_opacity(OUTLINED_SEGMENTED_BUTTON_DISABLED_CONTENT_OPACITY),
            OnSecondaryContainer,
        ),
        OUTLINED_SEGMENTED_BUTTON_ICON_SIZE,
        OUTLINED_SEGMENTED_BUTTON_CHECKMARK_LINE_WIDTH,
    )
    .container_height(OUTLINED_SEGMENTED_BUTTON_CONTAINER_HEIGHT)
    .opacity(checkmark_opacity);
    let inner = hstack((checkmark, label))
        .spacing(OUTLINED_SEGMENTED_BUTTON_ICON_LABEL_SPACE)
        .padding_with(EdgeInsets::new(
            0.0,
            0.0,
            OUTLINED_SEGMENTED_BUTTON_LEADING_SPACE,
            OUTLINED_SEGMENTED_BUTTON_TRAILING_SPACE,
        ));
    let content = if shape.has_leading_separator() {
        AnyView::new(
            hstack((
                Rectangle
                    .fill(conditional_color(
                        disabled.clone(),
                        OnSurface.with_opacity(OUTLINED_SEGMENTED_BUTTON_DISABLED_OUTLINE_OPACITY),
                        Outline,
                    ))
                    .width(OUTLINED_SEGMENTED_BUTTON_OUTLINE_WIDTH)
                    .height(OUTLINED_SEGMENTED_BUTTON_CONTAINER_HEIGHT),
                inner,
            ))
            .spacing(0.0),
        )
    } else {
        AnyView::new(inner)
    };

    content
        .min_width(OUTLINED_SEGMENTED_BUTTON_MIN_WIDTH)
        .height(OUTLINED_SEGMENTED_BUTTON_CONTAINER_HEIGHT)
        .background(shape.shape().fill(background))
        .on_tap(move |env: Environment| {
            selected_state.set(!selected_state.get());
            action.call(&env);
        })
        .a11y_label(accessibility_label)
        .a11y_role(AccessibilityRole::Button)
        .a11y_children(AccessibilityChildren::ExcludeDescendants)
        .install(interaction_style_with_radii(
            state_layer_color,
            shape.interaction_radii(),
        ))
}

const fn noop(_env: &Environment) {}

#[cfg(test)]
mod tests {
    use super::{
        OUTLINED_SEGMENTED_BUTTON_CONTAINER_HEIGHT, OUTLINED_SEGMENTED_BUTTON_CONTAINER_SHAPE,
        OUTLINED_SEGMENTED_BUTTON_ICON_LABEL_SPACE, OUTLINED_SEGMENTED_BUTTON_ICON_SIZE,
        OUTLINED_SEGMENTED_BUTTON_LABEL_OFFSET_UNSELECTED, OUTLINED_SEGMENTED_BUTTON_LEADING_SPACE,
        OUTLINED_SEGMENTED_BUTTON_MIN_WIDTH, OUTLINED_SEGMENTED_BUTTON_OUTLINE_WIDTH,
        OUTLINED_SEGMENTED_BUTTON_TRAILING_SPACE,
    };

    #[test]
    fn outlined_segmented_button_tokens_match_compose_segmented_button_tokens() {
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_CONTAINER_HEIGHT, 40.0);
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_CONTAINER_SHAPE, 20.0);
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_OUTLINE_WIDTH, 1.0);
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_MIN_WIDTH, 58.0);
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_LEADING_SPACE, 12.0);
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_TRAILING_SPACE, 12.0);
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_ICON_SIZE, 18.0);
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_ICON_LABEL_SPACE, 8.0);
        assert_eq!(OUTLINED_SEGMENTED_BUTTON_LABEL_OFFSET_UNSELECTED, -13.0);
    }
}