zng_app/widget/node/
extend.rs

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
use std::sync::Arc;

use parking_lot::Mutex;
use zng_app_proc_macros::ui_node;

use crate::widget::WidgetUpdateMode;

use super::*;

/// Create a widget node that wraps the `widget` with any number of other non-widget nodes and
/// still delegates [`with_context`] to the `widget`.
///
/// Note that the [`with_context`] is called in the context of `widget`, not in the context of the `build_extension` nodes.
/// Other node operations are delegated to the `build_extension` nodes, and they in turn must delegate to the input child
/// node that is `widget`.
///
/// [`with_context`]: UiNode::with_context
pub fn extend_widget(widget: impl UiNode, build_extension: impl FnOnce(BoxedUiNode) -> BoxedUiNode) -> impl UiNode {
    let widget = Arc::new(Mutex::new(widget.boxed()));
    let child = build_extension(ExtendWidgetChildNode { widget: widget.clone() }.boxed());
    ExtendWidgetNode { widget, child }
}

struct ExtendWidgetChildNode {
    widget: Arc<Mutex<BoxedUiNode>>,
}
#[ui_node(delegate = self.widget.lock())]
impl UiNode for ExtendWidgetChildNode {
    fn is_widget(&self) -> bool {
        self.widget.lock().is_widget()
    }

    fn with_context<R, F>(&mut self, update_mode: WidgetUpdateMode, f: F) -> Option<R>
    where
        F: FnOnce() -> R,
    {
        self.widget.lock().with_context(update_mode, f)
    }
}

struct ExtendWidgetNode {
    widget: Arc<Mutex<BoxedUiNode>>,
    child: BoxedUiNode,
}
#[ui_node(child)]
impl UiNode for ExtendWidgetNode {
    fn is_widget(&self) -> bool {
        self.widget.lock().is_widget()
    }

    fn with_context<R, F>(&mut self, update_mode: WidgetUpdateMode, f: F) -> Option<R>
    where
        F: FnOnce() -> R,
    {
        self.widget.lock().with_context(update_mode, f)
    }
}