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

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

use waterui::accessibility::{AccessibilityChildren, AccessibilityRole};
use waterui::layout::{
    HorizontalAlignment, Layout, PlacedSubview, Point, ProposalSize, Rect, Size, SubView,
    SubviewPlacement, container::FixedContainer, padding::EdgeInsets,
};
use waterui::prelude::{PositionExt as _, UnitPoint, absolute};
use waterui::shape::{FixedRoundedRectangle, ShapeExt as _};
use waterui::signal::IntoComputed;
use waterui::style::Anchor;
use waterui::{Computed, Environment, SignalExt as _, Str, View, ViewExt as _};
use waterui_controls::label::{IntoLabel, Label};
use waterui_core::AnyView;
use waterui_core::handler::{Handler, SharedAction, boxed_action};
use waterui_core::view::TupleViews;

use crate::ModalInteraction;
use crate::color::{OnSurface, OnSurfaceVariant, Primary, Scrim, SurfaceContainerHigh};
use crate::elevation::{MaterialElevationLevel, material_elevation};
use crate::semantics::{interaction_style, label_plain_text};
use crate::theme::{motion, typography};

const DIALOG_CONTAINER_MIN_WIDTH: f32 = 280.0;
const DIALOG_CONTAINER_MAX_WIDTH: f32 = 560.0;
const DIALOG_CONTAINER_MIN_HEIGHT: f32 = 140.0;
const DIALOG_CONTAINER_SHAPE: f32 = 28.0;
const DIALOG_VIEWPORT_PADDING: f32 = 48.0;
const DIALOG_CONTENT_PADDING: f32 = 24.0;
const DIALOG_HEADLINE_BODY_SPACING: f32 = 16.0;
const DIALOG_CONTENT_BOTTOM_SPACE_WITH_ACTIONS: f32 = 8.0;
const DIALOG_ACTION_TOP_SPACE: f32 = 16.0;
const DIALOG_ACTION_TRAILING_SPACE: f32 = 24.0;
const DIALOG_ACTION_BOTTOM_SPACE: f32 = 24.0;
const DIALOG_ACTION_SPACING: f32 = 8.0;
const DIALOG_HIDDEN_OFFSET_Y: f32 = -30.0;

/// A Material Design 3 dialog action button.
pub struct DialogAction<Action = fn(&Environment)> {
    label: Label,
    action: Action,
}

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

impl DialogAction<fn(&Environment)> {
    /// Creates a dialog action with the given semantic label.
    #[must_use]
    pub fn new(label: impl IntoLabel) -> Self {
        Self {
            label: label.into_label(),
            action: noop,
        }
    }
}

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

impl<Action> View for DialogAction<Action>
where
    Action: FnMut(&Environment) + 'static,
{
    fn body(self, _env: &Environment) -> impl View {
        let accessibility_label = label_plain_text(&self.label);
        let mut action = self.action;
        self.label
            .font(typography::label_large())
            .foreground(Primary)
            .height(40.0)
            .padding_with(EdgeInsets::new(0.0, 0.0, 12.0, 12.0))
            .on_tap(move |env: Environment| action(&env))
            .a11y_label(accessibility_label)
            .a11y_role(AccessibilityRole::Button)
            .a11y_children(AccessibilityChildren::ExcludeDescendants)
            .install(interaction_style(Primary, 20.0))
    }
}

/// A Material Design 3 basic dialog.
pub struct Dialog<Actions = ()> {
    headline: Label,
    supporting_text: Label,
    accessibility_label: Str,
    actions: Actions,
    presented: Computed<bool>,
    overlay_action: SharedAction,
    close_on_escape: bool,
    escape_action: SharedAction,
}

impl<Actions> Debug for Dialog<Actions> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Dialog")
            .field("headline", &self.headline)
            .field("supporting_text", &self.supporting_text)
            .finish_non_exhaustive()
    }
}

impl Dialog<()> {
    /// Creates a Material dialog with headline and supporting text.
    #[must_use]
    pub fn new(headline: impl IntoLabel, supporting_text: impl IntoLabel) -> Self {
        let headline = headline.into_label();
        let supporting_text = supporting_text.into_label();
        let accessibility_label = label_plain_text(&headline);
        Self {
            headline,
            supporting_text,
            accessibility_label,
            actions: (),
            presented: Computed::constant(true),
            overlay_action: SharedAction::new(|_: Environment| {}),
            close_on_escape: false,
            escape_action: SharedAction::new(|_: Environment| {}),
        }
    }
}

impl<Actions> Dialog<Actions> {
    /// Sets the dialog action row.
    #[must_use]
    pub fn actions<NewActions>(self, actions: NewActions) -> Dialog<NewActions> {
        Dialog {
            headline: self.headline,
            supporting_text: self.supporting_text,
            accessibility_label: self.accessibility_label,
            actions,
            presented: self.presented,
            overlay_action: self.overlay_action,
            close_on_escape: self.close_on_escape,
            escape_action: self.escape_action,
        }
    }

    /// Controls whether the dialog is visible and modal.
    ///
    /// Keeping a controlled dialog mounted allows its the M3 reference open and close
    /// transitions to finish without rebuilding the surrounding view tree.
    #[must_use]
    pub fn presented(mut self, presented: impl IntoComputed<bool>) -> Self {
        self.presented = presented.into_computed();
        self
    }

    /// Sets the action emitted when the modal scrim is tapped.
    #[must_use]
    pub fn overlay_action<F, Args>(mut self, action: F) -> Self
    where
        F: Handler<Args, ()> + 'static,
    {
        let mut action = boxed_action(action);
        self.overlay_action = SharedAction::new(move |env: Environment| action(&env));
        self
    }

    /// Enables Escape-key dismissal and sets the emitted action.
    #[must_use]
    pub fn escape_action<F, Args>(mut self, action: F) -> Self
    where
        F: Handler<Args, ()> + 'static,
    {
        let mut action = boxed_action(action);
        self.close_on_escape = true;
        self.escape_action = SharedAction::new(move |env: Environment| action(&env));
        self
    }
}

impl<Actions> View for Dialog<Actions>
where
    Actions: TupleViews + 'static,
{
    fn body(self, _env: &Environment) -> impl View {
        let presented = self.presented;
        let modal = ModalInteraction::new(self.close_on_escape, self.escape_action)
            .active(presented.clone());
        let surface = DialogSurface::new(
            self.headline
                .font(typography::headline_small())
                .foreground(OnSurface),
            self.supporting_text
                .font(typography::body_medium())
                .foreground(OnSurfaceVariant),
            DialogActions {
                actions: self.actions,
            },
        )
        .background(FixedRoundedRectangle::new(DIALOG_CONTAINER_SHAPE).fill(SurfaceContainerHigh))
        .background(
            SurfaceContainerHigh
                .with_opacity(0.0)
                .on_tap(|_: Environment| {})
                .a11y_hidden(true)
                .install(
                    interaction_style(SurfaceContainerHigh.with_opacity(0.0), 0.0).pointer_only(),
                ),
        )
        .a11y_label(self.accessibility_label)
        .a11y_role(AccessibilityRole::Dialog);

        let surface = material_elevation(
            MaterialElevationLevel::LEVEL3,
            DIALOG_CONTAINER_SHAPE,
            surface,
        )
        .opacity(motion::dialog_opacity(presented.clone(), 0.0, 1.0))
        .offset(
            0.0,
            motion::dialog_transform(presented.clone(), DIALOG_HIDDEN_OFFSET_Y, 0.0),
        )
        .scale_from(
            1.0,
            motion::dialog_transform(presented.clone(), 0.0, 1.0),
            Anchor::new(0.5, 0.0),
        )
        .padding_with(EdgeInsets::all(DIALOG_VIEWPORT_PADDING))
        .position_in(UnitPoint::CENTER);

        let overlay_action = self.overlay_action;
        let scrim = Scrim
            .with_opacity(1.0)
            .opacity(motion::dialog_opacity(
                presented.clone(),
                0.0,
                crate::theme::colors::SCRIM_OPACITY,
            ))
            .on_tap(move |env: Environment| overlay_action.call(&env))
            .a11y_hidden(true)
            .install(interaction_style(Scrim.with_opacity(0.0), 0.0).pointer_only());

        let accessibility_state = presented
            .map(|presented| waterui::accessibility::AccessibilityState::new().hidden(!presented));

        absolute((scrim, surface))
            .hittable(presented)
            .a11y_state_signal(accessibility_state)
            .install(modal)
    }
}

#[derive(Debug)]
struct DialogSurface {
    headline: AnyView,
    supporting_text: AnyView,
    actions: AnyView,
}

impl DialogSurface {
    fn new(headline: impl View, supporting_text: impl View, actions: impl View) -> Self {
        Self {
            headline: AnyView::new(headline),
            supporting_text: AnyView::new(supporting_text),
            actions: AnyView::new(actions),
        }
    }
}

impl View for DialogSurface {
    fn body(self, _env: &Environment) -> impl View {
        FixedContainer::new(
            DialogSurfaceLayout,
            (self.headline, self.supporting_text, self.actions),
        )
    }
}

#[derive(Debug, Clone, Copy)]
struct DialogSurfaceLayout;

impl Layout for DialogSurfaceLayout {
    fn size_that_fits(&self, proposal: ProposalSize, children: &[&dyn SubView]) -> Size {
        let [headline, supporting_text, actions] = children else {
            return Size::zero();
        };

        let proposed_max_width = proposal
            .width
            .unwrap_or(DIALOG_CONTAINER_MAX_WIDTH)
            .min(DIALOG_CONTAINER_MAX_WIDTH);
        let action_size = actions.measure(ProposalSize::new(None, None)).size;
        let headline_intrinsic = headline.measure(ProposalSize::new(None, None)).size;
        let supporting_intrinsic = supporting_text.measure(ProposalSize::new(None, None)).size;
        let content_width = headline_intrinsic
            .width
            .max(supporting_intrinsic.width)
            .max(action_size.width);
        let width = DIALOG_CONTENT_PADDING
            .mul_add(2.0, content_width)
            .max(DIALOG_CONTAINER_MIN_WIDTH)
            .min(proposed_max_width);
        let text_width = DIALOG_CONTENT_PADDING.mul_add(-2.0, width).max(0.0);
        let headline_size = headline
            .measure(ProposalSize::new(Some(text_width), None))
            .size;
        let supporting_size = supporting_text
            .measure(ProposalSize::new(Some(text_width), None))
            .size
            .height;
        let height = (DIALOG_CONTENT_PADDING
            + headline_size.height
            + DIALOG_HEADLINE_BODY_SPACING
            + supporting_size
            + DIALOG_CONTENT_BOTTOM_SPACE_WITH_ACTIONS
            + DIALOG_ACTION_TOP_SPACE
            + action_size.height
            + DIALOG_ACTION_BOTTOM_SPACE)
            .max(DIALOG_CONTAINER_MIN_HEIGHT);

        Size::new(width, height)
    }

    fn place(
        &self,
        bounds: Rect,
        _proposal: ProposalSize,
        children: &[&dyn SubView],
    ) -> Vec<SubviewPlacement> {
        let [headline, supporting_text, actions] = children else {
            return vec![];
        };

        let text_width = DIALOG_CONTENT_PADDING
            .mul_add(-2.0, bounds.width())
            .max(0.0);
        let text_proposal = ProposalSize::new(Some(text_width), None);
        let headline_size = headline.measure(text_proposal).size;
        let supporting_size = supporting_text.measure(text_proposal).size;
        let action_size = actions.measure(ProposalSize::UNSPECIFIED).size;
        let headline_origin = Point::new(
            bounds.x() + DIALOG_CONTENT_PADDING,
            bounds.y() + DIALOG_CONTENT_PADDING,
        );
        let supporting_origin = Point::new(
            bounds.x() + DIALOG_CONTENT_PADDING,
            headline_origin.y + headline_size.height + DIALOG_HEADLINE_BODY_SPACING,
        );
        let actions_origin = Point::new(
            bounds.x() + bounds.width() - DIALOG_ACTION_TRAILING_SPACE - action_size.width,
            supporting_origin.y
                + supporting_size.height
                + DIALOG_CONTENT_BOTTOM_SPACE_WITH_ACTIONS
                + DIALOG_ACTION_TOP_SPACE,
        );

        vec![
            SubviewPlacement::new(
                Rect::new(headline_origin, Size::new(text_width, headline_size.height)),
                text_proposal,
            ),
            SubviewPlacement::new(
                Rect::new(
                    supporting_origin,
                    Size::new(text_width, supporting_size.height),
                ),
                text_proposal,
            ),
            SubviewPlacement::new(
                Rect::new(actions_origin, action_size),
                ProposalSize::UNSPECIFIED,
            ),
        ]
    }

    fn explicit_horizontal(
        &self,
        alignment: HorizontalAlignment,
        _bounds: Rect,
        children: &[PlacedSubview<'_>],
    ) -> Option<f32> {
        children
            .first()
            .and_then(|child| child.explicit_horizontal(alignment))
    }
}

struct DialogActions<Actions> {
    actions: Actions,
}

impl<Actions> View for DialogActions<Actions>
where
    Actions: TupleViews + 'static,
{
    fn body(self, _env: &Environment) -> impl View {
        waterui::component::hstack(self.actions).spacing(DIALOG_ACTION_SPACING)
    }
}

const fn noop(_env: &Environment) {}

/// Creates a Material Design 3 dialog.
#[must_use]
pub fn dialog(headline: impl IntoLabel, supporting_text: impl IntoLabel) -> Dialog<()> {
    Dialog::new(headline, supporting_text)
}

/// Creates a Material Design 3 dialog action.
#[must_use]
pub fn dialog_action(label: impl IntoLabel) -> DialogAction {
    DialogAction::new(label)
}

#[cfg(test)]
mod tests {
    use super::{
        DIALOG_ACTION_BOTTOM_SPACE, DIALOG_ACTION_SPACING, DIALOG_ACTION_TRAILING_SPACE,
        DIALOG_CONTAINER_MAX_WIDTH, DIALOG_CONTAINER_MIN_HEIGHT, DIALOG_CONTAINER_MIN_WIDTH,
        DIALOG_CONTAINER_SHAPE, DIALOG_CONTENT_BOTTOM_SPACE_WITH_ACTIONS, DIALOG_CONTENT_PADDING,
        DIALOG_HIDDEN_OFFSET_Y, DIALOG_VIEWPORT_PADDING,
    };

    #[test]
    fn dialog_tokens_match_compose_dialog_tokens() {
        assert_eq!(DIALOG_CONTAINER_MIN_WIDTH, 280.0);
        assert_eq!(DIALOG_CONTAINER_MAX_WIDTH, 560.0);
        assert_eq!(DIALOG_CONTAINER_MIN_HEIGHT, 140.0);
        assert_eq!(DIALOG_CONTAINER_SHAPE, 28.0);
        assert_eq!(DIALOG_VIEWPORT_PADDING, 48.0);
        assert_eq!(DIALOG_HIDDEN_OFFSET_Y, -30.0);
        assert_eq!(DIALOG_CONTENT_PADDING, 24.0);
        assert_eq!(DIALOG_CONTENT_BOTTOM_SPACE_WITH_ACTIONS, 8.0);
        assert_eq!(DIALOG_ACTION_SPACING, 8.0);
        assert_eq!(DIALOG_ACTION_TRAILING_SPACE, 24.0);
        assert_eq!(DIALOG_ACTION_BOTTOM_SPACE, 24.0);
    }
    #[test]
    fn layout_contract_dialog_retains_intrinsic_action_and_text_height() {
        use super::DialogSurfaceLayout;
        use crate::layout_test_support::FixedLeaf;
        use waterui::layout::{Layout, ProposalSize, Rect, Size};
        let headline = FixedLeaf(Size::new(180.0, 24.0));
        let body = FixedLeaf(Size::new(140.0, 60.0));
        let actions = FixedLeaf(Size::new(100.0, 40.0));
        let children: &[&dyn waterui::layout::SubView] = &[&headline, &body, &actions];
        let layout = DialogSurfaceLayout;
        let proposal = ProposalSize::new(Some(400.0), Some(300.0));
        let size = layout.size_that_fits(proposal, children);
        let placements = layout.place(Rect::from_size(size), proposal, children);
        assert_eq!(placements[0].proposal, ProposalSize::new(Some(232.0), None));
        assert_eq!(placements[1].proposal, placements[0].proposal);
        assert_eq!(placements[2].proposal, ProposalSize::UNSPECIFIED);
    }
}