воскресенье, 29 января 2017 г.

clojurescript + reagent = track mouse example

Here is pretty simple example of mouse tracking app

(ns hello-world-cljs.core
  (:require [reagent.core :as r]))

(println "Hello App is started!")
(defonce app-state (r/atom {:mouse-trac? false :pointer {:x 0 :y 0}}))
(defn mouse-coords [e] {:x (.-pageX e) :y (.-pageY e)})
(defn mouse-handler [e] (swap! app-state assoc-in [:pointer] (mouse-coords e)))
(defn start-mouse-listen [handler] (js/document.addEventListener "mousemove" handler))
(defn stop-mouse-listen [handler] (js/document.removeEventListener "mousemove" handler))

(defn trac-mouse-button []
  [:div   [:button {:type "button" :class "btn btn-default" :on-click (fn [e] (swap! app-state update-in [:mouse-trac?] not))}
    "Mouse track?"]])

(defn trac-button-state-label [] [:div [:label (str (:mouse-trac? @app-state))]])

(defn mouse-coords-label [] [:div [:label (str "Pointer moved to: " (str (:pointer @app-state)))]])

(defn mouse-changer
  "this fn called every time when state of :mouse-trac? is changed"  []
  [:div   (if (:mouse-trac? @app-state)
     (start-mouse-listen mouse-handler)
     (stop-mouse-listen mouse-handler))])

(defn app-hello [] [:div [trac-mouse-button] [trac-button-state-label] [mouse-coords-label] [mouse-changer]])

(r/render-component [app-hello]
                    (.getElementById js/document "app"))

Here is result: