@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,656 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · the page, part 15 of 15: the code editor
3
+ ;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).
4
+
5
+ (in-ns 'user)
6
+
7
+ ;; ───────────────────────── the code editor (issue #8) ─────────────────────────
8
+ ;; The code of a box (faust~, script, component, tree) is written in a window of its own, over the page:
9
+ ;; it can be moved by its bar and resized by its corner, and it stays open while you play. Inside is
10
+ ;; CodeMirror 6 (core/vendor/codemirror.mjs, bundled from core/vendor/codemirror/): line numbers, automatic
11
+ ;; indentation, matching and closing brackets, structural editing for Clojure, search, and completion of
12
+ ;; the names each language knows. Ctrl/⌘+Enter applies the code (one event of the history) and keeps the
13
+ ;; window open, to go on; Esc or × closes it, asking first if something is not applied.
14
+ ;; If the editor cannot be loaded, a plain text area does the same.
15
+ ;; The same window opens the data of a canvas, freqt or score as EDN (discussion #30: { } in its header,
16
+ ;; or a double-click on the right of it): applying it writes what changed as one event of the history.
17
+ ;; The code of a faust~ also opens as a patch of Faust's own elements, beside it (discussion #115, Study
18
+ ;; 31, @kairotic/faust-units): editing the patch rewrites the code in the editor, editing the code redraws
19
+ ;; the patch, and applying is still one event. The window opens beside the box, so the parameters the box
20
+ ;; shows in the patch stay in sight while you play them.
21
+
22
+ (defonce code-win (atom nil)) ; {:id :path :lang :data? :ed :original :dirty :confirm :error :fv}
23
+ (defonce cm-module (atom nil)) ; Promise of the bundle
24
+
25
+ (defn open-definition
26
+ "[path id] of the component box open in the code window, or nil."
27
+ [] (when-let [w @code-win] (when (= "component" (:lang w)) [(:path w) (:id w)])))
28
+
29
+ (defn code-win-box
30
+ "The box whose code is open in the editor (in the patch on screen), or nil."
31
+ [] (when-let [w @code-win] (when (= (:path w) (cmd-path)) (:id w))))
32
+
33
+ (defn load-cm []
34
+ (or @cm-module
35
+ (reset! cm-module
36
+ (-> ((.-kairoticImport js/window) "kairotic/vendor/codemirror.mjs")
37
+ (.catch (fn [e] (js/console.warn "code editor: a plain text area instead" e) nil))))))
38
+
39
+ ;; ───── what completion offers, by language ─────
40
+
41
+ (def faust-words
42
+ ["process" "import(\"stdfaust.lib\");" "declare" "with" "letrec" "environment" "hslider" "vslider" "nentry"
43
+ "button" "checkbox" "hgroup" "vgroup" "tgroup" "hbargraph" "vbargraph" "attach" "mem" "min" "max" "abs"
44
+ "os.osc" "os.sawtooth" "os.square" "os.triangle" "os.phasor" "os.lf_saw" "os.pulsetrain" "os.oscsin"
45
+ "no.noise" "no.pink_noise" "fi.lowpass" "fi.highpass" "fi.resonlp" "fi.resonhp" "fi.resonbp" "fi.bandpass"
46
+ "fi.dcblocker" "fi.zero" "fi.pole" "ve.moog_vcf" "ve.korg35LPF" "en.adsr" "en.ar" "en.asr" "en.adsre"
47
+ "de.delay" "de.fdelay" "de.sdelay" "re.mono_freeverb" "re.stereo_freeverb" "re.zita_rev1_stereo"
48
+ "ef.echo" "ef.cubicnl" "co.compressor_mono" "co.limiter_1176_R4_mono" "si.smoo" "si.smooth" "si.bus"
49
+ "si.block" "ba.db2linear" "ba.linear2db" "ba.midikey2hz" "ba.hz2midikey" "ba.beat" "ba.pulse" "ba.if"
50
+ "ba.selectn" "ma.SR" "ma.PI" "ma.EPSILON" "sp.panner" "pm.ks" "aa.tanh1"])
51
+
52
+ (def tree-words
53
+ [":voice" ":measure" ":section" ":seq" ":par" ":piece" ":chord" ":note" ":rest" ":tuplet" ":rtm" ":shares"
54
+ ":pitches" ":meter" ":groups" ":dur"
55
+ ":pitch" ":tempo" ":key" ":dyn" ":defs" ":use" ":vel" ":ties"])
56
+
57
+ (def buffer-words
58
+ (into [":strokes" ":gx" ":gy" ":ax" ":step" ":cycles" ":name" ":ref" ":cents" ":x" ":y" ":lo" ":hi" ":log"]
59
+ (map pr-str (sort (keys cv/tunings)))))
60
+
61
+ (def component-words
62
+ [":class" ":doc" ":usage" ":license" ":io" ":args" ":receive" ":view" ":derive" ":draw" ":gesture"
63
+ ":persist" ":size" ":audio" ":patch" ":params" ":model" ":state" ":value" ":inlet" ":out" ":show"
64
+ ":effects" ":later" ":display"])
65
+
66
+ (defn ns-names
67
+ "The public names of a namespace, written with a prefix (\"api/clamp\"), when this runtime knows them."
68
+ [ns-sym prefix]
69
+ (try (vec (sort (map (fn [s] (str prefix s)) (keys (ns-publics ns-sym))))) (catch :default _ [])))
70
+
71
+ (defn words-for [lang]
72
+ (case lang
73
+ "faust" faust-words
74
+ "edn" tree-words
75
+ "component" (vec (concat component-words (ns-names 'kairotic.api "api/") (ns-names 'clojure.core "")))
76
+ "clojurescript" (vec (concat (ns-names 'clojure.core "") (ns-names 'clojure.string "str/")))
77
+ "pbind" ["#pat/seq" "#pat/choose" "#pat/shuffle" "#pat/white" "#pat/walk" "#pat/series" "#pat/hold" "#pat/chord"
78
+ ":degree" ":note" ":freq" ":dur" ":legato" ":sustain" ":amp" ":scale" ":root" ":octave" ":transpose" ":rest"]
79
+ "pattern" (vec (concat (map str kairotic.patterns/code-names) (ns-names 'clojure.core "")))
80
+ []))
81
+
82
+ ;; ───── the window ─────
83
+
84
+ (defn cw-el [] ($ "code-win"))
85
+
86
+ (defn cw-status!
87
+ "The foot of the window: whether the code is applied, and how its compilation went."
88
+ []
89
+ (when-let [{:keys [id dirty gone lang data? error]} @code-win]
90
+ (when-let [el (.querySelector (cw-el) ".cw-foot")]
91
+ (let [b (when-not gone (get-in (patch-in (root-patch) (:path @code-win)) [:boxes id]))
92
+ r (cond error {:status :error :error error}
93
+ (and b (not data?)) (cbox/compiled lang (str (get-in b [:data :source]))))
94
+ comp-st (case (:status r)
95
+ :ok (str "✓ " (or (get-in r [:info :summary]) "ready"))
96
+ :compiling "compiling…"
97
+ :error (str "✗ " (first (str/split-lines (str (:error r)))))
98
+ "")]
99
+ (set! (.-className el) (str "cw-foot" (when (= :error (:status r)) " err")))
100
+ (set! (.-textContent el)
101
+ (cond gone (if (= "component" lang)
102
+ "This component is not in the work any more: copy what you need, then close."
103
+ "This box is not in the patch any more: copy what you need, then close.")
104
+ error (str "✗ " (first (str/split-lines (str error))))
105
+ dirty (str "edited · Ctrl/⌘+Enter applies" (when (seq comp-st) (str " · last applied: " comp-st)))
106
+ :else (str "applied" (when (seq comp-st) (str " · " comp-st)))))))))
107
+
108
+ (defn cw-text [] (when-let [w @code-win] (if (:ed w) (.getValue (:ed w)) (.-value (:ta w)))))
109
+
110
+ (defn wrap-path
111
+ "A call made in the sub-patch `path`, written from the patch on screen: (inside :b5 …) for each step down."
112
+ [path code]
113
+ (let [here (cmd-path)]
114
+ (when-not (= here (vec (take (count here) path)))
115
+ (fail "That code belongs to a patch that is not on screen: go back to it to apply it."))
116
+ (reduce (fn [c id] (str "(inside " id " " c ")")) code (reverse (drop (count here) path)))))
117
+
118
+ (defn apply-code! []
119
+ (when-let [{:keys [id path original gone data?]} @code-win]
120
+ (let [v (cw-text)]
121
+ (cond
122
+ gone nil
123
+ (= v original) (do (swap! code-win assoc :dirty false :error nil) (cw-status!))
124
+ (str/blank? v) (repl-print! "err" "; the code is empty: write something, or delete the box")
125
+ :else (let [before @recent-errors
126
+ _ (gesture! (wrap-path path (str "(code " id " " (pr-str v) ")")))
127
+ err (when-not (identical? before @recent-errors) (last @recent-errors))]
128
+ (if err
129
+ ;; what cannot be read is not applied: it stays here, edited, saying what is wrong
130
+ (swap! code-win assoc :error (str "not applied: " err))
131
+ (swap! code-win assoc :original v :dirty false :error nil))
132
+ (cw-status!))))))
133
+
134
+ (defn close-code-win! []
135
+ (when-let [w @code-win]
136
+ (when-let [fv (:fv w)] (.destroy fv))
137
+ (when-let [c (:rcp w)] (.abort c))
138
+ (when-let [ed (:ed w)] (.destroy ed))
139
+ (when-let [el (cw-el)] (.remove el))
140
+ (reset! code-win nil)
141
+ (render-scene (current))))
142
+
143
+ (defn ask-close! []
144
+ (if (and (:dirty @code-win) (not (:gone @code-win)))
145
+ (do (swap! code-win assoc :confirm true)
146
+ (when-let [c (.querySelector (cw-el) ".cw-confirm")] (set! (.-hidden c) false)))
147
+ (close-code-win!)))
148
+
149
+ (defn place-window!
150
+ "Over the box, inside the window of the browser; a wide one (a faust~ with its patch) beside the box,
151
+ so that what the box shows in the patch (its parameters) stays in sight."
152
+ ([el id b] (place-window! el id b false))
153
+ ([el id b wide?]
154
+ (let [r (when-let [g (.querySelector js/document (str "#scene .box[data-box=\"" (name id) "\"]"))] (.getBoundingClientRect g))
155
+ vw (.-innerWidth js/window) vh (.-innerHeight js/window)
156
+ ;; a wide one goes where it covers nothing of the box: beside it (on the side with more room, as
157
+ ;; wide as that room) if a side has 560 px, else below or above it if there are 280, else beside
158
+ ;; it if a side has 400; and over it as the others only when nothing else fits
159
+ right-room (when r (- vw 16 (.-right r) 12)) left-room (when r (- (.-left r) 12 16))
160
+ below-room (when r (- vh 16 (.-bottom r) 12)) above-room (when r (- (.-top r) 12 16))
161
+ side-room (when r (max right-room left-room)) vert-room (when r (max below-room above-room))
162
+ place (when (and wide? r)
163
+ (cond (>= side-room 560) (if (>= right-room left-room) :right :left)
164
+ (>= vert-room 280) (if (>= below-room above-room) :below :above)
165
+ (>= side-room 400) (if (>= right-room left-room) :right :left)))
166
+ w (case place
167
+ :right (min 1040 right-room) :left (min 1040 left-room)
168
+ (min (if wide? 1040 620) (- vw 32)))
169
+ h (case place
170
+ :below (min 520 below-room) :above (min 520 above-room)
171
+ (min (if wide? 520 420) (- vh 32)))
172
+ [x y] (case place
173
+ :right [(+ (.-right r) 12) (.-top r)]
174
+ :left [(- (.-left r) 12 w) (.-top r)]
175
+ :below [(.-left r) (+ (.-bottom r) 12)]
176
+ :above [(.-left r) (- (.-top r) 12 h)]
177
+ [(if r (.-left r) 40) (if r (+ (.-top r) hdr) 80)])]
178
+ (set! (.. el -style -width) (str w "px"))
179
+ (set! (.. el -style -height) (str h "px"))
180
+ (set! (.. el -style -left) (str (max 16 (min x (- vw w 16))) "px"))
181
+ (set! (.. el -style -top) (str (max 16 (min y (- vh h 16))) "px")))))
182
+
183
+ (defn drag-window!
184
+ "The window moves with its bar."
185
+ [el e]
186
+ (when-not (.closest (.-target e) "button")
187
+ (.preventDefault e)
188
+ (let [x0 (.-clientX e) y0 (.-clientY e)
189
+ l0 (.-offsetLeft el) t0 (.-offsetTop el)
190
+ move (fn [ev]
191
+ (set! (.. el -style -left) (str (max 0 (min (- (.-innerWidth js/window) 80) (+ l0 (- (.-clientX ev) x0)))) "px"))
192
+ (set! (.. el -style -top) (str (max 0 (min (- (.-innerHeight js/window) 40) (+ t0 (- (.-clientY ev) y0)))) "px")))
193
+ up (fn up [_]
194
+ (.removeEventListener js/window "pointermove" move)
195
+ (.removeEventListener js/window "pointerup" up))]
196
+ (.addEventListener js/window "pointermove" move)
197
+ (.addEventListener js/window "pointerup" up))))
198
+
199
+ (declare toggle-patch-view! toggle-recipe! find-recipe-click! find-recipe! play-recipe!)
200
+
201
+ (defn window-shell [id b lang]
202
+ (let [el (js/document.createElement "div")]
203
+ (set! (.-id el) "code-win")
204
+ (set! (.-className el) "code-win")
205
+ (.setAttribute el "role" "dialog")
206
+ (.setAttribute el "aria-label" (str "Code of " (name id)))
207
+ (set! (.-innerHTML el)
208
+ (str "<div class=\"cw-bar\"><span class=\"cw-title\"><b>" (esc (name id)) "</b> "
209
+ (esc (if (definition? b)
210
+ (let [c (get-in (cbox/compiled "component" (str (get-in b [:data :source]))) [:info :class])]
211
+ (str "component" (when c (str " · " c))))
212
+ (:text b)))
213
+ "</span>"
214
+ "<span class=\"cw-lang\">" (esc lang) "</span>"
215
+ (when (= lang "faust")
216
+ (str "<button class=\"act cw-pv\" data-cw=\"patch\" aria-pressed=\"" (not (false? (:faust-patch? @ui)))
217
+ "\" title=\"Show or hide its patch: the code as Faust's own elements\">Patch</button>"
218
+ "<button class=\"act cw-pv\" data-cw=\"recipe\" aria-pressed=\"false\""
219
+ " title=\"Find the values of its sliders that sound closest to a sound: a recipe\">Recipe</button>"))
220
+ "<button class=\"act primary\" data-cw=\"apply\" title=\"Apply the code (Ctrl/⌘+Enter)\">Apply</button>"
221
+ "<button class=\"act cw-x\" data-cw=\"close\" title=\"Close (Esc)\" aria-label=\"Close\">×</button></div>"
222
+ "<div class=\"cw-confirm\" hidden>Something is not applied. "
223
+ "<button class=\"act primary\" data-cw=\"apply-close\">Apply and close</button>"
224
+ "<button class=\"act\" data-cw=\"discard\">Discard</button>"
225
+ "<button class=\"act\" data-cw=\"stay\">Keep editing</button></div>"
226
+ (when (= lang "faust")
227
+ (str "<div class=\"cw-rcp\" hidden><label>Sliders that sound like <select class=\"rcp-src\"></select></label>"
228
+ "<select class=\"rcp-len\" title=\"How long it listens\"><option value=\"quick\">quick</option>"
229
+ "<option value=\"careful\">careful</option></select>"
230
+ "<button class=\"act primary\" data-cw=\"find\">Find</button>"
231
+ "<span class=\"rcp-st\" aria-live=\"polite\"></span>"
232
+ "<button class=\"act rcp-play\" data-cw=\"play-target\" hidden title=\"The sound it listened to (its first second)\">▶ sound</button>"
233
+ "<button class=\"act rcp-play\" data-cw=\"play-found\" hidden title=\"The code at the values found\">▶ found</button>"
234
+ "<input type=\"file\" accept=\"audio/*\" class=\"rcp-file\" hidden></div>"))
235
+ "<div class=\"cw-body\"></div><div class=\"cw-foot\"></div>"))
236
+ (.addEventListener (.querySelector el ".cw-bar") "pointerdown" (fn [e] (drag-window! el e)))
237
+ (.addEventListener el "click"
238
+ (fn [e]
239
+ (case (some-> (.closest (.-target e) "[data-cw]") (.getAttribute "data-cw"))
240
+ "apply" (apply-code!)
241
+ "patch" (toggle-patch-view!)
242
+ "recipe" (toggle-recipe!)
243
+ "find" (find-recipe-click!)
244
+ "play-target" (play-recipe! :target)
245
+ "play-found" (play-recipe! :found)
246
+ "close" (ask-close!)
247
+ "apply-close" (do (apply-code!) (when-not (:dirty @code-win) (close-code-win!)))
248
+ "discard" (close-code-win!)
249
+ "stay" (do (swap! code-win assoc :confirm false)
250
+ (set! (.-hidden (.querySelector el ".cw-confirm")) true)
251
+ (some-> (:ed @code-win) .focus))
252
+ nil)))
253
+ (when-let [f (.querySelector el ".rcp-file")]
254
+ (.addEventListener f "change"
255
+ (fn [_] (when-let [file (aget (.-files f) 0)]
256
+ (set! (.-value f) "")
257
+ (find-recipe! (.then (.arrayBuffer file) snd/decode) (.-name file))))))
258
+ ;; keys typed in the editor are the editor's (space, Delete, ⌘A… do not reach the patch)
259
+ (.addEventListener el "keydown" (fn [e] (.stopPropagation e)))
260
+ el))
261
+
262
+ (defn textarea-editor!
263
+ "Without CodeMirror: a plain text area with the same keys."
264
+ [body text]
265
+ (let [ta (js/document.createElement "textarea")]
266
+ (set! (.-className ta) "cw-plain")
267
+ (set! (.-spellcheck ta) false)
268
+ (set! (.-value ta) text)
269
+ (.appendChild body ta)
270
+ (.addEventListener ta "input" (fn [_] (swap! code-win assoc :dirty (not= (.-value ta) (:original @code-win)) :error nil) (cw-status!)
271
+ (when-let [fv (:fv @code-win)] (.setCode fv (.-value ta)))))
272
+ (.addEventListener ta "keydown"
273
+ (fn [e]
274
+ (let [k (.-key e)]
275
+ (cond
276
+ (and (= k "Enter") (or (.-ctrlKey e) (.-metaKey e))) (do (.preventDefault e) (apply-code!))
277
+ (= k "Escape") (do (.preventDefault e) (ask-close!))
278
+ (= k "Tab") (do (.preventDefault e)
279
+ (let [a (.-selectionStart ta) z (.-selectionEnd ta) v (.-value ta)]
280
+ (set! (.-value ta) (str (subs v 0 a) " " (subs v z)))
281
+ (set! (.-selectionStart ta) (+ a 2))
282
+ (set! (.-selectionEnd ta) (+ a 2))))))))
283
+ (.focus ta)
284
+ ta))
285
+
286
+ (declare open-code-editor-at!)
287
+
288
+ ;; ───── the patch of a faust~ (@kairotic/faust-units) ─────
289
+
290
+ (defn set-editor-text!
291
+ "Code the patch view wrote, into the editor: edited, not applied yet."
292
+ [v]
293
+ (when-let [{:keys [ed ta]} @code-win]
294
+ (cond ed (.setValue ed v) ta (set! (.-value ta) v))
295
+ (swap! code-win assoc :dirty (not= v (:original @code-win)) :error nil)
296
+ (cw-status!)))
297
+
298
+ (defn mount-faust-view!
299
+ "Draws the patch of the faust~ open in the window, in `pane`, once its module is loaded."
300
+ [id pane text]
301
+ (-> (api/import-module (lib/module-origins "@kairotic/faust-units" "view.mjs"))
302
+ (.then (fn [m]
303
+ (when (and @code-win (= id (:id @code-win)) (nil? (:fv @code-win)))
304
+ (let [w @code-win
305
+ fv ((.-mount m) pane #js {:code (if (or (:ed w) (:ta w)) (cw-text) text)
306
+ :onCode (fn [c] (set-editor-text! c))
307
+ :loadFaust (fn [] (kairotic.faust/load))})]
308
+ (swap! code-win assoc :fv fv)))))
309
+ (.catch (fn [e]
310
+ (set! (.-innerHTML pane) (str "<p class=\"cw-pv-err\">The patch could not be loaded: " (esc (or (.-message e) e)) "</p>"))))))
311
+
312
+ (defn toggle-patch-view!
313
+ "Shows or hides the patch beside the code of a faust~ (remembered for the next ones)."
314
+ []
315
+ (when-let [body (some-> (cw-el) (.querySelector ".cw-body.split"))]
316
+ (let [show? (.contains (.-classList body) "nopatch")]
317
+ (.toggle (.-classList body) "nopatch" (not show?))
318
+ (swap! ui assoc :faust-patch? show?)
319
+ (some-> (cw-el) (.querySelector "[data-cw=patch]") (.setAttribute "aria-pressed" (str show?))))))
320
+
321
+ ;; ───── the recipe of a faust~ (discussion #114, Study 35, @kairotic/faust-units) ─────
322
+ ;; The values of the sliders of the code in the editor that sound closest to a sound: the sound of a
323
+ ;; sample box of this patch, or a file. The code is compiled and played offline, a note of a second (a
324
+ ;; gate button, if it has one, held for 0.65 s), many times: a few random settings first, then a search
325
+ ;; that listens as features~ does (Meyda), the pitch heard apart (YIN, as pitch~) and held. What it finds
326
+ ;; is written in the editor, the sliders starting at those values: edited, not applied, so applying it is
327
+ ;; one event of the history and the box keeps its parameters in sight.
328
+
329
+ (def recipe-meyda "npm:meyda@5.6.3/dist/web/meyda.min.js")
330
+ (def recipe-lengths {"quick" {:bank 32 :budget 160} "careful" {:bank 64 :budget 400}})
331
+ (defonce recipe-sounds (atom nil)) ; {:target Float32Array :found Float32Array} of the last search
332
+
333
+ (defn rcp-el [sel] (some-> (cw-el) (.querySelector (str ".cw-rcp " sel))))
334
+
335
+ (defn rcp-status! [text & [err?]]
336
+ (when-let [el (rcp-el ".rcp-st")]
337
+ (set! (.-textContent el) text)
338
+ (set! (.-className el) (str "rcp-st" (when err? " err")))))
339
+
340
+ (defn recipe-sources
341
+ "The sample boxes with a sound in the patch of the code window: [[id seconds] …], in the order of their ids."
342
+ []
343
+ (when-let [{:keys [path]} @code-win]
344
+ (->> (:boxes (patch-in (root-patch) path))
345
+ (filter (fn [[_ b]] (and (= "sample" (klass (:text b))) (snd/sample? (:data b)))))
346
+ (map (fn [[id b]] [id (snd/seconds (:data b))]))
347
+ (sort-by (fn [[id _]] (js/parseInt (subs (name id) 1) 10))))))
348
+
349
+ (defn fill-recipe-sources! []
350
+ (when-let [sel (rcp-el ".rcp-src")]
351
+ (let [was (.-value sel)]
352
+ (set! (.-innerHTML sel)
353
+ (str (str/join (for [[id secs] (recipe-sources)]
354
+ (str "<option value=\"" (esc (name id)) "\">" (esc (name id)) " · "
355
+ (.toFixed secs 1) " s</option>")))
356
+ "<option value=\"file\">a sound file…</option>"))
357
+ (when (some #(= was (.-value %)) (array-seq (.-options sel))) (set! (.-value sel) was)))))
358
+
359
+ (defn toggle-recipe!
360
+ "Shows or hides the recipe's line under the bar of a faust~'s window."
361
+ []
362
+ (when-let [p (some-> (cw-el) (.querySelector ".cw-rcp"))]
363
+ (let [show? (.-hidden p)]
364
+ (set! (.-hidden p) (not show?))
365
+ (when show? (fill-recipe-sources!))
366
+ (some-> (cw-el) (.querySelector "[data-cw=recipe]") (.setAttribute "aria-pressed" (str show?))))))
367
+
368
+ (defn find-recipe-click!
369
+ "Find: from the sound chosen (a file asks for it first); Stop while it listens."
370
+ []
371
+ (if-let [c (:rcp @code-win)]
372
+ (.abort c)
373
+ (let [v (some-> (rcp-el ".rcp-src") .-value)]
374
+ (cond
375
+ (or (nil? v) (= v "file")) (some-> (rcp-el ".rcp-file") .click)
376
+ :else (let [b (get-in (patch-in (root-patch) (:path @code-win)) [:boxes (keyword v)])]
377
+ (if (snd/sample? (:data b))
378
+ (find-recipe! (snd/sound-for (:data b)) v)
379
+ (rcp-status! (str v " has no sound any more") true)))))))
380
+
381
+ (defn find-recipe!
382
+ "Listens for the recipe of the code in the editor, the target being the promise of a sound ({:sr :chans})."
383
+ [sound label]
384
+ (when-let [{:keys [id path]} @code-win]
385
+ (let [ctl (js/AbortController.)
386
+ code (cw-text)
387
+ {:keys [bank budget]} (get recipe-lengths (some-> (rcp-el ".rcp-len") .-value) (get recipe-lengths "quick"))
388
+ mine? (fn [] (and @code-win (= id (:id @code-win)) (= path (:path @code-win)) (identical? ctl (:rcp @code-win))))
389
+ btn (rcp-el "[data-cw=find]")]
390
+ (swap! code-win assoc :rcp ctl)
391
+ (when btn (set! (.-textContent btn) "Stop"))
392
+ (doseq [b (array-seq (.querySelectorAll (cw-el) ".rcp-play"))] (set! (.-hidden b) true))
393
+ (rcp-status! (str "loading what listens to " label "…"))
394
+ (-> (js/Promise.all #js [(api/import-module (lib/module-origins "@kairotic/faust-units" "recipe.mjs"))
395
+ (kairotic.faust/load)
396
+ (api/load-script recipe-meyda)
397
+ sound])
398
+ (.then (fn [[m fx _ s]]
399
+ (when-not (:chans s) (throw (js/Error. (str "the sound of " label " is not in this browser"))))
400
+ (rcp-status! "compiling…")
401
+ (.find m #js {:faust fx :code code :Meyda (.-Meyda js/window)
402
+ :sound #js {:sr (:sr s) :chans (:chans s)}
403
+ :bank bank :budget budget :signal (.-signal ctl)
404
+ :onProgress (fn [phase done total best]
405
+ (when (mine?)
406
+ (rcp-status! (if (= phase "bank")
407
+ (str "listening to random settings " done "/" total)
408
+ (str "searching " done "/" total " · distance " (.toFixed best 2))))))})))
409
+ (.then (fn [r]
410
+ (when (mine?)
411
+ (reset! recipe-sounds {:target (.-target r) :found (.-y r)})
412
+ (doseq [b (array-seq (.querySelectorAll (cw-el) ".rcp-play"))] (set! (.-hidden b) false))
413
+ (let [p (.-pitch r)
414
+ what (str "distance " (.toFixed (.-fx r) 2) " (the nearest random setting: " (.toFixed (.-nearestFx r) 2) ")"
415
+ (when (some? p) (str " · pitch " (api/midi-name (js/Math.round p)))))]
416
+ (if (= (cw-text) code)
417
+ (do (set-editor-text! (.-code r))
418
+ (when-let [fv (:fv @code-win)] (.setCode fv (.-code r)))
419
+ (rcp-status! (str "found: " what " · in the code, Ctrl/⌘+Enter applies it")))
420
+ (rcp-status! (str "found: " what ", but the code changed meanwhile: not written") true))))))
421
+ (.catch (fn [e]
422
+ (when (mine?)
423
+ (if (= "AbortError" (.-name e))
424
+ (rcp-status! "stopped")
425
+ (rcp-status! (str "✗ " (or (.-message e) e)) true)))))
426
+ (.finally (fn []
427
+ (when (mine?)
428
+ (swap! code-win dissoc :rcp)
429
+ (when btn (set! (.-textContent btn) "Find")))))))))
430
+
431
+ (defn play-recipe!
432
+ "Plays the sound the last search listened to (:target) or what it found (:found), once."
433
+ [which]
434
+ (when-let [y (get @recipe-sounds which)]
435
+ (let [ac (eng/ctx) buf (.createBuffer ac 1 (.-length y) 44100) src (.createBufferSource ac)]
436
+ (.copyToChannel buf y 0)
437
+ (set! (.-buffer src) buf)
438
+ (.connect src (.-destination ac))
439
+ (.then (.resume ac) (fn [_] (.start src))))))
440
+
441
+ (defn open-code-editor!
442
+ "Opens the code of a box in the editor window (or brings it back if it is the one open)."
443
+ [id] (open-code-editor-at! (cmd-path) id))
444
+
445
+ (defn open-code-editor-at!
446
+ "Opens the code of box id of the sub-patch at path (from the patch the work starts at) in the editor
447
+ window: a component box is not in the patch, so the Components tab opens it this way."
448
+ [path id]
449
+ (let [path (vec path) b (get-in (patch-in (root-patch) path) [:boxes id]) d (box-def b)]
450
+ (cond
451
+ (nil? b) nil
452
+ (and @code-win (= id (:id @code-win)) (= path (:path @code-win))) (some-> (:ed @code-win) .focus)
453
+ (and @code-win (:dirty @code-win) (not (:gone @code-win)))
454
+ (do (ask-close!) (repl-print! "out" "; first apply or discard the code that is open"))
455
+ :else
456
+ (do
457
+ (close-code-win!)
458
+ (let [data? (fn? (:source (comp/model-of b)))
459
+ lang (if data? "edn" (str (:language d)))
460
+ original (str (comp/source-of b))
461
+ text (if (and (not data?) (str/blank? original)) (or (:template d) "") original)
462
+ el (window-shell id b lang)
463
+ body (.querySelector el ".cw-body")
464
+ ;; a faust~: its patch on the left, the code on the right
465
+ faust? (and (not data?) (= lang "faust"))
466
+ pane (when faust? (js/document.createElement "div"))
467
+ body (if faust?
468
+ (let [t (js/document.createElement "div")]
469
+ (set! (.-className body) (str "cw-body split" (when (false? (:faust-patch? @ui)) " nopatch")))
470
+ (set! (.-className pane) "cw-patch")
471
+ (set! (.-className t) "cw-text")
472
+ (.appendChild body pane)
473
+ (.appendChild body t)
474
+ t)
475
+ body)]
476
+ (.appendChild (.-body js/document) el)
477
+ (place-window! el id b faust?)
478
+ (reset! code-win {:id id :path path :lang lang :data? data? :original original :dirty (not= text original)})
479
+ (cw-status!)
480
+ (render-scene (current))
481
+ (when faust? (mount-faust-view! id pane text))
482
+ (.then (load-cm)
483
+ (fn [cm]
484
+ (when (= (:id @code-win) id)
485
+ (if-let [create (and cm (.-createEditor cm))]
486
+ (let [ed (create #js {:parent body :doc text :language lang
487
+ :words (clj->js (if data? buffer-words (words-for lang)))
488
+ :onApply (fn [_] (apply-code!))
489
+ :onCancel (fn [] (ask-close!))
490
+ :onChange (fn [v] (swap! code-win assoc :dirty (not= v (:original @code-win)) :error nil) (cw-status!)
491
+ (when-let [fv (:fv @code-win)] (.setCode fv v)))})]
492
+ (swap! code-win assoc :ed ed)
493
+ (.focus ed))
494
+ (swap! code-win assoc :ta (textarea-editor! body text)))))))))))
495
+
496
+ (defn refresh-code-win!
497
+ "After the patch changed: if the box is gone, say so; if its code changed elsewhere and nothing is
498
+ edited here, show the new code."
499
+ []
500
+ (when-let [{:keys [id path ed ta dirty original]} @code-win]
501
+ (let [b (get-in (patch-in (root-patch) path) [:boxes id])]
502
+ (if (nil? b)
503
+ (swap! code-win assoc :gone true)
504
+ (let [src (str (comp/source-of b))]
505
+ (swap! code-win assoc :gone false)
506
+ (when (and (not dirty) (not= src original) (not (str/blank? src)))
507
+ (swap! code-win assoc :original src)
508
+ (cond ed (.setValue ed src) ta (set! (.-value ta) src))
509
+ (when-let [fv (:fv @code-win)] (.setCode fv src))
510
+ (swap! code-win assoc :dirty false))))
511
+ (cw-status!))))
512
+
513
+ (add-watch hist ::code-win (fn [_ _ _ _] (refresh-code-win!)))
514
+ (add-watch perf ::code-win (fn [_ _ _ _] (refresh-code-win!)))
515
+ (add-watch world ::code-win (fn [_ _ _ _] (refresh-code-win!)))
516
+
517
+ ;; ───────────────────────── the Code tab and the REPL line ─────────────────────────
518
+ ;; The same editor (CodeMirror, Clojure) replaces the text area of the Code tab and the input of the REPL
519
+ ;; once the bundle is loaded, a moment after the page starts. In the Code tab, Ctrl/⌘+Enter runs the code.
520
+ ;; In the REPL, Enter evaluates when the brackets are closed (otherwise it starts a new line; ⇧+Enter
521
+ ;; always does), and ↑ ↓ on the first or last line bring back what was written before.
522
+
523
+ (defn command-words
524
+ "The commands of the page that have a doc string, for completion in the Code tab and the REPL."
525
+ []
526
+ (try (vec (sort (keep (fn [[s v]] (when (:doc (meta v)) (str s))) (ns-publics 'user))))
527
+ (catch :default _ [])))
528
+
529
+ (defn balanced?
530
+ "Whether every bracket of a piece of code is closed (outside strings, comments and characters)."
531
+ [s]
532
+ (loop [cs (seq s) depth 0 in-str false]
533
+ (if-let [c (first cs)]
534
+ (cond
535
+ in-str (case c "\\" (recur (nnext cs) depth true) "\"" (recur (next cs) depth false) (recur (next cs) depth true))
536
+ (= c "\"") (recur (next cs) depth true)
537
+ (= c "\\") (recur (nnext cs) depth false)
538
+ (= c ";") (recur (drop-while (fn [x] (not= x "\n")) cs) depth false)
539
+ (#{"(" "[" "{"} c) (recur (next cs) (inc depth) false)
540
+ (#{")" "]" "}"} c) (recur (next cs) (dec depth) false)
541
+ :else (recur (next cs) depth false))
542
+ (and (<= depth 0) (not in-str)))))
543
+
544
+ (defn host-for!
545
+ "A place for an editor next to element `el`, which hides: keys typed there stay there."
546
+ [el cls]
547
+ (let [h (js/document.createElement "div")]
548
+ (set! (.-className h) cls)
549
+ (.insertBefore (.-parentNode el) h el)
550
+ (set! (.-hidden el) true)
551
+ (.addEventListener h "keydown" (fn [e] (.stopPropagation e)))
552
+ h))
553
+
554
+ ;; ───── the Code tab and the patch, seen together (issue #165) ─────
555
+ ;; Lines longer than 160 characters (the source of a code box, a buffer kept as data…) are folded after their
556
+ ;; first 48 characters, saying how many they hide; a click (or the fold gutter) shows them, and a line unfolded
557
+ ;; stays so while the tab is open. The lines of the boxes selected in the patch are marked, and the tab scrolls to
558
+ ;; them; the other way round, the cursor on a line of a box selects that box in the patch.
559
+
560
+ (defonce code-unfolded (atom #{})) ; the lines unfolded by the person, by their beginning: "(code :b7"
561
+ (defonce code-line-pick (atom false)) ; the selection comes from the cursor in the code: the tab does not scroll
562
+
563
+ (defn line-key "The beginning of a line of the code that names its box: \"(code :b7\", or nil." [text]
564
+ (re-find #"^\([^\s()]+ :b\d+" (str text)))
565
+
566
+ (defn ids-in-line "The box ids a line of code names, in order." [text]
567
+ (map keyword (map (fn [m] (subs m 1)) (re-seq #"(?<![\w:-]):b\d+(?![\w-])" (str text)))))
568
+
569
+ (defn code-mark-lines!
570
+ "Marks the lines of the Code tab that name a box selected in the patch; returns their numbers."
571
+ []
572
+ (when-let [e @code-ed]
573
+ (when (.-highlight e)
574
+ (let [chosen (set (sel-ids))
575
+ ls (if (empty? chosen) []
576
+ (vec (keep-indexed (fn [i l] (when (some chosen (ids-in-line l)) (inc i)))
577
+ (str/split-lines (.getValue e)))))]
578
+ (.highlight e (clj->js ls))
579
+ ls))))
580
+
581
+ (defn code-tab-refresh!
582
+ "After the code of the tab is written again: long lines folded (not the ones unfolded), boxes marked."
583
+ []
584
+ (when-let [e @code-ed]
585
+ (when (.-foldLong e) (.foldLong e 160 48 (fn [t] (contains? @code-unfolded (line-key t)))))
586
+ (code-mark-lines!)))
587
+
588
+ (defn code-line-chosen!
589
+ "The cursor went to a line of the Code tab: the boxes it names (one, or the two of a connect) are selected."
590
+ [text]
591
+ (let [p (current) ids (vec (distinct (filter (fn [id] (get-in p [:boxes id])) (ids-in-line text))))]
592
+ (when (seq ids)
593
+ (reset! code-line-pick true)
594
+ (try (swap! ui assoc :sel (sel-of ids) :insp nil :nsel nil :tsel nil)
595
+ (render-scene (current))
596
+ (finally (reset! code-line-pick false)))
597
+ ;; the patch shows the first one
598
+ (some-> (.querySelector ($ "scene") (str "g.box[data-box=\"" (name (first ids)) "\"]"))
599
+ (.scrollIntoView #js {:block "nearest" :inline "nearest"})))))
600
+
601
+ ;; the selection changed: its lines are marked, and the tab goes to them (unless the cursor chose them)
602
+ (add-watch ui ::code-marks
603
+ (fn [_ _ o n]
604
+ (when (not= (:sel o) (:sel n))
605
+ (let [ls (code-mark-lines!)]
606
+ (when (and (seq ls) (not @code-line-pick) @code-ed (.-showLine @code-ed))
607
+ (.showLine @code-ed (first ls)))))))
608
+
609
+ (defn upgrade-code-tab! [cm]
610
+ (when-not @code-ed
611
+ (let [ta ($ "code") host (host-for! ta "code-host")
612
+ ed ((.-createEditor cm)
613
+ #js {:parent host :doc (.-value ta) :language "clojurescript" :words (clj->js (command-words))
614
+ :onApply (fn [_] (run-panel-code!))
615
+ :onChange (fn [_] (when-not (:dirty @ui) (swap! ui assoc :dirty true) (render-code (current))))
616
+ :onLine (fn [_ text] (code-line-chosen! text))
617
+ :onUnfold (fn [text] (when-let [k (line-key text)] (swap! code-unfolded conj k)))})]
618
+ (.setAttribute (.-contentDOM (.-view ed)) "aria-label" "Patch code")
619
+ (reset! code-ed ed)
620
+ (code-tab-refresh!))))
621
+
622
+ (defn upgrade-data-view!
623
+ "The Data view of the Code tab: the same editor, read-only, with EDN colours, folding and search."
624
+ [cm]
625
+ (when-not @data-ed
626
+ (let [pre ($ "edn")
627
+ host (host-for! pre "data-host")
628
+ ed ((.-createEditor cm) #js {:parent host :doc (.-textContent pre) :language "edn" :readOnly true})]
629
+ (.setAttribute (.-contentDOM (.-view ed)) "aria-label" "The work as data (EDN)")
630
+ (reset! data-ed ed))))
631
+
632
+ (defn upgrade-repl! [cm]
633
+ (when-not @repl-ed
634
+ (let [inp ($ "repl-in") host (host-for! inp "repl-host")
635
+ ed (atom nil)
636
+ free? (fn [] (not (.completing @ed)))]
637
+ (reset! ed ((.-createEditor cm)
638
+ #js {:parent host :doc (.-value inp) :language "clojurescript" :gutter false
639
+ :placeholder (.-placeholder inp)
640
+ :words (clj->js (concat (command-words) (ns-names 'clojure.core "")))
641
+ :keys #js [#js {:key "Enter" :run (fn [] (when (and (free?) (balanced? (.getValue @ed))) (repl-submit!) true))}
642
+ #js {:key "Shift-Enter" :run (fn [] (.newline @ed) true)}
643
+ #js {:key "ArrowUp" :run (fn [] (boolean (and (free?) (= 1 (.cursorLine @ed)) (repl-recall! true))))}
644
+ #js {:key "ArrowDown" :run (fn [] (boolean (and (free?) (= (.cursorLine @ed) (.lineCount @ed)) (repl-recall! false))))}]}))
645
+ (.setAttribute (.-contentDOM (.-view @ed)) "aria-label" "REPL")
646
+ (when-let [l (.querySelector js/document "label[for=repl-in]")]
647
+ (.addEventListener l "click" (fn [_] (.focus @ed))))
648
+ (reset! repl-ed @ed))))
649
+
650
+ ;; a moment after the page starts (not in an embed, which shows neither)
651
+ (when-not embed-mode
652
+ (js/setTimeout
653
+ (fn [] (.then (load-cm) (fn [cm] (when cm (upgrade-code-tab! cm) (upgrade-data-view! cm) (upgrade-repl! cm)
654
+ ;; the hosts take the place of what was shown: show again the view that was chosen
655
+ (show-code-view! (or (:code-view @ui) :calls))))))
656
+ 300))