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

use core::fmt::{self, Debug};
use core::marker::PhantomData;
use waterui::accessibility::{AccessibilityChildren, AccessibilityRole, AccessibilityState};
use waterui::border::Border;
use waterui::color::Color;
use waterui::layout::frame::Frame;
use waterui::layout::padding::EdgeInsets;
use waterui::reactive::SignalExt as _;
use waterui::shape::{FixedRoundedRectangle, Rectangle, ShapeExt as _};
use waterui::{Binding, Environment, Str, View, ViewExt as _};
use waterui_controls::label::{IntoLabel, Label};
use waterui_core::handler::{Handler, SharedAction, boxed_action};

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

const ASSIST_CHIP_CONTAINER_HEIGHT: f32 = 32.0;
const ASSIST_CHIP_CONTAINER_SHAPE: f32 = 8.0;
const ASSIST_CHIP_OUTLINE_WIDTH: f32 = 1.0;
const ASSIST_CHIP_LEADING_SPACE: f32 = 16.0;
const ASSIST_CHIP_TRAILING_SPACE: f32 = 16.0;
const FILTER_CHIP_CONTAINER_HEIGHT: f32 = 32.0;
const FILTER_CHIP_CONTAINER_SHAPE: f32 = 8.0;
const FILTER_CHIP_UNSELECTED_OUTLINE_WIDTH: f32 = 1.0;
const FILTER_CHIP_SELECTED_OUTLINE_WIDTH: f32 = 0.0;
const FILTER_CHIP_LEADING_SPACE: f32 = 16.0;
const FILTER_CHIP_TRAILING_SPACE: f32 = 16.0;
const FILTER_CHIP_WITH_ICON_LEADING_SPACE: f32 = 8.0;
const FILTER_CHIP_ICON_LABEL_SPACE: f32 =
    FILTER_CHIP_LEADING_SPACE - FILTER_CHIP_WITH_ICON_LEADING_SPACE;
const FILTER_CHIP_ICON_SIZE: f32 = 18.0;
const FILTER_CHIP_CHECKMARK_LINE_WIDTH: f32 = 2.0;
const INPUT_CHIP_CONTAINER_HEIGHT: f32 = 32.0;
const INPUT_CHIP_CONTAINER_SHAPE: f32 = 8.0;
const INPUT_CHIP_UNSELECTED_OUTLINE_WIDTH: f32 = 1.0;
const INPUT_CHIP_LEADING_SPACE: f32 = 16.0;
const INPUT_CHIP_WITH_TRAILING_ICON_TRAILING_SPACE: f32 = 8.0;
const INPUT_CHIP_ICON_LABEL_SPACE: f32 = 8.0;
const INPUT_CHIP_TRAILING_ICON_SIZE: f32 = 18.0;
const INPUT_CHIP_REMOVE_ICON_LINE_WIDTH: f32 = 2.0;

/// Shared Material Design 3 outlined action chip foundation.
///
/// This implementation is pure `WaterUI` composition: no Hydrolysis renderer type
/// or backend-specific view ID is introduced.
pub struct OutlinedChip<Action = fn(&Environment), LabelColor = OnSurface> {
    label: Label,
    accessibility_label: Str,
    action: Action,
    label_color: PhantomData<LabelColor>,
}

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

impl<LabelColor> OutlinedChip<fn(&Environment), LabelColor> {
    /// Creates an outlined chip with the given semantic label.
    #[must_use]
    pub fn new(label: impl IntoLabel) -> Self {
        let label = label.into_label();
        let accessibility_label = label_plain_text(&label);
        Self {
            label,
            accessibility_label,
            action: noop,
            label_color: PhantomData,
        }
    }
}

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

impl<Action, LabelColor> View for OutlinedChip<Action, LabelColor>
where
    Action: FnMut(&Environment) + 'static,
    LabelColor: Default + Into<Color> + 'static,
{
    fn body(self, _env: &Environment) -> impl View {
        let mut action = self.action;
        let accessibility_label = self.accessibility_label.clone();
        let label = self
            .label
            .font(typography::label_large())
            .foreground(LabelColor::default());

        label
            .height(ASSIST_CHIP_CONTAINER_HEIGHT)
            .padding_with(EdgeInsets::new(
                0.0,
                0.0,
                ASSIST_CHIP_LEADING_SPACE,
                ASSIST_CHIP_TRAILING_SPACE,
            ))
            .background(FixedRoundedRectangle::new(ASSIST_CHIP_CONTAINER_SHAPE).fill(Surface))
            .border_with(
                Border::new(Outline, ASSIST_CHIP_OUTLINE_WIDTH)
                    .corner_radius(ASSIST_CHIP_CONTAINER_SHAPE),
            )
            .on_tap(move |env: Environment| action(&env))
            .a11y_label(accessibility_label)
            .a11y_role(AccessibilityRole::Button)
            .a11y_children(AccessibilityChildren::ExcludeDescendants)
            .install(interaction_style(
                LabelColor::default(),
                f64::from(ASSIST_CHIP_CONTAINER_SHAPE),
            ))
    }
}

const fn noop(_env: &Environment) {}

/// A Material Design 3 assist chip.
///
/// Assist chips represent a smart or supplemental action related to nearby
/// content.
pub type AssistChip<Action = fn(&Environment)> = OutlinedChip<Action, OnSurface>;

/// A Material Design 3 suggestion chip.
///
/// Suggestion chips present quick suggestions related to user input or content.
pub type SuggestionChip<Action = fn(&Environment)> = OutlinedChip<Action, OnSurfaceVariant>;

/// A Material Design 3 filter chip.
///
/// Filter chips toggle a selected state and expose that state through the
/// accessibility tree.
pub struct FilterChip<Action = fn(&Environment)> {
    label: Label,
    accessibility_label: Str,
    selected: Binding<bool>,
    action: Action,
}

/// A Material Design 3 input chip with a trailing remove action.
pub struct InputChip<Action = fn(&Environment), RemoveAction = fn(&Environment)> {
    label: Label,
    accessibility_label: Str,
    remove_accessibility_label: Str,
    action: Action,
    remove_action: RemoveAction,
}

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

impl InputChip<fn(&Environment), fn(&Environment)> {
    /// Creates an input chip with the given semantic label.
    #[must_use]
    pub fn new(label: impl IntoLabel) -> Self {
        let label = label.into_label();
        let accessibility_label = label_plain_text(&label);
        let remove_accessibility_label = Str::from(format!("Remove {accessibility_label}"));
        Self {
            label,
            accessibility_label,
            remove_accessibility_label,
            action: noop,
            remove_action: noop,
        }
    }
}

impl<Action, RemoveAction> InputChip<Action, RemoveAction> {
    /// Sets the action performed when the primary chip area is tapped.
    #[must_use]
    pub fn action<F, Args>(self, action: F) -> InputChip<impl FnMut(&Environment), RemoveAction>
    where
        F: Handler<Args, ()> + 'static,
    {
        InputChip {
            label: self.label,
            accessibility_label: self.accessibility_label,
            remove_accessibility_label: self.remove_accessibility_label,
            action: boxed_action(action),
            remove_action: self.remove_action,
        }
    }

    /// Sets the action performed when the trailing remove button is tapped.
    #[must_use]
    pub fn remove_action<F, Args>(self, action: F) -> InputChip<Action, impl FnMut(&Environment)>
    where
        F: Handler<Args, ()> + 'static,
    {
        InputChip {
            label: self.label,
            accessibility_label: self.accessibility_label,
            remove_accessibility_label: self.remove_accessibility_label,
            action: self.action,
            remove_action: boxed_action(action),
        }
    }
}

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

impl FilterChip<fn(&Environment)> {
    /// Creates a filter chip 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(),
            action: noop,
        }
    }
}

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

impl<Action> View for FilterChip<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_tap = self.selected.clone();
        let accessibility_state = self
            .selected
            .map(|selected| AccessibilityState::new().selected(selected));
        let foreground = conditional_color(
            self.selected.clone(),
            OnSecondaryContainer,
            OnSurfaceVariant,
        );
        let background = conditional_color(self.selected.clone(), SecondaryContainer, Surface);
        let outline = conditional_color(
            self.selected.clone(),
            Outline.with_opacity(FILTER_CHIP_SELECTED_OUTLINE_WIDTH),
            Outline,
        );
        let state_layer_color = conditional_color(
            self.selected.clone(),
            OnSecondaryContainer,
            OnSurfaceVariant,
        );
        let checkmark_opacity = self
            .selected
            .map(|selected| if selected { 1.0 } else { 0.0 });
        let checkmark_width = self.selected.map(
            |selected| {
                if selected { FILTER_CHIP_ICON_SIZE } else { 0.0 }
            },
        );
        let checkmark = Frame::new(
            CheckmarkIcon::new(
                OnSecondaryContainer,
                FILTER_CHIP_ICON_SIZE,
                FILTER_CHIP_CHECKMARK_LINE_WIDTH,
            )
            .container_height(FILTER_CHIP_CONTAINER_HEIGHT)
            .opacity(checkmark_opacity),
        )
        .width(checkmark_width);

        waterui::component::hstack((
            checkmark,
            self.label
                .font(typography::label_large())
                .foreground(foreground),
        ))
        .spacing(FILTER_CHIP_ICON_LABEL_SPACE)
        .height(FILTER_CHIP_CONTAINER_HEIGHT)
        .padding_with(EdgeInsets::new(
            0.0,
            0.0,
            FILTER_CHIP_WITH_ICON_LEADING_SPACE,
            FILTER_CHIP_TRAILING_SPACE,
        ))
        .background(FixedRoundedRectangle::new(FILTER_CHIP_CONTAINER_SHAPE).fill(background))
        .border_with(
            Border::new(outline, FILTER_CHIP_UNSELECTED_OUTLINE_WIDTH)
                .corner_radius(FILTER_CHIP_CONTAINER_SHAPE),
        )
        .on_tap(move |env: Environment| {
            selected_for_tap.set(!selected_for_tap.get());
            action.call(&env);
        })
        .a11y_label(self.accessibility_label)
        .a11y_role(AccessibilityRole::Button)
        .a11y_children(AccessibilityChildren::ExcludeDescendants)
        .a11y_state_signal(accessibility_state)
        .install(interaction_style(
            state_layer_color,
            f64::from(FILTER_CHIP_CONTAINER_SHAPE),
        ))
    }
}

impl<Action, RemoveAction> View for InputChip<Action, RemoveAction>
where
    Action: FnMut(&Environment) + 'static,
    RemoveAction: 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 mut remove_action = self.remove_action;
        let remove_action = SharedAction::new(move |env: Environment| remove_action(&env));
        let accessibility_label = self.accessibility_label;
        let remove_accessibility_label = self.remove_accessibility_label;

        waterui::component::hstack((
            self.label
                .font(typography::label_large())
                .foreground(OnSurfaceVariant)
                .on_tap(move |env: Environment| action.call(&env))
                .a11y_label(accessibility_label)
                .a11y_role(AccessibilityRole::Button)
                .a11y_children(AccessibilityChildren::ExcludeDescendants)
                .install(interaction_style(
                    OnSurfaceVariant,
                    f64::from(INPUT_CHIP_CONTAINER_SHAPE),
                )),
            RemoveButton {
                accessibility_label: remove_accessibility_label,
                action: remove_action,
            },
        ))
        .spacing(INPUT_CHIP_ICON_LABEL_SPACE)
        .height(INPUT_CHIP_CONTAINER_HEIGHT)
        .padding_with(EdgeInsets::new(
            0.0,
            0.0,
            INPUT_CHIP_LEADING_SPACE,
            INPUT_CHIP_WITH_TRAILING_ICON_TRAILING_SPACE,
        ))
        .background(FixedRoundedRectangle::new(INPUT_CHIP_CONTAINER_SHAPE).fill(Surface))
        .border_with(
            Border::new(Outline, INPUT_CHIP_UNSELECTED_OUTLINE_WIDTH)
                .corner_radius(INPUT_CHIP_CONTAINER_SHAPE),
        )
    }
}

/// Creates a Material Design 3 assist chip with the given semantic label.
#[must_use]
pub fn assist_chip(label: impl IntoLabel) -> AssistChip {
    AssistChip::new(label)
}

/// Creates a Material Design 3 suggestion chip with the given semantic label.
#[must_use]
pub fn suggestion_chip(label: impl IntoLabel) -> SuggestionChip {
    SuggestionChip::new(label)
}

/// Creates a Material Design 3 filter chip with the given semantic label.
#[must_use]
pub fn filter_chip(label: impl IntoLabel, selected: &Binding<bool>) -> FilterChip {
    FilterChip::new(label, selected)
}

/// Creates a Material Design 3 input chip with the given semantic label.
#[must_use]
pub fn input_chip(label: impl IntoLabel) -> InputChip {
    InputChip::new(label)
}

struct RemoveButton {
    accessibility_label: Str,
    action: SharedAction,
}

impl View for RemoveButton {
    fn body(self, _env: &Environment) -> impl View {
        let accessibility_label = self.accessibility_label;
        let action = self.action;
        waterui::component::hstack((RemoveIcon,))
            .size(INPUT_CHIP_TRAILING_ICON_SIZE, INPUT_CHIP_TRAILING_ICON_SIZE)
            .on_tap(move |env: Environment| action.call(&env))
            .a11y_label(accessibility_label)
            .a11y_role(AccessibilityRole::Button)
            .a11y_children(AccessibilityChildren::ExcludeDescendants)
            .install(interaction_style(
                OnSurfaceVariant,
                f64::from(INPUT_CHIP_TRAILING_ICON_SIZE * 0.5),
            ))
    }
}

struct RemoveIcon;

impl View for RemoveIcon {
    fn body(self, _env: &Environment) -> impl View {
        let line = || {
            Rectangle
                .fill(OnSurfaceVariant)
                .size(10.5, INPUT_CHIP_REMOVE_ICON_LINE_WIDTH)
        };
        waterui::component::zstack((line().rotation(45.0), line().rotation(-45.0)))
            .size(INPUT_CHIP_TRAILING_ICON_SIZE, INPUT_CHIP_TRAILING_ICON_SIZE)
    }
}

#[cfg(test)]
mod tests {
    use super::{
        ASSIST_CHIP_CONTAINER_HEIGHT, ASSIST_CHIP_CONTAINER_SHAPE, ASSIST_CHIP_LEADING_SPACE,
        ASSIST_CHIP_OUTLINE_WIDTH, ASSIST_CHIP_TRAILING_SPACE, FILTER_CHIP_CONTAINER_HEIGHT,
        FILTER_CHIP_CONTAINER_SHAPE, FILTER_CHIP_ICON_LABEL_SPACE, FILTER_CHIP_ICON_SIZE,
        FILTER_CHIP_LEADING_SPACE, FILTER_CHIP_SELECTED_OUTLINE_WIDTH, FILTER_CHIP_TRAILING_SPACE,
        FILTER_CHIP_UNSELECTED_OUTLINE_WIDTH, FILTER_CHIP_WITH_ICON_LEADING_SPACE,
        INPUT_CHIP_CONTAINER_HEIGHT, INPUT_CHIP_CONTAINER_SHAPE, INPUT_CHIP_ICON_LABEL_SPACE,
        INPUT_CHIP_LEADING_SPACE, INPUT_CHIP_TRAILING_ICON_SIZE,
        INPUT_CHIP_UNSELECTED_OUTLINE_WIDTH, INPUT_CHIP_WITH_TRAILING_ICON_TRAILING_SPACE,
    };

    #[test]
    fn assist_chip_tokens_match_compose_assist_chip_tokens() {
        assert_eq!(ASSIST_CHIP_CONTAINER_HEIGHT, 32.0);
        assert_eq!(ASSIST_CHIP_CONTAINER_SHAPE, 8.0);
        assert_eq!(ASSIST_CHIP_OUTLINE_WIDTH, 1.0);
        assert_eq!(ASSIST_CHIP_LEADING_SPACE, 16.0);
        assert_eq!(ASSIST_CHIP_TRAILING_SPACE, 16.0);
    }

    #[test]
    fn filter_chip_tokens_match_compose_filter_chip_tokens() {
        assert_eq!(FILTER_CHIP_CONTAINER_HEIGHT, 32.0);
        assert_eq!(FILTER_CHIP_CONTAINER_SHAPE, 8.0);
        assert_eq!(FILTER_CHIP_UNSELECTED_OUTLINE_WIDTH, 1.0);
        assert_eq!(FILTER_CHIP_SELECTED_OUTLINE_WIDTH, 0.0);
        assert_eq!(FILTER_CHIP_LEADING_SPACE, 16.0);
        assert_eq!(FILTER_CHIP_WITH_ICON_LEADING_SPACE, 8.0);
        assert_eq!(FILTER_CHIP_ICON_LABEL_SPACE, 8.0);
        assert_eq!(FILTER_CHIP_TRAILING_SPACE, 16.0);
        assert_eq!(FILTER_CHIP_ICON_SIZE, 18.0);
    }

    #[test]
    fn input_chip_tokens_match_compose_input_chip_tokens() {
        assert_eq!(INPUT_CHIP_CONTAINER_HEIGHT, 32.0);
        assert_eq!(INPUT_CHIP_CONTAINER_SHAPE, 8.0);
        assert_eq!(INPUT_CHIP_UNSELECTED_OUTLINE_WIDTH, 1.0);
        assert_eq!(INPUT_CHIP_LEADING_SPACE, 16.0);
        assert_eq!(INPUT_CHIP_ICON_LABEL_SPACE, 8.0);
        assert_eq!(INPUT_CHIP_WITH_TRAILING_ICON_TRAILING_SPACE, 8.0);
        assert_eq!(INPUT_CHIP_TRAILING_ICON_SIZE, 18.0);
    }
}