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
use crate::integration::popperjs;

use crate::integration::popperjs::{from_popper, Instance};
use crate::GlobalClose;
use std::fmt::Debug;
use std::marker::PhantomData;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsValue;
use yew::prelude::*;

// popper

#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props<T>
where
    T: Clone + PartialEq + Debug,
{
    #[prop_or_default]
    pub children: Children,
    #[prop_or_default]
    pub active: bool,

    pub content: T,

    /// Close callback that will be emitted when the popper's component will emit the onclose callback.
    #[prop_or_default]
    pub onclose: Callback<()>,
}

pub struct Popper<C>
where
    C: PopperContent + 'static,
    C::Properties: PartialEq + Debug,
{
    global_close: GlobalClose,
    target: NodeRef,
    popper: Option<popperjs::Instance>,
    _callback: Option<Closure<dyn Fn(&Instance)>>,

    active: bool,
    state: Option<popperjs::State>,

    _marker: PhantomData<C>,
}

#[derive(Clone, Debug)]
pub enum Msg {
    Close,
    State(popperjs::State),
}

impl<C> Component for Popper<C>
where
    C: PopperContent + 'static,
    C::Properties: Clone + PartialEq + Debug,
{
    type Message = Msg;
    type Properties = Props<C::Properties>;

    fn create(ctx: &Context<Self>) -> Self {
        Self {
            target: NodeRef::default(),
            popper: None,
            _callback: None,
            active: false,
            state: None,
            _marker: Default::default(),
            global_close: GlobalClose::new(NodeRef::default(), ctx.link().callback(|_| Msg::Close)),
        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            Msg::State(state) => {
                let state = Some(state);
                if self.state != state {
                    self.state = state;
                    true
                } else {
                    false
                }
            }
            Msg::Close => {
                if self.active {
                    ctx.props().onclose.emit(());
                }
                false
            }
        }
    }

    fn changed(&mut self, ctx: &Context<Self>) -> bool {
        let active = ctx.props().active;
        if self.active != active {
            self.active = active;
            if self.active {
                self.show(ctx).ok();
            } else {
                self.hide();
            }
            true
        } else {
            false
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        self.check_update().ok();

        let onclose = ctx.link().callback(|_| Msg::Close);

        let content = <C as PopperContent>::view(
            &ctx.props().content,
            onclose,
            self.global_close.clone(),
            self.state.clone(),
        );

        let content = create_portal(content, gloo_utils::body().into());

        html! (
            <>
                <span ref={self.target.clone()}>
                    { for ctx.props().children.iter() }
                </span>
                { content }
            </>
        )
    }
}

impl<C> Popper<C>
where
    C: PopperContent,
    C::Properties: Clone + PartialEq + Debug,
{
    fn show(&mut self, ctx: &Context<Self>) -> Result<(), JsValue> {
        if self.popper.is_some() {
            return Ok(());
        }

        let target = self
            .target
            .get()
            .ok_or_else(|| JsValue::from("Missing target"))?;
        let content = self
            .global_close
            .get()
            .ok_or_else(|| JsValue::from("Missing content"))?;

        let update = ctx.link().callback(|state| Msg::State(state));
        let update = Closure::wrap(Box::new(move |this: &Instance| {
            // web_sys::console::debug_2(&JsValue::from("apply: "), this);
            let msg = from_popper(this).unwrap();
            // log::info!("Msg: {:?}", msg);

            update.emit(msg);
        }) as Box<dyn Fn(&Instance)>);

        let opts = popperjs::create_default_opts(&update)?;

        //web_sys::console::debug_1(&opts);

        let popper = popperjs::create_popper(target, content, &opts);

        // web_sys::console::debug_1(&popper);
        self.popper = Some(popper);
        self._callback = Some(update);

        Ok(())
    }

    fn hide(&mut self) {
        self.destroy();
        self.state = None;
    }

    fn check_update(&self) -> Result<(), JsValue> {
        if let Some(popper) = &self.popper {
            popper.update();
        }
        Ok(())
    }

    fn destroy(&mut self) {
        if let Some(popper) = self.popper.take() {
            popper.destroy();
        }
    }
}

pub trait PopperContent: Component {
    fn view(
        props: &Self::Properties,
        onclose: Callback<()>,
        r#ref: NodeRef,
        state: Option<popperjs::State>,
    ) -> Html;
}