Skip to content

Commit

Permalink
Merge branch 'delayed'
Browse files Browse the repository at this point in the history
Conflicts:
	src/reagent/impl/template.cljs
  • Loading branch information
holmsand committed Feb 3, 2014
2 parents d1851d5 + 046912a commit aca6934
Show file tree
Hide file tree
Showing 15 changed files with 619 additions and 100 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
index.html
assets/
news/
/news/
target
pom.xml
.lein-repl-history
Expand Down
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ runtest:
$(MAKE) run PROF=test,$(PROF)

runsite: setup
(sleep 3 && open "http://127.0.0.1:$(PORT)") &
(sleep 3 && open "http://127.0.0.1:$(PORT)/$$(basename $$PWD)") &
( trap "kill 0" SIGINT SIGTERM EXIT; \
( python -m SimpleHTTPServer $(PORT) & ); \
lein -o with-profile $(PROF) cljsbuild auto $(CLJSBUILD) )
( cd .. && python -m SimpleHTTPServer $(PORT) & ); \
lein -o with-profile $(PROF),prod cljsbuild auto $(CLJSBUILD) )

install: leinbuild
lein install
Expand Down
7 changes: 4 additions & 3 deletions demo/demo.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@
[github-badge]])

(defn ^:export mountdemo [p]
(when p (reset! page p))
(when p (page/set-start-page p))
(reagent/render-component [demo] (.-body js/document)))

(defn gen-page [p timestamp]
(reset! page p)
(let [body (reagent/render-component-to-string [demo])
title @page/title-atom]
title @page/title-atom
load-page (case p "index.html" "" p)]
(str "<!doctype html>
<html>
<head>
Expand All @@ -53,7 +54,7 @@
<script type='text/javascript'
src='" (prefix "assets/demo.js") timestamp "'></script>
<script type='text/javascript'>
setTimeout(function() {demo.mountdemo('" p "')}, 200);
setTimeout(function() {demo.mountdemo('" load-page "')}, 200);
</script>
</body>
</html>")))
Expand Down
11 changes: 5 additions & 6 deletions demo/reagentdemo/common.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,7 @@
")

(defn src-for-names [srcmap names]
(string/join "\n" (-> srcmap
(select-keys names)
vals)))
(string/join "\n" (map srcmap names)))

(defn fun-map [src]
(-> src src-parts src-defs (assoc :ns nssrc)))
Expand All @@ -36,17 +34,18 @@
(fn []
[:div
(when comp
[:div.demo-example
[:div.demo-example.clearfix
[:a.demo-example-hide {:on-click (fn [e]
(.preventDefault e)
(swap! showing not))}
(swap! showing not)
false)}
(if @showing "hide" "show")]
[:h3.demo-heading "Example "]
(when @showing
(if-not complete
[:div.simple-demo [comp]]
[comp]))])
(when @showing
[:div.demo-source
[:div.demo-source.clearfix
[:h3.demo-heading "Source"]
src])])))
38 changes: 23 additions & 15 deletions demo/reagentdemo/news.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
[reagentdemo.syntax :refer-macros [get-source]]
[reagentdemo.page :refer [title link page-map]]
[reagentdemo.common :as common :refer [demo-component]]
[reagentdemo.news.async :as async]
[todomvc :as todomvc]))

(def funmap (-> "reagentdemo/news.cljs" get-source common/fun-map))
Expand Down Expand Up @@ -44,7 +45,7 @@
(reset! undo-list nil)
(remove-watch state ::undo-watcher))}))

(defn undo-example []
(defn undo-example [{:keys [summary]}]
(let [head "Cloact becomes Reagent: Undo is trivial"]
[:div.reagent-demo
[:h1 [link {:href undo-example} head]]
Expand All @@ -63,25 +64,32 @@
[:p "The API is otherwise unchanged, so a simple
search-and-replace should suffice."]

[:h2 "Undo the easy way"]
(if summary
[link {:href undo-example
:class 'news-read-more} "Read more"]
[:div.demo-text

[:p "To celebrate the undoing of the apparently disgusting name,
here is an example of how easy it is to add undo functionality
to Reagent components."]
[:h2 "Undo the easy way"]

[:p "It simply saves the old state whenever it changes, and
restores it when the button is clicked."]
[:p "To celebrate the undoing of the apparently disgusting
name, here is an example of how easy it is to add undo
functionality to Reagent components."]

[:p "The really nice thing about ClojureScript is that not only
is this easy and safe to do, courtesy of immutable data
structures, it is also efficient. ClojureScript figures out how
to represent ”changes” to maps and vectors efficiently, so that
you won’t have to."]

[undo-demo-cleanup]]]))
[:p "It simply saves the old state whenever it changes, and
restores it when the button is clicked."]

[:p "The really nice thing about ClojureScript is that not
only is this easy and safe to do, courtesy of immutable data
structures, it is also efficient. ClojureScript figures out
how to represent ”changes” to maps and vectors efficiently,
so that you won’t have to."]

[undo-demo-cleanup]])]]))

(defn main []
[undo-example])
[:div
[async/main {:summary true}]
[undo-example {:summary true}]])

(swap! page-map assoc
"news/cloact-reagent-undo-demo.html" undo-example)
197 changes: 197 additions & 0 deletions demo/reagentdemo/news/async.cljs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
(ns reagentdemo.news.async
(:require [reagent.core :as reagent :refer [atom]]
[reagent.debug :refer-macros [dbg println]]
[reagentdemo.syntax :refer-macros [get-source]]
[reagentdemo.page :refer [title link page-map]]
[reagentdemo.common :as common :refer [demo-component]]))

(def funmap (-> "reagentdemo/news/async.cljs" get-source common/fun-map))
(def src-for (partial common/src-for funmap))

(defn timing-wrapper [{f :component-fn}]
(let [start-time (atom nil)
render-time (atom nil)
now #(.now js/Date)
start #(reset! start-time (now))
stop #(reset! render-time (- (now) @start-time))
timed-f (with-meta f
{:component-will-mount start
:component-will-update start
:component-did-mount stop
:component-did-update stop})]
(fn [props children]
[:div
[:p [:em "render time: " @render-time "ms"]]
(into [timed-f props] children)])))

(def base-color (atom {:red 130 :green 160 :blue 120}))
(def ncolors (atom 20))
(def random-colors (atom nil))

(defn to-rgb [{:keys [red green blue]}]
(let [hex #(str (if (< % 16) "0")
(-> % js/Math.round (.toString 16)))]
(str "#" (hex red) (hex green) (hex blue))))

(defn tweak-color [{:keys [red green blue]}]
(let [rnd #(-> (js/Math.random) (* 256))
tweak #(-> % (+ (rnd)) (/ 2) js/Math.floor)]
{:red (tweak red) :green (tweak green) :blue (tweak blue)}))

(defn reset-random-colors []
(reset! random-colors
(repeatedly #(-> @base-color tweak-color to-rgb))))

(defn color-choose [{color-part :color-part}]
[:div.color-slider
(name color-part) " " (color-part @base-color)
[:input {:type "range" :min 0 :max 255
:value (color-part @base-color)
:on-change (fn [e]
(swap! base-color assoc
color-part (-> e .-target .-value int))
(reset-random-colors))}]])

(defn ncolors-choose []
[:div.color-slider
"number of color divs " @ncolors
[:input {:type "range" :min 0 :max 500
:value @ncolors
:on-change #(reset! ncolors (-> % .-target .-value))}]])

(defn color-plate [{color :color}]
[:div.color-plate
{:style {:background-color color}}])

(defn palette []
(let [color @base-color
n @ncolors]
[:div
[:div
[:p "base color: "]
[color-plate {:color (to-rgb color)}]]
[:div.color-samples
[:p n " random matching colors:"]
(map-indexed (fn [k v]
[color-plate {:key k :color v}])
(take n @random-colors))]]))

(defn color-demo []
(reset-random-colors)
(fn []
[:div
[:h2 "Matching colors"]
[color-choose {:color-part :red}]
[color-choose {:color-part :green}]
[color-choose {:color-part :blue}]
[ncolors-choose]
[timing-wrapper {:component-fn palette}]]))

(defn main [{:keys [summary]}]
(let [om-article {:href "http://swannodette.github.io/2013/12/17/the-future-of-javascript-mvcs/"}]
[:div.reagent-demo
[title "Reagent: Faster by waiting"]
[:h1 [link {:href main} "Faster by waiting"]]
[:div.demo-text
[:h2 "Reagent gets async rendering"]

[:p "Reagent already separates state from components. Now they
are also separated in time."]

[:p "From version 0.3.0, changes in application state (as
represented by Reagent’s " [:code "atom"] "s) are no longer
rendered immediately to the DOM. Instead, Reagent waits until
the browser is ready to repaint the window, and then all the
changes are rendered in one single go."]

(if summary
[link {:href main
:class 'news-read-more} "Read more"]
[:div.demo-text

[:p "This is good for all sorts of reasons:"]
[:ul

[:li "Reagent doesn't have to spend time doing renderings
that no one would ever see (because changes to application
state happened faster than the browser could repaint)."]

[:li "If two or more atoms are changed simultaneously, this
now leads to only one re-rendering, and not two."]

[:li "The new code does proper batching of renderings even
when changes to atoms are done outside of event
handlers (which is great for e.g core.async users)."]

[:li "Repaints can be synced by the browser with for example
CSS transitions, since Reagent uses requestAnimationFrame
to do the batching. That makes for example animations
smoother."]]

[:p "In short, Reagent renders less often, but at the right
times. For a much better description of why async rendering
is good, see David Nolen’s " [:a om-article "excellent
explanation here."]]

[:h2 "The bad news"]

[:p "Lunches in general tend to be non-free, and this is no
exception… The downside to async rendering is that you can no
longer depend on changes to atoms being immediately available
in the DOM. (Actually, you couldn’t before either, since
React.js itself does batching inside event handlers.)"]

[:p "This may make testing a bit more verbose: you now have
to call " [:code "reagent.core/flush"] " to force Reagent to
synchronize state with the DOM."]

[:h2 "An example"]

[:p "Here is an example to (hopefully) demonstrate the
virtues of async rendering. It consists of a simple color
chooser (three sliders to set the red, green and blue
components of a base color), and shows the base color + a
bunch of divs in random matching colors. As soon as the base
color is changed, a new set of random colors is shown."]

[:p "If you change one of the base color components, the base
color should change immediately, and smoothly (on my Macbook
Air, rendering takes around 2ms, with 20 colored divs
showing)."]

[:p "But perhaps more interesting is to see what happens when
the updates can’t be made smoothly (because the browser
simply cannot re-render the colored divs quickly enough). On
my machine, this starts to happen if I change the number of
divs shown to above 150 or so."]

[:p "As you increase the number of divs, you’ll notice that
the base color no longer changes quite so smoothly when you
move the color sliders."]

[:p "But the crucial point is that the sliders "
[:strong "still work"] ". Without async rendering, you could
quickly get into a situation where the browser hangs for a
while, doing updates corresponding to an old state. "]

[:p "With async rendering, the only thing that happens is
that the frame rate goes down."]

[:p "Btw, I find it quite impressive that React manages to
change 500 divs (12 full screens worth) in slightly more than
40ms. And even better: when I change the number of divs
shown, it only takes around 6ms to re-render the color
palette (because the individual divs don’t have to be
re-rendered, divs are just added or removed from the DOM as
needed)."]

[demo-component
{:comp color-demo
:src (src-for
[:ns :timing-wrapper :base-color :ncolors
:random-colors :to-rgb :tweak-color
:reset-random-colors :color-choose :ncolors-choose
:palette :color-demo])}]])]]))

(swap! page-map assoc
"news/reagent-is-async.html" main)
Loading

0 comments on commit aca6934

Please sign in to comment.