Skip to content

Commit

Permalink
add StateTrigger trait and make get! take a Store<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
lukechu10 committed Sep 6, 2023
1 parent 701d590 commit 49449f3
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
11 changes: 8 additions & 3 deletions packages/sycamore-reactive-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ fn impl_state_struct(
#(#node_idents: <#node_types as ::sycamore_reactive3::State>::Trigger,)*
}

impl #impl_generics #trigger_ident #ty_generics #where_clause {
pub fn new(cx: ::sycamore_reactive3::Scope) -> Self {
impl #impl_generics ::sycamore_reactive3::StateTrigger for #trigger_ident #ty_generics #where_clause {
fn new(cx: ::sycamore_reactive3::Scope) -> Self {
Self {
#(#leaf_idents: ::sycamore_reactive3::create_signal(cx, ()),)*
#(#node_idents: <#node_types as ::sycamore_reactive3::State>::Trigger::new(cx),)*
Expand Down Expand Up @@ -104,7 +104,12 @@ impl Parse for LensSegment {
#[proc_macro]
pub fn get(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let path = parse_macro_input!(input as LensPath);
let mut tokens = path.first.to_token_stream();
let first = path.first;

let mut tokens = quote! {
::sycamore_reactive3::Store::__get(&#first)
};

for segment in path.segments {
match segment {
LensSegment::Field(ident) => {
Expand Down
24 changes: 20 additions & 4 deletions packages/sycamore-reactive3/src/store2.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Stores: easy nested recursive data.

use crate::Scope;

pub struct Store<T: State> {
value: T,
trigger: T::Trigger,
Expand All @@ -13,20 +15,32 @@ impl<T: State> Store<T> {
}
}

pub fn create_store<T: State>(cx: Scope, value: T) -> Store<T> {
Store {
value,
trigger: T::Trigger::new(cx),
}
}

pub struct StoreLens<T> {
access: Box<dyn Fn() -> T>,
}

pub trait State {
/// The type of the struct containing all the triggers for fine-grained reactivity.
type Trigger;
type Trigger: StateTrigger;
}

pub trait StateTrigger {
fn new(cx: Scope) -> Self;
}

#[cfg(test)]
mod tests {
use sycamore_reactive_macro::{get, State};

use super::*;
use crate::create_root;

#[test]
fn test_derive() {
Expand All @@ -35,8 +49,10 @@ mod tests {
value: i32,
}

let foo = Foo { value: 123 };
let test = get!(foo.value);
panic!("test = {test}");
let _ = create_root(|cx| {
let foo = create_store(cx, Foo { value: 123 });
let test = get!(foo.value);
panic!("test = {test}");
});
}
}

0 comments on commit 49449f3

Please sign in to comment.