mtk-rs 0.1.0-beta.2

Muse Toolkit
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
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Declarative, reactive view hierarchy and event dispatch system for MTK.
//!
//! This module defines the core [`View`] trait, [`ViewSequence`] container composition,
//! state lenses, adapters, and input events ([`Event`]) used to compose user interfaces.

use crate::{Context, Node, ui::event::EventResult, windowing::WindowDimension};

pub mod adapter;
pub mod event;
pub mod focus;
pub mod kinetic;
pub mod layer;
pub mod lens;
pub mod memoize;
pub mod router;
pub mod style;
pub mod transition;
pub mod widgets;

pub use adapter::{ViewAdaptExt, adapt};
pub use event::{
    DragContext, DragElement, DragHandler, DragPhase, EventKind, KeyActionKind, KeyEventContext,
    KeyHandler, KeyScope, ThumbScrollContext, ThumbScrollHandler, TickHandler, ViewEventExt,
};
pub use focus::{Focusable, FocusableExt};
pub use kinetic::KineticTracker;
pub use layer::{Layer, ViewLayerExt, layer};
pub use lens::Lens;
pub use router::{Router, router};
pub use style::ViewStyleExt;
pub use transition::Transition;

/// Represents user interaction, layout lifecycle, and system input events dispatched down the view tree.
#[derive(Clone, Debug)]
pub enum Event {
    /// Dispatched when the mouse cursor moves across the viewport.
    CursorMoved {
        /// Absolute horizontal pixel position.
        x: f32,
        /// Absolute vertical pixel position.
        y: f32,
        /// Incremental horizontal pixel displacement since previous move.
        delta_x: f32,
        /// Incremental vertical pixel displacement since previous move.
        delta_y: f32,
        /// Ordered list of layout nodes hit-tested under the cursor.
        hit_nodes: Vec<Node>,
    },
    /// Dispatched when a mouse button press or release action occurs.
    MouseInput {
        /// Mouse button associated with this input event.
        button: winit::event::MouseButton,
        /// `true` if button was pressed down; `false` if released.
        pressed: bool,
        /// Absolute horizontal pixel position.
        x: f32,
        /// Absolute vertical pixel position.
        y: f32,
        /// Ordered list of layout nodes hit-tested under the cursor.
        hit_nodes: Vec<Node>,
    },
    /// Dispatched when mouse scroll wheel or touchpad scroll gestures are detected.
    MouseWheel {
        /// Horizontal scroll displacement.
        delta_x: f32,
        /// Vertical scroll displacement.
        delta_y: f32,
        /// `true` if scrolling originated from a continuous touchpad surface.
        is_touchpad: bool,
        /// Touch phase state associated with gesture scrolling.
        phase: winit::event::TouchPhase,
        /// Ordered list of layout nodes hit-tested under the cursor.
        hit_nodes: Vec<Node>,
    },
    /// Dispatched when a physical or virtual keyboard key is pressed or released.
    KeyboardInput {
        /// Key event payload.
        event: KeyEvent,
        /// `true` if generated synthetically by MTK event repeat logic.
        is_synthetic: bool,
    },
    /// Dispatched when an OS Input Method Editor (IME) updates preedit or commits text.
    Ime(winit::event::Ime),
    /// Dispatched once per frame tick to drive animations and physics interpolation.
    Tick {
        /// Elapsed time delta in seconds since the previous frame tick.
        dt: f32,
    },
    /// Dispatched when the parent application window size changes.
    WindowResized(WindowDimension),
    /// Dispatched when a scrollbar thumb is dragged or scrubbed.
    ThumbScroll {
        /// The scroll container node whose thumb moved.
        node: Node,
        /// Geometry and state of the thumb.
        context: ThumbScrollContext,
    },
    /// Dispatched when a previously focused node loses focus (e.g. on click outside or blur).
    FocusLost {
        /// The node that lost focus.
        node: Node,
    },
}

/// Describes a keyboard input targeting a window or UI node.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct KeyEvent {
    /// Position of the key independent of active keyboard layout (scancode).
    pub physical_key: winit::keyboard::PhysicalKey,
    /// Resolved logical representation of the key.
    pub logical_key: winit::keyboard::Key,
    /// UTF-8 text generated by this keypress, if any.
    pub text: Option<winit::keyboard::SmolStr>,
    /// Location of this key on the keyboard.
    pub location: winit::keyboard::KeyLocation,
    /// Key state: pressed or released.
    pub state: winit::event::ElementState,
    /// Whether this is an OS key repeat event.
    pub repeat: bool,
}

impl KeyEvent {
    /// Creates a new `KeyEvent` with standard defaults for location and repeat.
    pub fn new(logical_key: winit::keyboard::Key, state: winit::event::ElementState) -> Self {
        Self {
            physical_key: winit::keyboard::PhysicalKey::Unidentified(
                winit::keyboard::NativeKeyCode::Unidentified,
            ),
            logical_key,
            text: None,
            location: winit::keyboard::KeyLocation::Standard,
            state,
            repeat: false,
        }
    }
}

impl From<winit::event::KeyEvent> for KeyEvent {
    fn from(ev: winit::event::KeyEvent) -> Self {
        Self {
            physical_key: ev.physical_key,
            logical_key: ev.logical_key,
            text: ev.text,
            location: ev.location,
            state: ev.state,
            repeat: ev.repeat,
        }
    }
}

/// The foundational trait for all declarative, reactive UI components in MTK.
///
/// A `View` represents a lightweight blueprint for constructing and updating underlying
/// layout nodes ([`Node`]) bound to an application state (`State`).
pub trait View<State> {
    /// The persistent DOM-like element state maintained between render frames.
    type Element;
    /// The message type emitted by this view upon user interaction.
    type Message;

    /// Instantiates initial layout nodes and state primitives for this view.
    fn build(&self, ctx: &mut Context) -> Self::Element;

    /// Diffs and updates persistent element nodes when application state or properties change.
    fn rebuild(&self, prev: &Self, ctx: &mut Context, element: &mut Self::Element);

    /// Diffs and updates persistent element nodes, providing access to the parent container node for insertion.
    fn rebuild_with_parent(
        &self,
        prev: &Self,
        ctx: &mut Context,
        element: &mut Self::Element,
        _parent: Node,
        _next_sibling: Option<Node>,
    ) {
        self.rebuild(prev, ctx, element);
    }

    /// Destroys persistent layout nodes and frees resources associated with `element`.
    fn teardown(&self, ctx: &mut Context, element: &mut Self::Element);

    /// Returns the root layout node handle representing this view.
    fn get_node(&self, element: &Self::Element) -> Node;

    /// Handles incoming user interaction events, returning event consumption status and optional domain messages.
    fn handle_event(
        &self,
        element: &mut Self::Element,
        state: &State,
        event: Event,
        ctx: &mut Context,
    ) -> (EventResult, Option<Self::Message>);
}

/// Defines container composition for sequential views, such as tuples `(ViewA, ViewB)` or `Vec<V>`.
pub trait ViewSequence<State> {
    /// The persistent element tuple or collection corresponding to child views.
    type Elements;
    /// The common message type emitted by child views in this sequence.
    type Message;

    /// Instantiates initial layout nodes for all items in the sequence and appends them to `parent`.
    fn build(&self, ctx: &mut Context, parent: Node) -> Self::Elements;

    /// Diffs and updates layout nodes for all items in the sequence.
    fn rebuild(&self, prev: &Self, ctx: &mut Context, elements: &mut Self::Elements, parent: Node);

    /// Destroys layout nodes and cleans up resources for all items in the sequence.
    fn teardown(&self, ctx: &mut Context, elements: &mut Self::Elements);

    /// Routes events through items in the sequence sequentially until consumed.
    fn handle_event(
        &self,
        elements: &mut Self::Elements,
        state: &State,
        event: Event,
        ctx: &mut Context,
    ) -> (EventResult, Option<Self::Message>);
}

macro_rules! impl_view_tuple {
    ( $($idx:tt => $t:ident),* ) => {
        impl<State, Msg, $($t),*> ViewSequence<State> for ($($t,)*)
        where
            $($t: View<State, Message = Msg>),*
        {
            type Elements = ($($t::Element,)*);
            type Message = Msg;

            fn build(&self, ctx: &mut Context, parent: Node) -> Self::Elements {
                (
                    $({
                        let child_element = self.$idx.build(ctx);
                        parent.append(ctx, self.$idx.get_node(&child_element));
                        child_element
                    },)*
                )
            }

            fn rebuild(&self, prev: &Self, ctx: &mut Context, elements: &mut Self::Elements, parent: Node) {
                let mut nodes = [
                    $(self.$idx.get_node(&elements.$idx),)*
                ];

                #[allow(unused_assignments)]
                {
                    $(
                        let next_sibling = nodes[($idx + 1)..].iter().copied().find(|n| n.is_valid());
                        self.$idx.rebuild_with_parent(&prev.$idx, ctx, &mut elements.$idx, parent, next_sibling);
                        nodes[$idx] = self.$idx.get_node(&elements.$idx);
                    )*
                }
            }

            fn teardown(&self, ctx: &mut Context, elements: &mut Self::Elements) {
                $(
                    self.$idx.teardown(ctx, &mut elements.$idx);
                )*
            }

            fn handle_event(
                &self,
                elements: &mut Self::Elements,
                state: &State,
                event: Event,
                ctx: &mut Context,
            ) -> (EventResult, Option<Self::Message>) {
                let is_tick = matches!(event, Event::Tick { .. });
                let mut handled = EventResult::Ignored;
                let mut emitted_msg = None;

                $(
                    if (is_tick || handled == EventResult::Ignored) && emitted_msg.is_none() {
                        let (res, msg) = self.$idx.handle_event(
                            &mut elements.$idx,
                            state,
                            event.clone(),
                            ctx
                        );
                        handled = handled.or(res);
                        if msg.is_some() {
                            emitted_msg = msg;
                        }
                    }
                )*

                (handled, emitted_msg)
            }
        }
    };
}

// Generate implementations for tuples up to 10 elements
impl_view_tuple!(0 => A);
impl_view_tuple!(0 => A, 1 => B);
impl_view_tuple!(0 => A, 1 => B, 2 => C);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F, 6 => G);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F, 6 => G, 7 => H);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F, 6 => G, 7 => H, 8 => I);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F, 6 => G, 7 => H, 8 => I, 9 => J);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F, 6 => G, 7 => H, 8 => I, 9 => J, 10 => K);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F, 6 => G, 7 => H, 8 => I, 9 => J, 10 => K, 11 => L);
impl_view_tuple!(0 => A, 1 => B, 2 => C, 3 => D, 4 => E, 5 => F, 6 => G, 7 => H, 8 => I, 9 => J, 10 => K, 11 => L, 12 => M);

// Implement ViewSequence for Vec<V> to support dynamic lists
impl<State, Msg, V> ViewSequence<State> for Vec<V>
where
    V: View<State, Message = Msg>,
{
    type Elements = Vec<V::Element>;
    type Message = Msg;

    fn build(&self, ctx: &mut Context, parent: Node) -> Self::Elements {
        let mut elements = Vec::with_capacity(self.len());
        for view in self {
            let el = view.build(ctx);
            parent.append(ctx, view.get_node(&el));
            elements.push(el);
        }
        elements
    }

    fn rebuild(&self, prev: &Self, ctx: &mut Context, elements: &mut Self::Elements, parent: Node) {
        let min_len = self.len().min(prev.len());

        for i in 0..min_len {
            self[i].rebuild(&prev[i], ctx, &mut elements[i]);
        }

        for i in min_len..self.len() {
            let el = self[i].build(ctx);
            parent.append(ctx, self[i].get_node(&el));
            elements.push(el);
        }

        if self.len() < prev.len() {
            for i in min_len..prev.len() {
                prev[i].teardown(ctx, &mut elements[i]);
            }
            elements.truncate(self.len());
        }
    }

    fn teardown(&self, ctx: &mut Context, elements: &mut Self::Elements) {
        for (view, el) in self.iter().zip(elements.iter_mut()) {
            view.teardown(ctx, el);
        }
    }

    fn handle_event(
        &self,
        elements: &mut Self::Elements,
        state: &State,
        event: Event,
        ctx: &mut Context,
    ) -> (EventResult, Option<Self::Message>) {
        let is_tick = matches!(event, Event::Tick { .. });
        let mut handled = EventResult::Ignored;
        let mut emitted_msg = None;

        for (v, el) in self.iter().zip(elements.iter_mut()) {
            if (is_tick || handled == EventResult::Ignored) && emitted_msg.is_none() {
                let (res, msg) = v.handle_event(el, state, event.clone(), ctx);
                handled = handled.or(res);
                if msg.is_some() {
                    emitted_msg = msg;
                }
            }
        }

        (handled, emitted_msg)
    }
}

// Implement View for Option<V> to support conditional rendering as a standalone View
impl<State, V> View<State> for Option<V>
where
    V: View<State>,
{
    type Element = Option<V::Element>;
    type Message = V::Message;

    fn build(&self, ctx: &mut Context) -> Self::Element {
        self.as_ref().map(|v| v.build(ctx))
    }

    fn rebuild_with_parent(
        &self,
        prev: &Self,
        ctx: &mut Context,
        element: &mut Self::Element,
        parent: Node,
        next_sibling: Option<Node>,
    ) {
        match (self, prev, element) {
            (Some(new_view), Some(old_view), Some(el)) => {
                new_view.rebuild_with_parent(old_view, ctx, el, parent, next_sibling);
            }
            (Some(new_view), _, el_slot @ None) => {
                let el = new_view.build(ctx);
                let node = new_view.get_node(&el);
                if let Some(sibling) = next_sibling {
                    node.put_before(ctx, sibling);
                } else {
                    parent.append(ctx, node);
                }
                *el_slot = Some(el);
            }
            (None, Some(old_view), el_slot @ Some(_)) => {
                if let Some(mut el) = el_slot.take() {
                    let node = old_view.get_node(&el);
                    node.remove(ctx);
                    old_view.teardown(ctx, &mut el);
                }
            }
            _ => {}
        }
    }

    fn rebuild(&self, prev: &Self, ctx: &mut Context, element: &mut Self::Element) {
        match (self, prev, element) {
            (Some(new_view), Some(old_view), Some(el)) => {
                new_view.rebuild(old_view, ctx, el);
            }
            (Some(new_view), _, el_slot @ None) => {
                *el_slot = Some(new_view.build(ctx));
            }
            (None, Some(old_view), el_slot @ Some(_)) => {
                if let Some(mut el) = el_slot.take() {
                    let node = old_view.get_node(&el);
                    node.remove(ctx);
                    old_view.teardown(ctx, &mut el);
                }
            }
            _ => {}
        }
    }

    fn teardown(&self, ctx: &mut Context, element: &mut Self::Element) {
        if let (Some(view), Some(el)) = (self.as_ref(), element) {
            view.teardown(ctx, el);
        }
    }

    fn get_node(&self, element: &Self::Element) -> Node {
        if let (Some(view), Some(el)) = (self.as_ref(), element) {
            view.get_node(el)
        } else {
            Node::get_invalid()
        }
    }

    fn handle_event(
        &self,
        element: &mut Self::Element,
        state: &State,
        event: Event,
        ctx: &mut Context,
    ) -> (EventResult, Option<Self::Message>) {
        if let (Some(view), Some(el)) = (self.as_ref(), element) {
            view.handle_event(el, state, event, ctx)
        } else {
            (EventResult::Ignored, None)
        }
    }
}

// Implement ViewSequence for Option<V> to support conditional rendering
impl<State, V> ViewSequence<State> for Option<V>
where
    V: View<State>,
{
    type Elements = Option<V::Element>;
    type Message = V::Message;

    fn build(&self, ctx: &mut Context, parent: Node) -> Self::Elements {
        if let Some(view) = self {
            let el = view.build(ctx);
            parent.append(ctx, view.get_node(&el));
            Some(el)
        } else {
            None
        }
    }

    fn rebuild(&self, prev: &Self, ctx: &mut Context, elements: &mut Self::Elements, parent: Node) {
        match (self, prev, elements) {
            (Some(new_view), Some(old_view), Some(el)) => {
                new_view.rebuild_with_parent(old_view, ctx, el, parent, None);
            }
            (Some(new_view), _, el_slot @ None) => {
                let el = new_view.build(ctx);
                parent.append(ctx, new_view.get_node(&el));
                *el_slot = Some(el);
            }
            (None, Some(old_view), el_slot @ Some(_)) => {
                if let Some(mut el) = el_slot.take() {
                    let node = old_view.get_node(&el);
                    node.remove(ctx);
                    old_view.teardown(ctx, &mut el);
                }
            }
            _ => {}
        }
    }

    fn teardown(&self, ctx: &mut Context, elements: &mut Self::Elements) {
        if let (Some(view), Some(el)) = (self, elements) {
            view.teardown(ctx, el);
        }
    }

    fn handle_event(
        &self,
        elements: &mut Self::Elements,
        state: &State,
        event: Event,
        ctx: &mut Context,
    ) -> (EventResult, Option<Self::Message>) {
        if let (Some(view), Some(el)) = (self, elements) {
            view.handle_event(el, state, event, ctx)
        } else {
            (EventResult::Ignored, None)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ui::widgets::{button, row};

    #[test]
    fn test_vec_view_sequence_grow_and_shrink() {
        let mut ctx = Context::new();
        let list5: Vec<_> = (0..5).map(|i| button::<_, ()>(format!("{i}"))).collect();
        let list6: Vec<_> = (0..6).map(|i| button::<_, ()>(format!("{i}"))).collect();

        let row_view5 = row(list5);
        let row_view6 = row(list6);

        let mut el = View::<()>::build(&row_view5, &mut ctx);
        View::<()>::rebuild(&row_view6, &row_view5, &mut ctx, &mut el);
        View::<()>::teardown(&row_view6, &mut ctx, &mut el);
    }

    #[test]
    fn test_option_view_sequence_sibling_ordering() {
        use crate::ui::widgets::{Text, column, text};

        type OptText = Option<Text<()>>;

        let mut ctx = Context::new();

        // 1. Initial: Slot 0 (BANNER), Slot 1 (music_dir), Slot 2 (None), Slot 3 (None), Slot 4 (log)
        let view_1 = column((
            text::<_, ()>("BANNER"),
            Some(text::<_, ()>("music_dir")),
            None as OptText,
            None as OptText,
            text::<_, ()>("log"),
        ));

        let mut el = View::<()>::build(&view_1, &mut ctx);
        let parent_node = View::<()>::get_node(&view_1, &el);

        let initial_children = parent_node.children(&ctx);
        assert_eq!(initial_children.len(), 3);
        let banner_node = initial_children[0];
        let music_node = initial_children[1];
        let log_node = initial_children[2];

        // 2. Rebuild: Slot 1 becomes None, Slot 2 becomes Some("progress_bar")
        let view_2 = column((
            text::<_, ()>("BANNER"),
            None as OptText,
            Some(text::<_, ()>("progress_bar")),
            None as OptText,
            text::<_, ()>("log"),
        ));

        View::<()>::rebuild(&view_2, &view_1, &mut ctx, &mut el);

        let updated_children = parent_node.children(&ctx);
        assert_eq!(updated_children.len(), 3);
        assert_eq!(updated_children[0], banner_node);
        // Progress bar MUST be inserted before log, preserving declaration order!
        let progress_node = updated_children[1];
        assert_ne!(progress_node, music_node);
        assert_eq!(updated_children[2], log_node);

        View::<()>::teardown(&view_2, &mut ctx, &mut el);
    }
}