-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcore.cljs
More file actions
444 lines (375 loc) · 11.2 KB
/
Copy pathcore.cljs
File metadata and controls
444 lines (375 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
(ns hs-async.core
(:refer-clojure :exclude [map filter distinct remove])
(:require [cljs.core.async :refer [>! <! chan put! take! timeout close!]]
[goog.dom :as dom])
(:require-macros [cljs.core.async.macros :refer [go alt!]]))
;; ======================================================================
;; Basics
#_(.log js/console (go 5))
#_(.log js/console (<! (go 5)))
#_(go (.log js/console (<! (go 5))))
#_(let [c (chan)]
(go
(.log js/console "We got here")
(<! c)
(.log js/console "We'll never get here")))
#_(let [c (chan)]
(go
(.log js/console "We got here")
(<! c)
(.log js/console "We made progress"))
(go
(>! c (js/Date.))))
#_(let [c (chan)]
(go
(>! c (js/Date.)))
(go
(.log js/console "Order")
(<! c)
(.log js/console "doesn't matter")))
;; =============================================================================
;; Rx
(defn events [el type]
(let [out (chan)]
(.addEventListener el type
(fn [e] (put! out e)))
out))
#_(let [move (events js/window "mousemove")]
(go (while true
(.log js/console (<! move)))))
(defn map [f in]
(let [out (chan)]
(go (while true
(>! out (f (<! in)))))
out))
(defn e->v [e]
[(.-pageX e) (.-pageY e)])
#_(let [move (map e->v (events js/window "mousemove"))]
(go (while true
(.log js/console (pr-str (<! move))))))
(defn filter [pred in]
(let [out (chan)]
(go (while true
(let [x (<! in)]
(when (pred x)
(>! out x)))))
out))
(defn x-mod-5-y-mod-10 [[x y]]
(and (zero? (mod x 5))
(zero? (mod y 10))))
#_(let [filtered (filter x-mod-5-y-mod-10
(map e->v
(events js/window "mousemove")))]
(go (while true
(.log js/console (pr-str (<! filtered))))))
;; =============================================================================
;; Timeouts
#_(go
(.log js/console "Hello")
(<! (timeout 1000))
(.log js/console "async")
(<! (timeout 1000))
(.log js/console "world!"))
;; =============================================================================
;; Non-deterministic choice
#_(let [c (chan)
t (timeout 1000)]
(go
(let [[v sc] (alts! [c t])]
(.log js/console "Timeout channel closed!" (= sc t)))))
#_(let [c (chan)
t (timeout 1000)]
(go
(alt!
c ([v] (.log js/console "Channel responded"))
t ([v] (.log js/console "Timeout channel closed!")))))
;; =============================================================================
;; State
(defn distinct [in]
(let [out (chan)]
(go (loop [last nil]
(let [x (<! in)]
(when (not= x last)
(>! out x))
(recur x))))
out))
#_(let [keys (distinct
(map #(.-keyCode %)
(events js/window "keypress")))]
(go (while true
(.log js/console (<! keys)))))
;; =============================================================================
;; More coordination
(defn fan-in [ins]
(let [out (chan)]
(go (while true
(let [[x] (alts! ins)]
(>! out x))))
out))
(defn my-ints []
(let [out (chan)]
(go (loop [i 1]
(>! out i)
(recur (inc i))))
out))
(defn interval [msecs]
(let [out (chan)]
(go (while true
(>! out (js/Date.))
(<! (timeout msecs))))
out))
(defn process [name control]
(let [out (chan)
ints (my-ints)
tick (interval 1000)]
(go
(<! control)
(.log js/console "start" name)
(loop [acc 0]
(let [[v c] (alts! [tick control])]
(condp = c
control (do (.log js/console "pause" name)
(<! control)
(.log js/console "continue" name)
(recur acc))
(do
(>! out [name acc])
(recur (+ acc (<! ints))))))))
out))
(defn now [] (js/Date.))
#_(let [c0 (chan)
c1 (chan)
out (fan-in [(process "p0" c0) (process "p1" c1)])
keys (->> (events js/window "keyup")
(map #(.-keyCode %))
(filter #{32}))]
(go
(>! c0 (now))
(loop [state 0]
(recur
(alt!
out
([v] (do (.log js/console (pr-str v)) state))
keys
([v] (case state
0 (do (>! c0 (now)) (>! c1 (now)) 1)
1 (do (>! c1 (now)) (>! c0 (now)) 0))))))))
;; =============================================================================
;; Escaping Callback hell
(defn fake-search [kind]
(fn [c query]
(go
(<! (timeout (rand-int 100)))
(>! c [kind query]))))
(def web1 (fake-search :web1))
(def web2 (fake-search :web2))
(def image1 (fake-search :image1))
(def image2 (fake-search :image2))
(def video1 (fake-search :video1))
(def video2 (fake-search :video2))
(defn fastest [query & replicas]
(let [c (chan)]
(doseq [replica replicas]
(replica c query))
c))
(defn google [query]
(let [c (chan)
t (timeout 80)]
(go (>! c (<! (fastest query web1 web2))))
(go (>! c (<! (fastest query image1 image2))))
(go (>! c (<! (fastest query video1 video2))))
(go (loop [i 0 ret []]
(if (= i 3)
ret
(recur (inc i) (conj ret (alt! [c t] ([v] v)))))))))
#_(go (.log js/console (pr-str (<! (google "clojure")))))
;; =============================================================================
;; Getting fancier
;; -----------------------------------------------------------------------------
;; Declarations
(def ENTER 13)
(def UP_ARROW 38)
(def DOWN_ARROW 40)
(def SELECTOR_KEYS #{ENTER UP_ARROW DOWN_ARROW})
;; -----------------------------------------------------------------------------
;; Utils & DOM Helpers
(defn by-id [id]
(.getElementById js/document id))
(defn by-tag-name [el tag]
(.getElementsByTagName el tag))
(defn set-class [el name]
(set! (.-className el) name))
(defn clear-class [el]
(set! (.-className el) ""))
(defn key-event->keycode [e]
(.-keyCode e))
(defn tag-match [tag]
(fn [el]
(when-let [tag-name (.-tagName el)]
(= tag (.toLowerCase tag-name)))))
(defn index-of [node-list el]
(loop [i 0]
(if (< i (alength node-list))
(if (identical? (aget node-list i) el)
i
(recur (inc i)))
-1)))
(extend-type default
ICounted
(-count [coll]
(if (instance? js/NodeList coll)
(alength coll)
(accumulating-seq-count coll)))
IIndexed
(-nth
([coll n]
(-nth coll n nil))
([coll n not-found]
(if (instance? js/NodeList coll)
(if (< n (count coll))
(aget coll n)
(throw (js/Error. "NodeList access out of bounds")))
(linear-traversal-nth coll (.floor js/Math n) not-found)))))
;; -----------------------------------------------------------------------------
;; Reactive support
(defn put-all! [cs x]
(doseq [c cs]
(put! c x)))
(defn multiplex [in cs-or-n]
(let [cs (if (number? cs-or-n)
(repeatedly cs-or-n chan)
cs-or-n)]
(go (loop []
(let [x (<! in)]
(if-not (nil? x)
(do
(put-all! cs x)
(recur))
:done))))
cs))
(defn remove [f source]
(let [out (chan)]
(go (while true
(let [v (<! source)]
(when-not (f v)
(>! out v)))))
out))
;; -----------------------------------------------------------------------------
;; Selection process
(defprotocol IUIList
(-select! [list n])
(-unselect! [list n]))
(defn select [list idx key]
(if (= idx ::none)
(condp = key
:up (dec (count list))
:down 0)
(mod (({:up dec :down inc} key) idx)
(count list))))
(defn selector [in list data]
(let [out (chan)]
(go
(loop [selected ::none]
(let [v (<! in)]
(cond
(nil? v) :ok
(= v :select) (do (>! out (nth data selected))
(recur selected))
:else (do (when (number? selected)
(-unselect! list selected))
(if (= v :out)
(recur ::none)
(let [n (if (number? v) v (select list selected v))]
(-select! list n)
(recur n))))))))
out))
;; -----------------------------------------------------------------------------
;; HTML Demo
(defn hover-chan [el tag]
(let [matcher (tag-match tag)
matches (by-tag-name el tag)
over (->> (events el "mouseover")
(map
#(let [target (.-target %)]
(if (matcher target)
target
(if-let [el (dom/getAncestor target matcher)]
el
:no-match))))
(remove #{:no-match})
(map
#(index-of matches %)))
out (->> (events el "mouseout")
(filter
(fn [e]
(and (matcher (.-target e))
(not (matcher (.-relatedTarget e))))))
(map #(do :out)))]
(distinct (fan-in [over out]))))
(defn selector-key->keyword [code]
(condp = code
UP_ARROW :up
DOWN_ARROW :down
ENTER :select))
(extend-type js/HTMLUListElement
ICounted
(-count [list]
(alength (by-tag-name list "li")))
IUIList
(-select! [list n]
(set-class (nth (by-tag-name list "li") n) "selected"))
(-unselect! [list n]
(clear-class (nth (by-tag-name list "li") n))))
#_(let [el (by-id "list")
hover (hover-chan el "li")
keys (->> (events js/window "keydown")
(map key-event->keycode)
(filter SELECTOR_KEYS)
(map selector-key->keyword))
click (->> (events el "click")
(map #(do :select)))
c (selector (fan-in [hover keys click])
el ["one" "two" "three"])]
(go (while true
(.log js/console (<! c)))))
;; -----------------------------------------------------------------------------
;; Array Demo
(extend-type array
IUIList
(-select! [list n]
(aset list n (.replace (aget list n) " " "* ")))
(-unselect! [list n]
(aset list n (.replace (aget list n) "* " " "))))
#_(let [keys (->> (events js/window "keydown")
(map key-event->keycode)
(filter SELECTOR_KEYS)
(map selector-key->keyword))
[k0 k1] (multiplex keys 2)
k1 (filter #{:up :down} k1)
list (array " one" " two" " three")
c (selector k0 list ["one" "two" "three"])]
(.log js/console (.join list "\n"))
(go (while true
(alt!
k1 ([v] (.log js/console (.join list "\n")))
c ([v] (.log js/console v))))))
(defn spool [xs]
(let [out (chan)]
(go (loop [xs xs]
(if-not (empty? xs)
(do
(>! out (first xs))
(recur (rest xs)))
(close! out))))
out))
#_(let [c (spool [1 2 3 4 5])]
(go (loop []
(when-let [x (<! c)]
(.log js/console x)
(recur)))))
#_(let [test (spool [:down :down :select])
list (array " one" " two" " three")
c (selector test list ["one" "two" "three"])]
(go
(.log js/console (<! c))
(.log js/console (.join list "\n"))))