1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
//! Context API.

use sycamore_reactive::create_context_scope;
pub use sycamore_reactive::use_context;

use crate::prelude::*;

/// Props for [`ContextProvider`].
pub struct ContextProviderProps<T, F, G>
where
    T: 'static,
    F: FnOnce() -> View<G>,
    G: GenericNode,
{
    pub value: T,
    pub children: F,
}

/// Creates a new [`ReactiveScope`](crate::reactive::ReactiveScope) with a context.
///
/// If a context of the given type exists already, the existing context will be _shadowed_ within
/// the scope. This means that accessing the context inside the scope using [`use_context`] will
/// return the new value, not the shadowed value. Using [`use_context`] outside of this new context
/// scope will continue to return the old value.
///
/// # Example
/// ```
/// use sycamore::prelude::*;
/// use sycamore::context::{ContextProvider, ContextProviderProps, use_context};
///
/// #[derive(Clone)]
/// struct Counter(Signal<i32>);
///
/// #[component(CounterView<G>)]
/// fn counter_view() -> View<G> {
///     let counter = use_context::<Counter>();
///
///     view! {
///         (counter.0.get())
///     }
/// }
///
/// # #[component(App<G>)]
/// # fn app() -> View<G> {
/// view! {
///     ContextProvider(ContextProviderProps {
///         value: Counter(Signal::new(0)),
///         children: || view! {
///             CounterView()
///         }
///     })
/// }
/// # }
/// ```
#[component(ContextProvider<G>)]
#[cfg_attr(debug_assertions, track_caller)]
pub fn context_provider<T, F>(props: ContextProviderProps<T, F, G>) -> View<G>
where
    T: 'static,
    F: FnOnce() -> View<G>,
{
    let ContextProviderProps { value, children } = props;

    create_context_scope(value, children)
}

#[cfg(all(test, feature = "ssr"))]
mod tests {
    use super::*;
    use sycamore_reactive::{create_scope, use_context};

    #[test]
    fn basic_context() {
        sycamore::render_to_string(|| {
            view! {
                ContextProvider(ContextProviderProps {
                    value: 1i32,
                    children: || {
                        let ctx = use_context::<i32>();
                        assert_eq!(ctx, 1);
                        view! {}
                    },
                })
            }
        });
    }

    #[test]
    fn nested_contexts() {
        sycamore::render_to_string(|| {
            view! {
                ContextProvider(ContextProviderProps {
                    value: 1i32,
                    children: || {
                        view! {
                            ContextProvider(ContextProviderProps {
                                value: 2i64,
                                children: || {
                                    // Both the i32 and i64 contexts should be accessible here.
                                    let ctx_i32 = use_context::<i32>();
                                    assert_eq!(ctx_i32, 1);
                                    let ctx_i64 = use_context::<i64>();
                                    assert_eq!(ctx_i64, 2);
                                    view! {}
                                }
                            })
                        }
                    },
                })
            }
        });
    }

    #[test]
    fn use_context_inside_effect_when_reexecuting() {
        #[component(ContextConsumer<G>)]
        fn context_consumer() -> View<G> {
            let _ctx = use_context::<i32>();
            view! {}
        }

        let trigger = Signal::new(());

        let node = view! {
            ContextProvider(ContextProviderProps {
                value: 1i32,
                children: cloned!((trigger) => move || {
                    view! {
                        ({
                            trigger.get(); // subscribe to trigger
                            view! { ContextConsumer() }
                        })
                    }
                }),
            })
        };
        trigger.set(());
        trigger.set(());

        sycamore::render_to_string(|| node);
    }

    #[test]
    fn use_context_inside_effect_depending_on_context_value() {
        #[component(First<G>)]
        fn first() -> View<G> {
            let _ctx = use_context::<Signal<bool>>();
            view! {}
        }

        #[component(Second<G>)]
        fn second() -> View<G> {
            let _ctx = use_context::<Signal<bool>>();
            view! {}
        }

        let value = Signal::new(true);

        let node = view! {
            ContextProvider(ContextProviderProps {
                value: value.clone(),
                children: move || {
                    let ctx = use_context::<Signal<bool>>();
                    view! {
                        (match *ctx.get() {
                            true => view! { First() },
                            false => view! { Second() },
                        })
                    }
                },
            })
        };

        value.set(false);

        sycamore::render_to_string(|| node);
    }

    #[test]
    #[should_panic = "context not found for type"]
    fn should_panic_with_unknown_context_type() {
        let _ = use_context::<u32>();
    }

    #[test]
    #[should_panic = "context not found for type"]
    fn should_panic_with_unknown_context_type_inside_scope() {
        let _ = create_scope(move || {
            let _ = use_context::<u32>();
        });
    }
}