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
//! Components that run once ([`super::Component::view`]): their instance
//! and their [`Scope`].
//!
//! The instance makes the component's view once, under an owner of its
//! own, with its props held in signals: a prop from JS (or a parent's
//! binding) updates what read it. A region that makes the element again
//! makes a new instance, as TSX does. The core mounts
//! the view with its bindings and never asks for it again. The creating
//! Rust render run's cleanup or releasing the host disposes the owner,
//! and with it everything the component made.
use std::{any::Any, marker::PhantomData};
use super::{
AnyValue, Component, Event, IntoElement, JsResult, MethodCall, Owner, PropError, Props,
builder::{AnyEvent, ElNode},
};
use crate::NodeId;
/// What a component that runs once has of its own: it emits its events
/// (TS: calling an `on…` prop). `Copy`: closures capture it as it is.
pub struct Scope<E> {
host: NodeId,
_event: PhantomData<fn(E)>,
}
impl<E> Clone for Scope<E> {
fn clone(&self) -> Self {
*self
}
}
impl<E> Copy for Scope<E> {}
impl<E> std::fmt::Debug for Scope<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Scope({})", self.host)
}
}
impl<E> Scope<E> {
/// The node hosting the component.
#[doc(hidden)]
pub fn __host(&self) -> NodeId {
self.host
}
}
impl<E: Event> Scope<E> {
/// Sends `event` to the app (its `on<Event>` handler), or to the
/// component whose view has this one.
pub fn emit(&self, event: E) {
super::reactive::emit(self.host, Box::new(event));
}
/// Makes `api` what the component's ref does in JS (its methods) for as
/// long as the view lives; the component names it in its spec
/// (`#[component(methods = StepperApi)]`).
pub fn methods(&self, api: impl super::Api) {
super::reactive::register_api(self.host, api);
}
/// The edges system UI or a header covers where the component is: its
/// screen's (below the header) or modal's, else the safe area (TS:
/// `safeAreaInsets()`). Reading subscribes.
pub fn insets(&self) -> crate::EdgeInsets {
super::insets_of(self.host)
}
}
/// The instance of a component that runs once.
pub(crate) struct OnceInstance<C: Component> {
/// The props: as set before the view is made, held afterwards.
props: C::Props,
/// What does not depend on the component: one copy of its code for
/// all of them.
state: OnceState,
_component: PhantomData<fn() -> C>,
}
/// The part of a [`OnceInstance`] that does not depend on its component:
/// the owners and the node, and what is done with them.
struct OnceState {
/// What owns the props' own signals, made with the instance: they hold
/// the values JS and parents give for as long as the instance lives.
initial: Option<Owner>,
/// The component's owner, once its view is made.
owner: Option<Owner>,
/// Its placement context, adopted when another component receives it.
parent: Owner,
/// The run that created it; detached for externally managed JS hosts.
lifetime: Owner,
host: NodeId,
}
impl<C: Component> OnceInstance<C> {
pub(crate) fn new() -> Self {
let (initial, props) = super::create_root(C::Props::initial);
Self {
props,
state: OnceState {
initial: Some(initial),
owner: None,
parent: Owner::detached(),
lifetime: Owner::detached(),
host: 0,
},
_component: PhantomData,
}
}
}
impl OnceState {
/// Runs `f` under the props' owner while it lives.
fn with_initial(&self, f: &mut dyn FnMut()) {
match self.initial {
Some(initial) => initial.run(f),
None => f(),
}
}
/// Makes the view with `make` (given the host), once, under an owner
/// of its own that the creating run disposes.
#[inline(never)]
fn view(&mut self, make: &mut dyn FnMut(NodeId) -> ElNode) -> ElNode {
if self.owner.is_some() {
log::error!(target: "js", "a component's view was asked for again");
return ElNode::empty_view();
}
let host = self.host;
let (owner, node) = self.parent.run(|| super::create_root(|| make(host)));
// Placement can adopt another context, but the creating run owns its lifetime.
self.lifetime
.run(|| super::cleanup(move || owner.dispose()));
self.owner = Some(owner);
node
}
fn cleanup(&mut self) {
for owner in [self.owner.take(), self.initial.take()]
.into_iter()
.flatten()
{
owner.dispose();
}
}
fn adopt(&mut self, parent: Owner) {
if self.owner.is_some() || !parent.is_live() {
return;
}
// Preserve a caller's more specific scope (including error boundaries)
// when it is already under the placement owner. Otherwise the child
// belongs under the provider where its receiving component placed it.
let mut at = Some(self.parent);
while let Some(owner) = at {
if owner == parent {
return;
}
at = owner.parent();
}
self.parent = parent;
}
fn place(&mut self, host: NodeId, parent: Owner) {
self.host = host;
self.parent = parent;
self.lifetime = parent;
}
}
impl<C: Component> super::component::AnyInstance for OnceInstance<C> {
fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError> {
let props = &mut self.props;
let mut value = Some(value);
let mut result = Ok(false);
self.state.with_initial(&mut || {
if let Some(value) = value.take() {
result = props.set(name, value);
}
});
result
}
fn set_props(&mut self, props: &dyn Any) {
match props.downcast_ref::<C::Props>() {
// Before the view: the props it starts with, values in its own
// signals.
Some(p) if self.state.owner.is_none() => {
let props = &mut self.props;
self.state.with_initial(&mut || {
props.update_from(p);
});
}
// After: a new element is a new instance (the core never
// matches one with an old one).
Some(_) => log::error!(
target: "js",
"{}: props given after its view was made",
super::component::name_of::<C>()
),
None => {}
}
}
fn set_slot(&mut self, name: &'static str, filled: bool) {
self.props
.set_slot(name, filled.then(|| super::Slot::new(name)));
}
fn set_children(&mut self, present: bool) {
self.props.set_children(super::Children::new(present));
}
fn cleanup(&mut self) {
self.state.cleanup();
}
fn view(&mut self) -> ElNode {
let props = &mut self.props;
self.state.view(&mut |host| {
let scope = Scope {
host,
_event: PhantomData,
};
let held = props.held();
*props = held.clone();
C::view(held, scope).into_element().0
})
}
fn name(&self) -> &'static str {
super::component::name_of::<C>()
}
fn call(&mut self, call: MethodCall) -> Option<JsResult> {
super::reactive::call_api(self.state.host, call)
}
fn owner(&self) -> Option<Owner> {
self.state.owner
}
fn failure_owner(&self) -> Owner {
self.state.owner.unwrap_or(self.state.parent)
}
fn adopt(&mut self, parent: Owner) {
self.state.adopt(parent);
}
fn place(&mut self, host: NodeId, parent: Owner) {
self.state.place(host, parent);
}
}
/// An event a component that runs once emitted, for the core.
pub(crate) type Emitted = (NodeId, Box<dyn AnyEvent>);