anathema-widgets 0.2.11

Anathema widget base
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
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
use std::any::Any;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::time::Duration;

use anathema_state::{State, StateId, Value as StateValue};
use anathema_store::slab::Slab;
use anathema_templates::strings::{StringId, Strings};
use anathema_templates::{AssocEventMapping, ComponentBlueprintId};
use anathema_value_resolver::{Attributes, ValueKind};
use deferred::DeferredComponents;
use flume::SendError;

use self::events::{Event, KeyEvent, MouseEvent};
use crate::WidgetId;
use crate::layout::Viewport;
use crate::query::Children;
use crate::widget::Parent;

pub mod deferred;
pub mod events;

pub type ComponentFn = dyn Fn() -> Box<dyn AnyComponent>;
pub type StateFn = dyn FnMut() -> Box<dyn State>;

enum ComponentType {
    Component(Option<Box<dyn AnyComponent>>, Option<Box<dyn State>>),
    Prototype(Box<ComponentFn>, Box<StateFn>),
}

/// Store component factories.
/// This is how components are created.
pub struct ComponentRegistry(Slab<ComponentBlueprintId, ComponentType>);

impl ComponentRegistry {
    pub fn new() -> Self {
        Self(Slab::empty())
    }

    /// Both `add_component` and `add_prototype` are using `Slab::insert_at`.
    ///
    /// This is fine as the component ids are generated at the same time.
    pub fn add_component<S: State>(&mut self, id: ComponentBlueprintId, component: impl Component + 'static, state: S) {
        let comp_type = ComponentType::Component(Some(Box::new(component)), Some(Box::new(state)));
        self.0.insert_at(id, comp_type);
    }

    pub fn add_prototype<FC, FS, C, S>(&mut self, id: ComponentBlueprintId, proto: FC, mut state: FS)
    where
        FC: 'static + Fn() -> C,
        FS: 'static + FnMut() -> S,
        C: Component + 'static,
        S: State + 'static,
    {
        let comp_type =
            ComponentType::Prototype(Box::new(move || Box::new(proto())), Box::new(move || Box::new(state())));

        self.0.insert_at(id, comp_type);
    }

    // # Panics
    //
    // Panics if the component isn't registered.
    // This shouldn't happen as the statement eval should catch this.
    pub(super) fn get(
        &mut self,
        id: ComponentBlueprintId,
    ) -> Option<(ComponentKind, Box<dyn AnyComponent>, Box<dyn State>)> {
        match self.0.get_mut(id) {
            Some(component) => match component {
                ComponentType::Component(comp, state) => Some((ComponentKind::Instance, comp.take()?, state.take()?)),
                ComponentType::Prototype(proto, state) => Some((ComponentKind::Prototype, proto(), state())),
            },
            None => panic!(),
        }
    }

    /// Return a component back to the registry.
    ///
    /// # Panics
    ///
    /// Panics if the component entry doesn't exist or if the entry is for a prototype.
    pub fn return_component(
        &mut self,
        id: ComponentBlueprintId,
        current_component: Box<dyn AnyComponent>,
        current_state: Box<dyn State>,
    ) {
        match self.0.get_mut(id) {
            Some(component) => match component {
                ComponentType::Component(comp, state) => {
                    *comp = Some(current_component);
                    *state = Some(current_state);
                }
                ComponentType::Prototype(..) => {
                    // Can't return a prototype
                }
            },
            None => panic!(),
        }
    }
}

#[derive(Debug)]
pub struct ComponentId<T>(pub(crate) ComponentBlueprintId, pub(crate) PhantomData<T>);

impl<T> From<ComponentBlueprintId> for ComponentId<T> {
    fn from(value: ComponentBlueprintId) -> Self {
        Self(value, PhantomData)
    }
}

impl<T> Clone for ComponentId<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for ComponentId<T> {}

pub struct ViewMessage {
    pub(super) payload: Box<dyn Any + Send + Sync>,
    pub(super) recipient: Recipient,
}

impl ViewMessage {
    pub fn recipient(&self) -> Recipient {
        self.recipient
    }

    pub fn payload(self) -> Box<dyn Any + Send + Sync> {
        self.payload
    }
}

#[derive(Debug, Copy, Clone)]
pub enum Recipient {
    ComponentId(ComponentBlueprintId),
    WidgetId(WidgetId),
}

#[derive(Debug, Clone)]
pub struct Emitter(pub(crate) flume::Sender<ViewMessage>);

impl From<flume::Sender<ViewMessage>> for Emitter {
    fn from(value: flume::Sender<ViewMessage>) -> Self {
        Self(value)
    }
}

pub type MessageReceiver = flume::Receiver<ViewMessage>;

impl Emitter {
    pub fn new() -> (Self, MessageReceiver) {
        let (tx, rx) = flume::unbounded();
        (Self(tx), rx)
    }

    /// Emit a message to a component via a `ComponentId<T>`
    pub fn emit<T: 'static + Send + Sync>(
        &self,
        component_id: ComponentId<T>,
        value: T,
    ) -> Result<(), SendError<ViewMessage>> {
        let msg = ViewMessage {
            payload: Box::new(value),
            recipient: Recipient::ComponentId(component_id.0),
        };
        self.0.send(msg)
    }

    /// Emit a message to a component via a `ComponentId<T>` asynchronously
    pub async fn emit_async<T: 'static + Send + Sync>(
        &self,
        component_id: ComponentId<T>,
        value: T,
    ) -> Result<(), SendError<ViewMessage>> {
        let msg = ViewMessage {
            payload: Box::new(value),
            recipient: Recipient::ComponentId(component_id.0),
        };
        self.0.send_async(msg).await
    }

    /// Try to emit a message to a component via its `WidgetId`.
    /// Unlike the `emit` function there is no type associated with the widget id,
    /// and the message will fail to deliver silently if the wrong type is used.
    pub fn try_emit<T: 'static + Send + Sync>(
        &self,
        widget_id: WidgetId,
        value: T,
    ) -> Result<(), SendError<ViewMessage>> {
        let msg = ViewMessage {
            payload: Box::new(value),
            recipient: Recipient::WidgetId(widget_id),
        };
        self.0.send(msg)
    }

    /// Async counterpart of `try_emit`.
    pub async fn try_emit_async<T: 'static + Send + Sync>(
        &self,
        widget_id: WidgetId,
        value: T,
    ) -> Result<(), SendError<ViewMessage>> {
        let msg = ViewMessage {
            payload: Box::new(value),
            recipient: Recipient::WidgetId(widget_id),
        };
        self.0.send_async(msg).await
    }
}

pub struct Context<'frame, 'bp, T> {
    inner: AnyComponentContext<'frame, 'bp>,
    _p: PhantomData<T>,
}

impl<'frame, 'bp, T: 'static> Context<'frame, 'bp, T> {
    pub fn new(inner: AnyComponentContext<'frame, 'bp>) -> Self {
        Self { inner, _p: PhantomData }
    }

    /// Publish an event
    ///
    /// # Panics
    ///
    /// This will panic if the shared value is exclusively borrowed
    /// at the time of the invocation.
    pub fn publish<D: 'static>(&mut self, ident: &str, data: D) {
        // If there is no parent there is no one to emit the event to.
        let Some(parent) = self.parent else { return };

        let Some(ident_id) = self.inner.strings.lookup(ident) else { return };

        let ids = self.assoc_functions.iter().find(|assoc| assoc.internal == ident_id);

        let Some(assoc_event_map) = ids else { return };

        self.inner.assoc_events.push(
            self.state_id,
            parent,
            *assoc_event_map,
            self.ident_id,
            self.widget_id,
            data,
        );
    }

    /// Get a value from the component attributes
    pub fn attribute(&self, key: &str) -> Option<&ValueKind<'_>> {
        self.attributes.get(key)
    }

    /// Send a message to a given component
    pub fn emit<M: 'static + Send + Sync>(&self, recipient: ComponentId<M>, value: M) {
        self.emitter
            .emit(recipient, value)
            .expect("this will not fail unless the runtime is dropped")
    }
}

impl<'frame, 'bp, T> Deref for Context<'frame, 'bp, T> {
    type Target = AnyComponentContext<'frame, 'bp>;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'frame, 'bp, T> DerefMut for Context<'frame, 'bp, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

pub struct AnyComponentContext<'frame, 'bp> {
    parent: Option<Parent>,
    ident_id: StringId,
    pub widget_id: WidgetId,
    state_id: StateId,
    assoc_functions: &'frame [AssocEventMapping],
    assoc_events: &'frame mut AssociatedEvents,
    pub attributes: &'frame mut Attributes<'bp>,
    state: Option<&'frame mut StateValue<Box<dyn State>>>,
    pub emitter: &'frame Emitter,
    pub viewport: &'frame Viewport,
    pub strings: &'frame Strings,
    pub components: &'frame mut DeferredComponents,
    stop_runtime: &'frame mut bool,
}

impl<'frame, 'bp> AnyComponentContext<'frame, 'bp> {
    pub fn new(
        parent: Option<Parent>,
        ident_id: StringId,
        sender_id: WidgetId,
        state_id: StateId,
        assoc_functions: &'frame [AssocEventMapping],
        assoc_events: &'frame mut AssociatedEvents,
        components: &'frame mut DeferredComponents,
        attributes: &'frame mut Attributes<'bp>,
        state: Option<&'frame mut StateValue<Box<dyn State>>>,
        emitter: &'frame Emitter,
        viewport: &'frame Viewport,
        stop_runtime: &'frame mut bool,
        strings: &'frame Strings,
    ) -> Self {
        Self {
            parent,
            ident_id,
            widget_id: sender_id,
            state_id,
            assoc_functions,
            assoc_events,
            attributes,
            components,
            state,
            emitter,
            viewport,
            strings,
            stop_runtime,
        }
    }

    pub fn parent(&self) -> Option<Parent> {
        self.parent
    }

    pub fn stop_runtime(&mut self) {
        *self.stop_runtime = true;
    }
}

pub struct AssociatedEvent {
    pub state: StateId,
    pub parent: Parent,
    pub sender: StringId,
    pub sender_id: WidgetId,
    event_map: AssocEventMapping,
    data: Box<dyn Any>,
}

impl AssociatedEvent {
    pub fn to_event<'a>(
        &'a self,
        internal: &'a str,
        external: &'a str,
        sender: &'a str,
        sender_id: WidgetId,
    ) -> UserEvent<'a> {
        UserEvent {
            external_ident: external,
            internal_ident: internal,
            data: &*self.data,
            sender,
            sender_id,
            stop_propagation: false,
        }
    }

    pub fn external(&self) -> StringId {
        self.event_map.external
    }

    pub fn internal(&self) -> StringId {
        self.event_map.internal
    }
}

#[derive(Debug, Copy, Clone)]
pub struct UserEvent<'a> {
    pub sender: &'a str,
    pub sender_id: WidgetId,
    pub external_ident: &'a str,
    pub internal_ident: &'a str,
    data: &'a dyn Any,
    stop_propagation: bool,
}

impl<'a> UserEvent<'a> {
    pub fn stop_propagation(&mut self) {
        self.stop_propagation = true;
    }

    pub fn name(&self) -> &str {
        self.external_ident
    }

    /// Cast the event payload to a specific type
    ///
    /// # Panics
    ///
    /// This will panic if the type is incorrect
    pub fn data<T: 'static>(&self) -> &'a T {
        match self.data.downcast_ref() {
            Some(data) => data,
            None => panic!("invalid type when casting event data"),
        }
    }

    /// Try to cast the event payload to a specific type
    pub fn data_checked<T: 'static>(&self) -> Option<&'a T> {
        self.data.downcast_ref()
    }

    pub fn should_stop_propagation(&self) -> bool {
        self.stop_propagation
    }
}

// The reason the component can not have access
// to the children during this event is because the parent is borrowing from the
// child's state while this is happening.
pub struct AssociatedEvents {
    inner: Vec<AssociatedEvent>,
}

impl AssociatedEvents {
    pub fn new() -> Self {
        Self { inner: vec![] }
    }

    fn push<T: 'static>(
        &mut self,
        state: StateId,
        parent: Parent,
        assoc_event_map: AssocEventMapping,
        sender: StringId,
        sender_id: WidgetId,
        data: T,
    ) {
        self.inner.push(AssociatedEvent {
            state,
            parent,
            sender,
            sender_id,
            event_map: assoc_event_map,
            data: Box::new(data),
        })
    }

    pub fn next(&mut self) -> Option<AssociatedEvent> {
        self.inner.pop()
    }
}

pub trait Component: 'static {
    type State: State;
    type Message;

    const TICKS: bool = true;

    #[allow(unused_variables, unused_mut)]
    fn on_key(
        &mut self,
        key: KeyEvent,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_mount(
        &mut self,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_unmount(
        &mut self,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_blur(
        &mut self,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_focus(
        &mut self,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_mouse(
        &mut self,
        mouse: MouseEvent,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_tick(
        &mut self,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        context: Context<'_, '_, Self::State>,
        dt: Duration,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_message(
        &mut self,
        message: Self::Message,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_resize(
        &mut self,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    #[allow(unused_variables, unused_mut)]
    fn on_event(
        &mut self,
        event: &mut UserEvent<'_>,
        state: &mut Self::State,
        mut children: Children<'_, '_>,
        mut context: Context<'_, '_, Self::State>,
    ) {
    }

    fn accept_focus(&self) -> bool {
        true
    }
}

impl Component for () {
    type Message = ();
    type State = ();

    const TICKS: bool = false;

    fn accept_focus(&self) -> bool {
        false
    }
}

#[derive(Debug)]
pub enum ComponentKind {
    Instance,
    Prototype,
}

pub trait AnyComponent {
    fn any_event(&mut self, children: Children<'_, '_>, ctx: AnyComponentContext<'_, '_>, ev: Event) -> Event;

    fn any_message(&mut self, children: Children<'_, '_>, ctx: AnyComponentContext<'_, '_>, message: Box<dyn Any>);

    fn any_tick(&mut self, children: Children<'_, '_>, ctx: AnyComponentContext<'_, '_>, dt: Duration);

    fn any_focus(&mut self, children: Children<'_, '_>, ctx: AnyComponentContext<'_, '_>);

    fn any_blur(&mut self, children: Children<'_, '_>, ctx: AnyComponentContext<'_, '_>);

    fn any_resize(&mut self, children: Children<'_, '_>, ctx: AnyComponentContext<'_, '_>);

    fn any_component_event(
        &mut self,
        children: Children<'_, '_>,
        ctx: AnyComponentContext<'_, '_>,
        value: &mut UserEvent<'_>,
    );

    fn any_accept_focus(&self) -> bool;

    fn any_ticks(&self) -> bool;
}

impl<T> AnyComponent for T
where
    T: Component,
    T: 'static,
{
    fn any_event(&mut self, children: Children<'_, '_>, mut ctx: AnyComponentContext<'_, '_>, event: Event) -> Event {
        let mut state = ctx
            .state
            .take()
            .map(|s| s.to_mut_cast::<T::State>())
            .expect("components always have a state");
        let context = Context::<T::State>::new(ctx);
        match event {
            Event::Blur | Event::Focus => (), // Application focus, not component focus.
            Event::Key(ev) => self.on_key(ev, &mut *state, children, context),
            Event::Mouse(ev) => self.on_mouse(ev, &mut *state, children, context),
            Event::Tick(dt) => self.on_tick(&mut *state, children, context, dt),
            Event::Resize(_) => self.on_resize(&mut *state, children, context),
            Event::Mount => self.on_mount(&mut *state, children, context),
            Event::Unmount => self.on_unmount(&mut *state, children, context),
            Event::Noop | Event::Stop => (),
        }
        event
    }

    fn any_accept_focus(&self) -> bool {
        self.accept_focus()
    }

    fn any_ticks(&self) -> bool {
        T::TICKS
    }

    fn any_message(&mut self, children: Children<'_, '_>, mut ctx: AnyComponentContext<'_, '_>, message: Box<dyn Any>) {
        let mut state = ctx
            .state
            .take()
            .map(|s| s.to_mut_cast::<T::State>())
            .expect("components always have a state");
        let Ok(message) = message.downcast::<T::Message>() else { return };
        let context = Context::<T::State>::new(ctx);
        self.on_message(*message, &mut *state, children, context);
    }

    fn any_focus(&mut self, children: Children<'_, '_>, mut ctx: AnyComponentContext<'_, '_>) {
        let mut state = ctx
            .state
            .take()
            .map(|s| s.to_mut_cast::<T::State>())
            .expect("components always have a state");
        let context = Context::<T::State>::new(ctx);
        self.on_focus(&mut *state, children, context);
    }

    fn any_blur(&mut self, children: Children<'_, '_>, mut ctx: AnyComponentContext<'_, '_>) {
        let mut state = ctx
            .state
            .take()
            .map(|s| s.to_mut_cast::<T::State>())
            .expect("components always have a state");
        let context = Context::<T::State>::new(ctx);
        self.on_blur(&mut *state, children, context);
    }

    fn any_tick(&mut self, children: Children<'_, '_>, mut ctx: AnyComponentContext<'_, '_>, dt: Duration) {
        let mut state = ctx
            .state
            .take()
            .map(|s| s.to_mut_cast::<T::State>())
            .expect("components always have a state");
        let context = Context::<T::State>::new(ctx);
        self.on_tick(&mut *state, children, context, dt);
    }

    fn any_resize(&mut self, children: Children<'_, '_>, mut ctx: AnyComponentContext<'_, '_>) {
        let mut state = ctx
            .state
            .take()
            .map(|s| s.to_mut_cast::<T::State>())
            .expect("components always have a state");
        let context = Context::<T::State>::new(ctx);
        self.on_resize(&mut *state, children, context);
    }

    fn any_component_event(
        &mut self,
        children: Children<'_, '_>,
        mut ctx: AnyComponentContext<'_, '_>,
        event: &mut UserEvent<'_>,
    ) {
        let mut state = ctx
            .state
            .take()
            .map(|s| s.to_mut_cast::<T::State>())
            .expect("components always have a state");

        let context = Context::<T::State>::new(ctx);

        self.on_event(event, &mut *state, children, context);
    }
}

impl std::fmt::Debug for dyn AnyComponent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "<dyn AnyComponent>")
    }
}