@kairotic/app 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,96 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · shared core
3
+ ;; Utilities shared by all the studies: escaping text, encoding EDN ⇄ JSON
4
+ ;; without evaluating anything, and the REPL where every gesture is written as code.
5
+
6
+ (ns kairotic.core
7
+ (:require [clojure.string :as str]))
8
+
9
+ (defn esc [s]
10
+ (-> (str s)
11
+ (str/replace "&" "&")
12
+ (str/replace "<" "&lt;")
13
+ (str/replace ">" "&gt;")
14
+ (str/replace "\"" "&quot;")))
15
+
16
+ ;; ───────── EDN ⇄ JSON (for saving in the db) ─────────
17
+ ;; Keywords, names (symbols) and maps are tagged so they come back as EDN without evaluating foreign code.
18
+
19
+ (defn enc [x]
20
+ (cond (keyword? x) {"k" (if (namespace x) (str (namespace x) "/" (name x)) (name x))}
21
+ ;; a name (a msg sends inc, e4, 6/5 as names): its whole text, tagged like a keyword
22
+ (symbol? x) {"y" (str x)}
23
+ (map? x) {"m" (mapv (fn [[k v]] [(enc k) (enc v)]) x)}
24
+ (sequential? x) (mapv enc x)
25
+ :else x))
26
+
27
+ (defn dec* [x]
28
+ (cond (map? x) (cond (contains? x "k") (keyword (str (get x "k")))
29
+ (contains? x "y") (symbol (str (get x "y")))
30
+ (contains? x "m") (into {} (for [kv (get x "m") :when (and (sequential? kv) (= 2 (count kv)))]
31
+ [(dec* (first kv)) (dec* (second kv))]))
32
+ :else nil)
33
+ (sequential? x) (mapv dec* x)
34
+ :else x))
35
+
36
+ ;; ───────── evaluation ─────────
37
+ ;; All the code from the REPL and from gestures is evaluated in the `user` namespace,
38
+ ;; where each page defines its commands.
39
+
40
+ (defn eval-str [code]
41
+ (js/scittle.core.eval_string (str "(in-ns 'user)\n" code)))
42
+
43
+ ;; ───────── REPL ─────────
44
+
45
+ (defonce repl-state (atom {:out nil :hist [] :hidx nil}))
46
+
47
+ (defn repl-print! [cls html]
48
+ (when-let [out (some-> (:out @repl-state) (js/document.getElementById))]
49
+ (let [d (js/document.createElement "div")]
50
+ (set! (.-className d) cls)
51
+ (set! (.-innerHTML d) html)
52
+ (.appendChild out d)
53
+ (set! (.-scrollTop out) (.-scrollHeight out)))))
54
+
55
+ (defn repl-eval!
56
+ "Evaluates code and shows it in the REPL. `source` is :repl (typed) or :gesture (generated by the interface)."
57
+ [code source]
58
+ (repl-print! (str "in" (when (= source :gesture) " from-patch"))
59
+ (str "<span class=\"p\">" (if (= source :gesture) "⟵" "λ") "</span>" (esc code)))
60
+ (try
61
+ (let [v (eval-str code)]
62
+ (when (= source :repl) (repl-print! "out" (esc (pr-str v))))
63
+ v)
64
+ (catch :default e
65
+ (repl-print! "err" (esc (or (.-message e) (str e))))
66
+ nil)))
67
+
68
+ (defn gesture!
69
+ "A gesture in the interface is written as code and evaluated: that way interface and code are the same thing."
70
+ [code]
71
+ (repl-eval! code :gesture))
72
+
73
+ (defn mount-repl!
74
+ "Wires an input line and an output area (by id) as a REPL with ↑ ↓ history."
75
+ [out-id in-id]
76
+ (swap! repl-state assoc :out out-id)
77
+ (let [inp (js/document.getElementById in-id)]
78
+ (.addEventListener inp "keydown"
79
+ (fn [e]
80
+ (let [k (.-key e)]
81
+ (cond
82
+ (= k "Enter")
83
+ (let [code (str/trim (.-value inp))]
84
+ (when (seq code)
85
+ (swap! repl-state (fn [s] (-> s (update :hist conj code) (assoc :hidx nil))))
86
+ (set! (.-value inp) "")
87
+ (repl-eval! code :repl)))
88
+ (or (= k "ArrowUp") (= k "ArrowDown"))
89
+ (let [{:keys [hist hidx]} @repl-state n (count hist)]
90
+ (when (pos? n)
91
+ (.preventDefault e)
92
+ (let [i (if (= k "ArrowUp")
93
+ (if (nil? hidx) (dec n) (max 0 (dec hidx)))
94
+ (if (nil? hidx) nil (if (>= (inc hidx) n) nil (inc hidx))))]
95
+ (swap! repl-state assoc :hidx i)
96
+ (set! (.-value inp) (if (nil? i) "" (nth hist i))))))))))))
@@ -0,0 +1,473 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · corefns
3
+ ;; The functions of clojure.core (and clojure.string) as boxes, without writing a component for each
4
+ ;; (discussion #12): a box whose first word is one of them is that function. Its other words are its
5
+ ;; arguments, read as EDN; the message that arrives at the left inlet goes last, as with ->>:
6
+ ;;
7
+ ;; into [440] [1 2] → [440 1 2] take 3 [1 2 3 4] → [1 2 3]
8
+ ;; map inc [1 2] → [2 3] get % :freq {:freq 440} → 440
9
+ ;; conj % 440 [1 2] → [1 2 440] str/upper-case "do" → "DO"
10
+ ;;
11
+ ;; The text reads as Clojure, the inlets as Max: % puts the message somewhere else in the call
12
+ ;; (conj % 440, assoc % :freq 440, vector % 0 0), and whatever its place it is always the left inlet,
13
+ ;; the only hot one. The other arguments have an inlet each on the right, in the order they are written,
14
+ ;; which replaces them without sending; a bang on the left sends the last result again. A word that names
15
+ ;; one of these functions is that function (map inc, sort-by -).
16
+ ;;
17
+ ;; As in Clojure, data are functions too: a keyword (:freq, :freq 440 with a default), a set
18
+ ;; (#{60 64 67}: lets through only those) or a map ({60 :c 64 :e}: a table) written first is a box,
19
+ ;; and the message goes first: (:freq msg 440). A result that is nil sends nothing.
20
+ ;;
21
+ ;; ^:hot before the class (^:hot vector % 0 0) makes every inlet hot, like pak in Max: a new argument
22
+ ;; sends at once, with the last message (nil before the first one).
23
+ ;;
24
+ ;; Functions travel through the wires as their form, EDN data (issue #177): comp, partial, juxt,
25
+ ;; complement, fnil, constantly, every-pred and some-fn are boxes that send one, (comp inc (partial * 2)),
26
+ ;; and wherever a box takes an argument a name or such a form is that function: into the inlet of inc in
27
+ ;; map inc it changes the function live — msg dec too, since a msg sends a word without colon as a name.
28
+ ;; Nothing but these pure functions is ever made from a form.
29
+ ;;
30
+ ;; xf/ makes the transducer of a function into a box with memory, which goes through a stream of
31
+ ;; messages instead of a collection (clojure.org/reference/transducers):
32
+ ;;
33
+ ;; xf/partition-all 4 collects 4 messages and sends them as a vector (flush sends what is left)
34
+ ;; xf/partition 4 1 the last 4, at every message (a sliding window)
35
+ ;; xf/dedupe only when it changes · xf/take 1 the first one only (clear lets one more through)
36
+ ;;
37
+ ;; flush completes it (partition-all sends what it holds) and starts again; clear starts again without
38
+ ;; sending; a new argument on the right starts again too.
39
+ ;;
40
+ ;; Only pure functions are here (no evaluation of code, no time, no state of the page, nothing infinite),
41
+ ;; so these boxes are safe in a shared room: an xf/ box remembers only the messages that went through
42
+ ;; it. A result that is a sequence goes on as a vector, of at most 4096 elements. A class registered
43
+ ;; with the same name (+, -, print, mtof…) comes first.
44
+
45
+ (ns kairotic.corefns
46
+ (:require [clojure.string :as str]
47
+ [clojure.edn :as edn]
48
+ [kairotic.components :as comp]))
49
+
50
+ (defn format*
51
+ "clojure.core/format, as Java's printf writes it, for what a patch needs: %s (str of the value), %d (an
52
+ integer, rounded), %f %.2f (a number with that many decimals, 6 by default), %e, %x, %%, with a width
53
+ (%5.1f, %-8s left-aligned, %05d with zeros) and %n for a new line. A directive with no value left, or a
54
+ %d or %f with something that is not a number, writes it as %s does."
55
+ [fmt & args]
56
+ (let [re #"%([-0]?)(\d+)?(?:\.(\d+))?([sdfexn%])"]
57
+ (loop [out "" i 0 xs args]
58
+ (if-let [m (.exec (js/RegExp. (.-source re) "g") (subs fmt i))]
59
+ (let [[whole flag width prec conv] (vec (array-seq m))
60
+ at (+ i (.-index m))
61
+ lit (subs fmt i at)
62
+ next-i (+ at (count whole))]
63
+ (case conv
64
+ "%" (recur (str out lit "%") next-i xs)
65
+ "n" (recur (str out lit "\n") next-i xs)
66
+ (let [x (first xs)
67
+ num? (number? x)
68
+ body (cond
69
+ (and (= conv "d") num?) (str (js/Math.round x))
70
+ (and (= conv "f") num?) (.toFixed x (if prec (js/parseInt prec 10) 6))
71
+ (and (= conv "e") num?) (.toExponential x (if prec (js/parseInt prec 10) 6))
72
+ (and (= conv "x") num?) (.toString (js/Math.round x) 16)
73
+ (string? x) x
74
+ (nil? x) "nil"
75
+ :else (str x))
76
+ w (if width (js/parseInt width 10) 0)
77
+ pad (max 0 (- w (count body)))
78
+ body (cond (zero? pad) body
79
+ (= flag "-") (str body (apply str (repeat pad " ")))
80
+ (and (= flag "0") num?) (if (str/starts-with? body "-")
81
+ (str "-" (apply str (repeat pad "0")) (subs body 1))
82
+ (str (apply str (repeat pad "0")) body))
83
+ :else (str (apply str (repeat pad " ")) body))]
84
+ (recur (str out lit body) next-i (rest xs)))))
85
+ (str out (subs fmt i))))))
86
+
87
+ (def fns
88
+ {;; collections
89
+ "into" into "conj" conj "cons" cons "concat" concat "vec" vec "set" set "seq" seq "list" list "vector" vector
90
+ "hash-map" hash-map "first" first "second" second "last" last "rest" rest "next" next "butlast" butlast
91
+ "nth" nth "count" count "empty?" empty? "not-empty" not-empty "reverse" reverse "sort" sort "sort-by" sort-by
92
+ "distinct" distinct "dedupe" dedupe "flatten" flatten "frequencies" frequencies "group-by" group-by
93
+ "take" take "drop" drop "take-last" take-last "drop-last" drop-last "take-nth" take-nth
94
+ "take-while" take-while "drop-while" drop-while "interleave" interleave "interpose" interpose
95
+ "partition" partition "partition-all" partition-all "partition-by" partition-by "split-at" split-at
96
+ "map" map "mapv" mapv "mapcat" mapcat "map-indexed" map-indexed "filter" filter "filterv" filterv
97
+ "remove" remove "keep" keep "reduce" reduce "reductions" reductions "apply" apply "some" some
98
+ "every?" every? "range" range "repeat" repeat "zipmap" zipmap "identity" identity
99
+ ;; maps
100
+ "get" get "get-in" get-in "assoc" assoc "assoc-in" assoc-in "dissoc" dissoc "update" update
101
+ "update-in" update-in "select-keys" select-keys "keys" keys "vals" vals "merge" merge "find" find
102
+ "contains?" contains?
103
+ ;; numbers and comparison (+ - * / are boxes of their own)
104
+ "inc" inc "dec" dec "max" max "min" min "abs" (fn [x] (js/Math.abs x)) "quot" quot "rem" rem "mod" mod "max-key" max-key
105
+ "min-key" min-key "=" = "not=" not= "<" < ">" > "<=" <= ">=" >= "zero?" zero? "pos?" pos? "neg?" neg?
106
+ "even?" even? "odd?" odd? "number?" number? "not" not "nil?" nil? "some?" some?
107
+ ;; text and names
108
+ "str" str "format" format* "subs" subs "keyword" keyword "name" name
109
+ "str/upper-case" str/upper-case "str/lower-case" str/lower-case "str/capitalize" str/capitalize
110
+ "str/trim" str/trim "str/split" str/split "str/join" str/join "str/replace" str/replace
111
+ "str/includes?" str/includes? "str/starts-with?" str/starts-with? "str/ends-with?" str/ends-with?
112
+ "str/reverse" str/reverse "str/blank?" str/blank?})
113
+
114
+ (defn partition-xf
115
+ "The transducer clojure.core's partition does not have: (partition-xf n) or (partition-xf n step) sends
116
+ every n messages as a vector, the next one starting step after the start of the last (step 1: a
117
+ sliding window); like partition, an incomplete group at the end is not sent."
118
+ ([n] (partition-xf n n))
119
+ ([n step]
120
+ (fn [rf]
121
+ (let [buf (volatile! []) skip (volatile! 0)]
122
+ (fn
123
+ ([acc] (rf acc))
124
+ ([acc x]
125
+ (if (pos? @skip)
126
+ (do (vswap! skip dec) acc)
127
+ (let [b (vswap! buf conj x)]
128
+ (if (< (count b) n)
129
+ acc
130
+ (do (vreset! buf (if (< step n) (subvec b step) []))
131
+ (when (> step n) (vreset! skip (- step n)))
132
+ (rf acc b)))))))))))
133
+
134
+ ;; the functions whose transducer can be an xf/ box (each one called with the box's arguments)
135
+ (def xfs
136
+ {"map" map "map-indexed" map-indexed "keep" keep "keep-indexed" keep-indexed "mapcat" mapcat
137
+ "filter" filter "remove" remove "take" take "drop" drop "take-while" take-while "drop-while" drop-while
138
+ "take-nth" take-nth "partition-all" partition-all "partition-by" partition-by "partition" partition-xf
139
+ "dedupe" dedupe "distinct" distinct "interpose" interpose "cat" (fn [] cat)})
140
+
141
+ (def max-items 4096)
142
+
143
+ ;; ───────── functions as values (issue #177) ─────────
144
+ ;; A function travels through the wires as its form, EDN data: (comp inc (partial * 2)). Where a box takes
145
+ ;; an argument, a name or such a form is the function, rebuilt in each browser from these same pure
146
+ ;; functions — nothing else is evaluated, so it is as safe in a shared room as any argument.
147
+
148
+ (def builders
149
+ "The functions that make functions: as boxes they send a form; inside a form, they build it."
150
+ {"comp" comp "partial" partial "juxt" juxt "complement" complement "fnil" fnil "constantly" constantly
151
+ "every-pred" every-pred "some-fn" some-fn})
152
+
153
+ ;; names a form can use: the function boxes, the arithmetic that has boxes of its own, and the builders
154
+ (def ^:private symbols
155
+ (merge fns builders {"+" + "-" - "*" * "/" / "identity" identity}))
156
+
157
+ (defn fn-form?
158
+ "A form that makes a function: a list whose first element names one of the builders."
159
+ [x]
160
+ (and (seq? x) (symbol? (first x)) (contains? builders (str (first x)))))
161
+
162
+ (declare as-fn)
163
+
164
+ (def ^:private build
165
+ (memoize (fn [form] (apply (get builders (str (first form))) (map as-fn (rest form))))))
166
+
167
+ (defn as-fn
168
+ "An argument as a box uses it: a name of one of these functions is that function, a form that makes one
169
+ (comp …, partial …) is the function it makes; anything else stays as it is (a keyword is a function by
170
+ itself, and a key)."
171
+ [x]
172
+ (cond (symbol? x) (get symbols (str x) x)
173
+ (fn-form? x) (build x)
174
+ :else x))
175
+
176
+ (defn unknown-names
177
+ "What, inside a form (or a word), is not one of these functions — a name it does not know, or a list
178
+ that does not make a function ((inc 1) is a call, not a function): a form that has any cannot be made."
179
+ [x]
180
+ (cond (= x '%) []
181
+ (symbol? x) (if (contains? symbols (str x)) [] [x])
182
+ (fn-form? x) (vec (mapcat unknown-names (rest x)))
183
+ (seq? x) [x]
184
+ (coll? x) (vec (mapcat unknown-names x))
185
+ :else []))
186
+
187
+ (defn parse
188
+ "The arguments written after the class, as EDN data (a name or a form that makes a function stays
189
+ as written, and becomes the function when it is called: as-fn), or {:error message}. Its metadata says
190
+ whether the box is ^:hot."
191
+ [text]
192
+ (let [t (comp/strip-meta text)
193
+ rest-text (str/trim (subs t (count (comp/klass t))))]
194
+ (try (with-meta (vec (edn/read-string (str "[" rest-text "]")))
195
+ {:hot (contains? (comp/meta-flags text) :hot)})
196
+ (catch :default e {:error (str "cannot read its arguments: " (.-message e))}))))
197
+
198
+ (defn slots
199
+ "The places of the arguments that have an inlet of their own (all but %), in the order they are written:
200
+ inlet 1 replaces the first of them, inlet 2 the second…"
201
+ [args]
202
+ (vec (keep-indexed (fn [i a] (when-not (= a '%) i)) args)))
203
+
204
+ (defn- finite
205
+ "A result that can travel: a sequence becomes a vector (or an error, if it is too long)."
206
+ [r]
207
+ (if (and (seq? r) (not (counted? r)))
208
+ (let [v (vec (take (inc max-items) r))]
209
+ (if (> (count v) max-items) (throw (js/Error. (str "more than " max-items " elements"))) v))
210
+ (if (seq? r) (vec r) r)))
211
+
212
+ (defn call
213
+ "f with its arguments and the message: at the place of % if there is one, else last (first when
214
+ lead is true, as a keyword, a set or a map takes it)."
215
+ ([f args v] (call f args v false))
216
+ ([f args v lead]
217
+ (let [has% (some #{'%} args)
218
+ args (map (fn [a] (if (= a '%) a (as-fn a))) args)]
219
+ (finite (cond has% (apply f (map (fn [a] (if (= a '%) v a)) args))
220
+ lead (apply f v args)
221
+ :else (apply f (concat args [v])))))))
222
+
223
+ (defn- fresh
224
+ "The state of a box for this text: the one it has if it was made for the same class and arguments, else
225
+ a new one (the box was rewritten)."
226
+ [state n args]
227
+ (if (= (:sig state) [n args]) state {:sig [n args]}))
228
+
229
+ (defn- send-result [state v r]
230
+ {:state (assoc state :last v) :out (if (nil? r) [] [[0 r]])})
231
+
232
+ (defn receive
233
+ "A function box. Left inlet: calls the function with the message (a bang: with the last message, and
234
+ the arguments as they are now). Other inlets: replace an argument, sending nothing — or, ^:hot,
235
+ sending at once with the last message."
236
+ [{:keys [f n lead]} {:keys [args state inlet value]}]
237
+ (if (map? args)
238
+ {:effects [[:print (:error args)]]}
239
+ (let [state (fresh state n args)
240
+ as (or (:args state) args)]
241
+ (cond
242
+ (pos? inlet)
243
+ (if-let [i (get (slots args) (dec inlet))]
244
+ (let [st (assoc state :args (assoc as i value))]
245
+ (if (:hot (meta args))
246
+ (send-result st (:last st) (call f (:args st) (:last st) lead))
247
+ {:state st}))
248
+ {:state state})
249
+ (and (= value :bang) (not (contains? state :last))) {:state state}
250
+ :else (let [v (if (= value :bang) (:last state) value)]
251
+ (send-result state v (call f as v lead)))))))
252
+
253
+ (defn- xf-instance
254
+ "A transducer of make with these arguments, ready to take messages: what it lets through gathers in :buf."
255
+ [make args]
256
+ (let [buf (volatile! [])
257
+ rf ((apply make (map as-fn args)) (fn ([acc] acc) ([acc x] (vswap! buf conj x) acc)))]
258
+ {:rf rf :buf buf :done false}))
259
+
260
+ (defn- drain
261
+ "What an xf/ box let through since last time, as messages from its outlet (nil sends nothing)."
262
+ [st]
263
+ (let [xs @(:buf st)]
264
+ (vreset! (:buf st) [])
265
+ (vec (keep (fn [x] (let [x (finite x)] (when (some? x) [0 x]))) xs))))
266
+
267
+ (defn xf-receive
268
+ "An xf/ box: each message on the left goes through the transducer (a bang too: it is a message like any
269
+ other); flush completes it and starts again, clear starts again; the inlets on the right replace an
270
+ argument and start again."
271
+ [{:keys [make n]} {:keys [args state inlet value]}]
272
+ (if (map? args)
273
+ {:effects [[:print (:error args)]]}
274
+ (let [state (fresh state n args)
275
+ as (or (:args state) args)
276
+ st (if (:rf state) state (merge state (xf-instance make as)))]
277
+ (cond
278
+ (pos? inlet)
279
+ (if-let [i (get (slots args) (dec inlet))]
280
+ (let [as (assoc as i value)]
281
+ {:state (merge (assoc st :args as) (xf-instance make as))})
282
+ {:state st})
283
+ (#{:clear} value) {:state (merge st (xf-instance make as))}
284
+ (#{:flush} value) (do ((:rf st) nil)
285
+ {:state (merge st (xf-instance make as)) :out (drain st)})
286
+ (:done st) {:state st :out []}
287
+ :else (let [r ((:rf st) nil value)]
288
+ (if (reduced? r)
289
+ (do ((:rf st) nil) {:state (assoc st :done true) :out (drain st)})
290
+ {:state st :out (drain st)}))))))
291
+
292
+ ;; ───────── boxes that make functions ─────────
293
+
294
+ (defn builder-receive
295
+ "A box that makes a function (comp inc (partial * 2)): it sends its form, which the boxes that take a
296
+ function as an argument use as that function. Without %, any message on the left (a bang) sends it; with %,
297
+ the message goes there (comp % inc composes the function that arrives) and a bang sends it again. The
298
+ inlets on the right replace the other arguments, sending nothing (^:hot: sending). A form with a name that
299
+ is not one of these functions is not sent: it is written in the REPL."
300
+ [{:keys [n]} {:keys [args state inlet value]}]
301
+ (if (map? args)
302
+ {:effects [[:print (:error args)]]}
303
+ (let [state (fresh state n args)
304
+ as (or (:args state) args)
305
+ has% (some #{'%} args)
306
+ form (fn [as v] (apply list (symbol n) (if has% (map (fn [a] (if (= a '%) v a)) as) as)))
307
+ send (fn [st v]
308
+ (let [f (form (:args st as) v)
309
+ bad (unknown-names f)]
310
+ (if (seq bad)
311
+ {:state st :effects [[:print (str n ": " (str/join ", " (distinct bad)) " is not a function it knows")]]}
312
+ {:state (assoc st :last v) :out [[0 f]]})))]
313
+ (cond
314
+ (pos? inlet)
315
+ (if-let [i (get (slots args) (dec inlet))]
316
+ (let [st (assoc state :args (assoc as i value))]
317
+ (if (and (:hot (meta args)) (or (not has%) (contains? st :last))) (send st (:last st)) {:state st}))
318
+ {:state state})
319
+ (not has%) (send state nil)
320
+ (and (= value :bang) (not (contains? state :last))) {:state state}
321
+ :else (send state (if (= value :bang) (:last state) value))))))
322
+
323
+ ;; ───────── what each kind of box is ─────────
324
+
325
+ (defn data-fn
326
+ "A keyword, a set or a map written as the class, as the function it is in Clojure; nil for anything else."
327
+ [n]
328
+ (cond
329
+ (re-matches #":[^\s\[\]{}()\"#,;]+" n) (keyword (subs n 1))
330
+ (re-find #"^#?\{" n) (let [x (try (edn/read-string n) (catch :default _ nil))]
331
+ (when (or (map? x) (set? x)) x))
332
+ :else nil))
333
+
334
+ (defn docs-url
335
+ "The page of a function at clojuredocs.org (clojure.core or clojure.string)."
336
+ [n]
337
+ (let [[ns-name fname] (if (str/starts-with? n "str/") ["clojure.string" (subs n 4)] ["clojure.core" n])]
338
+ (str "https://clojuredocs.org/" ns-name "/" (js/encodeURIComponent (str/replace fname "?" "_q")))))
339
+
340
+ (def ^:private transducers-ref ["Transducers" "https://clojure.org/reference/transducers"])
341
+ (def ^:private hot-ref ["Metadata (^:hot)" "https://clojure.org/reference/metadata"])
342
+
343
+ (defn- clj-doc [n]
344
+ (try (:doc (meta (get (ns-publics (if (str/starts-with? n "str/") 'clojure.string 'clojure.core))
345
+ (symbol (str/replace n #"^str/" "")))))
346
+ (catch :default _ nil)))
347
+
348
+ (def ^:private how-fn
349
+ (str " as a box: the message at the left goes last among its arguments, or where % is, and is always the left"
350
+ " inlet, the only hot one; the other inlets replace the other arguments, in the order they are written,"
351
+ " without sending (^:hot before the class: sending); a bang sends the last result again; nil sends nothing."
352
+ " An argument that is a function (map inc) takes in its inlet another one: a form sent by comp, partial…"))
353
+
354
+ (defn- kind
355
+ "What a class name is: {:kind :fn|:builder|:data|:xf …}, or nil."
356
+ [n]
357
+ (cond
358
+ (contains? fns n) {:kind :fn :f (get fns n) :n n}
359
+ (contains? builders n) {:kind :builder :n n}
360
+ (and (str/starts-with? n "xf/") (contains? xfs (subs n 3))) {:kind :xf :make (get xfs (subs n 3)) :n n}
361
+ :else (when-let [f (data-fn n)] {:kind :data :f f :n n :lead true})))
362
+
363
+ (defn- describe
364
+ "The :doc, :usage and :ref of a kind of box."
365
+ [{:keys [kind n f]}]
366
+ (case kind
367
+ :builder {:doc (str "clojure.core/" n " as a box that makes a function: it sends its form — (" n " …) as written —"
368
+ " and a box that takes a function as an argument (map inc, xf/filter odd?, sort-by :freq…)"
369
+ " uses it in that argument's inlet, changing it live. A bang sends it; with %, the message"
370
+ " goes there (comp % inc composes the function that arrives). Inside, any function box"
371
+ " names a function, + - * / too, and the forms nest: comp inc (partial * 2). Only the form"
372
+ " travels, rebuilt in each browser from the same pure functions."
373
+ (when-let [clj (clj-doc n)] (when (seq clj) (str "\n\n" clj))))
374
+ :usage (str n " [functions and arguments…] · bang sends it · % takes the message")
375
+ :ref [[(str "clojure.core/" n) (docs-url n)]
376
+ ["Higher-order functions" "https://clojure.org/guides/higher_order_functions"]]}
377
+ :fn (let [qual (str (if (str/starts-with? n "str/") "clojure.string/" "clojure.core/") (str/replace n #"^str/" ""))
378
+ clj (clj-doc n)]
379
+ {:doc (str qual how-fn (when (seq clj) (str "\n\n" clj)))
380
+ :usage (str n " [arguments…] · % marks where the message goes · ^:hot " n " …: every inlet hot")
381
+ :ref [[qual (docs-url n)] hot-ref]})
382
+ :xf (let [base (subs n 3) clj (clj-doc base)]
383
+ {:doc (str "The transducer of clojure.core/" base " as a box with memory: it goes through the stream of messages"
384
+ " that arrive at the left (a bang is one more message), not through a collection; what it lets"
385
+ " through goes out one message at a time. flush completes it (partition-all sends what it holds)"
386
+ " and starts again; clear starts again without sending; a new argument on the right starts again."
387
+ (when (= base "partition") " (partition n step: every n messages, each group starting step after the last; step 1 is a sliding window.)")
388
+ (when (seq clj) (str "\n\n" clj)))
389
+ :usage (str n " [arguments…] · flush · clear")
390
+ :ref [[(str "clojure.core/" base) (docs-url base)] transducers-ref]})
391
+ :data (let [[what anchor] (cond (keyword? f) ["A keyword" "Keywords"] (set? f) ["A set" "Sets"] :else ["A map" "Maps"])]
392
+ {:doc (str what " as a function, as in Clojure: the message goes first, (" n " msg)"
393
+ (cond (keyword? f) " — its value under that key, or the argument written after it if there is none"
394
+ (set? f) " — the message if it is in the set, nothing if not: a filter"
395
+ :else " — what the map has under the message, or the argument after it: a table")
396
+ "; nil sends nothing. The other inlets replace the arguments, without sending (^:hot: sending).")
397
+ :usage (str n (when (keyword? f) " [default]"))
398
+ :ref [[(str what " as a function") (str "https://clojure.org/reference/data_structures#" anchor)] hot-ref]})))
399
+
400
+ (def ^:private defs (atom {}))
401
+
402
+ (defn definition
403
+ "The class of a box named after one of these functions, an xf/ transducer, or a keyword, set or map (made
404
+ once, then kept), or nil."
405
+ [n]
406
+ (when-let [k (and (string? n) (seq n) (kind n))]
407
+ (or (get @defs n)
408
+ (let [d (merge {:class n :origin :core :display :text :corefn true
409
+ :parse parse
410
+ :io (fn [{:keys [text]}] (let [a (parse text)] [(inc (if (map? a) 0 (count (slots a)))) 1]))
411
+ :dynamic-io true
412
+ :receive (case (:kind k)
413
+ :xf (fn [m] (xf-receive k m))
414
+ :builder (fn [m] (builder-receive k m))
415
+ (fn [m] (receive k m)))}
416
+ (describe k))]
417
+ (swap! defs assoc n d)
418
+ d))))
419
+
420
+ (defn names "The functions that can be boxes, the ones that make functions, and the xf/ transducers." []
421
+ (vec (concat (sort (keys fns)) (sort (keys builders)) (sort (map #(str "xf/" %) (keys xfs))))))
422
+
423
+ (swap! comp/fallbacks (fn [fs] (if (some #{definition} fs) fs (conj fs definition))))
424
+
425
+ ;; ───────── dispatch: a message to one of several outlets ─────────
426
+ ;; dispatch n has n outlets, numbered from 0 as every port is. What comes in on the left goes out by the one the
427
+ ;; selector chooses; the selector comes in on the right (and may be written after n): a number k is outlet k,
428
+ ;; nil or false closes the way (nothing goes out), true is outlet 0 (dispatch 1 as an open/closed gate). A function
429
+ ;; — a name, a form (comp …), a keyword, a map — chooses for each message: what it gives for the message is the
430
+ ;; outlet (a number, true, or nil/false to let nothing through); a set lets its members through outlet 0.
431
+
432
+ (defn- dispatch-of
433
+ "The outlet a selector sends message v to among n, or nil."
434
+ [sel v n]
435
+ (let [r (cond (or (nil? sel) (false? sel)) nil
436
+ (true? sel) 0
437
+ (number? sel) sel
438
+ (set? sel) (when (contains? sel v) 0)
439
+ :else ((as-fn sel) v))
440
+ r (if (true? r) 0 r)]
441
+ (when (and (number? r) (integer? r) (<= 0 r) (< r n)) r)))
442
+
443
+ (defn- dispatch-n [args] (let [n (first args)] (if (and (number? n) (>= n 1)) (js/Math.floor n) 2)))
444
+
445
+ (defn dispatch-receive [{:keys [args state inlet value]}]
446
+ (if (map? args)
447
+ {:effects [[:print (:error args)]]}
448
+ (let [n (dispatch-n args)
449
+ st (if (= (:sig state) args) state {:sig args :sel (second args)})]
450
+ (if (pos? inlet)
451
+ (let [bad (when (or (symbol? value) (seq? value)) (unknown-names value))]
452
+ (if (seq bad)
453
+ {:state st :effects [[:print (str "dispatch: " (str/join ", " (distinct bad)) " is not a function it knows")]]}
454
+ {:state (assoc st :sel value) :show (pr-str value)}))
455
+ (let [k (try (dispatch-of (:sel st) value n) (catch :default _ nil))]
456
+ {:state st :out (if k [[k value]] [])})))))
457
+
458
+ (comp/define! "dispatch"
459
+ {:doc (str "A message to one of several outlets, numbered from 0: dispatch n has n of them. The right inlet chooses"
460
+ " the way: a number k is outlet k; nil or false closes it (nothing goes out); true is outlet 0, so dispatch 1"
461
+ " is a gate that opens and closes. A function chooses for each message — a name or a form"
462
+ " (comp …, partial …), a keyword, a map ({60 0 64 1}): what it gives for the message is the outlet, nil"
463
+ " lets nothing through — and a set lets its members through outlet 0. The selector can be written after n"
464
+ " (dispatch 3 0, dispatch 2 {60 0 64 1}); a msg sends it as written (msg 1, msg nil, msg :freq). Named after the"
465
+ " dispatch function of Clojure's multimethods, which looks at a value and chooses where it goes.")
466
+ :usage "dispatch n [selector] · right: k · nil · true · a function, keyword, map or set"
467
+ :io (fn [{:keys [text]}] (let [a (parse text)] [2 (if (map? a) 1 (dispatch-n a))]))
468
+ :dynamic-io true
469
+ :parse parse
470
+ :receive dispatch-receive
471
+ :ref [["Multimethods: a dispatch function chooses" "https://clojure.org/reference/multimethods"]
472
+ ["Truthiness: nil and false" "https://clojure.org/guides/learn/flow#_truth"]
473
+ ["Maps, sets and keywords as functions" "https://clojure.org/reference/data_structures"]]})