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
//! # Svelte Store Bindings
//!
//! This crate is intended to make working with svelte stores
//! easy and ergonomic. Specifically, the goal is to allow
//! easier use of Rust as the backend of a svelte app where
//! the UI can directly react to changes that happen with
//! the Rust-WASM world.
//!
//! This crate exposes one struct, mainly [`Readable`], which
//! allows seemless management of readable Svelte stores in JS.
//! Despite it's name, [`Readable`] can be written to from Rust,
//! but only yields a `Readable` store to JS, making sure that
//! mutation can only happen within Rust's safety guarantees.
//!
//! These stores can additionally be annotated with Typescript types
//! to provide better safety from the JS side. To see how, check out
//! the [`Readable::get_store`] example. (Note: [`Readable::get_store`]
//! fn and example is only available on `wasm32` targets)

#![feature(once_cell)]

#[cfg(target_arch = "wasm32")]
#[macro_use]
extern crate clone_macro;

#[cfg(target_arch = "wasm32")]
mod bindings;

#[cfg(target_arch = "wasm32")]
use std::cell::{OnceCell, RefCell};
use std::{
    cell::UnsafeCell,
    fmt,
    ops::{self, Deref},
    rc::Rc,
};
use wasm_bindgen::prelude::*;

/// Rust-managed `Readable` Svelte store.
pub struct Readable<T> {
    value: Rc<UnsafeCell<T>>,
    #[cfg(target_arch = "wasm32")]
    store: bindings::Readable,
    #[cfg(target_arch = "wasm32")]
    set_store: Rc<OnceCell<js_sys::Function>>,
    #[cfg(target_arch = "wasm32")]
    _set_store_closure: Closure<dyn FnMut(js_sys::Function)>,
    #[allow(clippy::type_complexity)]
    #[cfg(target_arch = "wasm32")]
    mapped_set_fn: Rc<RefCell<dyn FnMut(&T) -> JsValue>>,
}

impl<T> fmt::Debug for Readable<T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Readable").field(self.deref()).finish()
    }
}

impl<T> fmt::Display for Readable<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.deref().fmt(f)
    }
}

impl<T> Default for Readable<T>
where
    T: Default + Clone + Into<JsValue> + 'static,
{
    fn default() -> Self {
        Self::new(T::default())
    }
}

/// [`Readable`] relies on the fact that only one instance
/// can exist at a time to provide transparent dereferencing
/// to the inner value. As a result, it is unsound to implement
/// [`Clone`]. If you need shared mutability, try using
/// [`Rc`](std::rc::Rc) and [`RefCell`](std::cell::RefCell).
impl<T> ops::Deref for Readable<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        // SAFETY:
        // This is safe because the `set` fn is the only way to
        // mutate T, which already requires an &mut Self, so the
        // borrow checker will make sure no outstanding aliases
        // are possible
        unsafe { &*self.value.get() }
    }
}

impl<T: 'static> Readable<T> {
    #[allow(unused_variables)]
    fn init_store<F>(initial_value: Rc<UnsafeCell<T>>, mapping_fn: F) -> Self
    where
        F: FnMut(&T) -> JsValue + 'static,
    {
        #[cfg(target_arch = "wasm32")]
        let this = {
            let mapped_set_fn = Rc::new(RefCell::new(
                Box::new(mapping_fn) as Box<dyn FnMut(&T) -> JsValue>
            ));

            let set_store = Rc::new(OnceCell::new());

            let start = Closure::<dyn FnMut(js_sys::Function)>::new(clone!(
                [set_store, initial_value, mapped_set_fn],
                move |set_fn: js_sys::Function| {
                    // Since the value might have changed from the moment the
                    // store was created, we need to set the store again
                    let _ = set_fn.call1(
                        &JsValue::NULL,
                        &(mapped_set_fn.borrow_mut())(unsafe {
                            &*initial_value.get()
                        }),
                    );

                    let _ = set_store.set(set_fn);
                }
            ));

            let store = bindings::readable(
                mapped_set_fn.borrow_mut()(unsafe { &*initial_value.get() }),
                &start,
            );

            Self {
                value: initial_value,
                store,
                set_store,
                _set_store_closure: start,
                mapped_set_fn,
            }
        };

        #[cfg(not(target_arch = "wasm32"))]
        let this = {
            Self {
                value: initial_value,
            }
        };

        this
    }

    /// Creates a `Readable` Svelte store.
    ///
    /// This function is only implemented for types that can be converted
    /// into [`JsValue`]. This includes all types annotated with
    /// `#[wasm_bindgen]`. If your type does not provide an [`Into<JsValue>`]
    /// implementation, use [`Readable::new_mapped`] instead.
    ///
    /// # Examples
    ///
    /// Using a type that already provides an implementation of
    /// [`Into<JsValue>`].
    ///
    /// ```
    /// use svelte_store::Readable;
    ///
    /// let store = Readable::new(0u8);
    /// ```
    ///
    /// Using a type annotated with `#[wasm_bindgen]`.
    ///
    /// ```
    /// use svelte_store::Readable;
    /// use wasm_bindgen::prelude::*;
    ///
    /// #[derive(Clone)]
    /// #[wasm_bindgen]
    /// pub struct MyStruct;
    ///
    /// let store = Readable::new(MyStruct);
    /// ```
    pub fn new(initial_value: T) -> Self
    where
        T: Clone + Into<JsValue>,
    {
        Self::init_store(Rc::new(UnsafeCell::new(initial_value)), |v| {
            v.clone().into()
        })
    }

    /// Creates a new `Readable` Svelte store which calls its mapping fn each
    /// time the store is set, to produce a [`JsValue`].
    ///
    /// This method should be used whenever [`Readable::new`] cannot be,
    /// due to lacking trait compatibility.
    ///
    /// # Examples
    ///
    /// Creating a store of [`Vec<u8>`].
    ///
    /// ```
    /// use svelte_store::Readable;
    /// use wasm_bindgen::prelude::*;
    ///
    /// let values = vec![7u8; 7];
    ///
    /// let store = Readable::new_mapped(values, |values: &Vec<u8>| {
    ///     values
    ///         .iter()
    ///         .cloned()
    ///         .map(JsValue::from)
    ///         .collect::<js_sys::Array>()
    ///         .into()
    /// });
    /// ```
    pub fn new_mapped<F>(initial_value: T, mapping_fn: F) -> Self
    where
        F: FnMut(&T) -> JsValue + 'static,
    {
        Self::init_store(Rc::new(UnsafeCell::new(initial_value)), mapping_fn)
    }

    /// Sets the value of the store, notifying all store
    /// listeners the value has changed.
    pub fn set(&mut self, new_value: T) {
        // SAFETY:
        // This is safe because this function is the only way to
        // mutate T, which already requires an &mut Self, so the
        // borrow checker will make sure no outstanding aliases
        // are possible
        let value = unsafe { &mut *self.value.get() };

        *value = new_value;

        #[cfg(target_arch = "wasm32")]
        if let Some(set_fn) = self.set_store.get() {
            set_fn
                .call1(&JsValue::NULL, &self.mapped_set_fn.borrow_mut()(value))
                .expect("failed to set readable store");
        }
    }

    /// Calls the provided `f` with a `&mut T`, returning
    /// whatever `f` returns. After this function is called,
    /// the store will be updated and all store listeners will
    /// be notified.
    pub fn set_with<F, O>(&mut self, f: F) -> O
    where
        F: FnOnce(&mut T) -> O,
    {
        // SAFETY:
        // This is safe because this function is the only way to
        // mutate T, which already requires an &mut Self, so the
        // borrow checker will make sure no outstanding aliases
        // are possible
        let value = unsafe { &mut *self.value.get() };

        #[allow(clippy::let_and_return)]
        let o = f(value);

        #[cfg(target_arch = "wasm32")]
        if let Some(set_fn) = self.set_store.get() {
            set_fn
                .call1(&JsValue::NULL, &self.mapped_set_fn.borrow_mut()(value))
                .expect("failed to set readable store");
        }

        o
    }

    /// Gets the store that can be directly passed to JS and subscribed
    /// to.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use wasm_bindgen::prelude::*;
    /// use svelte_store::Readable;
    ///
    /// #[wasm_bindgen(typescript_custom_section)]
    /// const TYPESCRIPT_TYPES: &str = r#"
    /// import type { Readable } from "svelte/store";
    ///
    /// type ReadableNumber = Readable<number>;
    /// "#;
    ///
    /// #[wasm_bindgen]
    /// extern "C" {
    ///     #[wasm_bindgen(typescript_type = "ReadableNumber")]
    ///     type ReadableNumber;
    /// }
    ///
    /// #[wasm_bindgen]
    /// pub struct MyStruct {
    ///     my_number: Readable<u8>,
    /// }
    ///
    /// #[wasm_bindgen]
    /// impl MyStruct {
    ///     #[wasm_bindgen(getter)]
    ///     pub fn number(&self) -> ReadableNumber {
    ///         self.my_number.get_store().into()
    ///     }
    /// }
    /// ```
    #[cfg(target_arch = "wasm32")]
    pub fn get_store(&self) -> JsValue {
        self.store.clone()
    }
}