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
//! A Rust [`Signal`] or [`Memo`] returned to JS: TS gets a read-only
//! `Accessor<T>` (`() => T`) that JS's reactive graph tracks.
//!
//! The two graphs stay apart. The call that returns the signal (a function
//! with `cx`, or an `async` one: both run where Rust's graph is) makes a
//! Rust effect in a root of its own; JS gets a signal of its graph holding
//! the value at the call. Each later change the effect sees is posted to JS
//! (the next JS turn), where it writes that signal, so JS reads it one turn
//! after Rust. The signal's writer does not keep it: once JS lets the
//! accessor go, the next write finds it gone and the effect disposes its
//! root at the change after that. Writing stays Rust's (the module's
//! methods): TS has no `set`.
use std::{
cell::{Cell, RefCell},
rc::Rc,
};
use super::{
JsHost, JsOwned, Memo, PropError, Signal, TsTypes,
call::ToJs,
callback::{CallbackHandle, JsCall, ReplyFn},
class::{ClassDef, Ret},
reactive::{Owner, create_root, effect},
};
/// What links a Rust value to the JS signal mirroring it.
struct Link<T> {
/// The value JS has not got yet: the one at the call, then the latest
/// change before JS took the accessor.
pending: RefCell<Option<T>>,
/// What writes the JS signal, once JS has it.
writer: RefCell<Option<Rc<dyn CallbackHandle>>>,
/// JS let the accessor go (or never got it): the effect stops.
gone: Cell<bool>,
/// The root of the effect.
owner: RefCell<Option<Owner>>,
}
/// Starts mirroring what `read` reads (tracked) for JS: the call's result,
/// converted when JS receives it. Runs where Rust's graph is (a call with
/// `cx`, a task).
pub(crate) fn bridge<T: Ret + Clone + 'static>(read: impl Fn() -> T + 'static) -> Box<dyn ToJs> {
let link = Rc::new(Link {
pending: RefCell::new(None),
writer: RefCell::new(None),
gone: Cell::new(false),
owner: RefCell::new(None),
});
let (owner, ()) = create_root(|| {
let link = link.clone();
effect(move || {
if link.gone.get() {
// Read nothing: it never runs again, its root goes.
let owner = link.owner.borrow_mut().take();
if let Some(owner) = owner {
owner.dispose();
}
return;
}
let value = read();
let writer = link.writer.borrow().clone();
match writer {
Some(writer) => {
let gone = Rc::downgrade(&link);
let reply: ReplyFn = Box::new(move |result| {
// `false`: the JS signal was collected.
if let Ok(v) = result
&& v.host().bool(v.raw()) == Some(false)
&& let Some(link) = gone.upgrade()
{
link.gone.set(true);
}
});
writer.post(JsCall::new(
writer.clone(),
value,
Some(reply),
false,
false,
));
}
None => *link.pending.borrow_mut() = Some(value),
}
});
});
*link.owner.borrow_mut() = Some(owner);
Box::new(Mirror { link })
}
/// A mirrored value on its way to JS ([`bridge`]).
struct Mirror<T> {
link: Rc<Link<T>>,
}
impl<T> Drop for Mirror<T> {
fn drop(&mut self) {
// Never reached JS (its promise went, its conversion failed): the
// effect stops at the next change.
if self.link.writer.borrow().is_none() {
self.link.gone.set(true);
}
}
}
impl<T: Ret + 'static> Ret for Mirror<T> {
fn ts_type(types: &mut TsTypes) -> String {
accessor_type::<T>(types)
}
fn into_js<'a>(self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
let value = self
.link
.pending
.borrow_mut()
.take()
.ok_or_else(|| PropError("the value was handed to JS already".into()))?;
let initial = value.into_js(host)?.into_raw();
let (read, write) = host.new_signal(initial)?;
let read = JsOwned::new(host, read);
let writer = host.callback(write);
host.free(write);
let writer =
writer.ok_or_else(|| PropError("the signal's writer is no function".into()))?;
*self.link.writer.borrow_mut() = Some(writer);
Ok(read)
}
fn classes(out: &mut Vec<&'static ClassDef>) {
T::classes(out);
}
}
/// `Accessor<T>`, declared next to the module's types.
fn accessor_type<T: Ret>(types: &mut TsTypes) -> String {
let name = types.declare("Accessor", |_| {
"/** A value Rust owns, read by calling it (tracked). */\nexport interface Accessor<T> {\n (): T;\n}".into()
});
format!("{name}<{}>", T::ts_type(types))
}
/// Where Rust's graph is not (a synchronous function without `cx`).
#[cold]
fn outside_graph(what: &str) -> PropError {
PropError(format!(
"a {what} is returned from a function with `cx` or an `async` one, where Rust's reactive graph runs"
))
}
/// A signal for JS: `Accessor<T>`, read-only, tracked by JS's graph
/// (writes go through the module's own functions).
impl<T: Ret + Clone + 'static> Ret for Signal<T> {
fn ts_type(types: &mut TsTypes) -> String {
accessor_type::<T>(types)
}
fn into_js<'a>(self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
Err(outside_graph("Signal"))
}
fn boxed(self) -> Box<dyn ToJs> {
bridge(move || self.get())
}
fn classes(out: &mut Vec<&'static ClassDef>) {
T::classes(out);
}
}
/// A memo for JS, as a [`Signal`]: `Accessor<T>`.
impl<T: Ret + Clone + 'static> Ret for Memo<T> {
fn ts_type(types: &mut TsTypes) -> String {
accessor_type::<T>(types)
}
fn into_js<'a>(self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
Err(outside_graph("Memo"))
}
fn boxed(self) -> Box<dyn ToJs> {
bridge(move || self.get())
}
fn classes(out: &mut Vec<&'static ClassDef>) {
T::classes(out);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::element::reactive::{Runtime, signal};
#[test]
fn a_mirror_js_never_took_stops_after_the_next_changes() {
let rt = Runtime::default();
let _entered = rt.enter();
let count = signal(1.0f64);
let before = rt.slots_in_use();
let mirror = count.boxed();
assert!(
rt.slots_in_use() > before,
"the effect is made with the call"
);
drop(mirror);
// The first change finds it gone and disposes its root.
count.set(2.0);
count.set(3.0);
assert_eq!(rt.slots_in_use(), before, "nothing of the mirror is left");
}
}