-
Notifications
You must be signed in to change notification settings - Fork 1
Embed yewdux crates into yewdux-middleware #3
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
Draft
Copilot
wants to merge
7
commits into
master
Choose a base branch
from
copilot/embed-yewdux-in-yewdux-middleware
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
0f6fb33
Initial plan
Copilot e855371
Embed yewdux crates into yewdux-middleware
Copilot 751dbf1
Fix test imports for embedded yewdux
Copilot 97cec3d
Rename yewdux-macros to yewdux-middleware-macros and update CI/publis…
Copilot cdef56d
Trigger CI with no-op change
Copilot c624722
Fix cargo fmt formatting issues
Copilot 6452b33
Fix CI build errors and add copilot reminder
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| use std::{ | ||
| any::{Any, TypeId}, | ||
| collections::HashMap, | ||
| }; | ||
|
|
||
| #[derive(Default)] | ||
| pub(crate) struct AnyMap { | ||
| map: HashMap<TypeId, Box<dyn Any>>, | ||
| } | ||
|
|
||
| impl AnyMap { | ||
| pub(crate) fn entry<T: 'static>(&mut self) -> Entry<T> { | ||
| Entry { | ||
| map: &mut self.map, | ||
| _marker: std::marker::PhantomData, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| pub(crate) struct Entry<'a, T: 'static> { | ||
| map: &'a mut HashMap<TypeId, Box<dyn Any>>, | ||
| _marker: std::marker::PhantomData<T>, | ||
| } | ||
|
|
||
| impl<'a, T: 'static> Entry<'a, T> { | ||
| pub(crate) fn or_insert_with<F>(self, default: F) -> &'a mut T | ||
| where | ||
| F: FnOnce() -> T, | ||
| { | ||
| let type_id = TypeId::of::<T>(); | ||
| let value = self | ||
| .map | ||
| .entry(type_id) | ||
| .or_insert_with(|| Box::new(default())); | ||
| value.downcast_mut().expect("type id mismatch") | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,271 @@ | ||
| use std::rc::Rc; | ||
|
|
||
| use crate::yewdux::{ | ||
| anymap::AnyMap, | ||
| mrc::Mrc, | ||
| store::{Reducer, Store}, | ||
| subscriber::{Callable, SubscriberId, Subscribers}, | ||
| }; | ||
|
|
||
| pub(crate) struct Entry<S> { | ||
| pub(crate) store: Mrc<Rc<S>>, | ||
| } | ||
|
|
||
| impl<S> Clone for Entry<S> { | ||
| fn clone(&self) -> Self { | ||
| Self { | ||
| store: Mrc::clone(&self.store), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<S: Store> Entry<S> { | ||
| /// Apply a function to state, returning if it should notify subscribers or not. | ||
| pub(crate) fn reduce<R: Reducer<S>>(&self, reducer: R) -> bool { | ||
| let old = Rc::clone(&self.store.borrow()); | ||
| // Apply the reducer. | ||
| let new = reducer.apply(Rc::clone(&old)); | ||
| // Update to new state. | ||
| *self.store.borrow_mut() = new; | ||
| // Return whether or not subscribers should be notified. | ||
| self.store.borrow().should_notify(&old) | ||
| } | ||
| } | ||
|
|
||
| /// Execution context for a dispatch | ||
| /// | ||
| /// # Example | ||
| /// | ||
| /// ``` | ||
| /// use yewdux::prelude::*; | ||
| /// | ||
| /// #[derive(Clone, PartialEq, Default, Store)] | ||
| /// struct Counter(usize); | ||
| /// | ||
| /// // In a real application, you'd typically get the context from a parent component | ||
| /// let cx = yewdux::Context::new(); | ||
| /// let dispatch = Dispatch::<Counter>::new(&cx); | ||
| /// ``` | ||
| #[derive(Clone, Default, PartialEq)] | ||
| pub struct Context { | ||
| inner: Mrc<AnyMap>, | ||
| } | ||
|
|
||
| impl Context { | ||
| pub fn new() -> Self { | ||
| Default::default() | ||
| } | ||
|
|
||
| #[cfg(any(doc, feature = "doctests", target_arch = "wasm32"))] | ||
| pub fn global() -> Self { | ||
| thread_local! { | ||
| static CONTEXT: Context = Default::default(); | ||
| } | ||
|
|
||
| CONTEXT | ||
| .try_with(|cx| cx.clone()) | ||
| .expect("CONTEXTS thread local key init failed") | ||
| } | ||
|
|
||
| /// Initialize a store using a custom constructor. `Store::new` will not be called in this | ||
| /// case. If already initialized, the custom constructor will not be called. | ||
| pub fn init<S: Store, F: FnOnce(&Self) -> S>(&self, new_store: F) { | ||
| self.get_or_init(new_store); | ||
| } | ||
|
|
||
| /// Get or initialize a store using a custom constructor. `Store::new` will not be called in | ||
| /// this case. If already initialized, the custom constructor will not be called. | ||
| pub(crate) fn get_or_init<S: Store, F: FnOnce(&Self) -> S>(&self, new_store: F) -> Entry<S> { | ||
| // Get context, or None if it doesn't exist. | ||
| // | ||
| // We use an option here because a new Store should not be created during this borrow. We | ||
| // want to allow this store access to other stores during creation, so cannot be borrowing | ||
| // the global resource while initializing. Instead we create a temporary placeholder, which | ||
| // indicates the store needs to be created. Without this indicator we would have needed to | ||
| // check if the map contains the entry beforehand, which would have meant two map lookups | ||
| // per call instead of just one. | ||
| let maybe_entry = self.inner.with_mut(|x| { | ||
| x.entry::<Mrc<Option<Entry<S>>>>() | ||
| .or_insert_with(|| None.into()) | ||
| .clone() | ||
| }); | ||
|
|
||
| // If it doesn't exist, create and save the new store. | ||
| let exists = maybe_entry.borrow().is_some(); | ||
| if !exists { | ||
| // Init store outside of borrow. This allows the store to access other stores when it | ||
| // is being created. | ||
| let entry = Entry { | ||
| store: Mrc::new(Rc::new(new_store(self))), | ||
| }; | ||
|
|
||
| *maybe_entry.borrow_mut() = Some(entry); | ||
| } | ||
|
|
||
| // Now we get the context, which must be initialized because we already checked above. | ||
| let entry = maybe_entry | ||
| .borrow() | ||
| .clone() | ||
| .expect("Context not initialized"); | ||
|
|
||
| entry | ||
| } | ||
|
|
||
| /// Get or initialize a store with a default Store::new implementation. | ||
| pub(crate) fn get_or_init_default<S: Store>(&self) -> Entry<S> { | ||
| self.get_or_init(S::new) | ||
| } | ||
|
|
||
| pub fn reduce<S: Store, R: Reducer<S>>(&self, r: R) { | ||
| let entry = self.get_or_init_default::<S>(); | ||
| let should_notify = entry.reduce(r); | ||
|
|
||
| if should_notify { | ||
| let state = Rc::clone(&entry.store.borrow()); | ||
| self.notify_subscribers(state) | ||
| } | ||
| } | ||
|
|
||
| pub fn reduce_mut<S: Store + Clone, F: FnOnce(&mut S)>(&self, f: F) { | ||
| self.reduce(|mut state| { | ||
| f(Rc::make_mut(&mut state)); | ||
| state | ||
| }); | ||
| } | ||
|
|
||
| /// Set state to given value. | ||
| pub fn set<S: Store>(&self, value: S) { | ||
| self.reduce(move |_| value.into()); | ||
| } | ||
|
|
||
| /// Get current state. | ||
| pub fn get<S: Store>(&self) -> Rc<S> { | ||
| Rc::clone(&self.get_or_init_default::<S>().store.borrow()) | ||
| } | ||
|
|
||
| /// Send state to all subscribers. | ||
| pub fn notify_subscribers<S: Store>(&self, state: Rc<S>) { | ||
| let entry = self.get_or_init_default::<Mrc<Subscribers<S>>>(); | ||
| entry.store.borrow().notify(state); | ||
| } | ||
|
|
||
| /// Subscribe to a store. `on_change` is called immediately, then every time state changes. | ||
| pub fn subscribe<S: Store, N: Callable<S>>(&self, on_change: N) -> SubscriberId<S> { | ||
| // Notify subscriber with inital state. | ||
| on_change.call(self.get::<S>()); | ||
|
|
||
| self.get_or_init_default::<Mrc<Subscribers<S>>>() | ||
| .store | ||
| .borrow() | ||
| .subscribe(on_change) | ||
| } | ||
|
|
||
| /// Similar to [Self::subscribe], however state is not called immediately. | ||
| pub fn subscribe_silent<S: Store, N: Callable<S>>(&self, on_change: N) -> SubscriberId<S> { | ||
| self.get_or_init_default::<Mrc<Subscribers<S>>>() | ||
| .store | ||
| .borrow() | ||
| .subscribe(on_change) | ||
| } | ||
|
|
||
| /// Initialize a listener | ||
| pub fn init_listener<L: crate::yewdux::Listener, F: FnOnce() -> L>(&self, new_listener: F) { | ||
| crate::yewdux::init_listener(new_listener, self); | ||
| } | ||
|
|
||
| pub fn derived_from<Store, Derived>(&self) | ||
| where | ||
| Store: crate::Store, | ||
| Derived: crate::yewdux::derived_from::DerivedFrom<Store>, | ||
| { | ||
| crate::yewdux::derived_from::derive_from::<Store, Derived>(self); | ||
| } | ||
|
|
||
| pub fn derived_from_mut<Store, Derived>(&self) | ||
| where | ||
| Store: crate::Store, | ||
| Derived: crate::yewdux::derived_from::DerivedFromMut<Store>, | ||
| { | ||
| crate::yewdux::derived_from::derive_from_mut::<Store, Derived>(self); | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use std::cell::Cell; | ||
| use std::rc::Rc; | ||
|
|
||
| use crate::yewdux::*; | ||
|
|
||
| #[derive(Clone, PartialEq, Eq)] | ||
| struct TestState(u32); | ||
| impl Store for TestState { | ||
| fn new(_cx: &Context) -> Self { | ||
| Self(0) | ||
| } | ||
|
|
||
| fn should_notify(&self, other: &Self) -> bool { | ||
| self != other | ||
| } | ||
| } | ||
|
|
||
| #[derive(Clone, PartialEq, Eq)] | ||
| struct TestState2(u32); | ||
| impl Store for TestState2 { | ||
| fn new(cx: &Context) -> Self { | ||
| cx.get_or_init_default::<TestState>(); | ||
| Self(0) | ||
| } | ||
|
|
||
| fn should_notify(&self, other: &Self) -> bool { | ||
| self != other | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn can_access_other_store_for_new_of_current_store() { | ||
| let _context = Context::new().get_or_init_default::<TestState2>(); | ||
| } | ||
|
|
||
| #[derive(Clone, PartialEq, Eq)] | ||
| struct StoreNewIsOnlyCalledOnce(Rc<Cell<u32>>); | ||
| impl Store for StoreNewIsOnlyCalledOnce { | ||
| fn new(_cx: &Context) -> Self { | ||
| thread_local! { | ||
| /// Stores all shared state. | ||
| static COUNT: Rc<Cell<u32>> = Default::default(); | ||
| } | ||
|
|
||
| let count = COUNT.try_with(|x| x.clone()).unwrap(); | ||
|
|
||
| count.set(count.get() + 1); | ||
|
|
||
| Self(count) | ||
| } | ||
|
|
||
| fn should_notify(&self, other: &Self) -> bool { | ||
| self != other | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn store_new_is_only_called_once() { | ||
| let cx = Context::new(); | ||
| cx.get_or_init_default::<StoreNewIsOnlyCalledOnce>(); | ||
| let entry = cx.get_or_init_default::<StoreNewIsOnlyCalledOnce>(); | ||
|
|
||
| assert!(entry.store.borrow().0.get() == 1) | ||
| } | ||
|
|
||
| #[test] | ||
| fn recursive_reduce() { | ||
| let cx = Context::new(); | ||
| let cx2 = cx.clone(); | ||
| cx.reduce::<TestState, _>(|_s: Rc<TestState>| { | ||
| cx2.reduce::<TestState, _>(|s: Rc<TestState>| TestState(s.0 + 1).into()); | ||
| TestState(cx2.get::<TestState>().0 + 1).into() | ||
| }); | ||
|
|
||
| assert_eq!(cx.get::<TestState>().0, 2); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| use yew::prelude::*; | ||
|
|
||
| use crate::yewdux::context; | ||
|
|
||
| #[derive(PartialEq, Clone, Properties)] | ||
| pub struct Props { | ||
| pub children: Children, | ||
| } | ||
|
|
||
| #[function_component] | ||
| pub fn YewduxRoot(Props { children }: &Props) -> Html { | ||
| let ctx = use_state(context::Context::new); | ||
| html! { | ||
| <ContextProvider<context::Context> context={(*ctx).clone()}> | ||
| { children.clone() } | ||
| </ContextProvider<context::Context>> | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The yewdux-macros crate cannot be published on crates.io under this name, as it is already taken by the
yewdux-macrosupstream crate.You need to rename this to
yewdux-middleware-macros.Also please update the CI job to also build the yewdux-middleware-macros crate, and the publish actions to also publish this crate.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Renamed to
yewdux-middleware-macrosand updated all CI/publish workflows. The macros crate is now built separately in CI and published before the main crate. Changes in commit 97cec3d.