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| executor.act(Action::FocusBack { to, from }));
268    }
269
270    /// A popup that gives the keyboard focus back to the element
271    /// ([`Self::focus_back`]) opens: the core notes the focus and whether
272    /// a pointer opened it, so a popup opened by the keyboard gives the
273    /// focus back to its trigger and, on macOS and iOS, one opened by a
274    /// pointer gives it back where it was.
275    #[doc(hidden)]
276    pub fn focus_back_origin(&self) {
277        self.reach(|to, executor| executor.act(Action::FocusOrigin { to }));
278    }
279
280    /// Ends the press going on in the element (or inside it) without its
281    /// release: no `on_press_up` or `on_press` follow, and its `active:`
282    /// styles reset (`nsh-base`'s context menu opened by a held finger).
283    #[doc(hidden)]
284    pub fn cancel_press(&self) {
285        self.send(Command::CancelPress);
286    }
287
288    /// Unfocuses an input, or takes the keyboard focus off a view that
289    /// takes presses.
290    pub fn blur(&self) {
291        self.send(Command::Blur);
292    }
293
294    /// Clears the selection of a selectable view the element is, is inside
295    /// or holds (TS: `ref.clearSelection()`): its texts lose the highlight
296    /// and the selectable view hears `on_text_selection_change` with
297    /// nothing selected.
298    pub fn clear_selection(&self) {
299        self.send(Command::ClearSelection);
300    }
301
302    /// Selects all the text of the selectable view the element is or is
303    /// inside (TS: `ref.selectAll()`), as the selection menu's Select All
304    /// does: its texts are highlighted, phones show the handles and the
305    /// edit menu, and the selectable view hears `on_text_selection_change`.
306    pub fn select_all(&self) {
307        self.send(Command::SelectAll);
308    }
309
310    /// Moves the screen reader's focus to the element (TS:
311    /// `setAccessibilityFocus(ref)`).
312    pub fn set_accessibility_focus(&self) {
313        self.send(Command::AccessibilityFocus);
314    }
315
316    /// Animates with `transition` the frames that the element's change
317    /// moves in the next commit: its own and its subtree's, its siblings'
318    /// and those of its ancestors' siblings, which its size pushes along
319    /// (and the content of those that change size). The commit's other
320    /// frames change at once, as do its insertions and removals: a region
321    /// that grows (a reveal) springs, while a list updating in the same
322    /// commit elsewhere does not. [`super::animate_layout`] animates the
323    /// whole commit instead, and wins when both are asked for.
324    pub fn animate_layout(&self, transition: LayoutTransition) {
325        self.send(Command::LayoutAnimation(LayoutAnimation {
326            update: Some(transition),
327            ..LayoutAnimation::default()
328        }));
329    }
330
331    /// Selects `start..end` of an input (UTF-16 units; a caret when equal).
332    pub fn set_selection(&self, start: u32, end: u32) {
333        self.send(Command::SetSelection { start, end });
334    }
335
336    /// Inserts `text` into an input in place of its selection, as the
337    /// user's edit ([`Command::InsertText`]): reported by `on_change`, a
338    /// step of the input's undo history where the platform keeps one. With
339    /// [`crate::PasteBehavior::Report`], what `on_paste` reported goes in
340    /// this way once the app allows it (or what the app made of it).
341    pub fn insert_text(&self, text: impl Into<String>) {
342        self.send(Command::InsertText(text.into()));
343    }
344
345    /// Opens the system's edit menu over `bounds` (in the root view) on a
346    /// focused input, offering `actions` ([`Command::OpenEditMenu`]): a
347    /// chosen action comes back as [`super::EventKind::EditAction`], a
348    /// paste as the input's `on_paste`.
349    pub fn open_edit_menu(
350        &self,
351        bounds: Bounds<Points>,
352        actions: impl IntoIterator<Item = EditAction>,
353    ) {
354        self.send(Command::OpenEditMenu {
355            bounds,
356            actions: actions.into_iter().collect(),
357        });
358    }
359
360    /// Closes the edit menu [`ElementRef::open_edit_menu`] opened.
361    pub fn close_edit_menu(&self) {
362        self.send(Command::CloseEditMenu);
363    }
364
365    /// Scrolls a scroll view to a content offset.
366    pub fn scroll_to(&self, offset: Point<Points>, animated: bool) {
367        self.send(Command::ScrollTo {
368            x: offset.x,
369            y: offset.y,
370            animated,
371        });
372    }
373
374    /// Scrolls a list to `offset` along its axis.
375    pub fn scroll_to_offset(&self, offset: Points, animated: bool) {
376        self.send(Command::ScrollTo {
377            x: offset,
378            y: offset,
379            animated,
380        });
381    }
382
383    /// Scrolls a scroll view or a list to the end of its content.
384    pub fn scroll_to_end(&self, animated: bool) {
385        self.send(Command::ScrollToEnd { animated });
386    }
387
388    /// Scrolls a list to row `index`: `view_position` 0% puts it at the
389    /// start of the viewport, 100% at the end, `view_offset` further.
390    pub fn scroll_to_index(
391        &self,
392        index: u32,
393        view_position: Percentage,
394        view_offset: Points,
395        animated: bool,
396    ) {
397        self.send(Command::ScrollToIndex {
398            index,
399            animated,
400            view_position,
401            view_offset,
402        });
403    }
404
405    /// Scrolls the scroll views around the element so it shows, placed by
406    /// `options` (TS: `ref.reveal(options)`), with the layout of
407    /// the commit this call goes out with. Lists keep their rows' offsets
408    /// to `scroll_to_index`.
409    pub fn reveal(&self, options: crate::RevealOptions) {
410        self.send(Command::Reveal(options));
411    }
412
413    /// Zooms a scroll view to `scale`, around `center` (in the content) or
414    /// keeping the middle.
415    pub fn zoom_to(&self, scale: f32, center: Option<Point<Points>>, animated: bool) {
416        self.send(Command::ZoomTo {
417            scale,
418            center,
419            animated,
420        });
421    }
422
423    /// Reloads a web view's page.
424    pub fn reload(&self) {
425        self.send(Command::Reload);
426    }
427
428    /// Goes back in a web view's history.
429    pub fn go_back(&self) {
430        self.send(Command::GoBack);
431    }
432
433    /// Goes forward in a web view's history.
434    pub fn go_forward(&self) {
435        self.send(Command::GoForward);
436    }
437
438    /// Stops a web view loading.
439    pub fn stop_loading(&self) {
440        self.send(Command::StopLoading);
441    }
442
443    /// Runs `script` in a web view's page.
444    pub fn inject_java_script(&self, script: impl Into<String>) {
445        self.send(Command::InjectJavaScript(script.into()));
446    }
447
448    /// Runs `script` in a web view's page and answers with its result
449    /// (TS: `ref.evaluate(script, options)`): the script's completion value,
450    /// a returned Promise's once it settles, as JSON. Fails with
451    /// [`codes::WEBVIEW_SCRIPT`](super::codes::WEBVIEW_SCRIPT) when the
452    /// script throws, its Promise rejects or its value is not JSON,
453    /// [`codes::WEBVIEW_ABORTED`](super::codes::WEBVIEW_ABORTED) when the
454    /// page navigates or the web view goes away first,
455    /// [`codes::TIMED_OUT`](super::codes::TIMED_OUT) after
456    /// `options.timeout`, and
457    /// [`codes::UNAVAILABLE`](super::codes::UNAVAILABLE) where the platform
458    /// has none ([`web_evaluate_available`](super::web_evaluate_available)).
459    /// Await it in a task.
460    pub fn evaluate(
461        &self,
462        script: impl Into<String>,
463        options: EvaluateOptions,
464    ) -> Answer<Result<Evaluation, super::JsError>> {
465        let (answer, slot) = Answer::new();
466        let pending = slot.clone();
467        let script = script.into();
468        if self
469            .reach(|node, executor| {
470                executor.act(Action::Evaluate(node, script, options.timeout, pending))
471            })
472            .is_none()
473        {
474            slot.borrow_mut().deliver(Err(super::JsError::Error(
475                "the ref names no web view".into(),
476            )
477            .with_code(super::codes::WEBVIEW_ABORTED)));
478        }
479        answer
480    }
481
482    /// Sends `data` to a web view's page (a `message` event on `window`).
483    pub fn post_message(&self, data: impl Into<String>) {
484        self.send(Command::PostMessage(data.into()));
485    }
486
487    /// Gives a web view's page `input` as the user's own: its events are
488    /// trusted. Needs the `webview.input` capability; macOS delivers it,
489    /// the other platforms ignore it for now
490    /// ([`web_input_available`](super::web_input_available) tells).
491    pub fn send_input(&self, input: crate::WebInput) {
492        self.send(Command::SendInput(input));
493    }
494
495    /// Loads `load.src` in a web view with `load.headers` on the document
496    /// request only (not its subresources, later navigations or reloads),
497    /// as an `Authorization` header for a signed-in page. Its host must be
498    /// one the `webview` capability allows.
499    pub fn load(&self, load: crate::WebLoad) {
500        self.send(Command::Load(load));
501    }
502
503    /// Jumps a video to `seconds`.
504    pub fn seek(&self, seconds: f64) {
505        self.send(Command::Seek(seconds));
506    }
507
508    /// Calls command `name` of a native component with `args`.
509    pub fn command(&self, name: &str, args: JsonValue) {
510        self.send(Command::Native {
511            name: name.into(),
512            args,
513        });
514    }
515
516    /// Where the element is (TS: `ref.measure()`): its frame in its parent
517    /// and its top left corner in the root view it is in (the surface or
518    /// its modal; scroll offsets applied), from the layout of the commit
519    /// this call goes out with, so changes made before it count. `None`
520    /// when no rendered element carries the ref or it is not laid out.
521    /// Await it in a task.
522    pub fn measure(&self) -> Answer<Option<Measurement>> {
523        let (answer, slot) = Answer::new();
524        let pending = slot.clone();
525        if self
526            .reach(|node, executor| executor.act(Action::Measure(node, pending)))
527            .is_none()
528        {
529            slot.borrow_mut().deliver(None);
530        }
531        answer
532    }
533
534    /// Where a list's viewport starts among its rows (TS:
535    /// `ref.measureScrollPosition()`): the row there and how far into it,
536    /// as the list lays its rows out, from the layout of the commit this
537    /// call goes out with. [`ElementRef::scroll_to_index`] with the row
538    /// and a view offset of `-offset` puts the viewport's start back
539    /// there, as for a list made anew. `None` when no rendered list
540    /// carries the ref or it has no items. Await it in a task.
541    pub fn measure_scroll_position(&self) -> Answer<Option<ListScrollPosition>> {
542        let (answer, slot) = Answer::new();
543        let pending = slot.clone();
544        if self
545            .reach(|node, executor| executor.act(Action::MeasureScrollPosition(node, pending)))
546            .is_none()
547        {
548            slot.borrow_mut().deliver(None);
549        }
550        answer
551    }
552}
553
554impl ElementRef {
555    /// Passes a press on into the element: the innermost, topmost view in
556    /// it under `press.page_position` (in its root view, as a pointer's)
557    /// that hears presses gets `onPress`, its `position` in that view, with
558    /// the layout of the commit this call goes out with. Answers whether a
559    /// view took it. For a component whose own hit layer lies over content
560    /// the app renders (a table's cells): that content's pressable views
561    /// get the presses on them. The element's own `pointerEvents` do not
562    /// count; press states stay the hit layer's, hovers are passed on with
563    /// [`Self::hover_at`]. Await it in a task.
564    pub fn press_at(&self, press: crate::PressEvent) -> Answer<bool> {
565        let (answer, slot) = Answer::new();
566        let pending = slot.clone();
567        if self
568            .reach(|node, executor| executor.act(Action::PressAt(node, press, pending)))
569            .is_none()
570        {
571            slot.borrow_mut().deliver(false);
572        }
573        answer
574    }
575
576    /// Passes a pointer on into the element, as [`Self::press_at`] does a
577    /// press: the views in it under `mouse.page_position` (in its root
578    /// view, as a pointer's) and the views around them up to the element
579    /// are hovered, with the layout of the last commit. Their `hover:`
580    /// classes and the `group-hover:` classes inside them apply, and those
581    /// that listen hear `onMouseEnter` / `onMouseLeave` as the views under
582    /// the pointer change and `onMouseMove` on each call. `None`: the
583    /// pointer left the element. For a component whose own hit layer lies
584    /// over content the app renders (a table's cells), from the hit layer's
585    /// `onMouseMove` and `onMouseLeave`. The element's own `pointerEvents`
586    /// do not count.
587    pub fn hover_at(&self, mouse: Option<crate::MouseEvent>) {
588        self.reach(|node, executor| executor.act(Action::HoverAt(node, mouse)));
589    }
590
591    /// How long the element's transitions run (`transition*`: the
592    /// longest duration plus its delay), with the styles of the commit
593    /// this call goes out with, so a class or style set before it counts;
594    /// zero when it has none or no rendered element carries the ref. The
595    /// platforms run transitions without reporting their end: a component
596    /// that keeps an element through its exit (a popup's ending style)
597    /// waits this long. Await it in a task.
598    pub fn transition_time(&self) -> Answer<std::time::Duration> {
599        let (answer, slot) = Answer::new();
600        let pending = slot.clone();
601        if self
602            .reach(|node, executor| executor.act(Action::TransitionTime(node, pending)))
603            .is_none()
604        {
605            slot.borrow_mut().deliver(std::time::Duration::ZERO);
606        }
607        answer
608    }
609
610    /// The text the element shows (the DOM's `textContent`): the texts
611    /// inside it in tree order, joined, with the commit this call goes out
612    /// with, so a text changed before it counts. What `display: none`
613    /// hides is left out; empty when no rendered element carries the ref.
614    /// For a component that matches its content's words (a menu's
615    /// typeahead). Await it in a task.
616    pub fn text_content(&self) -> Answer<String> {
617        let (answer, slot) = Answer::new();
618        let pending = slot.clone();
619        if self
620            .reach(|node, executor| executor.act(Action::TextContent(node, pending)))
621            .is_none()
622        {
623            slot.borrow_mut().deliver(String::new());
624        }
625        answer
626    }
627}
628
629impl PartialEq for ElementRef {
630    fn eq(&self, other: &Self) -> bool {
631        self.0 == other.0
632    }
633}
634
635impl fmt::Debug for ElementRef {
636    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
637        f.debug_tuple("ElementRef")
638            .field(&self.node().unwrap_or(0))
639            .finish()
640    }
641}
642
643/// A component of a view (TS: a `ref` to a component, its methods): made
644/// with [`super::component_ref`], put on the component's element
645/// ([`super::ComponentElement::component_ref`]); [`Self::api`] reaches its
646/// methods, with no encoding. A `Copy` handle, as [`ElementRef`] is.
647pub struct ComponentRef<C: Component> {
648    element: ElementRef,
649    _component: PhantomData<fn() -> C>,
650}
651
652impl<C: Component> ComponentRef<C> {
653    pub(crate) fn new(executor: &Rc<Executor>) -> Self {
654        Self {
655            element: ElementRef::new(executor),
656            _component: PhantomData,
657        }
658    }
659
660    pub(crate) fn element(&self) -> &ElementRef {
661        &self.element
662    }
663
664    /// The component's host node, while one is rendered (and the ref's
665    /// owner lives).
666    pub fn node(&self) -> Option<NodeId> {
667        self.element.node()
668    }
669
670    /// The API a component that runs once registered
671    /// ([`super::Scope::methods`]), while one is mounted: Rust calls its
672    /// methods directly (`stepper.api::<StepperApi>()?.set_value(5.0)`).
673    pub fn api<A: super::Api>(&self) -> Option<Rc<A>> {
674        super::reactive::api_of::<A>(self.node()?)
675    }
676}
677
678impl<C: Component> Clone for ComponentRef<C> {
679    fn clone(&self) -> Self {
680        *self
681    }
682}
683
684impl<C: Component> Copy for ComponentRef<C> {}
685
686impl<C: Component> PartialEq for ComponentRef<C> {
687    fn eq(&self, other: &Self) -> bool {
688        self.element == other.element
689    }
690}
691
692impl<C: Component> fmt::Debug for ComponentRef<C> {
693    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
694        f.debug_tuple("ComponentRef")
695            .field(&self.node().unwrap_or(0))
696            .finish()
697    }
698}
699
700/// How [`ElementRef::evaluate`] runs (TS: `ref.evaluate`'s options).
701#[non_exhaustive]
702#[derive(Debug, Clone, Copy, PartialEq)]
703pub struct EvaluateOptions {
704    /// How long the script may take to answer, a returned Promise
705    /// included; past it the call fails with
706    /// [`codes::TIMED_OUT`](super::codes::TIMED_OUT). 30 seconds by
707    /// default.
708    pub timeout: std::time::Duration,
709}
710
711impl Default for EvaluateOptions {
712    fn default() -> Self {
713        Self {
714            timeout: std::time::Duration::from_secs(30),
715        }
716    }
717}
718
719/// What a web view's script answered ([`ElementRef::evaluate`]; TS:
720/// `{ value }`).
721#[non_exhaustive]
722#[derive(Debug, Clone, PartialEq, Default)]
723pub struct Evaluation {
724    /// The script's result as JSON: `null`, a boolean, a finite number, a
725    /// string, an array or a plain object of these. It comes from the page:
726    /// check it before trusting it.
727    pub value: JsonValue,
728}
729
730#[cfg(test)]
731mod tests {
732    use super::*;
733    use crate::{
734        element::reactive::{Runtime, create_root},
735        geometry::{point, px},
736    };
737
738    fn commands(executor: &Executor) -> Vec<(NodeId, Command)> {
739        executor
740            .take_actions()
741            .into_iter()
742            .filter_map(|a| match a {
743                Action::Command(node, command) => Some((node, command)),
744                _ => None,
745            })
746            .collect()
747    }
748
749    #[test]
750    fn refs_are_copies_until_their_owner_goes() {
751        let runtime = Runtime::default();
752        let entered = runtime.enter();
753        let executor = Rc::new(Executor::default());
754        let (owner, field) = create_root(|| ElementRef::new(&executor));
755        let carried = field.target().expect("live");
756        carried.attach(7);
757        // Copies, in closures or not, name the one element.
758        let focus = move || field.focus();
759        let blur = move || field.blur();
760        focus();
761        blur();
762        let copy = field;
763        assert_eq!((copy, copy.node()), (field, Some(7)));
764        assert_eq!(format!("{field:?}"), "ElementRef(7)");
765        assert_eq!(
766            commands(&executor),
767            [(7, Command::Focus), (7, Command::Blur)]
768        );
769
770        // Its owner goes: it names nothing and does nothing; the element
771        // still holding what it named mounts and unmounts as before.
772        owner.dispose();
773        assert_eq!(field.node(), None);
774        focus();
775        field.scroll_to(point(px(0.0), px(10.0)), false);
776        assert_eq!(commands(&executor), []);
777        assert!(field.target().is_none());
778        carried.detach(7);
779        carried.attach(9);
780        assert_eq!(field.node(), None);
781        assert_eq!(format!("{field:?}"), "ElementRef(0)");
782
783        // Off the engine thread (no graph entered), a live ref names
784        // nothing either, and does not panic.
785        let live = ElementRef::new(&executor);
786        live.target().expect("live").attach(3);
787        drop(entered);
788        assert_eq!(live.node(), None);
789    }
790}