Skip to content

Instantly share code, notes, and snippets.

@borkdude
Created May 31, 2018 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borkdude/26685d175e117597a249c191396688d8 to your computer and use it in GitHub Desktop.
Save borkdude/26685d175e117597a249c191396688d8 to your computer and use it in GitHub Desktop.
cursor.cljs
(require '[cljs.nodejs :as node])
(node/enable-util-print!)
(def v8 (js/require "v8"))
(.setFlagsFromString v8 "--no-use_strict")
(def blessed (node/require "blessed"))
(def state (atom {:blink? false
:position 0}))
(declare cursor screen)
(def width #(.-width screen))
(def height #(.-height screen))
(def max-column #(dec (* (width) (height))))
(defn set-pos! [v]
(swap! state update :position (min (max-column) (max 0 v))))
(defn update-pos! [f]
(swap! state update :position (comp #(min (max-column)
(max 0 %))
f)))
(defn render-pos! [pos]
(let [left (mod pos (width))
top (quot pos (width))]
(if (>= top (height))
(js/process.exit)
(do
(set! (.-rleft cursor)
left)
(set! (.-rtop cursor)
top)
(.render screen)))))
(def interval-ids (atom #{}))
(defn render-blink! [blink?]
(if blink?
(let [id-black
(js/setInterval (fn []
(set! (.. cursor -style -bg) "black")
(.render screen))
1000)
id-green
(js/setTimeout #(js/setInterval
(fn []
(set! (.. cursor -style -bg) "green")
(.render screen)) 1000)
500)]
(swap! interval-ids conj id-black id-green))
(let [[old new] (reset-vals! interval-ids #{})]
(doseq [id old]
(js/clearInterval id)))))
(add-watch state :cursor
(fn [k r o n]
(let [new-pos (get n :position)
old-pos (get o :position)
new-blink? (get n :blink?)
old-blink? (get o :blink)]
(when (not= new-pos old-pos)
(render-pos! new-pos))
(when (not= new-blink? old-blink?)
(render-blink! new-blink?)))))
(def screen (.screen blessed #js {:smartCSR true}))
(def table (.box blessed #js
{:top 0
:left 0
:width (width)
:height (height)}))
(def cursor (.box blessed #js
{:top 0
:left 0
:width 1
:height 1
:bg "green"}))
(.append screen table)
(.append table cursor)
(.key screen #js ["left"]
(fn [ch key]
(update-pos! dec)))
(.key screen #js ["right"]
(fn [ch key]
(update-pos! inc)))
(.key screen #js ["up"]
(fn [ch key]
(update-pos!
(fn [v]
(- v (width))))))
(.key screen #js ["down"]
(fn [ch key]
(update-pos!
(fn [v]
(+ v (width))))))
(.key screen #js ["b"]
(fn [ch key]
(swap! state update :blink? not)))
(.key screen #js ["escape"
"q"
"C-c"]
(fn [ch key]
(js/process.exit)))
(.render screen)
@sandipmw
Copy link

does --no-use_strict works ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment