From 526dfa61ea87b80cb292dd96ca868303a000c41f Mon Sep 17 00:00:00 2001 From: Dan Holmsand Date: Wed, 11 Feb 2015 06:38:57 +0100 Subject: [PATCH] Make swap! on non-active Reaction correct --- src/reagent/ratom.cljs | 20 ++++++++++++++------ test/reagenttest/testcursor.cljs | 10 ++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/reagent/ratom.cljs b/src/reagent/ratom.cljs index a6aaa55..7a8d979 100644 --- a/src/reagent/ratom.cljs +++ b/src/reagent/ratom.cljs @@ -193,7 +193,8 @@ (defprotocol IComputedImpl (-update-watching [this derefed]) - (-handle-change [k sender oldval newval])) + (-handle-change [k sender oldval newval]) + (-peek-at [this])) (deftype Reaction [f ^:mutable state ^:mutable dirty? ^:mutable active? ^:mutable watching ^:mutable watches @@ -229,13 +230,13 @@ ISwap (-swap! [a f] - (-reset! a (f state))) + (-reset! a (f (-peek-at a)))) (-swap! [a f x] - (-reset! a (f state x))) + (-reset! a (f (-peek-at a) x))) (-swap! [a f x y] - (-reset! a (f state x y))) + (-reset! a (f (-peek-at a) x y))) (-swap! [a f x y more] - (-reset! a (apply f state x y more))) + (-reset! a (apply f (-peek-at a) x y more))) IComputedImpl (-handle-change [this sender oldval newval] @@ -252,6 +253,12 @@ (remove-watch w this))) (set! watching derefed)) + (-peek-at [this] + (if-not dirty? + state + (binding [*ratom-context* nil] + (-deref this)))) + IRunnable (run [this] (let [oldstate state @@ -278,7 +285,8 @@ (-notify-watches this oldstate state)))) state) (do - (notify-deref-watcher! this) + (when (some? *ratom-context*) + (notify-deref-watcher! this)) (if dirty? (run this) state)))) diff --git a/test/reagenttest/testcursor.cljs b/test/reagenttest/testcursor.cljs index 08e7a33..54d6fd1 100644 --- a/test/reagenttest/testcursor.cljs +++ b/test/reagenttest/testcursor.cljs @@ -416,3 +416,13 @@ (is (= (:new @witness) "new")) ;; shouldn't have changed (is (= @test-wrap @test-atom)) )) + +(deftest test-cursor-swap + (let [a (atom {:b 1}) + b (r/cursor a [:b])] + (is (= 1 @b)) + (is (= 2 (swap! b inc))) + + (swap! a update-in [:b] inc) + (is (= 4 (swap! b inc))) + (is (= 4 @b))))