Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Listener Injection #52

Merged
merged 4 commits into from
Mar 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/yewdux-input/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use std::{rc::Rc, str::FromStr};

use serde::{Deserialize, Serialize};
use wasm_bindgen::JsCast;
use web_sys::{HtmlInputElement, HtmlTextAreaElement};
use yew::prelude::*;
use yewdux::prelude::*;
use serde::{Deserialize, Serialize};

pub enum InputElement {
Input(HtmlInputElement),
Expand Down
18 changes: 17 additions & 1 deletion crates/yewdux-macros/src/store.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use darling::FromDeriveInput;
use darling::{util::PathList, FromDeriveInput};
use proc_macro2::TokenStream;
use quote::quote;
use syn::DeriveInput;
Expand All @@ -8,13 +8,26 @@ use syn::DeriveInput;
struct Opts {
storage: Option<String>,
storage_tab_sync: bool,
listener: PathList,
}

pub(crate) fn derive(input: DeriveInput) -> TokenStream {
let opts = Opts::from_derive_input(&input).expect("Invalid options");
let ident = input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

let extra_listeners: Vec<_> = opts
.listener
.iter()
.map(|path| {
quote! {
::yewdux::listener::init_listener(
#path
);
}
})
.collect();

let impl_ = match opts.storage {
Some(storage) => {
let area = match storage.as_ref() {
Expand Down Expand Up @@ -42,6 +55,7 @@ pub(crate) fn derive(input: DeriveInput) -> TokenStream {
::yewdux::listener::init_listener(
::yewdux::storage::StorageListener::<Self>::new(#area)
);
#(#extra_listeners)*

#sync

Expand All @@ -58,12 +72,14 @@ pub(crate) fn derive(input: DeriveInput) -> TokenStream {

#[cfg(not(target_arch = "wasm32"))]
fn new() -> Self {
#(#extra_listeners)*
Default::default()
}
}
}
None => quote! {
fn new() -> Self {
#(#extra_listeners)*
Default::default()
}
},
Expand Down
37 changes: 32 additions & 5 deletions crates/yewdux/src/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ pub trait Listener: 'static {
fn on_change(&mut self, state: Rc<Self::Store>);
}

struct ListenerStore<S: Store>(Option<SubscriberId<S>>);
impl<S: Store> Store for Mrc<ListenerStore<S>> {
struct ListenerStore<L: Listener>(Option<SubscriberId<L::Store>>);
impl<L: Listener> Store for Mrc<ListenerStore<L>> {
fn new() -> Self {
ListenerStore(None).into()
}
Expand All @@ -28,9 +28,7 @@ pub fn init_listener<L: Listener>(listener: L) {
dispatch::subscribe_silent(move |state| listener.borrow_mut().on_change(state))
};

dispatch::reduce_mut(|state: &mut Mrc<ListenerStore<L::Store>>| {
state.borrow_mut().0 = Some(id)
});
dispatch::reduce_mut(|state: &mut Mrc<ListenerStore<L>>| state.borrow_mut().0 = Some(id));
}

#[cfg(test)]
Expand Down Expand Up @@ -62,6 +60,16 @@ mod tests {
}
}

#[derive(Clone)]
struct AnotherTestListener(Rc<Cell<u32>>);
impl Listener for AnotherTestListener {
type Store = TestState;

fn on_change(&mut self, state: Rc<Self::Store>) {
self.0.set(state.0);
}
}

#[derive(Clone, PartialEq, Eq)]
struct TestState2;
impl Store for TestState2 {
Expand Down Expand Up @@ -113,6 +121,25 @@ mod tests {
assert_eq!(listener2.0.get(), 2);
}

#[test]
fn listener_of_different_type_is_not_replaced() {
let listener1 = TestListener(Default::default());
let listener2 = AnotherTestListener(Default::default());

init_listener(listener1.clone());

dispatch::reduce_mut(|state: &mut TestState| state.0 = 1);

assert_eq!(listener1.0.get(), 1);

init_listener(listener2.clone());

dispatch::reduce_mut(|state: &mut TestState| state.0 = 2);

assert_eq!(listener1.0.get(), 2);
assert_eq!(listener2.0.get(), 2);
}

#[test]
fn can_init_listener_from_store() {
dispatch::get::<TestState2>();
Expand Down
21 changes: 21 additions & 0 deletions docs/src/persistence.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,24 @@ struct State {
}
```

## Additional Listeners

You can inject additional listeners into the `#[store]` macro.

```rust
#[derive(Default, Clone, PartialEq, Eq, Deserialize, Serialize, Store)]
#[store(storage = "local", listener(LogListener))]
struct State {
count: u32,
}

struct LogListener;
impl Listener for LogListener {
type Store = State;

fn on_change(&mut self, state: Rc<Self::Store>) {
log!(Level::Info, "Count changed to {}", state.count);
}
}
```

1 change: 1 addition & 0 deletions examples/listener/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ edition = "2018"

[dependencies]
serde = { version = "1.0.114" }
wasm-logger = "0.2.0"
yew = { git = "https://github.com/yewstack/yew.git", features = ["csr"] }
yewdux = { path = "../../crates/yewdux" }
16 changes: 15 additions & 1 deletion examples/listener/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
use std::rc::Rc;

use yew::prelude::*;
use yewdux::prelude::*;
#[cfg(target_arch = "wasm32")]
use yewdux::storage;
use yewdux::{
log::{log, Level},
prelude::*,
};

use serde::{Deserialize, Serialize};

struct LogListener;
impl Listener for LogListener {
type Store = State;

fn on_change(&mut self, state: Rc<Self::Store>) {
log!(Level::Info, "Count changed to {}", state.count);
}
}

struct StorageListener;
impl Listener for StorageListener {
type Store = State;
Expand All @@ -33,6 +45,7 @@ impl Store for State {
#[cfg(target_arch = "wasm32")]
fn new() -> Self {
init_listener(StorageListener);
init_listener(LogListener);

storage::load(storage::Area::Local)
.ok()
Expand All @@ -59,5 +72,6 @@ fn App() -> Html {
}

fn main() {
wasm_logger::init(wasm_logger::Config::default());
yew::Renderer::<App>::new().render();
}
1 change: 1 addition & 0 deletions examples/persistent/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ edition = "2018"

[dependencies]
serde = { version = "1.0.114" }
wasm-logger = "0.2.0"
yew = { git = "https://github.com/yewstack/yew.git", features = ["csr"] }
yewdux = { path = "../../crates/yewdux" }
19 changes: 17 additions & 2 deletions examples/persistent/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
use std::rc::Rc;

use yew::prelude::*;
use yewdux::prelude::*;
use yewdux::{
log::{log, Level},
prelude::*,
};

use serde::{Deserialize, Serialize};

#[derive(Default, Clone, PartialEq, Eq, Deserialize, Serialize, Store)]
#[store(storage = "local")]
#[store(storage = "local", listener(LogListener))]
struct State {
count: u32,
}
Expand All @@ -23,5 +28,15 @@ fn App() -> Html {
}

fn main() {
wasm_logger::init(wasm_logger::Config::default());
yew::Renderer::<App>::new().render();
}

struct LogListener;
impl Listener for LogListener {
type Store = State;

fn on_change(&mut self, state: Rc<Self::Store>) {
log!(Level::Info, "Count changed to {}", state.count);
}
}
5 changes: 1 addition & 4 deletions examples/todomvc/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,7 @@ pub struct Entry {
pub editing: bool,
}

#[derive(Clone, Copy, Debug, EnumIter, Display, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Default)]
#[derive(Clone, Copy, Debug, EnumIter, Display, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Filter {
#[default]
All,
Expand All @@ -145,5 +144,3 @@ impl Filter {
}
}
}