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

Add Signal::modify to mutate a value #399

Merged
merged 2 commits into from
Mar 21, 2022
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
38 changes: 8 additions & 30 deletions examples/todomvc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,30 +52,15 @@ pub struct AppState {

impl AppState {
fn add_todo(&self, title: String) {
self.todos.set(
self.todos
.get()
.as_ref()
.clone()
.into_iter()
.chain(Some(create_rc_signal(Todo {
title,
completed: false,
id: Uuid::new_v4(),
})))
.collect(),
)
self.todos.modify().push(create_rc_signal(Todo {
title,
completed: false,
id: Uuid::new_v4(),
}))
}

fn remove_todo(&self, id: Uuid) {
self.todos.set(
self.todos
.get()
.iter()
.filter(|todo| todo.get().id != id)
.cloned()
.collect(),
);
self.todos.modify().retain(|todo| todo.get().id != id);
}

fn todos_left(&self) -> usize {
Expand Down Expand Up @@ -110,14 +95,7 @@ impl AppState {
}

fn clear_completed(&self) {
self.todos.set(
self.todos
.get()
.iter()
.filter(|todo| !todo.get().completed)
.cloned()
.collect(),
);
self.todos.modify().retain(|todo| !todo.get().completed);
}
}

Expand Down Expand Up @@ -456,7 +434,7 @@ pub fn Footer<G: Html>(cx: Scope) -> View<G> {
}
}
} else {
View::empty()
view! { cx, }
})
}
}
Expand Down
60 changes: 59 additions & 1 deletion packages/sycamore-reactive/src/signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use std::fmt::{Debug, Display, Formatter};
use std::hash::Hash;
use std::ops::{AddAssign, Deref, DivAssign, MulAssign, SubAssign};
use std::ops::{AddAssign, Deref, DerefMut, DivAssign, MulAssign, SubAssign};

use crate::effect::EFFECTS;
use crate::*;
Expand Down Expand Up @@ -246,6 +246,49 @@ impl<T> Signal<T> {
}
}

/// A mutable reference for modifying a [`Signal`].
///
/// Construct this using the [`Signal::modify()`] method.
pub struct Modify<'a, T>(Option<T>, &'a Signal<T>);

impl<'a, T> Deref for Modify<'a, T> {
type Target = T;

fn deref(&self) -> &Self::Target {
self.0.as_ref().unwrap()
}
}
impl<'a, T> DerefMut for Modify<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.as_mut().unwrap()
}
}

/// When the mutable handle is dropped, update the [`Signal`].
impl<T> Drop for Modify<'_, T> {
fn drop(&mut self) {
self.1.set(self.0.take().unwrap())
}
}

impl<T: Clone> Signal<T> {
/// Return a mutable handle to make it easier to mutate the inner value.
/// This requires the inner type to implement [`Clone`].
///
/// # Example
/// ```
/// # use sycamore_reactive::*;
/// # create_scope_immediate(|cx| {
/// let state = create_signal(cx, "Hello ".to_string());
/// state.modify().push_str("World!");
/// assert_eq!(*state.get(), "Hello World!");
/// # });
/// ```
pub fn modify(&self) -> Modify<T> {
Modify(Some(self.value.borrow().as_ref().clone()), self)
}
}

impl<T: Default> Signal<T> {
/// Take the current value out and replace it with the default value.
///
Expand Down Expand Up @@ -662,4 +705,19 @@ mod tests {
assert_eq!(*counter.get(), 5);
});
}

#[test]
fn signal_modify() {
create_scope_immediate(|cx| {
let signal = create_signal(cx, "Hello ".to_string());
let counter = create_signal(cx, 0);
create_effect(cx, || {
signal.track();
counter.set(*counter.get_untracked() + 1);
});
signal.modify().push_str("World!");
assert_eq!(*signal.get(), "Hello World!");
assert_eq!(*counter.get(), 2);
});
}
}
2 changes: 1 addition & 1 deletion packages/sycamore-router/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ version = "0.8.0-beta.3"

[dependencies]
sycamore = { path = "../sycamore", version = "0.8.0-beta.3" }
sycamore-router-macro = { path = "../sycamore-router-macro", version = "0.8.0-beta.3" }
sycamore-router-macro = { path = "../sycamore-router-macro", version = "=0.8.0-beta.3" }
wasm-bindgen = "0.2.79"

[dependencies.web-sys]
Expand Down
2 changes: 1 addition & 1 deletion packages/sycamore/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ js-sys = "0.3.56"
once_cell = { version = "1.10.0", optional = true }
paste = "1.0.6"
sycamore-futures = { path = "../sycamore-futures", version = "0.8.0-beta.3", optional = true }
sycamore-macro = { path = "../sycamore-macro", version = "0.8.0-beta.3" }
sycamore-macro = { path = "../sycamore-macro", version = "=0.8.0-beta.3" }
sycamore-reactive = { path = "../sycamore-reactive", version = "0.8.0-beta.3" }
wasm-bindgen = "0.2.79"
wasm-bindgen-futures = { version = "0.4.29", optional = true }
Expand Down