Skip to main content

nsh_core/element/
element_ref.rs

1//! Handles to the elements a component renders (TS: `ref`), to send
2//! them commands: focus an input, scroll a scroll view, drive a web view or
3//! a video, call a native component; and to the components it renders, to
4//! call their methods ([`ComponentRef`]).
5//!
6//! Both are `Copy` handles kept by the reactive owner current when one is
7//! made (the component, a region, a row), as signals are: closures share
8//! them as they are, and they are released when that owner is disposed.
9//! Used after that, a ref does nothing and names no node (no panic). The
10//! element carrying a ref holds what it names ([`RefTarget`]) for as long
11//! as it is mounted, so mounting and unmounting it never reach the ref's
12//! owner. Listeners and tasks run under the owner that made them, so a ref
13//! one makes is that owner's; made with no owner at all (outside any
14//! component), a ref lives as long as the surface, as a signal made there
15//! does.
16
17use std::{
18    cell::Cell,
19    fmt,
20    marker::PhantomData,
21    rc::{Rc, Weak},
22};
23
24use super::{
25    Answer, Component,
26    reactive::Kept,
27    task::{Action, Executor},
28};
29use crate::{
30    Command, EditAction, JsonValue, LayoutAnimation, LayoutTransition, ListScrollPosition,
31    Measurement, NodeId,
32    geometry::{Bounds, Percentage, Point, Points},
33};
34
35/// An element of a view: made with [`super::element_ref`], put on
36/// the element ([`super::Element::element_ref`]). Its commands go to
37/// whatever element carries it now, in order with the component's other
38/// changes; they do nothing while no rendered element carries it, and once
39/// the owner it was made under is gone. Works from listeners and tasks
40/// alike. A `Copy` handle (see the module's docs).
41#[derive(Clone, Copy)]
42pub struct ElementRef(Kept<Target>);
43
44/// What an element ref names: the node carrying it and where its commands
45/// go.
46pub(crate) struct Target {
47    /// The node, 0 while none carries it.
48    node: Cell<NodeId>,
49    executor: Weak<Executor>,
50}
51
52/// What the element carrying a ref holds, to tell the ref where it is.
53#[derive(Clone)]
54pub(crate) struct RefTarget(Rc<Target>);
55
56impl RefTarget {
57    pub(crate) fn attach(&self, node: NodeId) {
58        self.0.node.set(node);
59    }
60
61    /// Forgets `node` when it is the one carrying the ref.
62    pub(crate) fn detach(&self, node: NodeId) {
63        if self.0.node.get() == node {
64            self.0.node.set(0);
65        }
66    }
67}
68
69impl fmt::Debug for RefTarget {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        f.debug_tuple("RefTarget")
72            .field(&self.0.node.get())
73            .finish()
74    }
75}
76
77impl PartialEq for RefTarget {
78    fn eq(&self, other: &Self) -> bool {
79        Rc::ptr_eq(&self.0, &other.0)
80    }
81}
82
83/// The element a view's frame follows ([`super::View::follow`]): whatever
84/// element carries the ref, looked up as the core lays out, so the
85/// element may be rendered after the view that follows it.
86#[derive(Debug, Clone, PartialEq)]
87pub struct FollowTarget(pub(crate) RefTarget);
88
89impl FollowTarget {
90    /// The node carrying the ref now.
91    pub(crate) fn node(&self) -> Option<NodeId> {
92        Some(self.0.0.node.get()).filter(|&n| n != 0)
93    }
94
95    /// A target carried by `node`, with no ref behind it (the core's
96    /// tests).
97    #[cfg(test)]
98    pub(crate) fn of_node(node: NodeId) -> Self {
99        Self(RefTarget(Rc::new(Target {
100            node: Cell::new(node),
101            executor: Weak::new(),
102        })))
103    }
104}
105
106/// An element another one names for assistive technologies
107/// ([`crate::AccessibilityProp::ActiveDescendant`],
108/// [`crate::AccessibilityProp::Controls`],
109/// [`crate::AccessibilityProp::DescribedBy`]) or as the scroll view it
110/// floats over ([`ScrollEdgeTarget`]): a node JS passes (a `ref`),
111/// or whatever element carries a Rust [`ElementRef`], looked up as the
112/// core commits, so the element may be rendered after the one naming it
113/// (a list's row made as the list lays out).
114#[derive(Debug, Clone, PartialEq)]
115pub struct ElementTarget(pub(crate) Named);
116
117/// What an [`ElementTarget`] names.
118#[derive(Debug, Clone, PartialEq)]
119pub(crate) enum Named {
120    /// A node JS made.
121    Node(NodeId),
122    /// The node carrying a Rust ref.
123    Ref(RefTarget),
124}
125
126/// A Rust ref, as the element carrying it (a component's prop that names
127/// an element, set from Rust: `Some(error_line)`).
128impl From<ElementRef> for Option<ElementTarget> {
129    fn from(element: ElementRef) -> Self {
130        element.element_target()
131    }
132}
133
134/// `ViewRef`: a node JS passes (a `ref`), as a component's prop that names
135/// an element.
136impl super::JsValue for ElementTarget {
137    fn ts_type(_types: &mut super::TsTypes) -> String {
138        "ViewRef".into()
139    }
140
141    fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
142        value
143            .host()
144            .node(value.raw())
145            .map(Self::of_node)
146            .ok_or_else(|| value.expected("a node"))
147    }
148
149    /// The node's JS object (`null` while none carries it).
150    fn to_js<'a>(
151        &self,
152        host: &'a dyn super::JsHost,
153    ) -> Result<super::JsOwned<'a>, super::PropError> {
154        Ok(super::JsOwned::new(
155            host,
156            match self.node() {
157                Some(node) => host.node_value(node),
158                None => host.null(),
159            },
160        ))
161    }
162}
163
164impl ElementTarget {
165    /// Node `node` (JS's ref).
166    pub(crate) fn of_node(node: NodeId) -> Self {
167        Self(Named::Node(node))
168    }
169
170    /// The node it names now.
171    pub(crate) fn node(&self) -> Option<NodeId> {
172        match &self.0 {
173            Named::Node(node) => Some(*node),
174            Named::Ref(target) => Some(target.0.node.get()).filter(|&n| n != 0),
175        }
176    }
177}
178
179/// The scroll view a view floats over and the edge of it the view sits
180/// at ([`crate::Prop::ScrollEdgeElement`], `ios={{ scrollEdgeElement }}`).
181/// The scroll view is looked up as the core commits, as an
182/// [`ElementTarget`] is.
183#[derive(Debug, Clone, PartialEq)]
184pub struct ScrollEdgeTarget {
185    pub(crate) scroll_view: ElementTarget,
186    pub(crate) edge: crate::ScrollEdge,
187}
188
189impl ScrollEdgeTarget {
190    /// Scroll view `scroll_view` (JS's ref), at `edge`.
191    pub(crate) fn of_node(scroll_view: NodeId, edge: crate::ScrollEdge) -> Self {
192        Self {
193            scroll_view: ElementTarget::of_node(scroll_view),
194            edge,
195        }
196    }
197}
198
199impl ElementRef {
200    /// What names the element carrying it for assistive technologies
201    /// ([`ElementTarget`]); `None` once its owner is gone.
202    pub(crate) fn element_target(&self) -> Option<ElementTarget> {
203        self.target().map(|t| ElementTarget(Named::Ref(t)))
204    }
205
206    pub(crate) fn new(executor: &Rc<Executor>) -> Self {
207        Self(Kept::new(Rc::new(Target {
208            node: Cell::new(0),
209            executor: Rc::downgrade(executor),
210        })))
211    }
212
213    /// The element's node, while one is rendered (and the ref's owner
214    /// lives).
215    pub fn node(&self) -> Option<NodeId> {
216        self.0.with(|t| t.node.get()).filter(|&n| n != 0)
217    }
218
219    /// What an element carrying the ref holds; `None` once its owner is
220    /// gone.
221    pub(crate) fn target(&self) -> Option<RefTarget> {
222        self.0.get().map(RefTarget)
223    }
224
225    /// `act` of the node carrying it and its executor, if one does (it
226    /// runs inside the graph's borrow: queuing an action reaches only the
227    /// executor).
228    fn reach<R>(&self, act: impl FnOnce(NodeId, &Executor) -> R) -> Option<R> {
229        self.0
230            .with(|t| {
231                let node = t.node.get();
232                let executor = t.executor.upgrade().filter(|_| node != 0)?;
233                Some(act(node, &executor))
234            })
235            .flatten()
236    }
237
238    pub(crate) fn send(&self, command: Command) {
239        self.reach(|node, executor| executor.act(Action::Command(node, command)));
240    }
241
242    /// Focuses an input (showing the keyboard), or gives a view that takes
243    /// presses the keyboard focus where Tab stops at it (macOS, the web),
244    /// as Tab does: `focus:` styles, `on_focus`. A view `focusable(false)`,
245    /// disabled or hidden stays unfocused.
246    pub fn focus(&self) {
247        self.send(Command::Focus);
248    }
249
250    /// [`Self::focus`] as `from` closes, given way to any other move of the
251    /// focus out of `from` in the same commit (a `focus()` from Rust or
252    /// JS): a popup closing gives the keyboard focus back to its trigger,
253    /// but not over the focus the choice that closed it moved elsewhere (an
254    /// item that starts editing a field). A move inside `from` does not
255    /// count: it is going, and keys typed ahead (Down, then Return) move
256    /// the focus to the item they choose in the commit that closes it. The
257    /// last one asked for in a commit is the one that counts.
258    ///
259    /// On macOS and iOS, a popup opened by a pointer ([`Self::focus_back_origin`] called on
260    /// this element as it opened) gives the focus back where it was when
261    /// it opened instead, or takes it off the popup when nothing had it:
262    /// a pointer's press leaves the keyboard focus where it is, so the
263    /// trigger it pressed never had it.
264    #[doc(hidden)]
265    pub fn focus_back(&self, from: ElementRef) {
266        let from = from.node();
267        self.reach(|to, executor| {
268            executor.act(Action::FocusBack {
269                to,
270                from,
271                past: None,
272            })
273        });
274    }
275
276    /// [`Self::focus_back`], to the stop that comes after the element in
277    /// the Tab order (`forward`) or before it instead, as a Tab or
278    /// Shift+Tab pressed on it would move the focus: a menu Tab closes
279    /// moves the focus on from its trigger in that one press (WAI-ARIA's
280    /// menu button). The stops are those of the element's window (or the
281    /// dialog it is in), in the app's tree order, past `from` and wrapping
282    /// around at the ends; with no other stop, the element itself. On
283    /// every platform, whether its own toolkit or the core orders Tab:
284    /// the key itself stops at the popup, whose window may be the key one.
285    #[doc(hidden)]
286    pub fn focus_past(&self, from: ElementRef, forward: bool) {
287        let from = from.node();
288        self.reach(|to, executor| {
289            executor.act(Action::FocusBack {
290                to,
291                from,
292                past: Some(forward),
293            })
294        });
295    }
296
297    /// A popup that gives the keyboard focus back to the element
298    /// ([`Self::focus_back`]) opens: the core notes the focus and whether
299    /// a pointer opened it, so a popup opened by the keyboard gives the
300    /// focus back to its trigger and, on macOS and iOS, one opened by a
301    /// pointer gives it back where it was.
302    #[doc(hidden)]
303    pub fn focus_back_origin(&self) {
304        self.reach(|to, executor| executor.act(Action::FocusOrigin { to }));
305    }
306
307    /// Ends the press going on in the element (or inside it) without its
308    /// release: no `on_press_up` or `on_press` follow, and its `active:`
309    /// styles reset (`nsh-base`'s context menu opened by a held finger).
310    #[doc(hidden)]
311    pub fn cancel_press(&self) {
312        self.send(Command::CancelPress);
313    }
314
315    /// Unfocuses an input, or takes the keyboard focus off a view that
316    /// takes presses.
317    pub fn blur(&self) {
318        self.send(Command::Blur);
319    }
320
321    /// Clears the selection of a selectable view the element is, is inside
322    /// or holds (TS: `ref.clearSelection()`): its texts lose the highlight
323    /// and the selectable view hears `on_text_selection_change` with
324    /// nothing selected.
325    pub fn clear_selection(&self) {
326        self.send(Command::ClearSelection);
327    }
328
329    /// Selects all the text of the selectable view the element is or is
330    /// inside (TS: `ref.selectAll()`), as the selection menu's Select All
331    /// does: its texts are highlighted, phones show the handles and the
332    /// edit menu, and the selectable view hears `on_text_selection_change`.
333    pub fn select_all(&self) {
334        self.send(Command::SelectAll);
335    }
336
337    /// Moves the screen reader's focus to the element (TS:
338    /// `setAccessibilityFocus(ref)`).
339    pub fn set_accessibility_focus(&self) {
340        self.send(Command::AccessibilityFocus);
341    }
342
343    /// Animates with `transition` the frames that the element's change
344    /// moves in the next commit: its own and its subtree's, its siblings'
345    /// and those of its ancestors' siblings, which its size pushes along
346    /// (and the content of those that change size). The commit's other
347    /// frames change at once, as do its insertions and removals: a region
348    /// that grows (a reveal) springs, while a list updating in the same
349    /// commit elsewhere does not. [`super::animate_layout`] animates the
350    /// whole commit instead, and wins when both are asked for.
351    pub fn animate_layout(&self, transition: LayoutTransition) {
352        self.send(Command::LayoutAnimation(LayoutAnimation {
353            update: Some(transition),
354            ..LayoutAnimation::default()
355        }));
356    }
357
358    /// Selects `start..end` of an input (UTF-16 units; a caret when equal).
359    pub fn set_selection(&self, start: u32, end: u32) {
360        self.send(Command::SetSelection { start, end });
361    }
362
363    /// Inserts `text` into an input in place of its selection, as the
364    /// user's edit ([`Command::InsertText`]): reported by `on_change`, a
365    /// step of the input's undo history where the platform keeps one. With
366    /// [`crate::PasteBehavior::Report`], what `on_paste` reported goes in
367    /// this way once the app allows it (or what the app made of it).
368    pub fn insert_text(&self, text: impl Into<String>) {
369        self.send(Command::InsertText(text.into()));
370    }
371
372    /// Opens the system's edit menu over `bounds` (in the root view) on a
373    /// focused input, offering `actions` ([`Command::OpenEditMenu`]): a
374    /// chosen action comes back as [`super::EventKind::EditAction`], a
375    /// paste as the input's `on_paste`.
376    pub fn open_edit_menu(
377        &self,
378        bounds: Bounds<Points>,
379        actions: impl IntoIterator<Item = EditAction>,
380    ) {
381        self.send(Command::OpenEditMenu {
382            bounds,
383            actions: actions.into_iter().collect(),
384        });
385    }
386
387    /// Closes the edit menu [`ElementRef::open_edit_menu`] opened.
388    pub fn close_edit_menu(&self) {
389        self.send(Command::CloseEditMenu);
390    }
391
392    /// Scrolls a scroll view to a content offset.
393    pub fn scroll_to(&self, offset: Point<Points>, animated: bool) {
394        self.send(Command::ScrollTo {
395            x: offset.x,
396            y: offset.y,
397            animated,
398        });
399    }
400
401    /// Scrolls a list to `offset` along its axis.
402    pub fn scroll_to_offset(&self, offset: Points, animated: bool) {
403        self.send(Command::ScrollTo {
404            x: offset,
405            y: offset,
406            animated,
407        });
408    }
409
410    /// Scrolls a scroll view or a list to the end of its content.
411    pub fn scroll_to_end(&self, animated: bool) {
412        self.send(Command::ScrollToEnd { animated });
413    }
414
415    /// Scrolls a list to row `index`: `view_position` 0% puts it at the
416    /// start of the viewport, 100% at the end, `view_offset` further.
417    pub fn scroll_to_index(
418        &self,
419        index: u32,
420        view_position: Percentage,
421        view_offset: Points,
422        animated: bool,
423    ) {
424        self.send(Command::ScrollToIndex {
425            index,
426            animated,
427            view_position,
428            view_offset,
429        });
430    }
431
432    /// Scrolls the scroll views around the element so it shows, placed by
433    /// `options` (TS: `ref.reveal(options)`), with the layout of
434    /// the commit this call goes out with. Lists keep their rows' offsets
435    /// to `scroll_to_index`.
436    pub fn reveal(&self, options: crate::RevealOptions) {
437        self.send(Command::Reveal(options));
438    }
439
440    /// Zooms a scroll view to `scale`, around `center` (in the content) or
441    /// keeping the middle.
442    pub fn zoom_to(&self, scale: f32, center: Option<Point<Points>>, animated: bool) {
443        self.send(Command::ZoomTo {
444            scale,
445            center,
446            animated,
447        });
448    }
449
450    /// Reloads a web view's page.
451    pub fn reload(&self) {
452        self.send(Command::Reload);
453    }
454
455    /// Goes back in a web view's history.
456    pub fn go_back(&self) {
457        self.send(Command::GoBack);
458    }
459
460    /// Goes forward in a web view's history.
461    pub fn go_forward(&self) {
462        self.send(Command::GoForward);
463    }
464
465    /// Stops a web view loading.
466    pub fn stop_loading(&self) {
467        self.send(Command::StopLoading);
468    }
469
470    /// Runs `script` in a web view's page.
471    pub fn inject_java_script(&self, script: impl Into<String>) {
472        self.send(Command::InjectJavaScript(script.into()));
473    }
474
475    /// Runs `script` in a web view's page and answers with its result
476    /// (TS: `ref.evaluate(script, options)`): the script's completion value,
477    /// a returned Promise's once it settles, as JSON. Fails with
478    /// [`codes::WEBVIEW_SCRIPT`](super::codes::WEBVIEW_SCRIPT) when the
479    /// script throws, its Promise rejects or its value is not JSON,
480    /// [`codes::WEBVIEW_ABORTED`](super::codes::WEBVIEW_ABORTED) when the
481    /// page navigates or the web view goes away first,
482    /// [`codes::TIMED_OUT`](super::codes::TIMED_OUT) after
483    /// `options.timeout`, and
484    /// [`codes::UNAVAILABLE`](super::codes::UNAVAILABLE) where the platform
485    /// has none ([`web_evaluate_available`](super::web_evaluate_available)).
486    /// Await it in a task.
487    pub fn evaluate(
488        &self,
489        script: impl Into<String>,
490        options: EvaluateOptions,
491    ) -> Answer<Result<Evaluation, super::JsError>> {
492        let (answer, slot) = Answer::new();
493        let pending = slot.clone();
494        let script = script.into();
495        if self
496            .reach(|node, executor| {
497                executor.act(Action::Evaluate(node, script, options.timeout, pending))
498            })
499            .is_none()
500        {
501            slot.borrow_mut().deliver(Err(super::JsError::Error(
502                "the ref names no web view".into(),
503            )
504            .with_code(super::codes::WEBVIEW_ABORTED)));
505        }
506        answer
507    }
508
509    /// Sends `data` to a web view's page (a `message` event on `window`).
510    pub fn post_message(&self, data: impl Into<String>) {
511        self.send(Command::PostMessage(data.into()));
512    }
513
514    /// Gives a web view's page `input` as the user's own: its events are
515    /// trusted. Needs the `webview.input` capability; macOS delivers it,
516    /// the other platforms ignore it for now
517    /// ([`web_input_available`](super::web_input_available) tells).
518    pub fn send_input(&self, input: crate::WebInput) {
519        self.send(Command::SendInput(input));
520    }
521
522    /// Loads `load.src` in a web view with `load.headers` on the document
523    /// request only (not its subresources, later navigations or reloads),
524    /// as an `Authorization` header for a signed-in page. Its host must be
525    /// one the `webview` capability allows.
526    pub fn load(&self, load: crate::WebLoad) {
527        self.send(Command::Load(load));
528    }
529
530    /// Jumps a video to `seconds`.
531    pub fn seek(&self, seconds: f64) {
532        self.send(Command::Seek(seconds));
533    }
534
535    /// Calls command `name` of a native component with `args`.
536    pub fn command(&self, name: &str, args: JsonValue) {
537        self.send(Command::Native {
538            name: name.into(),
539            args,
540        });
541    }
542
543    /// Where the element is (TS: `ref.measure()`): its frame in its parent
544    /// and its top left corner in the root view it is in (the surface or
545    /// its modal; scroll offsets applied), from the layout of the commit
546    /// this call goes out with, so changes made before it count. `None`
547    /// when no rendered element carries the ref or it is not laid out.
548    /// Await it in a task.
549    pub fn measure(&self) -> Answer<Option<Measurement>> {
550        let (answer, slot) = Answer::new();
551        let pending = slot.clone();
552        if self
553            .reach(|node, executor| executor.act(Action::Measure(node, pending)))
554            .is_none()
555        {
556            slot.borrow_mut().deliver(None);
557        }
558        answer
559    }
560
561    /// Where a list's viewport starts among its rows (TS:
562    /// `ref.measureScrollPosition()`): the row there and how far into it,
563    /// as the list lays its rows out, from the layout of the commit this
564    /// call goes out with. [`ElementRef::scroll_to_index`] with the row
565    /// and a view offset of `-offset` puts the viewport's start back
566    /// there, as for a list made anew. `None` when no rendered list
567    /// carries the ref or it has no items. Await it in a task.
568    pub fn measure_scroll_position(&self) -> Answer<Option<ListScrollPosition>> {
569        let (answer, slot) = Answer::new();
570        let pending = slot.clone();
571        if self
572            .reach(|node, executor| executor.act(Action::MeasureScrollPosition(node, pending)))
573            .is_none()
574        {
575            slot.borrow_mut().deliver(None);
576        }
577        answer
578    }
579}
580
581impl ElementRef {
582    /// Passes a press on into the element: the innermost, topmost view in
583    /// it under `press.page_position` (in its root view, as a pointer's)
584    /// that hears presses gets `onPress`, its `position` in that view, with
585    /// the layout of the commit this call goes out with. Answers whether a
586    /// view took it. For a component whose own hit layer lies over content
587    /// the app renders (a table's cells): that content's pressable views
588    /// get the presses on them. The element's own `pointerEvents` do not
589    /// count; press states stay the hit layer's, hovers are passed on with
590    /// [`Self::hover_at`]. Await it in a task.
591    pub fn press_at(&self, press: crate::PressEvent) -> Answer<bool> {
592        let (answer, slot) = Answer::new();
593        let pending = slot.clone();
594        if self
595            .reach(|node, executor| executor.act(Action::PressAt(node, press, pending)))
596            .is_none()
597        {
598            slot.borrow_mut().deliver(false);
599        }
600        answer
601    }
602
603    /// Passes a pointer on into the element, as [`Self::press_at`] does a
604    /// press: the views in it under `mouse.page_position` (in its root
605    /// view, as a pointer's) and the views around them up to the element
606    /// are hovered, with the layout of the last commit. Their `hover:`
607    /// classes and the `group-hover:` classes inside them apply, and those
608    /// that listen hear `onMouseEnter` / `onMouseLeave` as the views under
609    /// the pointer change and `onMouseMove` on each call. `None`: the
610    /// pointer left the element. For a component whose own hit layer lies
611    /// over content the app renders (a table's cells), from the hit layer's
612    /// `onMouseMove` and `onMouseLeave`. The element's own `pointerEvents`
613    /// do not count.
614    pub fn hover_at(&self, mouse: Option<crate::MouseEvent>) {
615        self.reach(|node, executor| executor.act(Action::HoverAt(node, mouse)));
616    }
617
618    /// How long the element's transitions run (`transition*`: the
619    /// longest duration plus its delay), with the styles of the commit
620    /// this call goes out with, so a class or style set before it counts;
621    /// zero when it has none or no rendered element carries the ref. The
622    /// platforms run transitions without reporting their end: a component
623    /// that keeps an element through its exit (a popup's ending style)
624    /// waits this long. Await it in a task.
625    pub fn transition_time(&self) -> Answer<std::time::Duration> {
626        let (answer, slot) = Answer::new();
627        let pending = slot.clone();
628        if self
629            .reach(|node, executor| executor.act(Action::TransitionTime(node, pending)))
630            .is_none()
631        {
632            slot.borrow_mut().deliver(std::time::Duration::ZERO);
633        }
634        answer
635    }
636
637    /// The text the element shows (the DOM's `textContent`): the texts
638    /// inside it in tree order, joined, with the commit this call goes out
639    /// with, so a text changed before it counts. What `display: none`
640    /// hides is left out; empty when no rendered element carries the ref.
641    /// For a component that matches its content's words (a menu's
642    /// typeahead). Await it in a task.
643    pub fn text_content(&self) -> Answer<String> {
644        let (answer, slot) = Answer::new();
645        let pending = slot.clone();
646        if self
647            .reach(|node, executor| executor.act(Action::TextContent(node, pending)))
648            .is_none()
649        {
650            slot.borrow_mut().deliver(String::new());
651        }
652        answer
653    }
654}
655
656impl PartialEq for ElementRef {
657    fn eq(&self, other: &Self) -> bool {
658        self.0 == other.0
659    }
660}
661
662impl fmt::Debug for ElementRef {
663    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
664        f.debug_tuple("ElementRef")
665            .field(&self.node().unwrap_or(0))
666            .finish()
667    }
668}
669
670/// A component of a view (TS: a `ref` to a component, its methods): made
671/// with [`super::component_ref`], put on the component's element
672/// ([`super::ComponentElement::component_ref`]); [`Self::api`] reaches its
673/// methods, with no encoding. A `Copy` handle, as [`ElementRef`] is.
674pub struct ComponentRef<C: Component> {
675    element: ElementRef,
676    _component: PhantomData<fn() -> C>,
677}
678
679impl<C: Component> ComponentRef<C> {
680    pub(crate) fn new(executor: &Rc<Executor>) -> Self {
681        Self {
682            element: ElementRef::new(executor),
683            _component: PhantomData,
684        }
685    }
686
687    pub(crate) fn element(&self) -> &ElementRef {
688        &self.element
689    }
690
691    /// The component's host node, while one is rendered (and the ref's
692    /// owner lives).
693    pub fn node(&self) -> Option<NodeId> {
694        self.element.node()
695    }
696
697    /// The API a component that runs once registered
698    /// ([`super::Scope::methods`]), while one is mounted: Rust calls its
699    /// methods directly (`stepper.api::<StepperApi>()?.set_value(5.0)`).
700    pub fn api<A: super::Api>(&self) -> Option<Rc<A>> {
701        super::reactive::api_of::<A>(self.node()?)
702    }
703}
704
705impl<C: Component> Clone for ComponentRef<C> {
706    fn clone(&self) -> Self {
707        *self
708    }
709}
710
711impl<C: Component> Copy for ComponentRef<C> {}
712
713impl<C: Component> PartialEq for ComponentRef<C> {
714    fn eq(&self, other: &Self) -> bool {
715        self.element == other.element
716    }
717}
718
719impl<C: Component> fmt::Debug for ComponentRef<C> {
720    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
721        f.debug_tuple("ComponentRef")
722            .field(&self.node().unwrap_or(0))
723            .finish()
724    }
725}
726
727/// How [`ElementRef::evaluate`] runs (TS: `ref.evaluate`'s options).
728#[non_exhaustive]
729#[derive(Debug, Clone, Copy, PartialEq)]
730pub struct EvaluateOptions {
731    /// How long the script may take to answer, a returned Promise
732    /// included; past it the call fails with
733    /// [`codes::TIMED_OUT`](super::codes::TIMED_OUT). 30 seconds by
734    /// default.
735    pub timeout: std::time::Duration,
736}
737
738impl Default for EvaluateOptions {
739    fn default() -> Self {
740        Self {
741            timeout: std::time::Duration::from_secs(30),
742        }
743    }
744}
745
746/// What a web view's script answered ([`ElementRef::evaluate`]; TS:
747/// `{ value }`).
748#[non_exhaustive]
749#[derive(Debug, Clone, PartialEq, Default)]
750pub struct Evaluation {
751    /// The script's result as JSON: `null`, a boolean, a finite number, a
752    /// string, an array or a plain object of these. It comes from the page:
753    /// check it before trusting it.
754    pub value: JsonValue,
755}
756
757#[cfg(test)]
758mod tests {
759    use super::*;
760    use crate::{
761        element::reactive::{Runtime, create_root},
762        geometry::{point, px},
763    };
764
765    fn commands(executor: &Executor) -> Vec<(NodeId, Command)> {
766        executor
767            .take_actions()
768            .into_iter()
769            .filter_map(|a| match a {
770                Action::Command(node, command) => Some((node, command)),
771                _ => None,
772            })
773            .collect()
774    }
775
776    #[test]
777    fn refs_are_copies_until_their_owner_goes() {
778        let runtime = Runtime::default();
779        let entered = runtime.enter();
780        let executor = Rc::new(Executor::default());
781        let (owner, field) = create_root(|| ElementRef::new(&executor));
782        let carried = field.target().expect("live");
783        carried.attach(7);
784        // Copies, in closures or not, name the one element.
785        let focus = move || field.focus();
786        let blur = move || field.blur();
787        focus();
788        blur();
789        let copy = field;
790        assert_eq!((copy, copy.node()), (field, Some(7)));
791        assert_eq!(format!("{field:?}"), "ElementRef(7)");
792        assert_eq!(
793            commands(&executor),
794            [(7, Command::Focus), (7, Command::Blur)]
795        );
796
797        // Its owner goes: it names nothing and does nothing; the element
798        // still holding what it named mounts and unmounts as before.
799        owner.dispose();
800        assert_eq!(field.node(), None);
801        focus();
802        field.scroll_to(point(px(0.0), px(10.0)), false);
803        assert_eq!(commands(&executor), []);
804        assert!(field.target().is_none());
805        carried.detach(7);
806        carried.attach(9);
807        assert_eq!(field.node(), None);
808        assert_eq!(format!("{field:?}"), "ElementRef(0)");
809
810        // Off the engine thread (no graph entered), a live ref names
811        // nothing either, and does not panic.
812        let live = ElementRef::new(&executor);
813        live.target().expect("live").attach(3);
814        drop(entered);
815        assert_eq!(live.node(), None);
816    }
817}