Skip to content

Instantly share code, notes, and snippets.

@DarrenN
Last active December 31, 2015 09:29
Show Gist options
  • Save DarrenN/7967104 to your computer and use it in GitHub Desktop.
Save DarrenN/7967104 to your computer and use it in GitHub Desktop.
Create a queue of dom elements with core.async
(ns buffers.core
(:require
[cljs.core.async :refer (<! >! chan put! take! alts! timeout close! dropping-buffer sliding-buffer)]
[domina :as dom]
[domina.css :as css]
[domina.events :as ev]
[hiccups.runtime :as hiccupsrt])
(:require-macros
[cljs.core.async.macros :refer (go alt!)]
[hiccups.core :as hiccups]))
(defn ^:export log [thing] (.log js/console (clj->js thing)))
(aset js/window "log" log)
(def countr (atom 0))
(def buffer-length 250)
(def ul (dom/by-id "list"))
(defn rand-hsb []
(map Math/floor [(rand 360) (rand 100) (+ 25 (rand 50))]))
(def base-color (atom (rand-hsb)))
(defn make-base [hsb]
(let [[h s b] hsb]
(cond
(< h 359) [(+ h 1) s b]
(< s 100) [h (+ s 1) b]
(< b 100) [h s (+ b 1)]
:else (rand-hsb))))
(defn make-bg []
(let [color @base-color
[h s l] (make-base color)
color (conj [h] (str s "%") (str l "%"))]
(reset! base-color [h s l])
(str "background-color: hsl(" (clojure.string/join "," color) ")")))
(defn make-li [id]
(let [lid (str "li_" id)
hsb (make-bg)]
(dom/append! ul (hiccups/html [:li {:id lid :style hsb}]))))
(defn remove-li [id]
(let [lid (str "li_" id)]
(dom/detach! (dom/by-id lid))))
(defn load-squares [v]
(let [c (chan buffer-length)]
(doseq [i v]
(put! c i)
(swap! countr inc))
c))
(defn render-squares [c]
(go
(while true
(let [id (<! c)
offset (- @countr id)
floor (- @countr buffer-length)]
(make-li id)
(remove-li (- floor offset))
(<! (timeout 10))))))
(ev/listen! (dom/by-id "button-pause") :click (fn [evt]
(ev/prevent-default evt)
(render-squares (load-squares (vec (range @countr (+ @countr buffer-length)))))))
<html>
<head>
<style type="text/css" media="screen">
ul {
margin: 20px;
}
li {
list-style-type: none;
width: 40px;
height: 40px;
display: inline-block;
margin: 1px;
padding: 0;
}
</style>
</head>
<body>
<form method="get" id="buffer" action="#">
<input type="submit" name="pause" id="button-pause" value="MAKE SQUAREZ!" />
</form>
<ul id="list"></ul>
<script src="out/goog/base.js" type="text/javascript"></script>
<script src="buffers.js" type="text/javascript"></script>
<script type="text/javascript">goog.require("buffers.core");</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment