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
use std::cell::Cell;
use hearth_foundation::context::Cx;
use hearth_view::{NodeViewParts, PartsWriter};
use serde::Serialize;
use crate::{Js, Surrogate, Surrogated};
/// A value with a JavaScript expression that can produce it in the browser.
///
/// Expressions that read no signals render as static content. Their
/// JavaScript remains available when needed for browser execution.
#[derive(Debug, Clone)]
pub struct Expr<T> {
pub(crate) evaluated: T,
pub(crate) js: Js,
pub(crate) is_static: bool,
}
impl<T> Expr<T> {
/// Evaluates an expression while observing signal reads.
///
/// The evaluation is synchronous. Its signal reads must represent the
/// dependencies of the JavaScript expression as well.
#[inline]
pub fn evaluate(evaluate: impl FnOnce() -> T, js: Js) -> Self {
let _scope = ReadScope::enter();
let evaluated = evaluate();
Self {
evaluated,
js,
is_static: SIGNAL_READ.get() == Some(false),
}
}
/// [hearth fork] A value whose browser JS is supplied by the caller and
/// which always renders as dynamic, e.g. the current row of a client
/// list (`cx.row(0)`). Captures of it inside `$()` inline that JS.
#[inline]
pub fn evaluate_dynamic(value: T, js: Js) -> Self {
Self {
evaluated: value,
js,
is_static: false,
}
}
/// Whether this expression is known not to require reactive evaluation.
///
/// Signal reads during [`evaluate`](Self::evaluate) make it dynamic.
#[inline]
#[must_use]
pub fn is_static(&self) -> bool {
self.is_static
}
/// Returns the value and its JavaScript, including for static expressions.
#[inline]
pub fn into_evaluated_and_js(self) -> (T, Js) {
(self.evaluated, self.js)
}
/// Returns the captured value, carrying its dependencies into evaluation.
#[doc(hidden)]
pub fn into_captured_value(self) -> T::Surrogate
where
T: Surrogated,
{
if !self.is_static {
mark_signal_read();
}
self.evaluated.into_surrogate()
}
}
impl<T> From<T> for Expr<T>
where
T: Surrogated,
T::Surrogate: Serialize,
{
/// Creates a static expression from a value in the runtime vocabulary.
///
/// # Panics
///
/// Panics if the value's surrogate cannot be serialized.
fn from(value: T) -> Self {
let surrogate = value.into_surrogate();
let js = Js::builder()
.compiled("cx.hydrate(__hearthCaptures.values[0])")
.surrogate(&surrogate)
.build();
Self::evaluate(|| surrogate.into_real(), js)
}
}
impl<T> NodeViewParts for Expr<T>
where
T: NodeViewParts,
{
fn into_view_parts(self, cx: &Cx, parts: &mut PartsWriter<'_>) {
if self.is_static {
self.evaluated.into_view_parts(cx, parts);
return;
}
// <!-- ::hearth::expr::start("<js>") -->
//
// The comment context seals the source, so a `"` inside it renders
// as `"` and the quotes stay unambiguous delimiters on the
// client.
parts.push_comment(|comment| {
comment.push_promoted_str_unescaped(&"::hearth::expr::start(\"");
self.js.write(comment);
comment.push_promoted_str_unescaped(&"\")");
});
self.evaluated.into_view_parts(cx, parts);
parts.push_comment(|comment| {
comment.push_promoted_str_unescaped(&"::hearth::expr::end");
});
}
}
thread_local! {
static SIGNAL_READ: Cell<Option<bool>> = const { Cell::new(None) };
}
/// Records a read and returns whether an expression is being evaluated.
pub(crate) fn mark_signal_read() -> bool {
if SIGNAL_READ.get().is_some() {
SIGNAL_READ.set(Some(true));
true
} else {
false
}
}
/// Restores the enclosing synchronous evaluation, including during unwinding.
struct ReadScope {
previous: Option<bool>,
}
impl ReadScope {
fn enter() -> Self {
Self {
previous: SIGNAL_READ.replace(Some(false)),
}
}
}
impl Drop for ReadScope {
fn drop(&mut self) {
let read = SIGNAL_READ.replace(self.previous) == Some(true);
if read {
mark_signal_read();
}
}
}
#[cfg(test)]
mod tests {
use std::{panic::catch_unwind, sync::Barrier};
use super::*;
#[test]
fn nested_evaluations_propagate_reads_without_contaminating_siblings() {
let outer = Expr::evaluate(
|| {
let inner = Expr::evaluate(mark_signal_read, Js::source(""));
assert!(!inner.is_static());
let sibling = Expr::evaluate(|| 1, Js::source(""));
assert!(sibling.is_static());
},
Js::source(""),
);
assert!(!outer.is_static());
assert!(Expr::evaluate(|| 1, Js::source("")).is_static());
}
#[test]
fn panic_restores_the_parent_scope_and_preserves_its_reads() {
let outer = Expr::evaluate(
|| {
let panic = catch_unwind(|| {
Expr::evaluate(
|| {
mark_signal_read();
panic!("evaluation failed");
},
Js::source(""),
)
});
assert!(panic.is_err());
},
Js::source(""),
);
assert!(!outer.is_static());
assert!(Expr::evaluate(|| 1, Js::source("")).is_static());
}
#[test]
fn concurrent_evaluations_do_not_share_reads() {
let barrier = Barrier::new(2);
std::thread::scope(|scope| {
let dynamic = scope.spawn(|| {
Expr::evaluate(
|| {
mark_signal_read();
barrier.wait();
barrier.wait();
},
Js::source(""),
)
});
let constant = Expr::evaluate(
|| {
barrier.wait();
barrier.wait();
},
Js::source(""),
);
assert!(constant.is_static());
assert!(!dynamic.join().unwrap().is_static());
});
}
}