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
use std::{
  cell::{Ref, RefCell},
  fmt::Debug,
  rc::Rc,
};
use wasm_bindgen::{
  convert::{FromWasmAbi, IntoWasmAbi},
  describe::WasmDescribe,
  prelude::Closure,
  JsValue, UnwrapThrowExt,
};

/// A zero-sized helper struct to simulate a JS-interoperable [`Callback`] with no input
/// arguments.
///
/// ```
/// # use wasm_react::*;
/// # fn f() {
/// let callback: Callback<Void> = Callback::new(|_: Void| ());
/// # }
/// ```
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub struct Void;

impl WasmDescribe for Void {
  fn describe() {
    JsValue::describe()
  }
}

impl FromWasmAbi for Void {
  type Abi = <JsValue as FromWasmAbi>::Abi;

  unsafe fn from_abi(js: Self::Abi) -> Self {
    JsValue::from_abi(js);
    Void
  }
}

impl From<Void> for JsValue {
  fn from(_: Void) -> Self {
    JsValue::undefined()
  }
}

/// This is a simplified, reference-counted wrapper around an [`FnMut(T) -> U`](FnMut)
/// Rust closure that may be called from JS when `T` and `U` allow.
///
/// You can also use the [`callback!`](crate::callback!) macro to create a [`Callback`]
/// which supports clone-capturing the environment.
///
/// It only supports closures with exactly one input argument and some return
/// value. Memory management is handled by Rust. Whenever Rust drops all clones
/// of the [`Callback`], the closure will be dropped and the function cannot be
/// called from JS anymore.
///
/// Use [`Void`] to simulate a callback with no arguments.
pub struct Callback<T, U = ()> {
  closure: Rc<RefCell<dyn FnMut(T) -> U>>,
  js: Rc<RefCell<Option<Closure<dyn FnMut(T) -> U>>>>,
}

impl<T, U> Callback<T, U>
where
  T: 'static,
  U: 'static,
{
  /// Creates a new [`Callback`] from a Rust closure.
  pub fn new(f: impl FnMut(T) -> U + 'static) -> Self {
    Self {
      closure: Rc::new(RefCell::new(f)),
      js: Default::default(),
    }
  }

  /// Returns a Rust closure from the callback.
  pub fn to_closure(&self) -> impl FnMut(T) -> U + 'static {
    let closure = self.closure.clone();

    move |arg| {
      let mut f = closure.borrow_mut();
      f(arg)
    }
  }

  /// Calls the callback with the given argument.
  pub fn call(&self, arg: T) -> U {
    let mut f = self.closure.borrow_mut();
    f(arg)
}

  /// Returns a new [`Callback`] by prepending the given closure to the callback.
  pub fn premap<V>(
    &self,
    mut f: impl FnMut(V) -> T + 'static,
  ) -> Callback<V, U> {
    Callback {
      closure: Rc::new(RefCell::new({
        let closure = self.closure.clone();

        move |v| {
          let t = f(v);
          let mut g = closure.borrow_mut();
          g(t)
        }
      })),
      js: Default::default(),
    }
  }

  /// Returns a new [`Callback`] by appending the given closure to the callback.
  pub fn postmap<V>(
    &self,
    mut f: impl FnMut(U) -> V + 'static,
  ) -> Callback<T, V> {
    Callback {
      closure: Rc::new(RefCell::new({
        let closure = self.closure.clone();

        move |t| {
          let mut g = closure.borrow_mut();
          let u = g(t);
          f(u)
        }
      })),
      js: Default::default(),
    }
  }

  /// Returns a reference to `JsValue` of the callback.
  pub fn as_js(&self) -> Ref<'_, JsValue>
  where
    T: FromWasmAbi,
    U: IntoWasmAbi,
  {
    {
      let mut borrow = self.js.borrow_mut();

      if borrow.is_none() {
        *borrow = Some(Closure::new({
          let closure = self.closure.clone();

          move |arg| {
            let mut f = closure.borrow_mut();
            f(arg)
          }
        }));
      }
    }

    Ref::map(self.js.borrow(), |x| {
      x.as_ref().expect_throw("no closure available").as_ref()
    })
  }
}

impl<T: 'static> Callback<T> {
  /// Returns a new [`Callback`] that does nothing.
  pub fn noop() -> Self {
    Callback::new(|_| ())
  }
}

impl<T, U> Default for Callback<T, U>
where
  T: 'static,
  U: Default + 'static,
{
  fn default() -> Self {
    Self::new(|_| U::default())
  }
}

impl<F, T, U> From<F> for Callback<T, U>
where
  F: FnMut(T) -> U + 'static,
  T: 'static,
  U: 'static,
{
  fn from(value: F) -> Self {
    Self::new(value)
  }
}

impl<T, U> Debug for Callback<T, U> {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str("Callback(|_| { … })")
  }
}

impl<T, U> PartialEq for Callback<T, U> {
  fn eq(&self, other: &Self) -> bool {
    Rc::ptr_eq(&self.closure, &other.closure) && Rc::ptr_eq(&self.js, &other.js)
  }
}

impl<T, U> Eq for Callback<T, U> {}

impl<T, U> Clone for Callback<T, U> {
  fn clone(&self) -> Self {
    Self {
      closure: self.closure.clone(),
      js: self.js.clone(),
    }
  }
}