@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.
- package/README.md +9 -2
- package/index.html +1101 -0
- package/kairotic/api.cljs +362 -0
- package/kairotic/assistant.cljs +505 -0
- package/kairotic/backends/gun-backend.js +371 -0
- package/kairotic/canvas.cljs +751 -0
- package/kairotic/code.cljs +108 -0
- package/kairotic/components.cljs +838 -0
- package/kairotic/core.cljs +96 -0
- package/kairotic/corefns.cljs +473 -0
- package/kairotic/docs.mjs +2 -0
- package/kairotic/engine.cljs +482 -0
- package/kairotic/examples.mjs +96 -0
- package/kairotic/faust.cljs +225 -0
- package/kairotic/help.cljs +1036 -0
- package/kairotic/hiccup.cljs +566 -0
- package/kairotic/input.cljs +271 -0
- package/kairotic/kfile.mjs +138 -0
- package/kairotic/library.cljs +214 -0
- package/kairotic/links.cljs +41 -0
- package/kairotic/mt.cljs +1604 -0
- package/kairotic/mtboxes.cljs +276 -0
- package/kairotic/packages/analysis.mjs +64 -0
- package/kairotic/packages/controls.mjs +28 -0
- package/kairotic/packages/data.mjs +22 -0
- package/kairotic/packages/faust-units/cmaes.mjs +82 -0
- package/kairotic/packages/faust-units/graph.mjs +212 -0
- package/kairotic/packages/faust-units/listen.mjs +125 -0
- package/kairotic/packages/faust-units/notation.mjs +139 -0
- package/kairotic/packages/faust-units/parse.mjs +439 -0
- package/kairotic/packages/faust-units/recipe.mjs +195 -0
- package/kairotic/packages/faust-units/render.mjs +69 -0
- package/kairotic/packages/faust-units/units.mjs +130 -0
- package/kairotic/packages/faust-units/view.mjs +353 -0
- package/kairotic/packages/faust-units.mjs +9 -0
- package/kairotic/packages/io.mjs +58 -0
- package/kairotic/packages/net.mjs +28 -0
- package/kairotic/packages/patterns.mjs +34 -0
- package/kairotic/packages/spatial.mjs +22 -0
- package/kairotic/packages/spectral/shift.mjs +169 -0
- package/kairotic/packages/spectral.mjs +16 -0
- package/kairotic/packages/synth.mjs +28 -0
- package/kairotic/packages/theory/counterpoint.mjs +798 -0
- package/kairotic/packages/theory/mirror.mjs +221 -0
- package/kairotic/packages/theory.mjs +46 -0
- package/kairotic/patterns.cljs +538 -0
- package/kairotic/presets.cljs +227 -0
- package/kairotic/quantize.cljs +782 -0
- package/kairotic/record.cljs +169 -0
- package/kairotic/release.cljs +90 -0
- package/kairotic/ring.cljs +129 -0
- package/kairotic/ringaudio.cljs +232 -0
- package/kairotic/ringcore.mjs +270 -0
- package/kairotic/score.cljs +176 -0
- package/kairotic/shapes.cljs +283 -0
- package/kairotic/signal.cljs +327 -0
- package/kairotic/sounds.cljs +565 -0
- package/kairotic/sounds.mjs +108 -0
- package/kairotic/span.cljs +129 -0
- package/kairotic/spell.cljs +281 -0
- package/kairotic/structure.cljs +145 -0
- package/kairotic/talk.cljs +115 -0
- package/kairotic/tempo.cljs +226 -0
- package/kairotic/treecanvas.cljs +299 -0
- package/kairotic/tutorials.mjs +1283 -0
- package/kairotic/vendor/codemirror.mjs +23 -0
- package/package.json +23 -4
- package/page/00-work.cljs +862 -0
- package/page/01-commands.cljs +1219 -0
- package/page/02-patch-view.cljs +1051 -0
- package/page/03-history-view.cljs +481 -0
- package/page/04-panels.cljs +448 -0
- package/page/05-gestures.cljs +1247 -0
- package/page/06-connection.cljs +219 -0
- package/page/07-claude.cljs +430 -0
- package/page/08-sessions.cljs +423 -0
- package/page/09-learn.cljs +602 -0
- package/page/10-embed.cljs +469 -0
- package/page/11-startup.cljs +61 -0
- package/page/12-feedback.cljs +172 -0
- package/page/13-perform.cljs +325 -0
- package/page/14-editor.cljs +656 -0
- package/page/15-presets.cljs +230 -0
- package/page/16-release.cljs +242 -0
- package/page/17-sounds.cljs +147 -0
- package/page/18-lines.cljs +594 -0
- package/page/19-files.cljs +247 -0
- package/page/19-html.cljs +152 -0
- package/page/20-talk.cljs +527 -0
- package/page/21-net.cljs +110 -0
- package/page/22-learn.cljs +303 -0
- package/page/23-ids.cljs +233 -0
- package/page/24-clipboard.cljs +136 -0
- package/page/25-tidy.cljs +74 -0
- package/page/26-probes.cljs +111 -0
- package/sources.mjs +2 -0
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
;; SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
;; Kairotic · api
|
|
3
|
+
;; What a component that does not live in the core may use. Packages (@kairotic/synth, …) and
|
|
4
|
+
;; components written in a work use these functions instead of the core's own modules, so the core
|
|
5
|
+
;; can change inside without breaking them. Inside a component source this namespace is `api`.
|
|
6
|
+
;;
|
|
7
|
+
;; The API has a version: a package declares the one it was written for ({:api 1}). A change that
|
|
8
|
+
;; breaks a function here raises the major version; adding functions does not.
|
|
9
|
+
|
|
10
|
+
(ns kairotic.api
|
|
11
|
+
(:require [clojure.string :as str]
|
|
12
|
+
[clojure.edn :as edn]
|
|
13
|
+
[kairotic.components :as comp]
|
|
14
|
+
[kairotic.canvas :as cv]
|
|
15
|
+
[kairotic.code :as code]
|
|
16
|
+
[kairotic.patterns :as pat]
|
|
17
|
+
[kairotic.structure :as st]))
|
|
18
|
+
|
|
19
|
+
(def version 1)
|
|
20
|
+
|
|
21
|
+
;; ───────── numbers ─────────
|
|
22
|
+
|
|
23
|
+
(defn clamp "x between a and b (in either order)." [x a b] (comp/clamp x a b))
|
|
24
|
+
(defn nice "A value rounded to a sensible precision for display and sending." [v] (comp/nice v))
|
|
25
|
+
(defn num-of "A number from a message: the number itself, or the first of a list (else nil)." [v] (comp/num-of v))
|
|
26
|
+
(defn to-unit "v between lo and hi as 0…1 (logarithmic with log?)." [v lo hi log?] (comp/to-unit v lo hi log?))
|
|
27
|
+
(defn from-unit "0…1 back to lo…hi (logarithmic with log?)." [u lo hi log?] (comp/from-unit u lo hi log?))
|
|
28
|
+
|
|
29
|
+
(defn padded
|
|
30
|
+
"The numbers written in a box text, the missing ones taken from defaults: (padded [20] [10 100]) → [20 100]."
|
|
31
|
+
[args defaults]
|
|
32
|
+
(let [ns (filterv number? args)] (vec (take (count defaults) (concat ns (drop (count ns) defaults))))))
|
|
33
|
+
|
|
34
|
+
;; ───────── audio ─────────
|
|
35
|
+
|
|
36
|
+
(defn stereo-outlets
|
|
37
|
+
"Two outlets (left, right) from a stereo AudioNode: [[splitter 0] [splitter 1]]."
|
|
38
|
+
[ac node]
|
|
39
|
+
(let [sp (.createChannelSplitter ac 2)] (.connect node sp) [[sp 0] [sp 1]]))
|
|
40
|
+
|
|
41
|
+
(defonce worklet-modules (atom {})) ; [AudioContext name] → Promise
|
|
42
|
+
|
|
43
|
+
(defn worklet-ready
|
|
44
|
+
"Promise that resolves when the AudioWorklet code `source` is loaded in `ac` under `name` (once per
|
|
45
|
+
context, whoever asks first). `source` is JavaScript that calls registerProcessor(name, …)."
|
|
46
|
+
[ac name source]
|
|
47
|
+
(let [k [ac name]]
|
|
48
|
+
(or (get @worklet-modules k)
|
|
49
|
+
(let [url (js/URL.createObjectURL (js/Blob. #js [source] #js {:type "application/javascript"}))
|
|
50
|
+
p (.addModule (.-audioWorklet ac) url)]
|
|
51
|
+
(swap! worklet-modules assoc k p)
|
|
52
|
+
p))))
|
|
53
|
+
|
|
54
|
+
(defn worklet-node
|
|
55
|
+
"Promise of an AudioWorkletNode of processor `name` (defined in `source`) with these options."
|
|
56
|
+
[ac name source opts]
|
|
57
|
+
(.then (worklet-ready ac name source)
|
|
58
|
+
(fn [_] (js/AudioWorkletNode. ac name (clj->js opts)))))
|
|
59
|
+
|
|
60
|
+
(defn param "The AudioParam `k` of an AudioWorkletNode." [w k] (.get (.-parameters w) k))
|
|
61
|
+
|
|
62
|
+
;; ───────── from the sound back to the messages ─────────
|
|
63
|
+
;; An audio node cannot send messages itself: it reports what it finds to its own box, whose :receive
|
|
64
|
+
;; gets it on inlet :audio and decides what to send (:out), show (:show) or keep (:state).
|
|
65
|
+
|
|
66
|
+
(defn report!
|
|
67
|
+
"From an audio node: gives box `id` (the :id of the box its :create got) a value found in the sound.
|
|
68
|
+
It arrives at the box's :receive as {:inlet :audio :value value :at at}, at instant `at` (an
|
|
69
|
+
AudioContext time; now if nil). Only while the engine runs."
|
|
70
|
+
[id value at]
|
|
71
|
+
(when-let [f @comp/audio-report] (f id value at)))
|
|
72
|
+
|
|
73
|
+
(defn effect!
|
|
74
|
+
"From an audio node: an effect of box `id` for the page, such as [:sample [:set d]] (keep a recording
|
|
75
|
+
as the data of the box). Unlike report!, it also works when the engine has just stopped."
|
|
76
|
+
[id e]
|
|
77
|
+
(when-let [f @comp/audio-effect] (f id e)))
|
|
78
|
+
|
|
79
|
+
(def tap-source
|
|
80
|
+
"class KairoticTap extends AudioWorkletProcessor {
|
|
81
|
+
// Listens to its input and hands it to the page every `hop` samples, in one of three forms:
|
|
82
|
+
// frames — the last `size` samples of each channel, oldest first
|
|
83
|
+
// summary — for each channel its last sample, its level (rms) and its peak over the last `size`
|
|
84
|
+
// trace — for each channel `columns` pairs [min, max] over `size` samples, starting at the first
|
|
85
|
+
// rising zero crossing of the older half of a ring of 2 × size (a steady picture of a
|
|
86
|
+
// periodic wave; where there is none, the newest `size` samples)
|
|
87
|
+
// with the AudioContext time of the last sample. No output: the input connected to it keeps it
|
|
88
|
+
// running. A message {size, hop, columns} changes them; {active: false} stops handing (true starts again,
|
|
89
|
+
// from the next hop: frames with size = hop then hold only samples heard since); {flush: true} hands at
|
|
90
|
+
// once the samples heard since the last hand-over (frames only), marked last.
|
|
91
|
+
constructor(o) {
|
|
92
|
+
super();
|
|
93
|
+
const p = (o && o.processorOptions) || {};
|
|
94
|
+
this.C = Math.max(1, p.channels | 0 || 1);
|
|
95
|
+
this.mode = p.mode || 'frames';
|
|
96
|
+
this.active = p.active !== false;
|
|
97
|
+
this.columns = Math.max(2, p.columns | 0 || 128);
|
|
98
|
+
this.resize(p.size | 0 || 2048, p.hop | 0 || 1024);
|
|
99
|
+
this.port.onmessage = (e) => {
|
|
100
|
+
const d = e.data || {};
|
|
101
|
+
if (d.columns) this.columns = Math.max(2, Math.min(2000, d.columns | 0));
|
|
102
|
+
if (d.size || d.hop) this.resize(d.size | 0 || this.size, d.hop | 0 || this.hop);
|
|
103
|
+
if (d.flush) {
|
|
104
|
+
const data = [];
|
|
105
|
+
for (let c = 0; c < this.C; c++) data.push(this.ordered(c).slice(this.R - Math.min(this.count, this.R)));
|
|
106
|
+
this.port.postMessage({ data, at: currentTime, sr: sampleRate, last: true }, data.map((x) => x.buffer));
|
|
107
|
+
this.count = 0;
|
|
108
|
+
}
|
|
109
|
+
if (d.active !== undefined) { if (d.active && !this.active) this.count = 0; this.active = !!d.active; }
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
resize(size, hop) {
|
|
113
|
+
this.size = Math.max(16, Math.min(1 << 17, size)); this.hop = Math.max(16, Math.min(1 << 17, hop));
|
|
114
|
+
this.R = this.mode === 'trace' ? 2 * this.size : this.size;
|
|
115
|
+
this.rings = []; for (let c = 0; c < this.C; c++) this.rings.push(new Float32Array(this.R));
|
|
116
|
+
this.w = 0; this.count = 0;
|
|
117
|
+
}
|
|
118
|
+
ordered(c) {
|
|
119
|
+
const r = this.rings[c], f = new Float32Array(this.R);
|
|
120
|
+
f.set(r.subarray(this.w)); f.set(r.subarray(0, this.w), this.R - this.w);
|
|
121
|
+
return f;
|
|
122
|
+
}
|
|
123
|
+
block() {
|
|
124
|
+
const out = [];
|
|
125
|
+
for (let c = 0; c < this.C; c++) {
|
|
126
|
+
if (this.mode === 'summary') {
|
|
127
|
+
const r = this.rings[c], N = this.R; let s = 0, pk = 0;
|
|
128
|
+
for (let i = 0; i < N; i++) { const x = r[i]; s += x * x; const a = x < 0 ? -x : x; if (a > pk) pk = a; }
|
|
129
|
+
out.push([r[(this.w + N - 1) % N], Math.sqrt(s / N), pk]);
|
|
130
|
+
} else if (this.mode === 'trace') {
|
|
131
|
+
const f = this.ordered(c), S = this.size, K = this.columns;
|
|
132
|
+
let t = S;
|
|
133
|
+
for (let i = 1; i < S; i++) if (f[i - 1] <= 0 && f[i] > 0) { t = i; break; }
|
|
134
|
+
const col = new Float32Array(2 * K);
|
|
135
|
+
for (let k = 0; k < K; k++) {
|
|
136
|
+
const a = t + Math.floor(k * S / K), b = Math.max(a + 1, t + Math.floor((k + 1) * S / K));
|
|
137
|
+
let lo = Infinity, hi = -Infinity;
|
|
138
|
+
for (let i = a; i < b && i < f.length; i++) { const x = f[i]; if (x < lo) lo = x; if (x > hi) hi = x; }
|
|
139
|
+
col[2 * k] = lo === Infinity ? 0 : lo; col[2 * k + 1] = hi === -Infinity ? 0 : hi;
|
|
140
|
+
}
|
|
141
|
+
out.push(col);
|
|
142
|
+
} else out.push(this.ordered(c));
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
process(inputs) {
|
|
147
|
+
const inp = inputs[0] || [];
|
|
148
|
+
const n = inp[0] ? inp[0].length : 128;
|
|
149
|
+
for (let i = 0; i < n; i++) {
|
|
150
|
+
for (let c = 0; c < this.C; c++) { const ch = inp[c] || inp[0]; this.rings[c][this.w] = ch ? ch[i] : 0; }
|
|
151
|
+
this.w = (this.w + 1) % this.R;
|
|
152
|
+
if (++this.count >= this.hop) {
|
|
153
|
+
this.count = 0;
|
|
154
|
+
if (!this.active) continue;
|
|
155
|
+
const data = this.block();
|
|
156
|
+
this.port.postMessage({ data, at: currentTime + (i + 1) / sampleRate, sr: sampleRate, last: false },
|
|
157
|
+
data.filter((d) => d instanceof Float32Array).map((d) => d.buffer));
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return true;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
registerProcessor('kairotic-tap', KairoticTap);
|
|
164
|
+
")
|
|
165
|
+
|
|
166
|
+
(defn tap
|
|
167
|
+
"Promise of an AudioWorkletNode that listens to a signal and gives it to the page in blocks; connect
|
|
168
|
+
the signal to it. Every `hop` samples, (on-block data at sr) gets the AudioContext time of the last
|
|
169
|
+
sample, the sample rate and, one entry per channel, according to :mode
|
|
170
|
+
:frames (default) a Float32Array of the last `size` samples, oldest first
|
|
171
|
+
:summary [last rms peak] over the last `size` samples
|
|
172
|
+
:trace a Float32Array of `columns` pairs min, max over `size` samples, from a rising zero
|
|
173
|
+
crossing (a steady oscilloscope picture)
|
|
174
|
+
The loops over samples run in the worklet, so the page only handles small arrays (except :frames).
|
|
175
|
+
(retap w {:size n :hop n :columns n}) changes the sizes while it runs; {:active false} stops handing
|
|
176
|
+
blocks (:active true in the options starts it so) and {:flush true} hands at once, as :frames, what
|
|
177
|
+
was heard since the last block. on-block also gets a fourth argument, {:last true} for that block."
|
|
178
|
+
[ac {:keys [channels size hop mode columns active]} on-block]
|
|
179
|
+
(.then (worklet-node ac "kairotic-tap" tap-source
|
|
180
|
+
{:numberOfInputs 1 :numberOfOutputs 0
|
|
181
|
+
:channelCount (or channels 1) :channelCountMode "explicit" :channelInterpretation "discrete"
|
|
182
|
+
:processorOptions {:channels (or channels 1) :size (or size 2048) :hop (or hop 1024)
|
|
183
|
+
:mode (name (or mode :frames)) :columns (or columns 128)
|
|
184
|
+
:active (not (false? active))}})
|
|
185
|
+
(fn [w]
|
|
186
|
+
(set! (.. w -port -onmessage)
|
|
187
|
+
(fn [e] (let [d (.-data e)]
|
|
188
|
+
(try (on-block (vec (array-seq (.-data d))) (.-at d) (.-sr d) {:last (true? (.-last d))})
|
|
189
|
+
(catch :default ex (js/console.error ex))))))
|
|
190
|
+
w)))
|
|
191
|
+
|
|
192
|
+
(defn untap
|
|
193
|
+
"A tap is done with (the box is gone, or the engine stopped): it stops handing blocks and is disconnected.
|
|
194
|
+
Without it, a tap whose input was disconnected goes on handing silence to its box."
|
|
195
|
+
[w]
|
|
196
|
+
(when w
|
|
197
|
+
(try (set! (.. w -port -onmessage) nil) (.postMessage (.-port w) #js {:active false}) (.disconnect w)
|
|
198
|
+
(catch :default _ nil))))
|
|
199
|
+
|
|
200
|
+
(defn retap "A tap while it runs: new sizes {:size n :hop n :columns n}, {:active bool}, {:flush true}." [w sizes]
|
|
201
|
+
(.postMessage (.-port w) (clj->js sizes)))
|
|
202
|
+
|
|
203
|
+
(defn db "A level (0…1) in decibels, -100 for silence." [x]
|
|
204
|
+
(if (> x 1e-5) (* 20 (/ (js/Math.log x) js/Math.LN10)) -100))
|
|
205
|
+
|
|
206
|
+
;; ───────── pitch ─────────
|
|
207
|
+
|
|
208
|
+
(defn hz->midi "A frequency as a MIDI pitch (fractional: 440 → 69)." [hz] (cv/hz->midi hz))
|
|
209
|
+
(defn midi->hz "A MIDI pitch as a frequency (69 → 440)." [m] (cv/midi->hz m))
|
|
210
|
+
(defn midi-name "The name of a whole MIDI pitch: 60 → \"C4\", 61 → \"C#4\"." [m] (cv/midi-name m))
|
|
211
|
+
(defn pitch-class "The pitch class of a MIDI pitch as a keyword: 61 → :c#." [m]
|
|
212
|
+
(keyword (str/lower-case (nth cv/note-names (mod (js/Math.round m) 12)))))
|
|
213
|
+
|
|
214
|
+
;; ───────── libraries ─────────
|
|
215
|
+
|
|
216
|
+
(defonce scripts (atom {})) ; url → Promise
|
|
217
|
+
|
|
218
|
+
(defn load-script
|
|
219
|
+
"Promise that resolves when the classic script at `url` has run, once per page whoever asks first.
|
|
220
|
+
npm:package@version/path is served by jsDelivr (the only place a page inside claude.ai can load
|
|
221
|
+
code from). For libraries that put a global on window, such as Meyda: (.-Meyda js/window)."
|
|
222
|
+
[url]
|
|
223
|
+
(let [u (if (str/starts-with? url "npm:") (str "https://cdn.jsdelivr.net/npm/" (subs url 4)) url)]
|
|
224
|
+
(or (get @scripts u)
|
|
225
|
+
(let [p (js/Promise.
|
|
226
|
+
(fn [ok fail]
|
|
227
|
+
(let [s (.createElement js/document "script")]
|
|
228
|
+
(set! (.-src s) u)
|
|
229
|
+
(set! (.-async s) true)
|
|
230
|
+
(set! (.-onload s) (fn [_] (ok true)))
|
|
231
|
+
(set! (.-onerror s) (fn [_] (swap! scripts dissoc u) (fail (js/Error. (str "could not load " u)))))
|
|
232
|
+
(.appendChild (.-head js/document) s))))]
|
|
233
|
+
(swap! scripts assoc u p)
|
|
234
|
+
p))))
|
|
235
|
+
|
|
236
|
+
(defonce modules (atom {})) ; [origin …] → Promise
|
|
237
|
+
|
|
238
|
+
(defn import-module
|
|
239
|
+
"Promise of the default export of an ES module, once per page whoever asks first. `origins` is one
|
|
240
|
+
place or a list of them, tried in order until one answers: npm:package@version/path (jsDelivr) or a
|
|
241
|
+
path of this page (kairotic/packages/…, the page's own copy of a package's files). For modules a
|
|
242
|
+
package carries beside its components, such as a WebAssembly wrapped in JavaScript."
|
|
243
|
+
[origins]
|
|
244
|
+
(let [os (if (string? origins) [origins] (vec origins))]
|
|
245
|
+
(or (get @modules os)
|
|
246
|
+
(let [imp (.-kairoticImport js/window)
|
|
247
|
+
go (fn go [[o & more] errors]
|
|
248
|
+
(if-not o
|
|
249
|
+
(js/Promise.reject (js/Error. (str "could not load " (str/join " nor " os) " (" (str/join "; " errors) ")")))
|
|
250
|
+
(.catch (imp (if (str/starts-with? o "npm:") (str "https://cdn.jsdelivr.net/npm/" (subs o 4)) o))
|
|
251
|
+
(fn [e] (go more (conj errors (str (or (.-message e) e))))))))
|
|
252
|
+
p (.catch (go os [])
|
|
253
|
+
(fn [e] (swap! modules dissoc os) (throw e)))]
|
|
254
|
+
(swap! modules assoc os p)
|
|
255
|
+
p))))
|
|
256
|
+
|
|
257
|
+
;; ───────── the network (for :tasks) ─────────
|
|
258
|
+
;; A component never fetches from its :receive: it asks for a task (:tasks), and these help the task.
|
|
259
|
+
|
|
260
|
+
(defn url-of
|
|
261
|
+
"A URL from a message: a string, or a word as a msg box sends it (msg https://… arrives as a name).
|
|
262
|
+
github:owner/repo@ref/path is served by jsDelivr (@main without @ref), the one site a page inside
|
|
263
|
+
claude.ai can read. nil if it is not a URL."
|
|
264
|
+
[v]
|
|
265
|
+
(let [s (cond (string? v) v (symbol? v) (str v) (keyword? v) (subs (str v) 1) :else nil)
|
|
266
|
+
s (some-> s str/trim (str/replace #"^\"|\"$" ""))
|
|
267
|
+
gh (when s (re-matches #"github:([^/\s]+)/([^/@\s]+)(@[^/\s]+)?/(\S+)" s))]
|
|
268
|
+
(cond (nil? s) nil
|
|
269
|
+
(re-matches #"https?://\S+" s) s
|
|
270
|
+
gh (let [[_ owner repo ref path] gh]
|
|
271
|
+
(str "https://cdn.jsdelivr.net/gh/" owner "/" repo (or ref "@main") "/" path))
|
|
272
|
+
:else nil)))
|
|
273
|
+
|
|
274
|
+
(defn- readable-key
|
|
275
|
+
"A key of a JSON object as EDN: a keyword when it can be written and read back as one, else the string."
|
|
276
|
+
[k]
|
|
277
|
+
(if (and (string? k) (re-matches #"[A-Za-z*+!_?<>=][A-Za-z0-9*+!_?<>=.\-]*" k)) (keyword k) k))
|
|
278
|
+
|
|
279
|
+
(defn json->edn
|
|
280
|
+
"Parsed JSON (js->clj) as EDN that can be written and read back: the keys of objects become keywords
|
|
281
|
+
where they can (\"name\" → :name; \"2024\" and \"a b\" stay strings)."
|
|
282
|
+
[x]
|
|
283
|
+
(cond (map? x) (into {} (map (fn [[k v]] [(readable-key k) (json->edn v)])) x)
|
|
284
|
+
(vector? x) (mapv json->edn x)
|
|
285
|
+
:else x))
|
|
286
|
+
|
|
287
|
+
(defn http-get
|
|
288
|
+
"Promise of what is at `url` (https://…, or github:owner/repo@ref/path): with {:as :json} (the default)
|
|
289
|
+
parsed into EDN (json->edn), :text as a string, :edn read as EDN. It fails with a reason in words when
|
|
290
|
+
the site refuses this page (CORS) or cannot be reached, answers an error, takes longer than :timeout
|
|
291
|
+
seconds (20) or sends more than :max characters (1000000)."
|
|
292
|
+
([url] (http-get url {}))
|
|
293
|
+
([url {:keys [as timeout max] :or {as :json timeout 20 max 1000000}}]
|
|
294
|
+
(if-let [u (url-of url)]
|
|
295
|
+
(let [ctl (js/AbortController.)
|
|
296
|
+
timer (js/setTimeout (fn [] (.abort ctl)) (* 1000 timeout))]
|
|
297
|
+
(-> (js/fetch u #js {:signal (.-signal ctl)})
|
|
298
|
+
(.then (fn [r]
|
|
299
|
+
(if (.-ok r)
|
|
300
|
+
(.text r)
|
|
301
|
+
(throw (js/Error. (str "the site answered " (.-status r) (when (= 404 (.-status r)) " (not found)")))))))
|
|
302
|
+
(.then (fn [text]
|
|
303
|
+
(when (> (count text) max)
|
|
304
|
+
(throw (js/Error. (str "too long: " (count text) " characters (" max " at most)"))))
|
|
305
|
+
(case as
|
|
306
|
+
:text text
|
|
307
|
+
:edn (edn/read-string text)
|
|
308
|
+
(json->edn (js->clj (js/JSON.parse text))))))
|
|
309
|
+
(.catch (fn [e]
|
|
310
|
+
(throw (cond (= "AbortError" (.-name e)) (js/Error. (str "no answer in " timeout " s"))
|
|
311
|
+
;; fetch itself fails (a TypeError) when the site refuses the page or cannot be reached
|
|
312
|
+
(instance? js/TypeError e) (js/Error. "the site does not let this page read it (CORS), or cannot be reached")
|
|
313
|
+
(instance? js/SyntaxError e) (js/Error. (str "not " (name as) ": " (.-message e)))
|
|
314
|
+
:else e))))
|
|
315
|
+
(.finally (fn [] (js/clearTimeout timer)))))
|
|
316
|
+
(js/Promise.reject (js/Error. (str (pr-str url) " is not a URL (https://… or github:owner/repo/path)"))))))
|
|
317
|
+
|
|
318
|
+
;; ───────── code boxes ─────────
|
|
319
|
+
;; A component whose data is a source text in some language (:display :code :language "…" :model
|
|
320
|
+
;; api/code-model): each tab compiles the source with the compiler registered for that language.
|
|
321
|
+
|
|
322
|
+
(def code-model "The model of a code box: its data is {:source \"…\"}, with its own history." code/model)
|
|
323
|
+
|
|
324
|
+
(defn compiled
|
|
325
|
+
"The compilation of a source in a language: {:status :ok :value x :info {…}}, {:status :compiling},
|
|
326
|
+
{:status :error :error \"…\"} or {:status :empty}. Asked again when it is done (the page is told)."
|
|
327
|
+
[language source]
|
|
328
|
+
(code/compiled language source))
|
|
329
|
+
|
|
330
|
+
;; ───────── patterns (kairotic.patterns, for @kairotic/patterns) ─────────
|
|
331
|
+
;; A pattern value is a factory of streams: lazy seqs of event maps ({:degree 2 :dur 1/2}). It travels
|
|
332
|
+
;; along lines; the sequences are made in each tab, from a source and a seed.
|
|
333
|
+
|
|
334
|
+
(defn pattern? "Is x a pattern value?" [x] (pat/pattern? x))
|
|
335
|
+
(defn pattern-events "A new stream of a pattern: a lazy, perhaps endless, seq of event maps." [p] (pat/events p))
|
|
336
|
+
(defn pbind-pattern "The pattern of a pbind map, with {:seed n :repeat n|:inf}." [m opts] (pat/pbind-pattern m opts))
|
|
337
|
+
(defn code-pattern "The pattern of a compiled \"pattern\" source, with {:seed :repeat :source}." [f opts] (pat/code-pattern f opts))
|
|
338
|
+
(defn read-pbind "The text of a pbind as a map (#pat/… as generators); throws when it does not read." [source] (pat/read-spec source))
|
|
339
|
+
(defn pbind-problems "What is wrong with a pbind map: a list of reasons, empty if nothing." [m] (pat/problems m))
|
|
340
|
+
(defn pbind-source "A pbind map written back as the text of its box." [m] (pat/spec->source m))
|
|
341
|
+
(defn event-dur "The length of an event in beats (:dur, 1 if none)." [e] (pat/dur-of e))
|
|
342
|
+
(defn event-sustain "How long the notes of an event sound, in beats (:sustain, or :dur × :legato 0.8)." [e] (pat/sustain e))
|
|
343
|
+
(defn event-hz "The frequencies an event plays (a vector of Hz), [] for a rest, nil if it has no pitch." [e] (pat/hz e))
|
|
344
|
+
(defn rest-event? "Is the event a silence?" [e] (pat/rest? e))
|
|
345
|
+
(defn render-tree
|
|
346
|
+
"A stretch of a pattern as a musical tree, through time maps ({:from :to}, or {:maps [[[x y] …] …]}: x the
|
|
347
|
+
beats of the result, y those of the pattern), :tex / :tone the keys drawn as texture and colour."
|
|
348
|
+
[p opts] (pat/render-tree p opts))
|
|
349
|
+
(defn canvas-maps
|
|
350
|
+
"The strokes of a canvas, in order, as time maps for render-tree: [[[x y] …] …]."
|
|
351
|
+
[d] (mapv (fn [[_ s]] (:pts s)) (cv/sorted-strokes d)))
|
|
352
|
+
|
|
353
|
+
;; ───────── form: how alike the moments are (kairotic.structure, issue #120) ─────────
|
|
354
|
+
|
|
355
|
+
(defn ssm "The self-similarity matrix of frames (vectors of one length): {:n :data}, the cosine of every two." [vs] (st/ssm vs))
|
|
356
|
+
(defn ssm-at "The similarity of frames i and j in a matrix of ssm." [S i j] (st/at S i j))
|
|
357
|
+
(defn novelty "How much the music changes at each frame (a checkerboard of half-width L frames), scaled to 0 … 1." [S L] (st/novelty S L))
|
|
358
|
+
(defn novelty-at "The novelty of frame i alone, -1 … 1 (nil without L frames on either side): for a stream." [S L i] (st/novelty-at S L i))
|
|
359
|
+
(defn beat-spectrum "How alike frames are at each lag 0 … max-lag: its peaks are the periods that repeat." [S max-lag] (st/beat-spectrum S max-lag))
|
|
360
|
+
(defn periods "The peaks of a beat spectrum, strongest first: [[lag value] …]." [bs] (st/periods bs))
|
|
361
|
+
(defn boundaries "Where segments begin, from a novelty curve: {:shortest 8 :longest 64 :k 0.5} (frames)." [nov opts] (st/boundaries nov opts))
|
|
362
|
+
(defn note-frames "Notes ({:on :off :attrs {:pitch :vel}}) as one vector per frame between the times given." [notes times] (st/note-frames notes times))
|