@kairotic/app 0.0.0-stage → 0.2.1

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
+ // Generated by examples/build.mjs — the examples Claude reads in Kairotic
2
+ export default {
3
+ "examples": [
4
+ {
5
+ "name": "knob",
6
+ "category": "controls",
7
+ "kind": "component",
8
+ "about": "a rotary control with its own view, declared arguments, a gesture and :persist",
9
+ "source": ";; knob · a rotary control with its own view in the patch\n;; Part of @kairotic/controls. Written against the Kairotic API (api/…).\n{;; ── about ──────────────────────────────────────────────\n :class \"knob\"\n :license \"MPL-2.0\"\n :doc \"Rotary knob: drag it up or down (⇧ for fine control). Sends its value between min and max; with log the travel is logarithmic (frequencies), and with a name it sends [:name value] (e.g. a faust~ parameter). A number sets it and sends it on; a bang sends it again.\"\n :usage \"knob [min max initial] [log] [name]\"\n :io [1 1]\n :size [72 78]\n\n ;; ── arguments ──────────────────────────────────────────\n ;; numbers fill min, max and initial in order; \"log\" is a flag; any other word is the name\n :args [[:min 0] [:max 1] [:initial :min] [:log false] [:name nil]]\n\n ;; ── logic ──────────────────────────────────────────────\n :receive (fn [{:keys [state args value]}]\n (let [current (if (number? state) state (:initial args))\n outgoing (fn [v] (if (:name args) [(:name args) v] v))]\n (cond\n (number? value) (let [v (api/clamp value (:min args) (:max args))]\n {:state v :out [[0 (outgoing v)]] :show v})\n (= value :bang) {:state current :out [[0 (outgoing current)]] :show current}\n :else {:state current})))\n\n ;; on release the value stays in the box text as its initial value (Kairotic Study 13 and later)\n :persist (fn [v] {:initial (api/nice v)})\n\n :gesture (fn [{:keys [start args dy fine]}]\n (let [{lo :min hi :max log? :log} args\n u (api/to-unit (if (number? start) start (:initial args)) lo hi log?)]\n (api/from-unit (- u (/ dy (if fine 800 160))) lo hi log?)))\n\n ;; values for the holes of the view\n :derive (fn [{:keys [shown args]}]\n (let [{lo :min hi :max log? :log} args\n v (if (number? shown) shown (:initial args))]\n {:angle (+ -135 (* 270 (api/to-unit v lo hi log?)))\n :label (str (when (:name args) (str (name (:name args)) \" \")) (api/nice v))}))\n\n ;; ── view ───────────────────────────────────────────────\n :view [[:arc {:cx 36 :cy 33 :r 23 :from -135 :to 135 :stroke :grid :weight 5}]\n [:arc {:cx 36 :cy 33 :r 23 :from -135 :to :$angle :stroke :accent :weight 5}]\n [:circle {:cx 36 :cy 33 :r 16 :stroke :soft :fill :bg}]\n [:needle {:cx 36 :cy 33 :r0 5 :r 17 :angle :$angle :stroke :ink :weight 2.5}]\n [:text {:x 36 :y 72 :anchor :middle :size 11} :$label]]}\n"
10
+ },
11
+ {
12
+ "name": "adsr~",
13
+ "category": "synth",
14
+ "kind": "component",
15
+ "about": "an envelope with an AudioWorklet carried inside, a drawn view and gestures that rewrite the box",
16
+ "source": ";; adsr~ · an envelope that follows a gate\n;; Part of @kairotic/synth. Written against the Kairotic API (api/…), with its AudioWorklet inside.\n(let [;; ── the worklet: a linear envelope, one value per sample ──\n worklet \"class KairoticAdsr extends AudioWorkletProcessor {\n // An envelope that follows a gate: the input signal plus the gate parameter. Above 0 it attacks\n // (to the gate's level, from wherever it is), decays to sustain × that level and stays; at 0 it\n // releases from wherever it is. Times in seconds, every segment linear.\n static get parameterDescriptors() {\n return [{ name: 'gate', defaultValue: 0 },\n { name: 'a', defaultValue: 0.01, minValue: 0, automationRate: 'k-rate' },\n { name: 'd', defaultValue: 0.1, minValue: 0, automationRate: 'k-rate' },\n { name: 's', defaultValue: 0.7, minValue: 0, maxValue: 1, automationRate: 'k-rate' },\n { name: 'r', defaultValue: 0.2, minValue: 0, automationRate: 'k-rate' }];\n }\n constructor() { super(); this.v = 0; this.stage = 0; this.on = false; this.peak = 1; this.rel = 0; }\n process(inputs, outputs, params) {\n const inp = inputs[0] && inputs[0][0], o = outputs[0][0], gp = params.gate;\n const sr = sampleRate, a = params.a[0], d = params.d[0], s = params.s[0], r = params.r[0];\n for (let i = 0; i < o.length; i++) {\n const g = (inp ? inp[i] : 0) + (gp.length > 1 ? gp[i] : gp[0]);\n if (g > 0 && !this.on) { this.on = true; this.peak = g; this.stage = 1; }\n else if (g <= 0 && this.on) { this.on = false; this.stage = 4; this.rel = this.v / Math.max(1, r * sr); }\n if (this.stage === 1) {\n this.v += this.peak / Math.max(1, a * sr);\n if (this.v >= this.peak) { this.v = this.peak; this.stage = 2; }\n } else if (this.stage === 2) {\n const lo = s * this.peak;\n this.v -= (this.peak - lo) / Math.max(1, d * sr);\n if (this.v <= lo) { this.v = lo; this.stage = 3; }\n } else if (this.stage === 3) {\n this.v = s * this.peak;\n } else if (this.stage === 4) {\n this.v -= this.rel;\n if (this.v <= 0) { this.v = 0; this.stage = 0; }\n }\n o[i] = this.v;\n }\n return true;\n }\n}\nregisterProcessor('kairotic-adsr', KairoticAdsr);\n\"\n default [10 100 0.7 200]\n shape-of (fn [v] (when (and (sequential? v) (= 4 (count v)) (every? number? v))\n (let [[a d s r] v]\n [(api/clamp a 0 20000) (api/clamp d 0 20000) (api/clamp s 0 1) (api/clamp r 0 20000)])))\n written (fn [args] (shape-of (api/padded args default)))\n current (fn [{:keys [shown state args]}]\n (or (shape-of shown) (shape-of state)\n (if (map? args) (shape-of [(:a args) (:d args) (:s args) (:r args)]) (written args))\n default))\n ;; ── view: the envelope in a 148 × 64 box; the sustain is held for a quarter of the rest ──\n x0 6 x1 142 top 8 bottom 46\n points (fn [[a d s r]]\n (let [total (max 1 (+ a d r)) hold (* 0.25 total)\n k (/ (- x1 x0) (+ total hold))\n xa (+ x0 (* k a)) xd (+ xa (* k d)) xs (+ xd (* k hold)) xr (+ xs (* k r))\n ys (- bottom (* s (- bottom top)))]\n [[x0 bottom] [xa top] [xd ys] [xs ys] [xr bottom]]))\n ms (fn [x] (if (>= x 1000) (str (api/nice (/ x 1000)) \"s\") (str (js/Math.round x))))\n set-shape! (fn [node [a d s r] at]\n (when-let [w @(:worklet node)]\n (doseq [[k v] [[\"a\" (/ a 1000)] [\"d\" (/ d 1000)] [\"s\" s] [\"r\" (/ r 1000)]]]\n (.setValueAtTime (api/param w k) v at))))]\n {;; ── about ──\n :class \"adsr~\"\n :license \"MPL-2.0\"\n :doc \"An envelope that follows a gate, for the factor of a gain~. On the left a gate: a signal (reader~ … gate) or numbers (above 0 it attacks to that level, 0 releases); a bang plays attack and decay and then releases. A list [a d s r] changes its shape (a, d, r in ms; s, the sustain, from 0 to 1), and so does dragging over it: attack, decay and release sideways, sustain up and down (⇧ finer); on release the new shape is written in the box.\"\n :usage \"adsr~ [a d s r]\"\n :io [1 1]\n :size [148 64]\n\n ;; ── arguments ──\n :args [[:a 10] [:d 100] [:s 0.7] [:r 200]]\n :persist (fn [[a d s r]] {:a a :d d :s s :r r})\n\n ;; ── logic ──\n :receive (fn [{:keys [value] :as m}]\n (let [sh (current m)]\n (cond\n (shape-of value) (let [v (shape-of value)] {:state v :show v :effects [[:shape v]]})\n (= value :bang) {:state sh :show sh :effects [[:bang sh]]}\n (api/num-of value) {:state sh :show sh :effects [[:gate (max 0 (api/num-of value))]]}\n :else {:state sh :show sh})))\n :gesture (fn [{:keys [start x dx dy fine] :as m}]\n (let [[a d s r :as sh] (or (shape-of start) (current m))\n [_ [xa] [xd] [xs]] (points sh)\n from (- x dx) k (if fine 4 1)\n stretch (fn [t] (js/Math.round (* (max t 1) (js/Math.pow 2 (/ dx (* 30 k))))))\n sus (fn [] (/ (js/Math.round (* 100 (api/clamp (- s (/ dy (* 40 k))) 0 1))) 100))]\n (cond\n (< from xa) [(stretch a) d s r]\n (< from xd) [a (stretch d) (sus) r]\n (< from xs) [a d (sus) r]\n :else [a d s (stretch r)])))\n\n ;; ── view ──\n :derive (fn [m]\n (let [[a d s r :as sh] (current m)]\n {:pts (points sh)\n :label (str \"a \" (ms a) \" · d \" (ms d) \" · s \" (api/nice s) \" · r \" (ms r))}))\n :view [[:rect {:x 2 :y 2 :w 144 :h 60 :r 4 :stroke :grid :fill :bg}]\n [:line {:x1 6 :y1 46 :x2 142 :y2 46 :stroke :grid}]\n [:path {:points :$pts :stroke :accent :weight 1.5}]\n [:text {:x 6 :y 58 :size 9 :fill :soft} :$label]]\n\n ;; ── audio ──\n :audio {:create (fn [ac b _]\n (let [in (.createGain ac) out (.createGain ac)\n node {:in in :out out :shape (atom (or (shape-of (:state b)) (written (:args b))))\n :worklet (atom nil) :alive (atom true) :inlets [[in 0]] :outlets [[out 0]]}]\n (-> (api/worklet-node ac \"kairotic-adsr\" worklet\n {:numberOfInputs 1 :numberOfOutputs 1 :outputChannelCount [1]\n :channelCount 1 :channelCountMode \"explicit\"})\n (.then (fn [w]\n (when @(:alive node)\n (.connect in w) (.connect w out)\n (reset! (:worklet node) w)\n (set-shape! node @(:shape node) (.-currentTime ac)))))\n (.catch (fn [e] (js/console.error \"adsr~\" e))))\n node))\n ;; a new text (dragging over it rewrites it): the new shape, without rebuilding the node\n :update (fn [node b at] (let [v (written (:args b))] (reset! (:shape node) v) (set-shape! node v at)))\n :effects {:shape (fn [node v at] (reset! (:shape node) v) (set-shape! node v at))\n :gate (fn [node g at] (when-let [w @(:worklet node)] (.setValueAtTime (api/param w \"gate\") g at)))\n :bang (fn [node [a d] at]\n (when-let [w @(:worklet node)]\n (let [gp (api/param w \"gate\")]\n (.setValueAtTime gp 1 at)\n (.setValueAtTime gp 0 (+ at (/ (+ a d) 1000) 0.001)))))}\n :dispose (fn [node]\n (reset! (:alive node) false)\n (when-let [w @(:worklet node)] (try (.disconnect w) (catch :default _ nil))))}})\n"
17
+ },
18
+ {
19
+ "name": "synth~",
20
+ "category": "synth",
21
+ "kind": "component",
22
+ "about": "a polyphonic synthesizer built from Web Audio nodes, one voice per id",
23
+ "source": ";; synth~ · a polyphonic triangle-wave synthesizer, one voice per id\n;; Part of @kairotic/synth. Written against the Kairotic API (api/…).\n(let [;; each id is a voice: a new id attacks (at the level [:gain v] set, 0.5 by default), one that continues\n ;; glides to its new frequency at `at`, one that disappears is switched off\n voices! (fn [node [pairs level] at]\n (let [ac (.-context (:out node)) vs @(:voices node) incoming (into {} pairs)]\n (doseq [[vid {:keys [osc g]}] vs :when (not (contains? incoming vid))]\n (.setTargetAtTime (.-gain g) 0 at 0.03)\n (.stop osc (+ at 0.4)))\n (reset! (:voices node)\n (into {}\n (for [[vid hz] (take 16 pairs)]\n (if-let [v (get vs vid)]\n (do (.linearRampToValueAtTime (.-frequency (:osc v)) hz at) [vid v])\n (let [o (.createOscillator ac) g (.createGain ac)]\n (set! (.-type o) \"triangle\")\n (.setValueAtTime (.-frequency o) hz at)\n (.setValueAtTime (.-gain g) 0 at)\n (.linearRampToValueAtTime (.-gain g) (* 0.4 level) (+ at 0.015))\n (.connect o g)\n (.connect g (:out node))\n (.start o at)\n [vid {:osc o :g g}])))))))]\n {;; ── about ──\n :class \"synth~\"\n :license \"MPL-2.0\"\n :doc \"Polyphonic triangle-wave synthesizer: frequencies on the left (a number or a list), voice ids on the right (from a reader). [:gain v] (0…1, 0.5 by default) sets the level of the notes that start after it, as a player sends an event's :amp. :stop silences it.\"\n :usage \"synth~\"\n :io [2 1]\n\n ;; ── logic ──\n :receive (fn [{:keys [state inlet value]}]\n (let [level (if (number? (:level state)) (:level state) 0.5)]\n (cond\n (= inlet 1) {:state (assoc state :ids (if (sequential? value) (vec value) [value]))}\n ;; the level of the notes that start next (an event's :amp, from a player)\n (and (vector? value) (#{:gain :amp :vel :velocity} (first value)) (number? (second value)))\n {:state (assoc state :level (api/clamp (second value) 0 1))}\n (number? value) {:state (dissoc state :ids) :effects [[:voices [[[:v0 value]] level]]]}\n (sequential? value)\n (let [fs (filterv number? value)\n ids (:ids state)\n ids (if (= (count ids) (count fs)) ids (mapv (fn [i] (keyword (str \"v\" i))) (range (count fs))))]\n {:state (dissoc state :ids) :effects [[:voices [(mapv vector ids fs) level]]]})\n (= value :stop) {:effects [[:voices [[] level]]]}\n :else {})))\n\n ;; ── audio ──\n :audio {:create (fn [ac _ _] (let [out (.createGain ac)] (set! (.. out -gain -value) 0.3)\n {:outlets [[out 0]] :out out :voices (atom {})}))\n :effects {:voices voices!}\n :dispose (fn [node] (doseq [[_ v] @(:voices node)] (try (.stop (:osc v)) (catch :default _ nil))))}})\n"
24
+ },
25
+ {
26
+ "name": "pan~",
27
+ "category": "spatial",
28
+ "kind": "component",
29
+ "about": "the simplest audio component: one Web Audio node, a parameter set by messages, :update",
30
+ "source": ";; pan~ · stereo panning with equal power\n;; Part of @kairotic/spatial. Written against the Kairotic API (api/…).\n{;; ── about ──\n :class \"pan~\"\n :license \"MPL-2.0\"\n :doc \"Stereo panning with equal power: signal on the left inlet, position on the right (−1 left … 1 right). Two outlets: left and right.\"\n :usage \"pan~ [position]\"\n :io [2 2]\n\n ;; ── arguments ──\n :args [[:position 0]]\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value]}]\n (if (and (= 1 inlet) (api/num-of value))\n {:effects [[:pan (api/clamp (api/num-of value) -1 1)]] :show (api/num-of value)}\n {}))\n\n ;; ── audio ──\n :audio {:create (fn [ac b _]\n (let [p (.createStereoPanner ac)]\n (set! (.. p -pan -value) (api/clamp (first (api/padded (:args b) [0])) -1 1))\n {:p p :inlets [[p 0]] :outlets (api/stereo-outlets ac p)}))\n :effects {:pan (fn [node x at] (.setTargetAtTime (.-pan (:p node)) x at 0.01))}\n ;; a new text: the new position, without rebuilding the node\n :update (fn [node b at] (.setTargetAtTime (.-pan (:p node)) (api/clamp (first (api/padded (:args b) [0])) -1 1) at 0.01))}}\n"
31
+ },
32
+ {
33
+ "name": "space~",
34
+ "category": "spatial",
35
+ "kind": "component",
36
+ "about": "binaural placement with a 2D pad view, crossfading two HRTF panners",
37
+ "source": ";; space~ · a sound placed around the listener (binaural)\n;; Part of @kairotic/spatial. Written against the Kairotic API (api/…).\n(let [pos-of (fn [v] (when (and (sequential? v) (= 2 (count v)) (every? number? v))\n [(api/clamp (first v) -1 1) (api/clamp (second v) -1 1)]))\n ;; An HRTF panner clicks whenever its position changes (it swaps filters), so space~ keeps two:\n ;; the silent one jumps to the new place and they crossfade, at most every `step` seconds; it\n ;; gets its place `settle` seconds before it is heard. A move that comes sooner waits for the\n ;; next crossfade (and the latest one wins). Measured offline: a path every 10 ms clicked 57\n ;; times in 8 s with one panner, none in 20 s like this.\n step 0.05 settle 0.01\n move! (fn [node [x y] at]\n (let [{:keys [a s]} @(:live node) pair (:pair node)\n place! (fn [i t] (let [p (:p (pair i))]\n (doseq [prm [(.-positionX p) (.-positionZ p)]] (.cancelScheduledValues prm t))\n (.setValueAtTime (.-positionX p) (* 2 x) t)\n (.setValueAtTime (.-positionZ p) (* -2 y) t)))]\n (if (< at s)\n (place! a s) ; a crossfade is already waiting: move its target\n (let [t (max at (+ s step)) b (- 1 a)]\n (place! b t)\n (doseq [[i v] [[b 1] [a 0]] :let [g (.-gain (:g (pair i)))]]\n (.cancelScheduledValues g t)\n (.setTargetAtTime g v (+ t settle) (/ step 4)))\n (reset! (:live node) {:a b :s t})))))]\n {;; ── about ──\n :class \"space~\"\n :license \"MPL-2.0\"\n :doc \"A sound placed around the listener (binaural, HRTF): drag the dot, or send [x y] (−1…1; y = 1 is in front). Two outlets: left and right, for headphones. Dragging rewrites the box.\"\n :usage \"space~ [x y]\"\n :io [1 2]\n :size [104 104]\n\n ;; ── arguments ──\n :args [[:x 0] [:y 1]]\n :persist (fn [[x y]] {:x x :y y})\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (if-let [p (pos-of value)]\n {:state p :show p :effects [[:pos p]]}\n (let [p (or state (pos-of [(:x args) (:y args)]) [0 1])]\n (if (= value :bang) {:state p :show p :effects [[:pos p]]} {:state p}))))\n :gesture (fn [{:keys [x y]}]\n [(/ (js/Math.round (* 100 (api/clamp (/ (- x 52) 46) -1 1))) 100)\n (/ (js/Math.round (* 100 (api/clamp (/ (- 52 y) 46) -1 1))) 100)])\n\n ;; ── view ──\n :derive (fn [{:keys [shown args]}]\n (let [[x y] (or (pos-of shown) (pos-of [(:x args) (:y args)]) [0 1])]\n {:px (+ 52 (* 46 x)) :py (- 52 (* 46 y))\n :label (str (api/nice x) \" · \" (api/nice y))}))\n :view [[:rect {:x 2 :y 2 :w 100 :h 100 :r 4 :stroke :grid :fill :bg}]\n [:line {:x1 52 :y1 6 :x2 52 :y2 98 :stroke :grid}]\n [:line {:x1 6 :y1 52 :x2 98 :y2 52 :stroke :grid}]\n [:circle {:cx 52 :cy 52 :r 30 :stroke :grid}]\n [:path {:points [[47 50] [52 43] [57 50]] :closed true :fill :soft}]\n [:circle {:cx 52 :cy 52 :r 5 :stroke :soft :fill :bg}]\n [:line {:x1 52 :y1 52 :x2 :$px :y2 :$py :stroke :accent :weight 1}]\n [:circle {:cx :$px :cy :$py :r 6 :fill :accent}]\n [:text {:x 6 :y 98 :size 9 :fill :soft} :$label]]\n\n ;; ── audio ──\n :audio {:create (fn [ac b _]\n (let [[x y] (api/padded (:args b) [0 1])\n in (.createGain ac) out (.createGain ac)\n pair (vec (for [i [0 1]]\n (let [p (.createPanner ac) g (.createGain ac)]\n (set! (.-panningModel p) \"HRTF\")\n (set! (.-distanceModel p) \"inverse\")\n (set! (.-refDistance p) 1)\n (set! (.. p -positionX -value) (* 2 (api/clamp x -1 1)))\n (set! (.. p -positionY -value) 0)\n (set! (.. p -positionZ -value) (* -2 (api/clamp y -1 1)))\n (set! (.. g -gain -value) (if (zero? i) 1 0))\n (.connect in p) (.connect p g) (.connect g out)\n {:p p :g g})))]\n {:pair pair :live (atom {:a 0 :s -1}) :inlets [[in 0]] :outlets (api/stereo-outlets ac out)}))\n :effects {:pos (fn [node xy at] (move! node xy at))}\n ;; a new text (dragging the dot rewrites it): the sound goes to the new place\n :update (fn [node b at] (move! node (pos-of (api/padded (:args b) [0 1])) at))}})\n"
38
+ },
39
+ {
40
+ "name": "fetch",
41
+ "category": "data",
42
+ "kind": "component",
43
+ "about": "a task (:tasks) that reads a URL outside the pure logic, its outcome on inlet :task, kept in the work with [:keep d] and a :model",
44
+ "source": ";; fetch · what is at a URL (JSON, text or EDN), brought in as a task\n;; Part of @kairotic/data. Written against the Kairotic API (api/…).\n;; Its logic never touches the network: a URL asks for the task :get, the engine runs it (api/http-get)\n;; and what it finds comes back to this box on inlet :task. By default the box keeps it as its data\n;; ([:keep …]): one gesture of the history, the same for everyone in a room, and going back in the\n;; history does not fetch it again. With `live` it is only held in this tab, for answers that change.\n(let [formats #{:json :text :edn}\n fmt-of (fn [args] (if (formats (:as args)) (:as args) :json))\n ;; what the box holds: kept in the work, or (live) only here\n sane (fn [d] (if (and (map? d) (string? (:url d))) (select-keys d [:url :value :date]) {}))\n ;; kept in the work (its data) or, live or before it could be kept (inside a sub-patch, too long, played\n ;; by someone else in a jam), only here (its state)\n held-of (fn [args data state] (if (and (not (:live args)) (contains? data :value)) data (:got state)))\n kept? (fn [args data] (and (not (:live args)) (contains? data :value)))\n summary (fn [v] (cond (map? v) (str \"{} \" (count v) (if (= 1 (count v)) \" key\" \" keys\"))\n (sequential? v) (str \"[] \" (count v) (if (= 1 (count v)) \" item\" \" items\"))\n (string? v) (str \"\\\"\\\" \" (count v) \" characters\")\n (nil? v) \"nil\"\n :else (pr-str v)))\n url-in (fn [value]\n (cond (api/url-of value) (api/url-of value)\n (and (sequential? value) (#{:fetch :url} (first value))) (api/url-of (second value))\n :else nil))\n path-in (fn [value] (let [p (rest value)] (if (and (= 1 (count p)) (sequential? (first p))) (vec (first p)) (vec p))))]\n {;; ── about ──\n :class \"fetch\"\n :license \"MPL-2.0\"\n :doc \"Brings in what is at a URL: JSON (read as EDN: keys that can be keywords become keywords), text or EDN. A URL (https://…, or github:owner/repo@ref/path through jsDelivr) asks for it; what arrives goes out on the left and is kept as the data of the box, in the history, so everyone in a room has the same and going back does not fetch again (a URL it already holds is sent again, not fetched: refresh fetches it again). With live it is only held in this tab, for answers that change. On the right: :loading, :ready or [:error \\\"…\\\"].\"\n :usage \"fetch [json|text|edn] [live]\"\n :io [1 2]\n :size [230 42]\n\n ;; ── arguments ──\n :args [[:as nil] [:live false]]\n\n ;; ── data: what it keeps, in the history ──\n :model {:empty {}\n :step (fn [d [op x]] (case op :set (sane x) :clear {} d))\n :load sane\n :code (fn [id d] (when (contains? d :value) [(str \"(keep! \" id \" \" (pr-str d) \")\")]))}\n\n ;; ── tasks: outside its pure logic ──\n :tasks {:get (fn [{:keys [url as]} _]\n (.then (api/http-get url {:as as})\n (fn [v] {:body v :date (.toISOString (js/Date.))})))}\n\n ;; ── logic ──\n :receive (fn [{:keys [inlet value state data args]}]\n (let [st (or state {})\n held (held-of args data st)\n ask (fn [u] (let [req {:url u :as (fmt-of args) :n (inc (:n st 0))}]\n {:state (assoc st :waiting req :n (:n req))\n :show {:status :loading :url u}\n :out [[1 :loading]]\n :effects [[:get req]]}))]\n (cond\n ;; what the task found\n (= inlet :task)\n (cond\n (not= (:arg value) (:waiting st)) {} ; the answer to an older request: dropped\n (:error value)\n {:state (dissoc st :waiting)\n :show {:status :error :url (:url (:arg value)) :error (:error value)}\n :out [[1 [:error (:error value)]]]}\n :else\n (let [got {:url (:url (:arg value)) :value (:body (:value value)) :date (:date (:value value))}\n same? (and (kept? args data) (= (:url data) (:url got)) (= (:value data) (:value got)))]\n {:state (-> st (dissoc :waiting) (assoc :got got))\n :show {:status :ready :url (:url got) :summary (summary (:value got))}\n :out [[1 :ready] [0 (:value got)]]\n :effects (if (or (:live args) same?) [] [[:keep got]])}))\n\n ;; a URL: fetched, unless it is the one it already keeps (sent again, then)\n (url-in value)\n (let [u (url-in value)]\n (cond (= u (:url (:waiting st))) {}\n (and (kept? args data) (= u (:url held))) {:out [[1 :ready] [0 (:value held)]]}\n :else (ask u)))\n (#{:refresh} value)\n (if-let [u (or (:url held) (:url (:waiting st)))] (ask u) {})\n\n (#{:bang} value) (if held {:out [[1 :ready] [0 (:value held)]]} {})\n (and (sequential? value) (#{:get} (first value)))\n (if held\n (let [p (path-in value) x (get-in (:value held) p ::none)]\n (if (= x ::none)\n {:out [[1 [:error (str \"nothing at \" (pr-str p))]]]}\n {:out [[0 x]]}))\n {})\n (#{:clear} value)\n {:state {:n (:n st 0)} :show {:status :idle}\n :effects (if (kept? args data) [[:keep nil]] [])}\n :else {})))\n\n :derive (fn [{:keys [shown data state args]}]\n (let [held (held-of args data state)\n status (or (:status shown) (if held :held :idle))\n short (fn [s n] (if (> (count s) n) (str (subs s 0 (dec n)) \"…\") s))]\n {:color (case status (:ready :held) :accent :loading :soft :error :kairos :grid)\n :label (short (case status\n :loading \"loading…\"\n :error (str \"✕ \" (:error shown))\n (:ready :held) (str (cond (kept? args data) \"kept · \" (:live args) \"live · \" :else \"here · \")\n (summary (:value held)))\n (str \"send a URL\" (when (:live args) \" · live\")))\n 38)\n :url (short (str (or (:url shown) (:url held) \"\")) 46)}))\n\n ;; ── view ──\n :view [[:rect {:x 1 :y 1 :w 228 :h 40 :r 4 :stroke :grid :fill :bg}]\n [:circle {:cx 12 :cy 14 :r 4 :fill :$color}]\n [:text {:x 22 :y 17 :size 10 :fill :ink} :$label]\n [:text {:x 8 :y 33 :size 8 :fill :soft} :$url]]\n\n ;; ── help ──\n :help {:inlets [\"a URL (msg https://… · a string · [:fetch url]); refresh; bang; [:get key …]; clear\"]\n :outlets [\"what it found (or the part a [:get …] asks for)\" \":loading, :ready or [:error \\\"…\\\"]\"]\n :messages [[\"a URL\" \"brings it in (if it already keeps that URL, sends it again)\"]\n [\":refresh\" \"fetches its URL again\"]\n [\"bang\" \"sends what it holds\"]\n [\":get :items 0 :name · [:get [:items 0 :name]]\" \"sends one part of it\"]\n [\":clear\" \"forgets it\"]]\n :try \"Click the message with the URL: the answer comes out on the left, into an edn box. Go back in the history: it is still there, without fetching.\"}})\n"
45
+ },
46
+ {
47
+ "name": "edn",
48
+ "category": "data",
49
+ "kind": "component",
50
+ "about": "a drawn tree view with :hit parts, scrolling by dragging, and view gestures as idempotent messages to itself",
51
+ "source": ";; edn · any value as a tree to open, read and pick from\n;; Part of @kairotic/data. Written against the Kairotic API (api/…).\n;; After Portal (djblue/portal): what arrives is shown as a tree whose collections open and close, each\n;; value coloured by its kind, a closed collection previewed on its line. Picking a line sends that part\n;; of the value (left) and its path (right), the path a fetch box takes as [:get …]. Dragging scrolls.\n;; What happens in the view (open, pick, scroll) is a message to the box itself, like any gesture, so\n;; the same value sent again changes nothing.\n(let [row-h 14 top-y 22 foot-h 16 cw 5.6 ; a line, where lines start, the footer, a character (size 9)\n max-children 200 max-rows 3000\n coll-kind (fn [v] (cond (map? v) :map (vector? v) :vector (set? v) :set (sequential? v) :list :else nil))\n opener {:map \"{\" :vector \"[\" :set \"#{\" :list \"(\"}\n plural (fn [n one many] (str n \" \" (if (= 1 n) one many)))\n size-text (fn [v] (case (coll-kind v)\n :map (plural (count v) \"key\" \"keys\")\n (:vector :list) (plural (count v) \"item\" \"items\")\n :set (plural (count v) \"element\" \"elements\")\n nil))\n ;; the colour of a value, by its kind (the palette of the patch, light or dark)\n ink-of (fn [v] (cond (string? v) :ink (number? v) :kairos (keyword? v) :accent\n (or (nil? v) (boolean? v)) :soft (coll-kind v) :soft :else :ink))\n ;; one level down: the parts of a collection, in a steady order, at most max-children of them\n entries (fn [c]\n (let [es (case (coll-kind c)\n :map (for [[k v] (sort-by (fn [[k _]] (pr-str k)) c)] {:k k :label (pr-str k) :key? true :v v})\n :set (for [v (sort-by pr-str c)] {:k v :label \"\" :v v})\n (map-indexed (fn [i v] {:k i :label (str i) :v v}) c))\n shown (vec (take max-children es))]\n (if (> (count c) max-children)\n (conj shown {:more (- (count c) max-children)})\n shown)))\n ;; a part of the value by its path: get-in, also through lists and sets\n part (fn [root path]\n (reduce (fn [c k] (case (coll-kind c)\n (:map :set) (get c k)\n (:vector :list) (if (number? k) (nth (seq c) k nil) nil)\n nil))\n root path))\n ;; the lines of the tree as it is open: [{:path :depth :label :key? :v :open? :more}]\n rows-of (fn [{:keys [root open]}]\n (if-not (coll-kind root)\n []\n (loop [todo (into () (reverse (map (fn [e] (assoc e :path [(:k e)] :depth 0)) (entries root))))\n out (transient [])]\n (if (or (empty? todo) (>= (count out) max-rows))\n (persistent! out)\n (let [r (first todo) more (rest todo)\n open? (and (coll-kind (:v r)) (contains? open (:path r)) (not (:more r)))\n kids (when open? (map (fn [e] (assoc e :path (conj (:path r) (:k e)) :depth (inc (:depth r))))\n (entries (:v r))))]\n (recur (if open? (into more (reverse kids)) more)\n (conj! out (assoc r :open? open?))))))))\n visible (fn [h] (max 1 (js/Math.floor (/ (- h top-y foot-h) row-h))))\n size-of (fn [args] (api/padded (filter number? args) [320 300]))\n ;; every collection down to depth n, open (at most max-rows of them)\n open-to (fn [root n]\n (loop [todo (list [[] root 0]) acc #{}]\n (if (or (empty? todo) (> (count acc) max-rows))\n acc\n (let [[p v d] (first todo)\n kids (when (and (coll-kind v) (< d n))\n (for [e (entries v) :when (and (not (:more e)) (coll-kind (:v e)))] [(conj p (:k e)) (:v e) (inc d)]))]\n (recur (into (rest todo) kids) (if (and (seq p) (coll-kind v) (<= d n)) (conj acc p) acc))))))\n shown-of (fn [st] {:top (:top st 0) :sel (:sel st) :open (count (:open st))})\n with-top (fn [st top h] (let [n (count (rows-of st))] (assoc st :top (max 0 (min (js/Math.round top) (- n (visible h)))))))]\n {;; ── about ──\n :class \"edn\"\n :license \"MPL-2.0\"\n :doc \"Shows any value as a tree, like Portal: maps, vectors, sets and lists open and close (▸ ▾), each value coloured by its kind, a closed collection previewed on its line. Picking a line sends that part of the value (left) and its path (right): the path a fetch box takes as [:get …]. Dragging scrolls (or the bar on the right). :depth n opens it n levels down; bang sends the picked part again (the whole value if none); :clear empties it.\"\n :usage \"edn [width height]\"\n :io [1 2]\n :size (fn [box] (size-of (:args box)))\n\n ;; ── logic ──\n :receive (fn [{:keys [value state args]}]\n (let [st (or state {:open #{} :top 0})\n [_ h] (size-of args)\n msg? (fn [k] (and (vector? value) (= k (first value))))\n view (fn [st2] {:state st2 :show (shown-of st2)})]\n (cond\n ;; what happens in the view\n (msg? :edn-open)\n (let [[_ p on] value]\n (view (with-top (update st :open (if on conj disj) p) (:top st 0) h)))\n (msg? :edn-top) (view (with-top st (second value) h))\n (msg? :edn-pick)\n (let [p (second value)]\n (if (or (= p (:sel st)) (not (contains? st :root)))\n {:state st}\n {:state (assoc st :sel p) :show (shown-of (assoc st :sel p))\n :out [[1 p] [0 (part (:root st) p)]]}))\n ;; messages\n (and (msg? :depth) (number? (second value)))\n (view (with-top (assoc st :open (open-to (:root st) (max 0 (dec (second value))))) 0 h))\n (#{:bang} value)\n (if (contains? st :root)\n (let [p (or (:sel st) [])] {:out [[1 p] [0 (part (:root st) p)]]})\n {})\n (#{:clear} value) (view {:open #{} :top 0})\n ;; a value: the same again changes nothing; another keeps what was open and picked\n (and (contains? st :root) (= value (:root st))) {:state st}\n :else\n (let [st2 (assoc st :root value)]\n (view (with-top st2 (:top st 0) h))))))\n\n ;; a line pressed (on its arrow: open or close it; elsewhere: pick it), or a drag that scrolls\n :gesture (fn [{:keys [up hit dy start state h]}]\n (let [st (or state {}) rows (rows-of st) n (count rows) vis (visible h)\n t0 (:top start (:top st 0))]\n (cond\n (>= (js/Math.abs dy) 3)\n [:edn-top (if (= hit :bar)\n (+ t0 (* dy (/ n (* vis row-h))))\n (- t0 (/ dy row-h)))]\n (not up) nil\n ;; a line is its index; its arrow, -1 - its index\n (and (number? hit) (neg? hit))\n (when-let [r (get rows (- -1 hit))] (when (coll-kind (:v r)) [:edn-open (:path r) (not (:open? r))]))\n (number? hit) (when-let [r (get rows hit)] (when-not (:more r) [:edn-pick (:path r)]))\n :else nil)))\n\n ;; ── view ──\n :draw (fn [{:keys [state w h]}]\n (let [st (or state {}) root (:root st) rows (rows-of st) n (count rows)\n vis (visible h) top (max 0 (min (:top st 0) (- n vis))) bar? (> n vis)\n right (- w (if bar? 14 6))\n chars (fn [x] (max 0 (js/Math.floor (/ (- right x) cw))))\n cut (fn [s x] (let [m (chars x)] (if (> (count s) m) (str (subs s 0 (max 0 (dec m))) \"…\") s)))\n line (fn [j r i]\n (let [y (+ top-y (* j row-h)) base (+ y 10)\n x (+ 8 (* 12 (:depth r))) v (:v r) kind (coll-kind v)\n lbl (:label r) vx (+ x 12 (if (seq lbl) (* cw (inc (count lbl))) 0))\n sel? (= (:sel st) (:path r))]\n (if (:more r)\n [[:text {:x (+ x 12) :y base :size 9 :fill :soft} (str \"… \" (:more r) \" more\")]]\n (concat\n [[:rect {:x 2 :y y :w (- right 2) :h row-h :fill (if sel? :accent :bg) :opacity (if sel? 0.14 0) :hit i}]]\n (when kind\n [[:rect {:x (- x 2) :y y :w 12 :h row-h :fill :bg :opacity 0 :hit (- -1 i)}]\n [:text {:x x :y base :size 9 :fill :soft} (if (:open? r) \"▾\" \"▸\")]])\n (when (seq lbl)\n [[:text {:x (+ x 12) :y base :size 9 :fill (if (:key? r) :accent :soft)} (cut lbl (+ x 12))]])\n [[:text {:x vx :y base :size 9 :fill (ink-of v)}\n (cut (cond (and kind (:open? r)) (str (opener kind) \" \" (size-text v))\n kind (pr-str v)\n :else (pr-str v))\n vx)]]))))]\n (concat\n [[:rect {:x 1 :y 1 :w (- w 2) :h (- h 2) :r 4 :stroke :grid :fill :bg}]\n [:text {:x 8 :y 15 :size 9 :fill :soft}\n (cond (not (contains? st :root)) \"edn · send it a value\"\n (coll-kind root) (str (name (coll-kind root)) \" · \" (size-text root))\n :else (str (cond (string? root) \"string\" (number? root) \"number\" (keyword? root) \"keyword\"\n (nil? root) \"nil\" (boolean? root) \"boolean\" :else \"value\")))]\n [:line {:x1 1 :y1 19 :x2 (- w 1) :y2 19 :stroke :grid}]]\n ;; a value that is not a collection: itself, on one line\n (when (and (contains? st :root) (not (coll-kind root)))\n [[:text {:x 8 :y (+ top-y 10) :size 9 :fill (ink-of root)} (cut (pr-str root) 8)]])\n (mapcat (fn [j] (line j (nth rows (+ top j)) (+ top j))) (range (min vis (- n top))))\n (when bar?\n (let [track (* vis row-h) th (max 14 (* track (/ vis n))) ty (+ top-y (* (- track th) (/ top (max 1 (- n vis)))))]\n [[:rect {:x (- w 10) :y top-y :w 6 :h track :r 3 :fill :grid :hit :bar}]\n [:rect {:x (- w 10) :y ty :w 6 :h th :r 3 :fill :soft :hit :bar}]]))\n [[:line {:x1 1 :y1 (- h foot-h) :x2 (- w 1) :y2 (- h foot-h) :stroke :grid}]\n [:text {:x 8 :y (- h 5) :size 8 :fill :soft}\n (cut (cond (:sel st) (str \"→ \" (pr-str (:sel st)))\n (seq rows) (str n (if (= 1 n) \" line\" \" lines\") (when bar? (str \" · \" (inc top) \"–\" (min n (+ top vis)))) \" · pick a line\")\n :else \"\")\n 8)]])))\n\n ;; ── help ──\n :help {:inlets [\"any value: a map, a vector, a set, a list, or a single value; :depth n · bang · :clear\"]\n :outlets [\"the part picked\" \"its path, for [:get …] of a fetch box\"]\n :messages [[\":depth 2\" \"opens it two levels down\"]\n [\"bang\" \"sends the part picked again (the whole value if none)\"]\n [\":clear\" \"empties it\"]]\n :try \"Send it a fetch's answer and open the branches: pick a line and its path comes out on the right.\"}})\n"
52
+ },
53
+ {
54
+ "name": "filter-panel",
55
+ "category": "abstraction",
56
+ "kind": "abstraction",
57
+ "about": "an abstraction (bpatcher): a Faust resonant filter with two knobs; its instances show the knobs as a panel",
58
+ "source": "{:class \"filter-panel\"\n :license \"MPL-2.0\"\n :doc \"A resonant low-pass filter with its two knobs: a signal in on the left, the filtered signal out. An instance shows the cutoff and q knobs as its panel.\"\n :usage \"filter-panel\"\n ;; a patch inside: inlet~ → faust~ → outlet~, and two knobs that send [:cutoff v] and [:q v] to the faust~.\n ;; :present [x y] puts a box on the panel of every instance (only boxes with their own view act there).\n :patch {:boxes {:b1 {:text \"inlet~\" :x 20 :y 20}\n :b2 {:text \"knob 40 12000 1200 log cutoff\" :x 120 :y 20 :present [0 0]}\n :b3 {:text \"knob 0.5 20 2 q\" :x 220 :y 20 :present [84 0]}\n :b4 {:text \"faust~\" :x 20 :y 140\n :data {:source \"import(\\\"stdfaust.lib\\\");\\ncutoff = hslider(\\\"cutoff\\\", 1200, 40, 12000, 1) : si.smoo;\\nq = hslider(\\\"q\\\", 2, 0.5, 20, 0.01) : si.smoo;\\nprocess = fi.resonlp(cutoff, q, 1);\"}}\n :b5 {:text \"outlet~\" :x 20 :y 330}}\n :lines [[:b1 0 :b4 0] [:b2 0 :b4 0] [:b3 0 :b4 0] [:b4 0 :b5 0]]}}\n"
59
+ },
60
+ {
61
+ "name": "row",
62
+ "category": "cac",
63
+ "kind": "component",
64
+ "about": "a twelve-tone row and its forms (P, R, I, RI and transpositions); a bang plays its next note",
65
+ "source": ";; row · a twelve-tone row and its forms\n{;; ── about ──\n :class \"row\"\n :license \"MPL-2.0\"\n :doc \"A twelve-tone row and its forms. A bang sends the next note of the current form as MIDI (from base) on the left, and its position on the right. [:p n] [:r n] [:i n] [:ri n] choose the form and its transposition (and start it again); a list of twelve pitch classes sets the row.\"\n :usage \"row [base]\"\n :io [1 2]\n\n ;; ── arguments ──\n :args [[:base 60]]\n\n ;; ── logic ──\n :receive (fn [{:keys [state value args]}]\n (let [st (or state {:row [0 11 7 8 3 1 2 10 6 5 4 9] :form :p :t 0 :pos 0})\n {:keys [row form t pos]} st\n r0 (first row)\n prime (mapv (fn [x] (mod (+ x t) 12)) row)\n inv (mapv (fn [x] (mod (+ t r0 (- r0 x)) 12)) row)\n series (case form :p prime :r (vec (rseq prime)) :i inv :ri (vec (rseq inv)) prime)]\n (cond\n (= value :bang)\n {:state (assoc st :pos (mod (inc pos) 12))\n :out [[1 pos] [0 (+ (:base args) (nth series pos))]]\n :show (str (name form) t \" \" (inc pos) \"/12\")}\n\n (and (vector? value) (#{:p :r :i :ri} (first value)))\n (let [st (assoc st :form (first value) :t (mod (or (second value) 0) 12) :pos 0)]\n {:state st :show (str (name (:form st)) (:t st))})\n\n (and (sequential? value) (= 12 (count value)) (every? number? value)\n (= 12 (count (set (map #(mod % 12) value)))))\n {:state (assoc st :row (mapv #(mod % 12) value) :pos 0) :show \"new row\"}\n\n :else {:state st})))}\n"
66
+ },
67
+ {
68
+ "name": "fm-voice",
69
+ "category": "faust",
70
+ "kind": "faust",
71
+ "about": "a two-operator FM voice played by freq and gate (a reader's list of Hz sets freq and gate = 1)",
72
+ "source": "import(\"stdfaust.lib\");\nfreq = hslider(\"freq\", 220, 20, 4000, 0.01);\ngate = button(\"gate\");\nratio = hslider(\"ratio\", 2, 0.25, 8, 0.01);\nindex = hslider(\"index\", 1.5, 0, 10, 0.01) : si.smoo;\nenv = en.adsr(0.01, 0.2, 0.5, 0.6, gate);\nmodulator = os.osc(freq * ratio) * index * freq * env;\nprocess = os.osc(freq + modulator) * env * 0.3;\n"
73
+ },
74
+ {
75
+ "name": "resonant-filter",
76
+ "category": "faust",
77
+ "kind": "faust",
78
+ "about": "a resonant low-pass filter for one signal; cutoff and q are parameters ([:cutoff 800], [:q 4])",
79
+ "source": "import(\"stdfaust.lib\");\ncutoff = hslider(\"cutoff\", 1200, 40, 12000, 1) : si.smoo;\nq = hslider(\"q\", 2, 0.5, 20, 0.01) : si.smoo;\nprocess = fi.resonlp(cutoff, q, 1);\n"
80
+ },
81
+ {
82
+ "name": "note-name",
83
+ "category": "notation",
84
+ "kind": "component",
85
+ "about": "turns frequencies (Hz) or MIDI notes into note names with cents (\"A4\", \"C#5 +14c\"); for labels and scores",
86
+ "source": ";; note-name · a frequency or MIDI note as a note name\n{;; ── about ──\n :class \"note-name\"\n :license \"MPL-2.0\"\n :doc \"Turns a frequency in Hz (or a MIDI note with `midi`) into its note name, with the deviation in cents when it is not tempered: 440 → \\\"A4\\\", 450 → \\\"A4 +39c\\\". A list gives a list of names. Optional reference for A4 (440).\"\n :usage \"note-name [a4] [midi]\"\n :io [1 1]\n\n ;; ── arguments ──\n :args [[:a4 440] [:midi false]]\n\n ;; ── logic ──\n :receive (fn [{:keys [value args]}]\n (let [names [\"C\" \"C#\" \"D\" \"D#\" \"E\" \"F\" \"F#\" \"G\" \"G#\" \"A\" \"A#\" \"B\"]\n as-midi (fn [x] (if (:midi args) x (+ 69 (* 12 (/ (js/Math.log (/ x (:a4 args))) (js/Math.log 2))))))\n name-of (fn [x]\n (when (and (number? x) (pos? x))\n (let [m (as-midi x) n (js/Math.round m)\n cents (js/Math.round (* 100 (- m n)))]\n (str (nth names (mod n 12)) (dec (js/Math.floor (/ n 12)))\n (when-not (zero? cents) (str \" \" (when (pos? cents) \"+\") cents \"c\"))))))]\n (cond\n (number? value) (let [s (name-of value)] (if s {:out [[0 s]] :show s} {}))\n (sequential? value) (let [ss (vec (keep name-of value))] {:out [[0 ss]] :show (str/join \" \" ss)})\n :else {})))}\n"
87
+ },
88
+ {
89
+ "name": "walk",
90
+ "category": "notation",
91
+ "kind": "component",
92
+ "about": "a melody as a musical tree (kairotic.mt): a random walk on a scale, written in measures, for score, mt boxes and mt play",
93
+ "source": ";; walk · a random walk on a scale, as a tree\n{;; ── about ──\n :class \"walk\"\n :license \"MPL-2.0\"\n :doc \"On a bang, a random walk of n notes on a major scale from start, written as a musical tree: a voice in 4/4 measures of eighth notes (the last one completed with a rest). Send it to a freqt shown as a score, to mt boxes or to mt play.\"\n :usage \"walk [notes] [start]\"\n :io [1 1]\n\n ;; ── arguments ──\n :args [[:notes 16] [:start 60]]\n\n ;; ── help ──\n :help {:inlets [\"bang: a new melody\"]\n :outlets [\"a musical tree [:voice [:measure …] …]\"]\n :try \"Connect it to a freqt shown as a score ((view :bN :score)) and click a bang: each click, another walk. Then put an mt retrograde between them.\"}\n\n ;; ── logic ──\n ;; A tree is plain data: notes are [:note {:pitch \"e4\" :dur 0.5}] and the functions of kairotic.mt\n ;; (mt/pitch-name, mt/transpose, mt/events …) work on it, so the component only builds the vector.\n :receive (fn [{:keys [args value]}]\n (if (= value :bang)\n (let [scale [0 2 4 5 7 9 11]\n n (max 1 (js/Math.round (:notes args)))\n degrees (reductions + 0 (repeatedly (dec n) (fn [] (rand-nth [-2 -1 1 1 2]))))\n midi (fn [d] (+ (:start args) (* 12 (js/Math.floor (/ d 7))) (nth scale (mod d 7))))\n notes (mapv (fn [d] [:note {:pitch (mt/pitch-name (midi d)) :dur 0.5}]) degrees)\n bars (for [bar (partition-all 8 notes)]\n (into [:measure {:meter [4 4]}]\n (concat bar (when (< (count bar) 8) [[:rest {:dur (* 0.5 (- 8 (count bar)))}]]))))]\n {:out [[0 (into [:voice {:name \"walk\"}] bars)]]})\n {}))}\n"
94
+ }
95
+ ]
96
+ };
@@ -0,0 +1,225 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · faust~
3
+ ;; A Faust code box. The official compiler (faustwasm, WebAssembly) is downloaded the
4
+ ;; first time it is needed; each source is compiled in this tab and runs as an AudioWorklet.
5
+ ;; The box's audio inlets and outlets are those of the compiled `process`; the left inlet
6
+ ;; also receives messages for its parameters (hslider, nentry, button…):
7
+ ;; [:freq 440] → the freq parameter (msg :freq 440)
8
+ ;; 440 → freq (or the first parameter if there is no freq)
9
+ ;; [440 660 …] → freq = the first one, gate = 1 (empty list → gate = 0): this way a reader plays a faust~
10
+ ;;
11
+ ;; Polyphonic: a source that declares declare options "[nvoices:8]"; (the Faust convention, as in the
12
+ ;; Faust IDE) is compiled as voices, each with its freq, gain and gate, played by faustwasm's own
13
+ ;; allocator (one AudioWorklet; a voice taken from the oldest when they run out), and an optional
14
+ ;; effect = …; in the same source, applied once to the sum of the voices. Then, as synth~:
15
+ ;; [440 550 660] on the left · voice ids on the right (a keyboard, a reader, mt play): each id a voice;
16
+ ;; a new id starts a note, one that disappears releases it, one whose pitch changes plays it again ·
17
+ ;; a number: one voice · [:gain 0.5] the velocity of the next notes · :stop releases them all ·
18
+ ;; [:cutoff 1200] any other parameter, for every voice (or for the effect).
19
+ ;; Notes are sent as MIDI pitches with decimals (its allocator turns them into Hz without rounding),
20
+ ;; so any tuning sounds as written.
21
+
22
+ (ns kairotic.faust
23
+ (:refer-clojure :exclude [load])
24
+ (:require [clojure.string :as str]
25
+ [kairotic.components :as comp]
26
+ [kairotic.code :as code]))
27
+
28
+ (defonce loading (atom nil))
29
+
30
+ (defn load
31
+ "Promise of the compiler: {F: the faustwasm module, compiler: FaustCompiler}."
32
+ []
33
+ (or @loading (reset! loading ((.-kairoticLoadFaust js/window)))))
34
+
35
+ (defn hash-text [s]
36
+ (let [h (reduce (fn [h c] (bit-or 0 (+ (* h 31) (.charCodeAt c 0)))) 7 (str s))]
37
+ (.toString (js/Math.abs h) 36)))
38
+
39
+ (defn params-of
40
+ "Walks Faust's interface description and returns the input controls."
41
+ [ui]
42
+ (vec (mapcat (fn walk [it]
43
+ (let [kind (.-type it)]
44
+ (cond
45
+ (some? (.-items it)) (mapcat walk (array-seq (.-items it)))
46
+ (contains? #{"hslider" "vslider" "nentry" "button" "checkbox"} kind)
47
+ [{:label (.-label it) :address (.-address it) :type kind
48
+ :min (or (.-min it) 0) :max (or (.-max it) 1) :init (or (.-init it) 0) :step (or (.-step it) 0)}]
49
+ :else [])))
50
+ (array-seq ui))))
51
+
52
+ (defn poly-voices
53
+ "The number of voices a source declares (declare options \"[nvoices:8]\"), or nil: then it is mono."
54
+ [source]
55
+ (when-let [[_ n] (re-find #"declare\s+options\s+\"[^\"]*\[\s*nvoices\s*:\s*(\d+)\s*\]" (str source))]
56
+ (max 1 (min 64 (js/parseInt n 10)))))
57
+
58
+ ;; the controls of a voice its allocator sets itself, note by note: not parameters of the box
59
+ (def voice-controls #{"freq" "gain" "gate" "key" "vel" "velocity"})
60
+
61
+ (defn voice-control? [p] (contains? voice-controls (last (str/split (str (:address p)) #"/"))))
62
+
63
+ (defn compile-mono [fx source dsp-name]
64
+ (let [gen (js/Reflect.construct (.-FaustMonoDspGenerator (.-F fx)) #js [])]
65
+ (-> (.compile gen (.-compiler fx) dsp-name source "-ftz 2")
66
+ (.then (fn [g]
67
+ (when (nil? g) (throw (js/Error. "Faust could not compile this source")))
68
+ (let [meta (js/JSON.parse (.. gen -factory -json))]
69
+ {:value gen
70
+ :info {:name dsp-name :ins (.-inputs meta) :outs (.-outputs meta)
71
+ :params (params-of (.-ui meta))
72
+ :summary (str (.-inputs meta) " in · " (.-outputs meta) " out · " (count (params-of (.-ui meta))) " params")}}))))))
73
+
74
+ (defn compile-poly
75
+ "Voices, and the effect if the source has one (faustwasm compiles `effect` from the same source)."
76
+ [fx source dsp-name n]
77
+ (let [gen (js/Reflect.construct (.-FaustPolyDspGenerator (.-F fx)) #js [])]
78
+ (-> (.compile gen (.-compiler fx) dsp-name source "-ftz 2")
79
+ (.then (fn [g]
80
+ (when (or (nil? g) (nil? (.-voiceFactory gen))) (throw (js/Error. "Faust could not compile this source")))
81
+ (let [vm (js/JSON.parse (.. gen -voiceFactory -json))
82
+ em (some-> (.-effectFactory gen) .-json js/JSON.parse)
83
+ vps (params-of (.-ui vm))
84
+ ps (vec (concat (remove voice-control? vps) (when em (params-of (.-ui em)))))
85
+ outs (if em (.-outputs em) (.-outputs vm))]
86
+ (when-not (some (fn [p] (= "freq" (last (str/split (str (:address p)) #"/")))) vps)
87
+ (throw (js/Error. "a polyphonic voice needs a freq control (and gate, and gain for the velocity): freq = hslider(\"freq\", 440, 20, 20000, 0.01);")))
88
+ {:value gen
89
+ :info {:name dsp-name :poly n :effect (some? em) :ins (.-inputs vm) :outs outs :params ps
90
+ :summary (str n " voices" (when em " + effect") " · " outs " out · " (count ps) " params")}}))))))
91
+
92
+ (code/register-language! "faust"
93
+ (fn [source]
94
+ (-> (load)
95
+ (.then (fn [fx]
96
+ (let [dsp-name (str "k" (hash-text source))]
97
+ (if-let [n (poly-voices source)]
98
+ (compile-poly fx source dsp-name n)
99
+ (compile-mono fx source dsp-name))))))))
100
+
101
+ (defn info [c] (:info (code/compiled "faust" (get-in c [:data :source]))))
102
+
103
+ (defn find-param [node pname]
104
+ (let [ps (get-in node [:info :params])]
105
+ (or (first (filter (fn [p] (= (:label p) pname)) ps))
106
+ (first (filter (fn [p] (str/ends-with? (:address p) (str "/" pname))) ps)))))
107
+
108
+ (defn set-param! [node p v at]
109
+ (swap! (:values node) assoc (:label p) v)
110
+ ;; its copies elsewhere (in a ring~'s node, when it is in a loop of the ring: kairotic.ringaudio) follow it
111
+ (doseq [f (vals @(:mirrors node))] (f (:address p) v))
112
+ (if-let [n @(:faust node)]
113
+ (.setParamValue n (:address p) v (max at (.-currentTime (.-context n))))
114
+ (swap! (:pending node) assoc (:address p) v)))
115
+
116
+ (defn param! [node [pname v] at]
117
+ (when-let [p (find-param node (name pname))]
118
+ (when (number? v) (set-param! node p v at))))
119
+
120
+ (defn freqs! [node v at]
121
+ (let [fs (if (number? v) [v] (filter number? v))
122
+ pf (or (find-param node "freq") (when (number? v) (first (get-in node [:info :params]))))
123
+ pg (find-param node "gate")]
124
+ (if (seq fs)
125
+ (do (when pf (set-param! node pf (first fs) at))
126
+ (when (and pg (sequential? v)) (set-param! node pg 1 at)))
127
+ (when pg (set-param! node pg 0 at)))))
128
+
129
+ ;; ───── voices (polyphonic) ─────
130
+
131
+ (defn hz->pitch
132
+ "A frequency as the MIDI pitch faustwasm's allocator takes (with decimals: it does not round)."
133
+ [hz] (+ 69 (* 12 (/ (js/Math.log (/ hz 440)) (js/Math.log 2)))))
134
+
135
+ (defn voices!
136
+ "Plays the voices {:pairs [[id hz] …] :vel 0…1}: an id that is new starts a note, one that is gone
137
+ releases it, one whose pitch changed plays it again (one note per id, as synth~)."
138
+ [node {:keys [pairs vel]} at]
139
+ (if-let [n @(:faust node)]
140
+ (let [t (max at (.-currentTime (.-context n)))
141
+ old @(:voices node)
142
+ incoming (into {} (for [[id hz] (take (* 2 (or (get-in node [:info :poly]) 8)) pairs)
143
+ :when (and (number? hz) (pos? hz) (js/isFinite hz))]
144
+ [id (hz->pitch hz)]))
145
+ v (js/Math.round (* 127 (max 0 (min 1 (if (number? vel) vel 0.8)))))]
146
+ (doseq [[id p] old :when (not= p (get incoming id))] (.keyOff n 0 p 0 t))
147
+ (doseq [[id p] incoming :when (not= p (get old id))] (.keyOn n 0 p (max 1 v) t))
148
+ (reset! (:voices node) incoming))
149
+ ;; the node is still being made: what it should play when it is ready
150
+ (reset! (:want node) [{:pairs pairs :vel vel} at])))
151
+
152
+ (defn create [ac c _]
153
+ (let [r (code/compiled "faust" (get-in c [:data :source]))
154
+ inf (:info r)
155
+ ins (or (:ins inf) 0) outs (max 1 (or (:outs inf) 1))
156
+ merger (when (pos? ins) (.createChannelMerger ac ins))
157
+ splitter (.createChannelSplitter ac outs)
158
+ node {:inlets (if merger (vec (for [i (range ins)] [merger i])) [])
159
+ :outlets (vec (for [o (range outs)] [splitter o]))
160
+ :merger merger :splitter splitter :info inf
161
+ :faust (atom nil) :pending (atom {}) :alive (atom true) :voices (atom {}) :want (atom nil) :mirrors (atom {})
162
+ :values (atom (into {} (for [p (:params inf)] [(:label p) (:init p)])))}]
163
+ (when (= :ok (:status r))
164
+ (-> (if (:poly inf) (.createNode (:value r) ac (:poly inf) (:name inf)) (.createNode (:value r) ac (:name inf)))
165
+ (.then (fn [n]
166
+ (when (and n @(:alive node))
167
+ (when merger (.connect merger n))
168
+ (.connect n splitter)
169
+ (doseq [[a v] @(:pending node)] (.setParamValue n a v))
170
+ (reset! (:faust node) n)
171
+ (when-let [[w at] @(:want node)] (reset! (:want node) nil) (voices! node w at)))))
172
+ (.catch (fn [e] (js/console.error "faust~" e)))))
173
+ node))
174
+
175
+ (defn dispose [node]
176
+ (reset! (:alive node) false)
177
+ (when-let [n @(:faust node)]
178
+ (try (when (get-in node [:info :poly]) (.allNotesOff n true)) (.disconnect n) (.destroy n) (catch :default _ nil))))
179
+
180
+ (defn receive-poly
181
+ "The messages of a polyphonic faust~ (see the header): as synth~, with ids on the right."
182
+ [{:keys [state inlet value]}]
183
+ (let [st (if (map? state) state {})
184
+ vel (:vel st)
185
+ play (fn [pairs] {:state (dissoc st :ids) :effects [[:voices {:pairs pairs :vel vel}]]})]
186
+ (cond
187
+ (= inlet 1) {:state (assoc st :ids (if (sequential? value) (vec value) [value]))}
188
+ (not (zero? inlet)) {}
189
+ (and (vector? value) (#{:gain :vel :velocity} (first value)) (number? (second value)))
190
+ (let [v (second value)] {:state (assoc st :vel (if (> v 1) (/ (min v 127) 127) (max 0 v)))})
191
+ (and (vector? value) (or (keyword? (first value)) (string? (first value)))) {:effects [[:param value]]}
192
+ (number? value) (play (if (pos? value) [[:v0 value]] []))
193
+ (= value :stop) (play [])
194
+ (sequential? value)
195
+ (let [fs (filterv number? value)
196
+ ids (:ids st)
197
+ ids (if (= (count ids) (count fs)) ids (mapv (fn [i] (keyword (str "v" i))) (range (count fs))))]
198
+ (play (mapv vector ids fs)))
199
+ :else {})))
200
+
201
+ (def template
202
+ "import(\"stdfaust.lib\");
203
+ freq = hslider(\"freq\", 440, 40, 2000, 0.01);
204
+ gate = button(\"gate\");
205
+ cutoff = hslider(\"cutoff\", 2400, 200, 8000, 1);
206
+ process = os.sawtooth(freq) * en.adsr(0.01, 0.15, 0.6, 0.4, gate) * 0.25 : fi.lowpass(2, cutoff);")
207
+
208
+ (comp/define! "faust~"
209
+ {:doc "Faust code box: compiled in the page and played as an AudioWorklet. Its audio ports are those of process; the left inlet also accepts parameters ([:freq 440], a list of Hz with gate). With declare options \"[nvoices:8]\" it is polyphonic: Hz on the left and voice ids on the right, as synth~ (a keyboard, a reader, mt play), and an effect = …; for all of them."
210
+ :usage "faust~"
211
+ :display :code :language "faust" :model code/model :template template
212
+ :dynamic-io true
213
+ ;; polyphonic, a second inlet for the voice ids (as synth~)
214
+ :io (fn [c] (let [i (info c)] [(max (if (:poly i) 2 1) (or (:ins i) 0)) (max 1 (or (:outs i) 1))]))
215
+ :params (fn [c] (:params (info c)))
216
+ :receive (fn [{:keys [inlet value data] :as m}]
217
+ (cond
218
+ (:poly (info {:data data})) (receive-poly m)
219
+ (not (zero? inlet)) {}
220
+ (and (vector? value) (or (keyword? (first value)) (string? (first value)))) {:effects [[:param value]]}
221
+ (or (number? value) (sequential? value)) {:effects [[:freqs value]]}
222
+ :else {}))
223
+ :audio {:create create :dispose dispose
224
+ :key (fn [c] [(get-in c [:data :source]) (:status (code/compiled "faust" (get-in c [:data :source])))])
225
+ :effects {:param param! :freqs freqs! :voices voices!}}})