xilem 0.4.0

A next-generation cross-platform Rust UI framework.
Documentation
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
// Copyright 2024 the Xilem Authors
// SPDX-License-Identifier: Apache-2.0

use std::marker::PhantomData;

use masonry::core::{FromDynWidget, Widget, WidgetMut};
use masonry::properties::types::UnitPoint;
use masonry::widgets;
pub use masonry::widgets::ChildAlignment;

use crate::core::{
    AppendVec, ElementSplice, MessageContext, MessageResult, Mut, SuperElement, View, ViewElement,
    ViewMarker, ViewSequence,
};
use crate::{Pod, ViewCtx, WidgetView};

/// A widget that lays out its children on top of each other.
/// The children are laid out back to front.
///
/// # Example
///
/// This example shows how to add two text labels on top of each other.
///
/// ```
/// use xilem::WidgetView;
/// use xilem::view::{zstack, label, text_button};
///
/// fn view<State: 'static>() -> impl WidgetView<State> {
///     zstack((
///         label("Background"),
///         text_button("Click me", |_| {})
///     ))
/// }
/// ```
pub fn zstack<State, Action, Seq: ZStackSequence<State, Action>>(sequence: Seq) -> ZStack<Seq> {
    ZStack {
        sequence,
        alignment: UnitPoint::CENTER,
    }
}

/// A view container that lays the child widgets on top of each other.
///
/// See [`zstack`] for more details.
#[must_use = "View values do nothing unless provided to Xilem."]
pub struct ZStack<Seq> {
    sequence: Seq,
    alignment: UnitPoint,
}

impl<Seq> ZStack<Seq> {
    /// Changes the alignment of the children.
    pub fn alignment(mut self, alignment: impl Into<UnitPoint>) -> Self {
        self.alignment = alignment.into();
        self
    }
}

mod hidden {
    use super::ZStackElement;
    use crate::core::AppendVec;

    #[doc(hidden)]
    #[expect(
        unnameable_types,
        reason = "Implementation detail, public because of trait visibility rules"
    )]
    pub struct ZStackState<SeqState> {
        pub(crate) seq_state: SeqState,
        pub(crate) scratch: AppendVec<ZStackElement>,
    }
}

use hidden::ZStackState;

impl<Seq> ViewMarker for ZStack<Seq> {}
impl<State, Action, Seq> View<State, Action, ViewCtx> for ZStack<Seq>
where
    State: 'static,
    Action: 'static,
    Seq: ZStackSequence<State, Action>,
{
    type Element = Pod<widgets::ZStack>;

    type ViewState = ZStackState<Seq::SeqState>;

    fn build(&self, ctx: &mut ViewCtx, app_state: &mut State) -> (Self::Element, Self::ViewState) {
        let mut elements = AppendVec::default();
        let mut widget = widgets::ZStack::new().with_alignment(self.alignment);
        let seq_state = self.sequence.seq_build(ctx, &mut elements, app_state);
        for child in elements.drain() {
            widget = widget.with_child(child.widget.new_widget, child.alignment);
        }
        let pod = ctx.create_pod(widget);
        (
            pod,
            ZStackState {
                seq_state,
                scratch: elements,
            },
        )
    }

    fn rebuild(
        &self,
        prev: &Self,
        ZStackState { seq_state, scratch }: &mut Self::ViewState,
        ctx: &mut ViewCtx,
        mut element: Mut<'_, Self::Element>,
        app_state: &mut State,
    ) {
        if self.alignment != prev.alignment {
            widgets::ZStack::set_alignment(&mut element, self.alignment);
        }

        let mut splice = ZStackSplice::new(element, scratch);
        self.sequence
            .seq_rebuild(&prev.sequence, seq_state, ctx, &mut splice, app_state);
        debug_assert!(scratch.is_empty());
    }

    fn teardown(
        &self,
        ZStackState { seq_state, scratch }: &mut Self::ViewState,
        ctx: &mut ViewCtx,
        element: Mut<'_, Self::Element>,
    ) {
        let mut splice = ZStackSplice::new(element, scratch);
        self.sequence.seq_teardown(seq_state, ctx, &mut splice);
        debug_assert!(scratch.is_empty());
    }

    fn message(
        &self,
        ZStackState { seq_state, scratch }: &mut Self::ViewState,
        message: &mut MessageContext,
        element: Mut<'_, Self::Element>,
        app_state: &mut State,
    ) -> MessageResult<Action> {
        let mut splice = ZStackSplice::new(element, scratch);
        let result = self
            .sequence
            .seq_message(seq_state, message, &mut splice, app_state);
        debug_assert!(scratch.is_empty());
        result
    }
}

// --- MARK: ZStackExt

/// A trait that extends a [`WidgetView`] with methods to provide parameters for a parent [`ZStack`].
pub trait ZStackExt<State, Action>: WidgetView<State, Action> {
    /// Applies [`ChildAlignment`] to this view.
    /// This allows the view to override the default alignment of the parent [`ZStack`].
    /// This can only be used on views that are direct children of a [`ZStack`].
    fn alignment(self, alignment: impl Into<ChildAlignment>) -> ZStackItem<Self, State, Action>
    where
        State: 'static,
        Action: 'static,
        Self: Sized,
    {
        zstack_item(self, alignment)
    }
}

impl<State, Action, V: WidgetView<State, Action>> ZStackExt<State, Action> for V {}

/// A wrapper around a [`WidgetView`], with a specified [`ChildAlignment`].
/// This struct is most often constructed indirectly using [`ZStackExt::alignment`].
pub struct ZStackItem<V, State, Action> {
    view: V,
    alignment: ChildAlignment,
    phantom: PhantomData<fn() -> (State, Action)>,
}

/// Constructs a new `ZStackItem`.
/// See also [`ZStackExt::alignment`], for constructing a `ZStackItem` from an existing view.
pub fn zstack_item<V, State, Action>(
    view: V,
    alignment: impl Into<ChildAlignment>,
) -> ZStackItem<V, State, Action>
where
    State: 'static,
    Action: 'static,
    V: WidgetView<State, Action>,
{
    ZStackItem {
        view,
        alignment: alignment.into(),
        phantom: PhantomData,
    }
}

impl<V, State, Action> ViewMarker for ZStackItem<V, State, Action> {}

impl<State, Action, V> View<State, Action, ViewCtx> for ZStackItem<V, State, Action>
where
    State: 'static,
    Action: 'static,
    V: WidgetView<State, Action>,
{
    type Element = ZStackElement;

    type ViewState = V::ViewState;

    fn build(&self, ctx: &mut ViewCtx, app_state: &mut State) -> (Self::Element, Self::ViewState) {
        let (pod, state) = self.view.build(ctx, app_state);
        (ZStackElement::new(pod.erased(), self.alignment), state)
    }

    fn rebuild(
        &self,
        prev: &Self,
        view_state: &mut Self::ViewState,
        ctx: &mut ViewCtx,
        mut element: Mut<'_, Self::Element>,
        app_state: &mut State,
    ) {
        {
            if self.alignment != prev.alignment {
                widgets::ZStack::update_child_alignment(
                    &mut element.parent,
                    element.idx,
                    self.alignment,
                );
            }
            let mut child = widgets::ZStack::child_mut(&mut element.parent, element.idx)
                .expect("ZStackWrapper always has a widget child");
            self.view
                .rebuild(&prev.view, view_state, ctx, child.downcast(), app_state);
        }
    }

    fn teardown(
        &self,
        view_state: &mut Self::ViewState,
        ctx: &mut ViewCtx,
        mut element: Mut<'_, Self::Element>,
    ) {
        let mut child = widgets::ZStack::child_mut(&mut element.parent, element.idx)
            .expect("ZStackWrapper always has a widget child");
        self.view.teardown(view_state, ctx, child.downcast());
    }

    fn message(
        &self,
        view_state: &mut Self::ViewState,
        message: &mut MessageContext,
        mut element: Mut<'_, Self::Element>,
        app_state: &mut State,
    ) -> MessageResult<Action> {
        let mut child = widgets::ZStack::child_mut(&mut element.parent, element.idx)
            .expect("ZStackWrapper always has a corresponding child");
        self.view
            .message(view_state, message, child.downcast(), app_state)
    }
}

// --- MARK: ZStackElement

/// A struct implementing [`ViewElement`] for a `ZStack`.
pub struct ZStackElement {
    widget: Pod<dyn Widget>,
    alignment: ChildAlignment,
}

/// A mutable version of `ZStackElement`.
pub struct ZStackElementMut<'w> {
    parent: WidgetMut<'w, widgets::ZStack>,
    idx: usize,
}

impl ZStackElement {
    fn new(widget: Pod<dyn Widget>, alignment: ChildAlignment) -> Self {
        Self { widget, alignment }
    }
}

impl ViewElement for ZStackElement {
    type Mut<'a> = ZStackElementMut<'a>;
}

impl SuperElement<Self, ViewCtx> for ZStackElement {
    fn upcast(_ctx: &mut ViewCtx, child: Self) -> Self {
        child
    }

    fn with_downcast_val<R>(
        mut this: Mut<'_, Self>,
        f: impl FnOnce(Mut<'_, Self>) -> R,
    ) -> (Self::Mut<'_>, R) {
        let r = {
            let parent = this.parent.reborrow_mut();
            let reborrow = ZStackElementMut {
                idx: this.idx,
                parent,
            };
            f(reborrow)
        };
        (this, r)
    }
}

impl<W: Widget + FromDynWidget + ?Sized> SuperElement<Pod<W>, ViewCtx> for ZStackElement {
    fn upcast(_: &mut ViewCtx, child: Pod<W>) -> Self {
        Self::new(child.erased(), ChildAlignment::ParentAligned)
    }

    fn with_downcast_val<R>(
        mut this: Mut<'_, Self>,
        f: impl FnOnce(Mut<'_, Pod<W>>) -> R,
    ) -> (Self::Mut<'_>, R) {
        let ret = {
            let mut child = widgets::ZStack::child_mut(&mut this.parent, this.idx)
                .expect("This is supposed to be a widget");
            let downcast = child.downcast();
            f(downcast)
        };

        (this, ret)
    }
}

// MARK: Sequence

/// A trait implementing `ViewSequence` for `ZStackElement`.
pub trait ZStackSequence<State, Action = ()>:
    ViewSequence<State, Action, ViewCtx, ZStackElement>
{
}

impl<Seq, State, Action> ZStackSequence<State, Action> for Seq where
    Seq: ViewSequence<State, Action, ViewCtx, ZStackElement>
{
}

// MARK: Splice

/// An implementation of [`ElementSplice`] for `ZStackElement`.
pub struct ZStackSplice<'w, 's> {
    idx: usize,
    element: WidgetMut<'w, widgets::ZStack>,
    scratch: &'s mut AppendVec<ZStackElement>,
}

impl<'w, 's> ZStackSplice<'w, 's> {
    fn new(
        element: WidgetMut<'w, widgets::ZStack>,
        scratch: &'s mut AppendVec<ZStackElement>,
    ) -> Self {
        Self {
            idx: 0,
            element,
            scratch,
        }
    }
}

impl ElementSplice<ZStackElement> for ZStackSplice<'_, '_> {
    fn with_scratch<R>(&mut self, f: impl FnOnce(&mut AppendVec<ZStackElement>) -> R) -> R {
        let ret = f(self.scratch);
        for element in self.scratch.drain() {
            widgets::ZStack::insert_child(
                &mut self.element,
                element.widget.new_widget,
                element.alignment,
            );
            self.idx += 1;
        }
        ret
    }

    fn insert(&mut self, element: ZStackElement) {
        widgets::ZStack::insert_child(
            &mut self.element,
            element.widget.new_widget,
            element.alignment,
        );
        self.idx += 1;
    }

    fn mutate<R>(&mut self, f: impl FnOnce(Mut<'_, ZStackElement>) -> R) -> R {
        let child = ZStackElementMut {
            parent: self.element.reborrow_mut(),
            idx: self.idx,
        };
        let ret = f(child);
        self.idx += 1;
        ret
    }

    fn skip(&mut self, n: usize) {
        self.idx += n;
    }

    fn index(&self) -> usize {
        self.idx
    }

    fn delete<R>(&mut self, f: impl FnOnce(Mut<'_, ZStackElement>) -> R) -> R {
        let ret = {
            let child = ZStackElementMut {
                parent: self.element.reborrow_mut(),
                idx: self.idx,
            };
            f(child)
        };
        widgets::ZStack::remove_child(&mut self.element, self.idx);
        ret
    }
}