nsh_core/element/call.rs
1//! Calls from JS into Rust, and what goes back, as Rust values: no JSON
2//! between JS and Rust components, modules or classes.
3//!
4//! `nsh-js` converts a call's JS arguments into the Rust types in the JS
5//! call (the generated decoders, [`super::JsValue::from_js`]) and queues
6//! what the call does as an op ([`RustOp`]): a closure holding the typed
7//! arguments, which the core runs in order with the UI's ops (a module
8//! function with a [`super::ModuleCx`], the start of an `async` function's
9//! or member's task, a ref's method). Results are boxed Rust values
10//! ([`ToJs`]) the core hands back in its event stream ([`JsEvent`]), in
11//! order with the other events, and `nsh-js` converts them when it settles
12//! the promise. A Rust component's props cross the same way: decoded in
13//! the JS call into an [`AnyValue`], set by the core.
14//!
15//! Platform native components (the components an embedder registers in
16//! its own language) keep JSON (`Prop::ComponentProp`, `EventPayload::Native`,
17//! `Command::Native`): their values cross into another language.
18
19use std::{
20 any::Any,
21 cell::{Cell, RefCell},
22 collections::VecDeque,
23 fmt,
24 rc::Rc,
25 sync::Arc,
26};
27
28use super::{
29 ModuleCx, ModuleFuture, PropError,
30 callback::JsCall,
31 js::{JsHost, JsOwned},
32};
33use crate::{EventKind, EventPayload, NodeId};
34
35/// A Rust value of some type, decoded from JS for a component's prop.
36/// Cheap to clone; two are equal when they are the same value (the prop
37/// keeps its own comparison of what it holds).
38#[derive(Clone)]
39pub struct AnyValue(Rc<dyn Any>);
40
41impl AnyValue {
42 /// `value`, type-erased.
43 pub fn new<T: 'static>(value: T) -> Self {
44 Self(Rc::new(value))
45 }
46
47 /// The value, if it is a `T`.
48 pub fn take<T: Clone + 'static>(self) -> Option<T> {
49 self.0.downcast::<T>().ok().map(Rc::unwrap_or_clone)
50 }
51}
52
53impl PartialEq for AnyValue {
54 fn eq(&self, other: &Self) -> bool {
55 Rc::ptr_eq(&self.0, &other.0)
56 }
57}
58
59impl fmt::Debug for AnyValue {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 f.write_str("AnyValue")
62 }
63}
64
65/// A Rust value JS gets: converted when JS receives it (a call's result,
66/// an event's data).
67pub trait ToJs: 'static {
68 /// The value as a JS value of `host`.
69 fn to_js_value<'a>(self: Box<Self>, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
70}
71
72impl<T: super::Ret + 'static> ToJs for T {
73 fn to_js_value<'a>(self: Box<Self>, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
74 (*self).into_js(host)
75 }
76}
77
78/// The result of a call JS waits for: the value, or the message its
79/// promise rejects with.
80pub type JsResult = Result<Box<dyn ToJs>, super::Thrown>;
81
82/// A module function with a context, its arguments decoded: run by the
83/// core in order with the UI's ops.
84pub type OpCall = Box<dyn FnOnce(&mut ModuleCx) -> JsResult>;
85
86/// The start of an `async` function's or member's task, its arguments
87/// decoded: the core starts it in order with the UI's ops.
88pub type TaskStart = Box<dyn FnOnce() -> ModuleFuture>;
89
90/// A method of a component's ref, its arguments decoded: called with the
91/// API the component registered (`None`: an API of another type).
92pub type MethodCall = Box<dyn FnOnce(&dyn Any) -> Option<JsResult>>;
93
94/// What a call JS made into Rust does, carried by an op.
95pub enum RustCall {
96 /// A module function with a context.
97 Op(OpCall),
98 /// The start of an `async` function's or member's task.
99 Task(TaskStart),
100 /// A method of the ref of the component on node `0`.
101 Method(NodeId, MethodCall),
102 /// The place of a JS call posted during a synchronous call from JS
103 /// ([`Posts::park`]): applied (dropped), the call runs after what the
104 /// ops before it post.
105 Post(ParkedPost),
106}
107
108/// A call JS made into Rust ([`crate::Op::Rust`]): what it does, and the
109/// number of the promise its result settles (0: none).
110pub struct RustOp {
111 /// The promise's call number (0: JS does not wait).
112 pub call: u32,
113 /// What it does.
114 pub run: RustCall,
115}
116
117impl fmt::Debug for RustOp {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 let kind = match &self.run {
120 RustCall::Op(_) => "Op",
121 RustCall::Task(_) => "Task",
122 RustCall::Method(..) => "Method",
123 RustCall::Post(_) => "Post",
124 };
125 write!(f, "RustOp({kind}, call {})", self.call)
126 }
127}
128
129/// A Rust component's event JS hears: its name and data.
130#[doc(hidden)]
131pub trait EventToJs {
132 /// The event's name (`press`: JS's `onPress`).
133 fn name(&self) -> &'static str;
134 /// Its data as a JS value of `host`.
135 fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
136}
137
138/// What the core hands JS after a commit, in order: the platform's and the
139/// core's events, and the Rust values for JS (a Rust component's events,
140/// whether its lazy children are placed, calls' results).
141pub enum JsEvent {
142 /// An event of a node (layout, scroll, a platform component's).
143 Event(NodeId, EventKind, EventPayload),
144 /// The initial frame for one newly installed Rust layout listener.
145 /// Delivered by the engine to `Core::component_layout`.
146 #[doc(hidden)]
147 LayoutListener {
148 /// The component whose view installed the listener.
149 host: NodeId,
150 /// Its node.
151 id: NodeId,
152 /// The newly installed callback.
153 listener: super::Listener<EventPayload>,
154 /// The node's current frame.
155 frame: crate::Bounds<crate::Points>,
156 },
157 /// An event of the Rust component hosted by `host`.
158 Component {
159 /// The component's host node.
160 host: NodeId,
161 /// The event.
162 event: Box<dyn EventToJs>,
163 },
164 /// Whether the Rust component hosted by `host` places its lazy
165 /// children now.
166 Children {
167 /// The component's host node.
168 host: NodeId,
169 /// Placed.
170 wanted: bool,
171 },
172 /// The Rust component hosted by `host` places the content of its
173 /// render prop `prop` (`Option<Renderer<T>>`) for `key` with `value`,
174 /// which JS did not render yet: JS calls the app's function with it
175 /// and inserts what it returns into the host in a holder view of its
176 /// own (`componentRender`: the prop, U+001F, the key), replacing the
177 /// one it made for the key before. The core places the holder.
178 Render {
179 /// The component's host node.
180 host: NodeId,
181 /// The prop holding the app's function.
182 prop: &'static str,
183 /// The key, unique among the component's renders of the prop.
184 key: super::SharedString,
185 /// The value to render.
186 value: std::rc::Rc<dyn super::RenderValue>,
187 },
188 /// No element of the component's render (`prop`, `key`) is placed any
189 /// more ([`Self::Render`]): JS removes its holder and disposes what it
190 /// rendered.
191 Unrender {
192 /// The component's host node.
193 host: NodeId,
194 /// The prop holding the app's function.
195 prop: &'static str,
196 /// The key.
197 key: super::SharedString,
198 },
199 /// The `<Each>` rows whose placeholders ([`crate::Op::Placeholder`])
200 /// would be made now: JS renders them in their place.
201 #[doc(hidden)]
202 Rows(Vec<NodeId>),
203 /// The result of call `call` (its promise settles).
204 Reply {
205 /// The call number.
206 call: u32,
207 /// The value or the rejection's message.
208 result: JsResult,
209 },
210}
211
212impl fmt::Debug for JsEvent {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214 match self {
215 JsEvent::Event(id, kind, payload) => write!(f, "Event({id}, {kind:?}, {payload:?})"),
216 JsEvent::LayoutListener {
217 host, id, frame, ..
218 } => {
219 write!(f, "LayoutListener({host}, {id}, {frame:?})")
220 }
221 JsEvent::Component { host, event } => write!(f, "Component({host}, {})", event.name()),
222 JsEvent::Children { host, wanted } => write!(f, "Children({host}, {wanted})"),
223 JsEvent::Render {
224 host, prop, key, ..
225 } => write!(f, "Render({host}, {prop}, {key})"),
226 JsEvent::Unrender { host, prop, key } => write!(f, "Unrender({host}, {prop}, {key})"),
227 JsEvent::Rows(ids) => write!(f, "Rows({ids:?})"),
228 JsEvent::Reply { call, result } => write!(f, "Reply({call}, ok: {})", result.is_ok()),
229 }
230 }
231}
232
233// --- Posts ----------------------------------------------------------------------
234
235/// The place in [`Posts`] of a call posted during a synchronous call from
236/// JS, which [`RustCall::Post`] carries: dropping it lets the call run
237/// there, whichever path drops it (the op applied, or dropped unapplied).
238#[doc(hidden)]
239pub struct ParkedPost {
240 posts: Posts,
241 id: u64,
242}
243
244impl Drop for ParkedPost {
245 fn drop(&mut self) {
246 self.posts.release(self.id);
247 }
248}
249
250impl fmt::Debug for ParkedPost {
251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252 write!(f, "ParkedPost({})", self.id)
253 }
254}
255
256/// The calls of JS functions Rust posts ([`super::Callback::post`],
257/// `call_async`) for the next JS turn, in one ordered queue. One per
258/// engine, made by it and handed to `nsh-js` and the core. Cheap to clone.
259///
260/// The calls run in the order they were posted, with one exception that
261/// keeps JS's program order: a call posted during a synchronous call from
262/// JS is parked in its place until the op JS sent after it is applied
263/// ([`RustCall::Post`]), and what the ops before that one post while the
264/// core applies them goes before it. So a call a task posts after the
265/// synchronous call runs after it, and one an op JS sent before the call
266/// posts runs before it. The queue runs up to the first place not
267/// released yet; a place is released whichever way its op goes (applied,
268/// or dropped unapplied: [`ParkedPost`]), so no lost op stalls it.
269#[derive(Clone, Default)]
270pub struct Posts(Rc<PostsInner>);
271
272#[derive(Default)]
273struct PostsInner {
274 queue: RefCell<VecDeque<Entry>>,
275 next_parked: Cell<u64>,
276 /// The core is applying an op JS sent ([`Posts::in_op`]).
277 in_op: Cell<u32>,
278 notify: RefCell<Option<Arc<dyn Fn() + Send + Sync>>>,
279 /// JS stopped for good: calls are dropped (their replies say so).
280 closed: Cell<bool>,
281}
282
283enum Entry {
284 Ready(JsCall),
285 /// Parked as `id`; released (runnable) once its op goes.
286 Parked {
287 id: u64,
288 call: JsCall,
289 released: bool,
290 },
291}
292
293impl fmt::Debug for Posts {
294 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
295 f.debug_struct("Posts")
296 .field("queued", &self.0.queue.borrow().len())
297 .finish()
298 }
299}
300
301impl Posts {
302 /// An empty queue.
303 pub fn new() -> Self {
304 Self::default()
305 }
306
307 /// Calls `notify` when a call becomes runnable (it wakes the engine).
308 pub fn set_notify(&self, notify: Arc<dyn Fn() + Send + Sync>) {
309 *self.0.notify.borrow_mut() = Some(notify);
310 }
311
312 fn wake(&self) {
313 let notify = self.0.notify.borrow().clone();
314 if let Some(notify) = notify {
315 notify();
316 }
317 }
318
319 /// Queues `call` and wakes the engine.
320 #[doc(hidden)]
321 pub fn post(&self, call: JsCall) {
322 if self.0.closed.get() {
323 // Dropped: a reply waiting for it is told JS stopped.
324 drop(call);
325 return;
326 }
327 {
328 let mut queue = self.0.queue.borrow_mut();
329 // An op's post goes before the places of the calls JS posted
330 // after sending it (parked, not released: their ops come
331 // later).
332 let at = (self.0.in_op.get() > 0)
333 .then(|| {
334 queue.iter().position(|e| {
335 matches!(
336 e,
337 Entry::Parked {
338 released: false,
339 ..
340 }
341 )
342 })
343 })
344 .flatten();
345 match at {
346 Some(at) => queue.insert(at, Entry::Ready(call)),
347 None => queue.push_back(Entry::Ready(call)),
348 }
349 }
350 self.wake();
351 }
352
353 /// Runs `f`, the work of an op JS sent: what it posts goes before the
354 /// calls JS posted after the op.
355 pub(crate) fn in_op<R>(&self, f: impl FnOnce() -> R) -> R {
356 struct Raised<'a>(&'a Cell<u32>);
357 impl Drop for Raised<'_> {
358 fn drop(&mut self) {
359 self.0.set(self.0.get() - 1);
360 }
361 }
362 self.0.in_op.set(self.0.in_op.get() + 1);
363 let _raised = Raised(&self.0.in_op);
364 f()
365 }
366
367 /// Queues `call` parked in its place until the place it returns is
368 /// dropped: when its op is applied, or dropped by any other path (the
369 /// call then runs in its place, or with the queue when it closes), so
370 /// a lost op never holds back the calls after it.
371 #[doc(hidden)]
372 pub fn park(&self, call: JsCall) -> ParkedPost {
373 let id = self.0.next_parked.get() + 1;
374 self.0.next_parked.set(id);
375 if self.0.closed.get() {
376 drop(call);
377 } else {
378 self.0.queue.borrow_mut().push_back(Entry::Parked {
379 id,
380 call,
381 released: false,
382 });
383 }
384 ParkedPost {
385 posts: self.clone(),
386 id,
387 }
388 }
389
390 /// Lets the call parked as `id` run in its place.
391 fn release(&self, id: u64) {
392 let found = self.0.queue.borrow_mut().iter_mut().any(|e| match e {
393 Entry::Parked {
394 id: parked,
395 released,
396 ..
397 } if *parked == id => {
398 *released = true;
399 true
400 }
401 _ => false,
402 });
403 if found {
404 self.wake();
405 }
406 }
407
408 /// No JS runs any more (the VM stopped or went): the queued calls are
409 /// dropped, and so are those posted later (their replies say so).
410 pub fn close(&self) {
411 self.0.closed.set(true);
412 let queue = std::mem::take(&mut *self.0.queue.borrow_mut());
413 drop(queue);
414 }
415
416 /// Whether a call can run now.
417 pub fn has_calls(&self) -> bool {
418 matches!(
419 self.0.queue.borrow().front(),
420 Some(Entry::Ready(_) | Entry::Parked { released: true, .. })
421 )
422 }
423
424 /// The calls that can run now, in order: up to the first parked one not
425 /// released yet.
426 #[doc(hidden)]
427 pub fn take_calls(&self) -> Vec<JsCall> {
428 let mut queue = self.0.queue.borrow_mut();
429 let mut out = Vec::new();
430 while let Some(entry) = queue.front() {
431 if matches!(
432 entry,
433 Entry::Parked {
434 released: false,
435 ..
436 }
437 ) {
438 break;
439 }
440 match queue.pop_front() {
441 Some(Entry::Ready(call) | Entry::Parked { call, .. }) => out.push(call),
442 None => break,
443 }
444 }
445 out
446 }
447}