patternfly_yew/utils/
context.rs

1use std::ops::Deref;
2use yew::{BaseComponent, Callback, Component, Context, ContextHandle};
3
4pub struct ContextWrapper<C>
5where
6    C: Clone + PartialEq + 'static,
7{
8    context: Option<C>,
9    _handle: Option<ContextHandle<C>>,
10}
11
12impl<C> ContextWrapper<C>
13where
14    C: Clone + PartialEq + 'static,
15{
16    pub fn new(context: Option<(C, ContextHandle<C>)>) -> Self {
17        let (context, handle) = match context {
18            Some((context, handle)) => (Some(context), Some(handle)),
19            None => (None, None),
20        };
21        Self {
22            context,
23            _handle: handle,
24        }
25    }
26
27    pub fn with<COMP, F>(ctx: &Context<COMP>, cb: F) -> Self
28    where
29        COMP: BaseComponent,
30        F: Fn(C) -> COMP::Message + 'static,
31    {
32        let cb = ctx.link().callback(cb);
33        Self::new(ctx.link().context(cb))
34    }
35
36    pub fn set(&mut self, context: C) -> bool {
37        let context = Some(context);
38        if self.context != context {
39            self.context = context;
40            true
41        } else {
42            false
43        }
44    }
45}
46
47impl<C, COMP, F> From<(&Context<COMP>, F)> for ContextWrapper<C>
48where
49    COMP: Component,
50    F: Fn(C) -> COMP::Message + 'static,
51    C: PartialEq + Clone,
52{
53    fn from((ctx, f): (&Context<COMP>, F)) -> Self {
54        let link = ctx.link().clone();
55
56        Self::new(link.clone().context(Callback::from(move |v| {
57            link.send_message(f(v));
58        })))
59    }
60}
61
62impl<C> Deref for ContextWrapper<C>
63where
64    C: PartialEq + Clone,
65{
66    type Target = Option<C>;
67
68    fn deref(&self) -> &Self::Target {
69        &self.context
70    }
71}