window_of_opportunity 0.3.2

window_of_opportunity is attempting to make a native react style library
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use std::{collections::HashMap, rc::Rc, sync::Arc};

use crate::{component::Component, state::Handler};

#[derive(Debug, Clone)]
pub struct Element {
    pub element_type: ElementType,
    pub props: Props,
    /// events attached to this element, by prop name (on_click, on_resize).
    /// Rc-cloned into the tree each render — cheap, and stale copies are
    /// harmless (they address state slots by key).
    pub handlers: HashMap<String, Handler>,
    pub children: Vec<Box<Element>>,
}

#[derive(Debug, Clone)]
pub enum ElementType {
    Window,
    Button,
    Div,
    Text(String),
    Input,
    Image,
    List,
    /// A component invocation, as a tree node — expanded by the framework
    /// during render with access to state. (Rc so the enum stays Clone-able.)
    Component(Rc<dyn Component>),
}

/// Window-level props, parsed from the tree root (the Window element).
/// Parsed once before the window exists — style masks (resizability) can only be
/// set at creation — and again on every render, since sizing is live.
pub struct WindowSpec {
    pub width: Option<f64>,
    pub height: Option<f64>,
    pub resizable: bool,
    pub title: String,
}

pub fn window_spec(tree: &Element) -> WindowSpec {
    WindowSpec {
        width: tree.props.get_float(PropType::Width),
        height: tree.props.get_float(PropType::Height),
        title: tree
            .props
            .get_string(PropType::Title)
            .unwrap_or_default()
            .to_string(),
        resizable: tree.props.get_bool(PropType::Resizable).unwrap_or(true),
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Prop {
    Float(f64),
    Usize(usize),
    String(String),
    Bool(bool),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
pub enum PropType {
    Width,
    Height,
    Title,
    Resizable,
    Background,
    Rows,
    Color,
    FontSize,
    Value,
    Placeholder,
    Source,
    Direction,
    Gap,
    Padding,
    Grow,
}

#[derive(Debug, Clone, Default)]
pub struct Props(HashMap<PropType, Prop>);

impl Props {
    pub fn new() -> Self {
        Props::default()
    }
    pub fn insert(&mut self, prop_type: PropType, prop: Prop) {
        self.0.insert(prop_type, prop);
    }
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
    pub fn get_string(&self, prop: PropType) -> Option<&str> {
        if let Some(Prop::String(value)) = self.0.get(&prop) {
            Some(value)
        } else {
            None
        }
    }
    pub fn get(&self, prop: PropType) -> Option<&Prop> {
        self.0.get(&prop)
    }
    pub fn get_usize(&self, prop: PropType) -> Option<usize> {
        if let Some(Prop::Usize(val)) = self.0.get(&prop) {
            Some(*val)
        } else {
            None
        }
    }
    pub fn get_float(&self, prop: PropType) -> Option<f64> {
        if let Some(Prop::Float(val)) = self.0.get(&prop) {
            Some(*val)
        } else {
            None
        }
    }
    pub fn get_bool(&self, prop: PropType) -> Option<bool> {
        if let Some(Prop::Bool(val)) = self.0.get(&prop) {
            Some(*val)
        } else {
            None
        }
    }
}

/// ui! macro for easily creating ui element trees. The return type is `Box<window_of_opportunity::element::Element>`
///
/// You can reference a custom component (which must implement `Component`)
/// ```
/// use window_of_opportunity::{
/// element::Element,
/// ui,
/// };
///
/// #[derive(Debug, Default)]
/// struct CustomComponent {}
///
/// impl window_of_opportunity::component::Component for CustomComponent {
///     fn render(&self, ctx: &window_of_opportunity::state::Ctx, mut children: Vec<Box<window_of_opportunity::element::Element>>) -> Box<window_of_opportunity::element::Element> {
///         if children.is_empty() {
///             ui! { Button {{ Text { "Click Me" }}}}
///         } else {
///             let child = children.remove(0);
///             ui! {
///                 Div { CHILDREN child }
///             }
///         }
///         // note any children passed to the component are captured with the literal `CHILDREN` - one child at a time
///     }
/// }
///
/// let my_tree = ui! {
///    Window width(400.) {
///         {
///             Div {
///                 { CustomComponent }
///             }
///         }

/// }};
/// ```
/// *Note* `width(400.)` is a prop. Other props shown below.
///
/// All elements apart from Text can have children. Children are a set of `{}` surrounded by an initial set of `{}`
///
/// Elements and their props:
/// * Window
///     * `title(string)`
///     * `on_resize(|&State, w: f64, h: f64)`
/// * Div
///     * `direction(string - column/row)`
/// * Button
///     * `on_click(window_of_opportunity::state::Event)`
/// * Input
///     * `placeholder(string)`
///     * `on_change(|&State, String|)`
/// * Image
/// * List
///     * `rows(int)`
///     * `on_display_item(|Ctx, usize| -> Box<window_of_opportunity::element::Element>)`
/// * Text
///     * `color(string)`
///     * `font_size(int)`
///
/// In addition, there are generic props that can be applied to all elements:
/// * `gap(f64)` for space between multiple siblings (not the beginning or end)
/// * `height(f64)`
/// * `width(f64)`
/// * `padding(f64)`
/// * `background(string)`
///
#[macro_export]
macro_rules! ui {
    (Window $($val:tt) *) => {
        ui! { @element Window $($val)* }
    };
    (Div $($val:tt) *) => {
        ui! { @element Div $($val)* }
    };
    (Button $($val:tt) *) => {
        ui! { @element Button $($val)* }
    };
    (Input $($val:tt) *) => {
        ui! { @element Input $($val)* }
    };
    (Image $($val:tt) *) => {
        ui! { @element Image $($val)* }
    };
    (List $($val:tt) *) => {
        ui! { @element List $($val)* }
    };
    // Text with props — content is BRACED, the same convention as children
    // on the other elements: Text color("blue") font_size(10) { content }
    // The braces are load-bearing: without them a call-shaped content
    // (helper(x), item.clone()) is indistinguishable from one more prop at
    // the ident/expr boundary, and rustc raises a local-ambiguity error.
    // Props are RECORDED via @prop — same machinery as every other element
    // — so they're available to rendering later; whether a label honors
    // background/color is a separate, rendering-side task.
    (Text $($prop:ident ($($val:tt)*))* { $contents:expr }) => {
        {
            use std::collections::HashMap;
            let mut el = $crate::element::Element {
                element_type: $crate::element::ElementType::Text($contents.into()),
                props: $crate::element::Props::new(),
                handlers: HashMap::new(),
                children: vec![],
            };
            $( ui!(@prop el, $prop ($($val)*)); )*
            Box::new(el)
        }
    };
    (Text $contents:expr) => {
        {
            use std::collections::HashMap;
            Box::new($crate::element::Element {
                element_type: $crate::element::ElementType::Text($contents.into()),
                props: $crate::element::Props::new(),
                handlers: HashMap::new(),
                children: vec![],
            })
        }
    };
    (CHILDREN $expr:expr) => {
        $expr
    };
    // A bare component invocation: a component with no children.
    // Components are constructed via `Default` + field assignment (see the
    // props arms below): `Default` goes on the component STRUCT — it can't
    // be a `Component` supertrait, because `Default` isn't object-safe and
    // `ElementType::Component` holds `Rc<dyn Component>`.
    ($comp:ident) => {
        {
            use std::collections::HashMap;
            // A component invocation stays as a tree node — the framework
            // expands it with current state during render (see `expand`).
            // (Macro hygiene: the macro can't reference the caller's `state`
            // directly, so expansion happens outside the macro.)
            Box::new($crate::element::Element {
                element_type: $crate::element::ElementType::Component(std::rc::Rc::new($comp::default())),
                props: $crate::element::Props::new(),
                handlers: HashMap::new(),
                children: vec![],
            })
        }
    };
    // A component invocation with children: TodoView { { Text "hi" } }
    ($comp:ident { $($inner:tt)* }) => {
        {
            use std::collections::HashMap;
            let mut el = $crate::element::Element {
                element_type: $crate::element::ElementType::Component(std::rc::Rc::new($comp::default())),
                props: $crate::element::Props::new(),
                handlers: HashMap::new(),
                children: vec![],
            };
            ui!(@children el, $($inner)*);
            Box::new(el)
        }
    };
    // A component invocation with props and children:
    //   TodoView title("hi") count(3) { { Text "x" } }
    // Prop names are FIELD names; values are arbitrary expressions moved
    // into the fields (custom types welcome — no cloning, no erasure).
    // Fields must be visible at the call site (pub, or same module), and
    // unspecified fields keep their `Default` — hand-write `Default` if a
    // field's type doesn't implement it.
    ($comp:ident $($field:ident ($($val:tt)*))+ { $($inner:tt)* }) => {
        {
            use std::collections::HashMap;
            let mut comp = $comp::default();
            $( comp.$field = ($($val)*); )*
            let mut el = $crate::element::Element {
                element_type: $crate::element::ElementType::Component(std::rc::Rc::new(comp)),
                props: $crate::element::Props::new(),
                handlers: HashMap::new(),
                children: vec![],
            };
            ui!(@children el, $($inner)*);
            Box::new(el)
        }
    };
    // A component invocation with props, no children: TodoView count(3)
    ($comp:ident $($field:ident ($($val:tt)*))+) => {
        {
            use std::collections::HashMap;
            let mut comp = $comp::default();
            $( comp.$field = ($($val)*); )*
            Box::new($crate::element::Element {
                element_type: $crate::element::ElementType::Component(std::rc::Rc::new(comp)),
                props: $crate::element::Props::new(),
                handlers: HashMap::new(),
                children: vec![],
            })
        }
    };
    // element with props and a braced child list:
    //   Div direction("row") gap(10.) { ... }
    (@element $el:ident $($prop:ident ($($val:tt)*))* { $($children:tt)* }) => {
        {
            use std::collections::HashMap;
            let mut el = $crate::element::Element {
                element_type: $crate::element::ElementType::$el,
                props: $crate::element::Props::new(),
                handlers: HashMap::new(),
                children: vec![],
            };
            $( ui!(@prop el, $prop ($($val)*)); )*
            ui!(@children el, $($children)*);
            Box::new(el)
        }
    };
    // element with props, no children: Div height(80.) background("blue")
    (@element $el:ident $($prop:ident ($($val:tt)*))*) => {
        {
            use std::collections::HashMap;
            let mut el = $crate::element::Element {
                element_type: $crate::element::ElementType::$el,
                props: $crate::element::Props::new(),
                handlers: HashMap::new(),
                children: vec![],
            };
            $( ui!(@prop el, $prop ($($val)*)); )*
            Box::new(el)
        }
    };
    // ---- prop parsing ----
    // Handler props hold handler closures; every other prop is TYPED — each
    // arm names its PropType and Prop variant, and `@type_prop` inserts the
    // value (`.into()` type-checks at the call site).
    (@prop $el:ident, on_click($($val:tt)*)) => {
        $el.handlers.insert("on_click".to_string(), $crate::state::Handler::Simple(($($val)*)));
    };
    // on_resize takes |state, w, h| — it runs on every resize tick
    (@prop $el:ident, on_resize($($val:tt)*)) => {
        $el.handlers
            .insert("on_resize".to_string(), $crate::state::Handler::Resize(std::rc::Rc::new(($($val)*))));
    };
    // on_change takes |state, text| — it fires on each keystroke
    (@prop $el:ident, on_change($($val:tt)*)) => {
        $el.handlers
            .insert("on_change".to_string(), $crate::state::Handler::Change(std::rc::Rc::new(($($val)*))));
    };
    (@prop $el:ident, on_display_item($($val:tt)*)) => {
        $el.handlers
            .insert("on_display_item".to_string(), $crate::state::Handler::ListItem(std::rc::Rc::new(($($val)*))));
    };
    (@prop $el:ident, background($($val:tt)*)) => {
        ui!(@type_prop $el Background String ($($val)*));
    };
    (@prop $el:ident, rows($($val:tt)*)) => {
        ui!(@type_prop $el Rows Usize ($($val)*));
    };
    (@prop $el:ident, width($($val:tt)*)) => {
        ui!(@type_prop $el Width Float ($($val)*));
    };
    (@prop $el:ident, height($($val:tt)*)) => {
        ui!(@type_prop $el Height Float ($($val)*));
    };
    (@prop $el:ident, padding($($val:tt)*)) => {
        ui!(@type_prop $el Padding Float ($($val)*));
    };
    (@prop $el:ident, grow($($val:tt)*)) => {
        ui!(@type_prop $el Grow Bool ($($val)*));
    };
    (@prop $el:ident, resizable($($val:tt)*)) => {
        ui!(@type_prop $el Resizable Bool ($($val)*));
    };
    (@prop $el:ident, src($($val:tt)*)) => {
        ui!(@type_prop $el Source String ($($val)*));
    };
    (@prop $el:ident, gap($($val:tt)*)) => {
        ui!(@type_prop $el Gap Float ($($val)*));
    };
    (@prop $el:ident, font_size($($val:tt)*)) => {
        ui!(@type_prop $el FontSize Float ($($val)*));
    };
    (@prop $el:ident, direction($($val:tt)*)) => {
        ui!(@type_prop $el Direction String ($($val)*));
    };
    (@prop $el:ident, value($($val:tt)*)) => {
        ui!(@type_prop $el Value String ($($val)*));
    };
    (@prop $el:ident, placeholder($($val:tt)*)) => {
        ui!(@type_prop $el Placeholder String ($($val)*));
    };
    (@prop $el:ident, title($($val:tt)*)) => {
        ui!(@type_prop $el Title String ($($val)*));
    };
    (@prop $el:ident, color($($val:tt)*)) => {
        ui!(@type_prop $el Color String ($($val)*));
    };
    // An unknown prop fails LOUDLY at the call site — with a message,
    // not with a missing-variant error from inside this macro.
    (@prop $el:ident, $prop:ident($($val:tt)*)) => {
        compile_error!(concat!(
            "unknown prop `", stringify!($prop),
            "` — known props: width, height, padding, gap, grow, direction, background, color, font_size, title, value, placeholder, src, resizable, rows",
            " (handlers: on_click, on_resize, on_change, on_display_item)"
        ));
    };
    (@type_prop $el:ident $prop:ident $prop_type:ident ($($val:tt)*)) => {
        $el.props.insert($crate::element::PropType::$prop, $crate::element::Prop::$prop_type($($val.into())*));
    };
    // ---- child-list parsing ----
    // macro_rules can't know where one child ends and the next begins when
    // children are multi-token (`Div height(80.) {}` is 3+ tts), so child
    // elements must be wrapped in braces (one group = one child). Bare `Text`
    // literals, `CHILDREN` splices, and bare components with children are
    // recognized without braces.
    (@children $v:ident,) => {};
    (@children $v:ident, Text $text:literal $($rest:tt)*) => {
        $v.children.push(ui!(Text $text));
        ui!(@children $v, $($rest)*);
    };
    (@children $v:ident, { $($inner:tt)* } $($rest:tt)*) => {
        $v.children.push(ui! { $($inner)* });
        ui!(@children $v, $($rest)*);
    };
    (@children $v:ident, CHILDREN $splice:ident $($rest:tt)*) => {
        $v.children.push($splice);
        ui!(@children $v, $($rest)*);
    };
    (@children $v:ident, $comp:ident { $($inner:tt)* } $($rest:tt)*) => {
        $v.children.push(ui!($comp { $($inner)* }));
        ui!(@children $v, $($rest)*);
    };
    // ---- expression children ----
    // LAST arm, on purpose: anything that isn't an element, Text, the
    // CHILDREN splice, a component invocation, or an internal @-rule is an
    // expression evaluating to Box<Element>. So a match, an if, a function
    // call, or a parenthesized prebuilt element works directly as a child:
    //   { match flag { A => ui!{ Text "a" }, B => ui!{ Text "b" } } }
    // (A *bare* identifier stays a component invocation — splice a binding
    // instead with { CHILDREN my_element }.)
    ($expr:expr) => {
        {
            // the annotation turns "expected struct Element, found i32" into
            // an error pointing at the child expression itself
            let child: Box<$crate::element::Element> = $expr;
            child
        }
    };
}

/// Somewhere to hold some pixel data, to then add as src on an Image.
/// (`src` on the Image element names the slot). `version` ticks per frame so
/// the image widget can skip re-blitting unchanged data.
#[derive(Clone)]
pub struct BlitFrame {
    pub width: usize,
    pub height: usize,
    pub samples: u64,
    pub pixels: Arc<Vec<u8>>,
    pub version: u64,
}

impl BlitFrame {
    pub fn empty() -> Self {
        BlitFrame {
            width: 0,
            height: 0,
            samples: 0,
            pixels: Arc::new(Vec::new()),
            version: 0,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn helper(_x: usize) -> String {
        "helper!".to_string()
    }

    #[test]
    fn text_props_are_recorded_and_content_survives() {
        let el = crate::ui! { Text background("blue") { "Complete".to_string() } };
        assert_eq!(
            el.props.get_string(PropType::Background),
            Some("blue"),
            "prop must land in el.props"
        );
        assert!(
            matches!(&el.element_type, ElementType::Text(t) if t == "Complete"),
            "content must survive: {:?}",
            el.element_type
        );
    }

    #[test]
    fn text_plain_content_forms() {
        // literal, field access, macro call, plain call expression — the call
        // form is the ambiguous one vs. prop syntax, and must read as content
        let el = crate::ui! { Text "plain" };
        assert!(matches!(&el.element_type, ElementType::Text(t) if t == "plain"));

        let el = crate::ui! { Text helper(3) };
        assert!(matches!(&el.element_type, ElementType::Text(t) if t == "helper!"));

        let el = crate::ui! { Text format!("number: {}", 3) };
        assert!(matches!(&el.element_type, ElementType::Text(t) if t == "number: 3"));

        let item = String::from("field");
        let el = crate::ui! { Text item.clone() };
        assert!(matches!(&el.element_type, ElementType::Text(t) if t == "field"));
        assert!(
            el.props.is_empty(),
            "no props on plain content: {:?}",
            el.props
        );

        // multiple props + content: content goes in braces (see the macro
        // arm — unbraced content after props is ambiguous and won't compile)
        let el = crate::ui! { Text width(1) height(2) { item.clone() } };
        assert!(matches!(&el.element_type, ElementType::Text(t) if t == "field"));
        assert_eq!(el.props.get_float(PropType::Width), Some(1.));
        assert_eq!(el.props.get_float(PropType::Height), Some(2.));
    }
}
// (appended coverage for the typed-prop arms)
#[cfg(test)]
mod typed_prop_tests {
    #[test]
    fn every_framework_consumed_prop_has_an_arm() {
        // these three props are read by layout/window_spec/Image mount —
        // if a macro arm goes missing, this test fails to compile
        let el = crate::ui! { Image src("slot") width(2.) };
        assert_eq!(
            el.props.get_string(crate::element::PropType::Source),
            Some("slot")
        );

        let el = crate::ui! { Div grow(true) gap(4.) { { crate::ui! { Text "x" } } } };
        assert_eq!(
            el.props.get_bool(crate::element::PropType::Grow),
            Some(true)
        );
        assert_eq!(el.props.get_float(crate::element::PropType::Gap), Some(4.));

        let el = crate::ui! { Window width(400.) resizable(false) };
        assert_eq!(
            el.props.get_bool(crate::element::PropType::Resizable),
            Some(false)
        );
    }
}

// (component props: custom types, partial props, hand-written Default)
#[cfg(test)]
mod component_prop_tests {
    use crate::component::Component;

    #[derive(Debug)]
    struct Tag(&'static str); // deliberately NOT Default

    #[derive(Debug)]
    struct Fancy {
        tag: Tag,
        count: usize,
        label: String,
    }

    // hand-written Default: fields with non-Default types are fine as long as
    // this constructor supplies them
    impl Default for Fancy {
        fn default() -> Self {
            Self {
                tag: Tag("none"),
                count: 0,
                label: String::new(),
            }
        }
    }

    impl Component for Fancy {
        fn render(
            &self,
            _ctx: &crate::state::Ctx,
            _children: Vec<Box<crate::element::Element>>,
        ) -> Box<crate::element::Element> {
            crate::ui! { Text self.label.clone() }
        }
    }

    #[test]
    fn component_props_are_fields_with_custom_types() {
        // partial props: count set, label keeps its Default
        let el = crate::ui! { Fancy tag(Tag("hi")) count(2) };
        let debug = format!("{:?}", el.element_type);
        assert!(debug.contains("hi"), "custom type landed: {debug}");
        assert!(debug.contains("count: 2"), "primitive landed: {debug}");
        assert!(debug.contains("label: \"\""), "unset field kept Default: {debug}");

        // bare usage goes through Default too
        let el = crate::ui! { Fancy };
        let debug = format!("{:?}", el.element_type);
        assert!(debug.contains("tag: Tag(\"none\")"), "bare = Default: {debug}");

        // props + children both
        let el = crate::ui! { Fancy count(7) { { crate::ui! { Text "child" } } } };
        assert_eq!(el.children.len(), 1);
    }
}