This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

yew_agent/
scope_ext.rs

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
//! This module contains extensions to the component scope for agent access.

use std::any::type_name;
use std::fmt;
use std::rc::Rc;

use futures::stream::SplitSink;
use futures::{SinkExt, StreamExt};
use wasm_bindgen::UnwrapThrowExt;
use yew::html::Scope;
use yew::platform::pinned::RwLock;
use yew::platform::spawn_local;
use yew::prelude::*;

use crate::oneshot::{Oneshot, OneshotProviderState};
use crate::reactor::{Reactor, ReactorBridge, ReactorEvent, ReactorProviderState, ReactorScoped};
use crate::worker::{Worker, WorkerBridge, WorkerProviderState};

/// A Worker Bridge Handle.
#[derive(Debug)]
pub struct WorkerBridgeHandle<W>
where
    W: Worker,
{
    inner: WorkerBridge<W>,
}

impl<W> WorkerBridgeHandle<W>
where
    W: Worker,
{
    /// Sends a message to the worker agent.
    pub fn send(&self, input: W::Input) {
        self.inner.send(input)
    }
}

type ReactorTx<R> =
    Rc<RwLock<SplitSink<ReactorBridge<R>, <<R as Reactor>::Scope as ReactorScoped>::Input>>>;

/// A Reactor Bridge Handle.
pub struct ReactorBridgeHandle<R>
where
    R: Reactor + 'static,
{
    tx: ReactorTx<R>,
}

impl<R> fmt::Debug for ReactorBridgeHandle<R>
where
    R: Reactor + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct(type_name::<Self>()).finish_non_exhaustive()
    }
}

impl<R> ReactorBridgeHandle<R>
where
    R: Reactor + 'static,
{
    /// Sends a message to the reactor agent.
    pub fn send(&self, input: <R::Scope as ReactorScoped>::Input) {
        let tx = self.tx.clone();
        spawn_local(async move {
            let mut tx = tx.write().await;
            let _ = tx.send(input).await;
        });
    }
}

/// An extension to [`Scope`](yew::html::Scope) that provides communication mechanism to agents.
///
/// You can access them on `ctx.link()`
pub trait AgentScopeExt {
    /// Bridges to a Worker Agent.
    fn bridge_worker<W>(&self, callback: Callback<W::Output>) -> WorkerBridgeHandle<W>
    where
        W: Worker + 'static;

    /// Bridges to a Reactor Agent.
    fn bridge_reactor<R>(&self, callback: Callback<ReactorEvent<R>>) -> ReactorBridgeHandle<R>
    where
        R: Reactor + 'static,
        <R::Scope as ReactorScoped>::Output: 'static;

    /// Runs an oneshot in an Oneshot Agent.
    fn run_oneshot<T>(&self, input: T::Input, callback: Callback<T::Output>)
    where
        T: Oneshot + 'static;
}

impl<COMP> AgentScopeExt for Scope<COMP>
where
    COMP: Component,
{
    fn bridge_worker<W>(&self, callback: Callback<W::Output>) -> WorkerBridgeHandle<W>
    where
        W: Worker + 'static,
    {
        let inner = self
            .context::<Rc<WorkerProviderState<W>>>((|_| {}).into())
            .expect_throw("failed to bridge to agent.")
            .0
            .create_bridge(callback);

        WorkerBridgeHandle { inner }
    }

    fn bridge_reactor<R>(&self, callback: Callback<ReactorEvent<R>>) -> ReactorBridgeHandle<R>
    where
        R: Reactor + 'static,
        <R::Scope as ReactorScoped>::Output: 'static,
    {
        let (tx, mut rx) = self
            .context::<ReactorProviderState<R>>((|_| {}).into())
            .expect_throw("failed to bridge to agent.")
            .0
            .create_bridge()
            .split();

        spawn_local(async move {
            while let Some(m) = rx.next().await {
                callback.emit(ReactorEvent::<R>::Output(m));
            }

            callback.emit(ReactorEvent::<R>::Finished);
        });

        let tx = Rc::new(RwLock::new(tx));

        ReactorBridgeHandle { tx }
    }

    fn run_oneshot<T>(&self, input: T::Input, callback: Callback<T::Output>)
    where
        T: Oneshot + 'static,
    {
        let (inner, _) = self
            .context::<OneshotProviderState<T>>((|_| {}).into())
            .expect_throw("failed to bridge to agent.");

        spawn_local(async move { callback.emit(inner.create_bridge().run(input).await) });
    }
}