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

yew_agent/
utils.rs

1use std::rc::Rc;
2use std::sync::atomic::{AtomicUsize, Ordering};
3
4use wasm_bindgen::UnwrapThrowExt;
5use yew::Reducible;
6
7/// Convenience function to avoid repeating expect logic.
8pub fn window() -> web_sys::Window {
9    web_sys::window().expect_throw("Can't find the global Window")
10}
11
12/// Gets a unique worker id
13pub(crate) fn get_next_id() -> usize {
14    static CTR: AtomicUsize = AtomicUsize::new(0);
15
16    CTR.fetch_add(1, Ordering::SeqCst)
17}
18
19#[derive(Default, PartialEq)]
20pub(crate) struct BridgeIdState {
21    pub inner: usize,
22}
23
24impl Reducible for BridgeIdState {
25    type Action = ();
26
27    fn reduce(self: Rc<Self>, _: Self::Action) -> Rc<Self> {
28        Self {
29            inner: self.inner + 1,
30        }
31        .into()
32    }
33}
34
35pub(crate) enum OutputsAction<T> {
36    Push(Rc<T>),
37    Close,
38    Reset,
39}
40
41pub(crate) struct OutputsState<T> {
42    pub ctr: usize,
43    pub inner: Vec<Rc<T>>,
44    pub closed: bool,
45}
46
47impl<T> Clone for OutputsState<T> {
48    fn clone(&self) -> Self {
49        Self {
50            ctr: self.ctr,
51            inner: self.inner.clone(),
52            closed: self.closed,
53        }
54    }
55}
56
57impl<T> Reducible for OutputsState<T> {
58    type Action = OutputsAction<T>;
59
60    fn reduce(mut self: Rc<Self>, action: Self::Action) -> Rc<Self> {
61        {
62            let this = Rc::make_mut(&mut self);
63            this.ctr += 1;
64
65            match action {
66                OutputsAction::Push(m) => this.inner.push(m),
67                OutputsAction::Close => {
68                    this.closed = true;
69                }
70                OutputsAction::Reset => {
71                    this.closed = false;
72                    this.inner = Vec::new();
73                }
74            }
75        }
76
77        self
78    }
79}
80
81impl<T> Default for OutputsState<T> {
82    fn default() -> Self {
83        Self {
84            ctr: 0,
85            inner: Vec::new(),
86            closed: false,
87        }
88    }
89}