@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,69 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // @kairotic/faust-units · a faust~ played offline: compiled code (its WebAssembly and its JSON) rendered to
3
+ // samples (discussion #114, Study 35).
4
+ //
5
+ // The DSP's own interface does the work (init, setParamValue, compute), with the dsp at the start of its
6
+ // memory as Faust lays it out (its size in the JSON); its imports (the maths it calls: _powf, _tanhf…) are
7
+ // read from the module itself, so the same code runs whatever version of libfaust compiled it. A `gate`
8
+ // button, if the code has one, is held for the first `gate` seconds, as a note is played.
9
+ //
10
+ // const render = renderer(moduleOrBytes, json); render({ cutoff: 900 }, { dur: 1, gate: 0.65 }) → Float32Array
11
+ const MATH = {
12
+ fmod: (a, b) => a % b, remainder: (a, b) => a - Math.round(a / b) * b, rint: Math.round, round: Math.round,
13
+ isnan: (x) => (Number.isNaN(x) ? 1 : 0), isinf: (x) => (Number.isFinite(x) || Number.isNaN(x) ? 0 : 1),
14
+ copysign: (a, b) => Math.sign(b || 1) * Math.abs(a), exp10: (x) => Math.pow(10, x), log10: Math.log10
15
+ };
16
+ function imports(module) {
17
+ const env = {};
18
+ for (const imp of WebAssembly.Module.imports(module)) {
19
+ if (imp.kind === "function") {
20
+ const n = imp.name.replace(/^_+/, "").replace(/f$/, "");
21
+ env[imp.name] = MATH[n] || Math[n] || Math[imp.name.replace(/^_+/, "")] || (() => 0);
22
+ } else if (imp.kind === "global") env[imp.name] = new WebAssembly.Global({ value: "i32", mutable: false }, 0);
23
+ else if (imp.kind === "memory") env[imp.name] = new WebAssembly.Memory({ initial: 16 });
24
+ else if (imp.kind === "table") env[imp.name] = new WebAssembly.Table({ initial: 0, element: "anyfunc" });
25
+ }
26
+ return { env };
27
+ }
28
+
29
+ // the controls of a faust~ as the search sees them: sliders (with their scale) and buttons
30
+ export function controls(json) {
31
+ const walk = (xs) => xs.flatMap((i) => (i.items ? walk(i.items) : [i]));
32
+ return walk(json.ui || []).map((i) => {
33
+ const meta = Object.assign({}, ...(i.meta || []));
34
+ return { type: i.type, label: i.label, address: i.address, index: i.index, init: +i.init || 0, min: +i.min || 0, max: +(i.max ?? 1),
35
+ step: +i.step || 0, scale: meta.scale || "lin", unit: meta.unit || "" };
36
+ });
37
+ }
38
+
39
+ // a renderer for one compiled DSP: render(values, { dur, gate, sr }) → Float32Array (its first output)
40
+ export function renderer(code, json, { sr = 44100, block = 256 } = {}) {
41
+ const module = code instanceof WebAssembly.Module ? code : new WebAssembly.Module(code);
42
+ const ctl = controls(json), gateCtl = ctl.find((c) => c.type === "button" && /^gate$/i.test(c.label));
43
+ return function render(values = {}, { dur = 1.0, gate = 0.65 } = {}) {
44
+ const ex = new WebAssembly.Instance(module, imports(module)).exports, mem = ex.memory;
45
+ const ni = json.inputs, no = Math.max(1, json.outputs), n = Math.round(dur * sr);
46
+ let p = (json.size + 64 + 15) & ~15;
47
+ const ptrIns = p; p += 4 * Math.max(1, ni);
48
+ const ptrOuts = p; p += 4 * no; p = (p + 15) & ~15;
49
+ const need = p + (ni + no) * block * 4 + 1024;
50
+ if (mem.buffer.byteLength < need) mem.grow(Math.ceil((need - mem.buffer.byteLength) / 65536));
51
+ const view = () => new DataView(mem.buffer);
52
+ const bufs = [];
53
+ for (let i = 0; i < ni; i++) { view().setInt32(ptrIns + 4 * i, p, true); p += block * 4; } // inputs stay silent
54
+ for (let i = 0; i < no; i++) { view().setInt32(ptrOuts + 4 * i, p, true); bufs.push(p); p += block * 4; }
55
+ ex.init(0, sr);
56
+ for (const c of ctl) if (c.label in values && c.type !== "button") ex.setParamValue(0, c.index, values[c.label]);
57
+ const y = new Float32Array(n), gateAt = Math.round(gate * sr);
58
+ if (gateCtl) ex.setParamValue(0, gateCtl.index, 1);
59
+ for (let at = 0; at < n; at += block) {
60
+ // the gate is released at its time (to the nearest block)
61
+ if (gateCtl && at >= gateAt && at - block < gateAt) ex.setParamValue(0, gateCtl.index, 0);
62
+ const k = Math.min(block, n - at);
63
+ ex.compute(0, k, ptrIns, ptrOuts);
64
+ y.set(new Float32Array(mem.buffer, bufs[0], k), at);
65
+ }
66
+ for (let i = 0; i < n; i++) if (!Number.isFinite(y[i])) y[i] = 0;
67
+ return y;
68
+ };
69
+ }
@@ -0,0 +1,130 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // @kairotic/faust-units · the boxes of @kairotic/faust-units: Faust's own vocabulary, one box per element.
3
+ //
4
+ // Every unit has slots, in the order Faust takes them:
5
+ // "in" a signal input of the block (only library functions have these: the x of x : fi.lowpass(2, fc))
6
+ // "sig" a parameter that can be a signal: an inlet, or a number written after the box's name
7
+ // "const" a parameter that must be a number known when compiling (the order N of a filter)
8
+ // The inlets of a box are its "in" and "sig" slots, in order. Numbers written after its name fill
9
+ // slots the way Faust fills them when the unit is called with arguments:
10
+ // prim: from the end, as a partial application (`+ 0.5` is +(0.5), the right inlet)
11
+ // lib: the parameters in order (`fi.lowpass 2 1000` is fi.lowpass(2, 1000)); the "in" slots stay inlets
12
+ // An inlet that is wired takes the signal; otherwise the number written for it; otherwise its default.
13
+
14
+ const S = (name, def = 0, kind = "sig") => ({ name, def, kind });
15
+
16
+ // how a unit becomes Faust, given the text of each slot (already a name or a number)
17
+ const infix = (op) => (v) => `(${v[0]} ${op} ${v[1]})`;
18
+ const call = (f) => (v) => `${f}(${v.join(", ")})`;
19
+
20
+ export const UNITS = {};
21
+ function unit(name, spec) { UNITS[name] = { name, outs: 1, ...spec }; }
22
+
23
+ // ── primitives ──
24
+ for (const [op, base, doc] of [["+", "add", "sum"], ["-", "sub", "difference"], ["*", "mul", "product"],
25
+ ["/", "div", "quotient"], ["%", "mod", "remainder"], ["^", "pow", "power"],
26
+ ["<", "lt", "1 if less, else 0"], [">", "gt", "1 if greater, else 0"]]) {
27
+ unit(op, { kind: "prim", base, doc, slots: [S("a"), S("b", op === "*" || op === "/" || op === "^" ? 1 : 0)], code: infix(op), infix: op });
28
+ }
29
+ for (const f of ["min", "max"]) unit(f, { kind: "prim", base: f + "_", doc: f + " of two signals", slots: [S("a"), S("b")], code: call(f) });
30
+ for (const [f, doc] of [["sin", "sine (radians)"], ["cos", "cosine (radians)"], ["tanh", "hyperbolic tangent: a soft clip"],
31
+ ["abs", "absolute value"], ["sqrt", "square root"], ["exp", "e to the power"], ["log", "natural logarithm"], ["floor", "round down"]]) {
32
+ unit(f, { kind: "prim", base: f + "_", doc, slots: [S("x")], code: call(f) });
33
+ }
34
+ unit("select2", { kind: "prim", base: "sel", doc: "a if s is 0, b if s is 1", slots: [S("s"), S("a"), S("b")], code: call("select2") });
35
+ // the one-sample delay: the only box a loop may go through (as gen~'s history)
36
+ unit("'", { kind: "prim", base: "z", doc: "one-sample delay: the box a feedback loop goes through", slots: [S("x")], code: (v) => `${v[0]}'`, mem: true });
37
+ unit("@", { kind: "prim", base: "del", doc: "delay by n samples", slots: [S("x"), S("n", 1)], code: infix("@"), infix: "@" });
38
+
39
+ // ── constants, inputs and outputs of the subpatch ──
40
+ unit("num", { kind: "num", base: "k", doc: "a number", slots: [], code: () => "0" });
41
+ unit("in", { kind: "io", base: "x", doc: "an audio input of the faust~ box: in 1, in 2…", slots: [], code: () => "_" });
42
+ unit("out", { kind: "io", base: "y", doc: "an audio output of the faust~ box: out 1, out 2…", slots: [S("x")], outs: 0, code: (v) => v[0] });
43
+ unit("ma.SR", { kind: "lib", base: "sr", doc: "the sample rate", slots: [], code: () => "ma.SR" });
44
+ unit("ma.PI", { kind: "lib", base: "pi", doc: "π", slots: [], code: () => "ma.PI" });
45
+
46
+ // ── controls: they become parameters of the faust~ box (and its knobs) ──
47
+ const q = (s) => JSON.stringify(String(s));
48
+ unit("hslider", { kind: "ui", base: "slider", doc: "a parameter: hslider name init min max step", ui: ["label", "init", "min", "max", "step"],
49
+ defs: ["p", 0, 0, 1, 0.01], slots: [], code: (v, a) => `hslider(${q(a[0])}, ${a.slice(1).join(", ")})` });
50
+ unit("nentry", { kind: "ui", base: "entry", doc: "a numeric parameter: nentry name init min max step", ui: ["label", "init", "min", "max", "step"],
51
+ defs: ["n", 0, 0, 1, 1], slots: [], code: (v, a) => `nentry(${q(a[0])}, ${a.slice(1).join(", ")})` });
52
+ unit("button", { kind: "ui", base: "button", doc: "1 while pressed: button name", ui: ["label"], defs: ["gate"], slots: [], code: (v, a) => `button(${q(a[0])})` });
53
+ unit("checkbox", { kind: "ui", base: "check", doc: "0 or 1: checkbox name", ui: ["label"], defs: ["on"], slots: [], code: (v, a) => `checkbox(${q(a[0])})` });
54
+
55
+ // ── library functions: called by name, never expanded ──
56
+ function lib(name, base, doc, slots) {
57
+ const ins = slots.filter((s) => s.kind === "in"), params = slots.filter((s) => s.kind !== "in");
58
+ unit(name, {
59
+ kind: "lib", base, doc, slots,
60
+ code: (v) => {
61
+ const pv = [], iv = [];
62
+ slots.forEach((s, i) => (s.kind === "in" ? iv : pv).push(v[i]));
63
+ const f = params.length ? `${name}(${pv.join(", ")})` : name;
64
+ return ins.length ? `(${iv.join(", ")} : ${f})` : f;
65
+ }
66
+ });
67
+ }
68
+ lib("os.osc", "osc", "sine oscillator", [S("freq", 440)]);
69
+ lib("os.sawtooth", "saw", "sawtooth oscillator (band-limited)", [S("freq", 440)]);
70
+ lib("os.square", "square", "square oscillator (band-limited)", [S("freq", 440)]);
71
+ lib("os.triangle", "tri", "triangle oscillator (band-limited)", [S("freq", 440)]);
72
+ lib("no.noise", "noise", "white noise", []);
73
+ lib("fi.lowpass", "lowpass", "Butterworth lowpass of order N", [S("x", 0, "in"), S("N", 2, "const"), S("fc", 1000)]);
74
+ lib("fi.highpass", "highpass", "Butterworth highpass of order N", [S("x", 0, "in"), S("N", 2, "const"), S("fc", 1000)]);
75
+ lib("fi.resonlp", "resonlp", "resonant lowpass: fc, Q, gain", [S("x", 0, "in"), S("fc", 1000), S("Q", 1), S("gain", 1)]);
76
+ lib("en.adsr", "adsr", "ADSR envelope: attack, decay (s), sustain (0–1), release (s), gate", [S("a", 0.01), S("d", 0.1), S("s", 0.8), S("r", 0.2), S("gate", 0)]);
77
+ lib("en.ar", "ar", "attack-release envelope: attack, release (s), gate", [S("a", 0.01), S("r", 0.2), S("gate", 0)]);
78
+ lib("ba.db2linear", "db2lin", "decibels → gain", [S("x", 0, "in")]);
79
+ lib("ba.midikey2hz", "key2hz", "MIDI key → Hz", [S("x", 0, "in")]);
80
+ lib("si.smoo", "smoo", "smooths a control signal", [S("x", 0, "in")]);
81
+ lib("de.delay", "delay", "delay of d samples, at most maxd", [S("x", 0, "in"), S("maxd", 65536, "const"), S("d", 0)]);
82
+
83
+ // a box whose text is not in the vocabulary is a Faust expression, kept as it is (opaque)
84
+ export const CODE = { name: "faust", kind: "code", base: "code", doc: "Faust code kept as it is", slots: [] };
85
+
86
+ export function unitOf(box) { return box.type === "faust" ? CODE : UNITS[box.type]; }
87
+
88
+ // the inlets of a box, as slot indices
89
+ export function inletSlots(u) { return u.slots.map((s, i) => [s, i]).filter(([s]) => s.kind !== "const").map(([, i]) => i); }
90
+
91
+ // box text → {type, args}; args are numbers, or strings for controls' labels
92
+ export function tokens(text) {
93
+ const out = [], re = /"((?:[^"\\]|\\.)*)"|(\S+)/g;
94
+ let m;
95
+ while ((m = re.exec(text))) out.push(m[1] !== undefined ? { str: m[1] } : { tok: m[2] });
96
+ return out;
97
+ }
98
+ export function readBox(text) {
99
+ const t = String(text).trim();
100
+ if (/^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i.test(t)) return { type: "num", args: [+t] };
101
+ const ts = tokens(t);
102
+ if (!ts.length) return null;
103
+ const head = ts[0].tok;
104
+ const u = head && UNITS[head];
105
+ if (u && u.kind !== "num") {
106
+ const rest = ts.slice(1);
107
+ if (u.kind === "ui") {
108
+ const args = u.defs.map((d, i) => {
109
+ const r = rest[i];
110
+ if (!r) return d;
111
+ if (i === 0) return r.str !== undefined ? r.str : r.tok;
112
+ return isFinite(+r.tok) ? +r.tok : d;
113
+ });
114
+ return { type: head, args };
115
+ }
116
+ if (rest.every((r) => r.tok !== undefined && isFinite(+r.tok))) {
117
+ const n = u.kind === "io" ? 1 : u.slots.filter((s) => s.kind !== "in").length;
118
+ if (rest.length <= Math.max(n, u.kind === "io" ? 1 : 0)) return { type: head, args: rest.map((r) => +r.tok) };
119
+ }
120
+ }
121
+ return { type: "faust", args: [t] };
122
+ }
123
+ export function boxText(box) {
124
+ const u = unitOf(box);
125
+ if (box.type === "num") return fmt(box.args[0]);
126
+ if (box.type === "faust") return box.args[0];
127
+ if (u.kind === "ui") return [box.type].concat(box.args.map((a, i) => (i === 0 ? (/[\s"]/.test(a) || a === "" ? JSON.stringify(a) : a) : fmt(a)))).join(" ");
128
+ return [box.type].concat((box.args || []).map(fmt)).join(" ");
129
+ }
130
+ export function fmt(x) { return typeof x === "number" ? String(+x.toPrecision(6)) : String(x); }
@@ -0,0 +1,353 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // @kairotic/faust-units · the patch view of a faust~ box (discussion #115, Study 31).
3
+ //
4
+ // A pane that shows Faust code as a patch of unit boxes and edits it: moving a box, wiring an outlet to
5
+ // an inlet, writing a box (a name, a number or any Faust expression), Delete. Every edit of the patch
6
+ // gives new code (onCode); new code given to it (setCode) redraws the patch. The code is what the box
7
+ // keeps; this is a view of it, so the page decides when code is applied.
8
+ //
9
+ // const v = mount(host, { code, onCode: (code) => …, loadFaust: () => Promise<{F, compiler}> });
10
+ // v.setCode(code) // the code was written elsewhere (the editor beside it)
11
+ // v.destroy()
12
+
13
+ import { UNITS, readBox, boxText, unitOf } from "./units.mjs";
14
+ import { toFaust, inlets, outlets, newBox, name } from "./graph.mjs";
15
+ import { toGraphAsync } from "./parse.mjs";
16
+
17
+ const CSS = `
18
+ .fu { display: flex; flex-direction: column; height: 100%; min-height: 0; background: var(--sheet); }
19
+ .fu-canvas { position: relative; flex: 1; min-height: 0; overflow: auto; touch-action: none; outline: none; }
20
+ .fu-canvas:focus-visible { box-shadow: inset 0 0 0 2px var(--accent); }
21
+ .fu-canvas.stale svg { opacity: 0.35; }
22
+ .fu-canvas svg { display: block; }
23
+ .fu .b rect.body { fill: var(--box); stroke: var(--ink); stroke-width: 1; }
24
+ .fu .b.io rect.body { stroke: var(--accent); stroke-width: 1.5; }
25
+ .fu .b.ui rect.body { fill: color-mix(in srgb, var(--kairos) 10%, var(--box)); stroke: var(--kairos); }
26
+ .fu .b.mem rect.body { fill: var(--accent-soft); stroke: var(--accent); }
27
+ .fu .b.code rect.body { stroke-dasharray: 4 3; }
28
+ .fu .b.sel rect.body { stroke: var(--accent); stroke-width: 2; fill: color-mix(in srgb, var(--accent) 12%, var(--box)); }
29
+ .fu .b text { font: 12.5px var(--f-code); fill: var(--ink); pointer-events: none; }
30
+ .fu .b { cursor: grab; }
31
+ /* patching, as in the patch (app/index.html): curved wires; an outlet within reach lights up and the pointer
32
+ is a cross; the inlet a wire would land on too */
33
+ .fu .port { fill: var(--ink); stroke: none; transform-box: fill-box; transform-origin: center; transition: transform 0.08s ease-out, fill 0.08s; }
34
+ .fu .b.ui .port { fill: var(--kairos); }
35
+ .fu .port.out { cursor: crosshair; }
36
+ .fu .port.out.hot, .fu .port.in.target { fill: var(--accent); transform: scale(1.4, 2); }
37
+ .fu-canvas.near-out, .fu-canvas.near-out *, .fu-canvas.wiring, .fu-canvas.wiring * { cursor: crosshair !important; }
38
+ .fu .wire { fill: none; stroke: var(--ink); stroke-width: 1.5; }
39
+ .fu .wire.sel { stroke: var(--accent); stroke-width: 2.5; }
40
+ .fu .wire-hit { fill: none; stroke: transparent; stroke-width: 12; cursor: pointer; }
41
+ .fu .wire.temp { stroke: var(--accent); stroke-dasharray: 4 4; pointer-events: none; }
42
+ .fu-editor { position: absolute; font: 12px var(--f-code); padding: 3px 5px; border: 1.5px solid var(--accent); border-radius: 3px;
43
+ background: var(--box); color: var(--ink); min-width: 160px; z-index: 2; }
44
+ /* two lines that never wrap: the paper above keeps its size whatever they say (the whole text is their title) */
45
+ .fu-foot { flex: none; padding: 4px 10px; border-top: 1px solid var(--rule); font: 11.5px/1.45 var(--f-code); color: var(--ink-soft); }
46
+ .fu-foot > div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
47
+ .fu-foot b { color: var(--ink); font-weight: 500; }
48
+ .fu-foot .ok { color: var(--ok); } .fu-foot .bad { color: var(--error); } .fu-foot .warn { color: var(--kairos); }
49
+ `;
50
+
51
+ function style() {
52
+ if (document.getElementById("faust-units-css")) return;
53
+ const s = document.createElement("style");
54
+ s.id = "faust-units-css";
55
+ s.textContent = CSS;
56
+ document.head.appendChild(s);
57
+ }
58
+ function names() {
59
+ if (document.getElementById("faust-units-names")) return;
60
+ const d = document.createElement("datalist");
61
+ d.id = "faust-units-names";
62
+ d.innerHTML = Object.keys(UNITS).filter((n) => n !== "num").map((n) => `<option value="${esc(n)}">${esc(UNITS[n].doc)}</option>`).join("");
63
+ document.body.appendChild(d);
64
+ }
65
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
66
+ const NS = "http://www.w3.org/2000/svg";
67
+ function el(tag, attrs, parent) { const e = document.createElementNS(NS, tag); for (const k in attrs) e.setAttribute(k, attrs[k]); if (parent) parent.appendChild(e); return e; }
68
+
69
+ export function mount(host, { code = "", onCode = () => {}, loadFaust } = {}) {
70
+ style(); names();
71
+ host.innerHTML = `<div class="fu"><div class="fu-canvas" tabindex="0" aria-label="The patch of this faust~ box: boxes and wires. Double-click to add a box."><svg xmlns="${NS}"></svg></div>
72
+ <div class="fu-foot"><div class="fu-sync"></div><div class="fu-info"></div></div></div>`;
73
+ const canvas = host.querySelector(".fu-canvas"), svg = host.querySelector("svg");
74
+ const syncEl = host.querySelector(".fu-sync"), infoEl = host.querySelector(".fu-info");
75
+ let graph = { boxes: [], wires: [] }, sel = null, emitted = null, current = code, alive = true;
76
+
77
+ // how many inputs and outputs a piece of Faust code has, asked of the compiler
78
+ const arity = new Map();
79
+ async function arityOf(text) {
80
+ if (arity.has(text)) return arity.get(text);
81
+ let a = null;
82
+ try {
83
+ const fx = await loadFaust();
84
+ const gen = new fx.F.FaustMonoDspGenerator();
85
+ const g = await gen.compile(fx.compiler, "fu" + (arity.size + 1), 'import("stdfaust.lib");\nprocess = ' + text + ";\n", "-ftz 2");
86
+ if (g) { const j = JSON.parse(gen.factory.json); a = { ins: j.inputs, outs: j.outputs }; }
87
+ } catch (_) { a = null; }
88
+ arity.set(text, a);
89
+ return a;
90
+ }
91
+
92
+ const sync = (kind, text) => { syncEl.innerHTML = `<span class="${kind}">${kind === "ok" ? "✓" : kind === "bad" ? "✗" : "⚠"}</span> ${esc(text)}`; syncEl.title = text; };
93
+
94
+ // ── patch → code ──
95
+ function changed() {
96
+ try {
97
+ const c = toFaust(graph);
98
+ emitted = c; current = c;
99
+ canvas.classList.remove("stale");
100
+ sync("ok", "the patch wrote the code: apply it to hear it");
101
+ onCode(c);
102
+ } catch (e) { sync("bad", e.message); }
103
+ render(); info(); reveal();
104
+ }
105
+ // ── code → patch ──
106
+ let timer = 0, seq = 0;
107
+ async function read(c) {
108
+ const my = ++seq;
109
+ // code the boxes do not know is asked of the compiler, which can take a moment the first time
110
+ const slow = setTimeout(() => { if (my === seq) sync("ok", "reading the code…"); }, 300);
111
+ try {
112
+ const g = await toGraphAsync(c, arityOf, arity);
113
+ if (!alive || my !== seq) return;
114
+ graph = g; sel = null;
115
+ canvas.classList.remove("stale");
116
+ sync("ok", "the patch is the code");
117
+ } catch (e) {
118
+ if (!alive || my !== seq) return;
119
+ canvas.classList.add("stale");
120
+ sync("warn", "outside what the boxes can show: " + e.message + " — the code still compiles and plays");
121
+ }
122
+ clearTimeout(slow);
123
+ render(); info();
124
+ }
125
+ function setCode(c) {
126
+ c = String(c || "");
127
+ if (c === emitted || c === current) return;
128
+ current = c;
129
+ clearTimeout(timer);
130
+ timer = setTimeout(() => read(c), 400);
131
+ }
132
+
133
+ // ── drawing ──
134
+ // the patch's measures (app/page/02-patch-view.cljs: box-h, box-w, pw, port-x)
135
+ const H = 24, PORT = 10, REACH = 10;
136
+ const width = (b) => Math.max(56, 20 + 7.6 * boxText(b).length, Math.max(inlets(b), outlets(b)) * 18);
137
+ const portX = (b, i, n) => (n <= 1 ? b.x : b.x + (width(b) - PORT) * (i / (n - 1)));
138
+ // the patch's curve (wire-d): down from an outlet, into an inlet from above; back up, it loops out
139
+ const r1 = (v) => Math.round(v * 10) / 10;
140
+ function wireD(x1, y1, x2, y2) {
141
+ const dy = y2 - y1, k = dy >= 24 ? Math.max(16, 0.45 * dy) : 36 + Math.min(70, 0.25 * Math.abs(x2 - x1));
142
+ return `M${r1(x1)},${r1(y1)} C${r1(x1)},${r1(y1 + k)} ${r1(x2)},${r1(y2 - k)} ${r1(x2)},${r1(y2)}`;
143
+ }
144
+ // the outlet ("out") or inlet ("in") nearest to p within reach, as the patch's port-near: [id, k] or null
145
+ function portNear(kind, p, skip) {
146
+ let best = null;
147
+ for (const b of graph.boxes) {
148
+ if (b.id === skip) continue;
149
+ const n = kind === "out" ? outlets(b) : inlets(b), w = width(b);
150
+ const dy = kind === "out" ? p.y - (b.y + H) : b.y - p.y;
151
+ if (!n || dy < -4 || dy > REACH + 2 || p.x < b.x - REACH || p.x > b.x + w + REACH) continue;
152
+ for (let k = 0; k < n; k++) {
153
+ const dx = Math.abs(p.x - (portX(b, k, n) + PORT / 2));
154
+ if (dx > PORT / 2 + REACH) continue;
155
+ const d = dx * dx + dy * dy;
156
+ if (!best || d < best[0]) best = [d, [b.id, k]];
157
+ }
158
+ }
159
+ return best && best[1];
160
+ }
161
+ let hot = null, target = null;
162
+ const same = (a, b) => (a && b ? a[0] === b[0] && a[1] === b[1] : a === b);
163
+ const kindOf = (b) => { const u = unitOf(b); return b.type === "'" ? "mem" : u.kind === "io" ? "io" : u.kind === "ui" ? "ui" : u.kind === "code" ? "code" : ""; };
164
+ function render() {
165
+ const W = Math.max(canvas.clientWidth - 2, ...graph.boxes.map((b) => b.x + width(b) + 40));
166
+ const Hh = Math.max(canvas.clientHeight - 2, ...graph.boxes.map((b) => b.y + H + 60));
167
+ svg.setAttribute("width", W); svg.setAttribute("height", Hh);
168
+ svg.innerHTML = "";
169
+ const byId = new Map(graph.boxes.map((b) => [b.id, b]));
170
+ const wiresG = el("g", {}, svg);
171
+ graph.wires.forEach((w, wi) => {
172
+ const a = byId.get(w.from[0]), b = byId.get(w.to[0]);
173
+ if (!a || !b) return;
174
+ const x1 = portX(a, w.from[1], outlets(a)) + PORT / 2, y1 = a.y + H, x2 = portX(b, w.to[1], inlets(b)) + PORT / 2, y2 = b.y;
175
+ const d = wireD(x1, y1, x2, y2);
176
+ el("path", { d, class: "wire" + (sel && sel.wire === wi ? " sel" : "") }, wiresG);
177
+ el("path", { d, class: "wire-hit", "data-wire": wi }, wiresG);
178
+ });
179
+ for (const b of graph.boxes) {
180
+ const g = el("g", { class: "b " + kindOf(b) + (sel && sel.box === b.id ? " sel" : ""), "data-id": b.id }, svg);
181
+ el("rect", { class: "body", x: b.x, y: b.y, width: width(b), height: H, rx: 3 }, g);
182
+ el("text", { x: b.x + 10, y: b.y + 16 }, g).textContent = boxText(b);
183
+ const ni = inlets(b), no = outlets(b);
184
+ for (let i = 0; i < ni; i++) el("rect", { class: "port in" + (same(target, [b.id, i]) ? " target" : ""), x: portX(b, i, ni), y: b.y - 1, width: PORT, height: 4 }, g);
185
+ for (let i = 0; i < no; i++) el("rect", { class: "port out" + (same(hot, [b.id, i]) ? " hot" : ""), "data-box": b.id, "data-out": i, x: portX(b, i, no), y: b.y + H - 3, width: PORT, height: 4 }, g);
186
+ }
187
+ }
188
+ function info() {
189
+ const b = sel && sel.box !== undefined && graph.boxes.find((x) => x.id === sel.box);
190
+ infoEl.title = "";
191
+ if (!b) {
192
+ infoEl.innerHTML = sel && sel.wire !== undefined ? "a wire · <b>Delete</b> removes it"
193
+ : `${graph.boxes.length} boxes · ${graph.wires.length} wires · <b>double-click</b>: a box · drag outlet → inlet · <b>Delete</b>`;
194
+ return;
195
+ }
196
+ const line = current.split("\n").find((l) => new RegExp("^\\s*" + b.name + "(\\(|\\s*=)").test(l));
197
+ infoEl.innerHTML = `<b>${esc(boxText(b))}</b> — ${esc(unitOf(b).doc || "")}${line ? " · " + esc(line.trim()) : ""}`;
198
+ infoEl.title = boxText(b) + " — " + (unitOf(b).doc || "") + (line ? "\n" + line.trim() : "");
199
+ }
200
+ // the selected box in sight (a box written near the edge, or found by its code)
201
+ function reveal() {
202
+ const b = sel && sel.box !== undefined && graph.boxes.find((x) => x.id === sel.box);
203
+ if (!b) return;
204
+ const pad = 12, w = width(b);
205
+ if (b.x - pad < canvas.scrollLeft) canvas.scrollLeft = Math.max(0, b.x - pad);
206
+ else if (b.x + w + pad > canvas.scrollLeft + canvas.clientWidth) canvas.scrollLeft = b.x + w + pad - canvas.clientWidth;
207
+ if (b.y - pad < canvas.scrollTop) canvas.scrollTop = Math.max(0, b.y - pad);
208
+ else if (b.y + H + pad > canvas.scrollTop + canvas.clientHeight) canvas.scrollTop = b.y + H + pad - canvas.clientHeight;
209
+ }
210
+
211
+ // ── gestures ──
212
+ let drag = null, lastDown = { t: 0, x: 0, y: 0 }, editing = null;
213
+ const pt = (e) => { const r = svg.getBoundingClientRect(); return { x: e.clientX - r.left, y: e.clientY - r.top }; };
214
+ const boxAt = (p) => [...graph.boxes].reverse().find((b) => p.x >= b.x - 2 && p.x <= b.x + width(b) + 2 && p.y >= b.y - 4 && p.y <= b.y + H + 4);
215
+ const nearest = (b, n, x) => { let k = 0, best = 1e9; for (let i = 0; i < n; i++) { const d = Math.abs(portX(b, i, n) + PORT / 2 - x); if (d < best) { best = d; k = i; } } return k; };
216
+ svg.addEventListener("pointerdown", (e) => {
217
+ if (editing) return;
218
+ const p = pt(e);
219
+ const hit = e.target.closest && e.target.closest(".wire-hit");
220
+ if (hit) { sel = { wire: +hit.getAttribute("data-wire") }; canvas.focus({ preventScroll: true }); render(); info(); return; }
221
+ const b = boxAt(p);
222
+ // a double-click, told by hand: the view is redrawn on every press, so the browser never sees two clicks on one element
223
+ const now = performance.now(), dbl = now - lastDown.t < 400 && Math.abs(p.x - lastDown.x) < 6 && Math.abs(p.y - lastDown.y) < 6;
224
+ lastDown = dbl ? { t: 0, x: 0, y: 0 } : { t: now, x: p.x, y: p.y };
225
+ if (dbl) { e.preventDefault(); edit(b, b ? b.x : p.x, b ? b.y : p.y); return; }
226
+ canvas.focus({ preventScroll: true });
227
+ // an outlet within reach of the pointer (not only right on it) starts a wire
228
+ const out = portNear("out", p);
229
+ if (out) {
230
+ const ob = graph.boxes.find((x) => x.id === out[0]), no = outlets(ob);
231
+ drag = { wire: out, x0: portX(ob, out[1], no) + PORT / 2, y0: ob.y + H };
232
+ canvas.classList.add("wiring");
233
+ svg.setPointerCapture(e.pointerId);
234
+ e.preventDefault();
235
+ return;
236
+ }
237
+ if (!b) { sel = null; render(); info(); return; }
238
+ drag = { box: b, dx: p.x - b.x, dy: p.y - b.y, moved: false };
239
+ sel = { box: b.id };
240
+ svg.setPointerCapture(e.pointerId);
241
+ render(); info();
242
+ });
243
+ // where a wire would land: the box under the pointer and its nearest inlet, or an inlet within reach above a box
244
+ function dropAt(p, from) {
245
+ const b = boxAt(p);
246
+ if (b && b.id !== from && inlets(b)) return [b.id, nearest(b, inlets(b), p.x)];
247
+ return portNear("in", p, from);
248
+ }
249
+ // the outlet within reach lights up, and the pointer becomes a cross: press there to wire
250
+ function hover(p) {
251
+ const h = editing ? null : portNear("out", p);
252
+ if (same(h, hot)) return;
253
+ const elOf = (q) => q && svg.querySelector(`.port.out[data-box="${q[0]}"][data-out="${q[1]}"]`);
254
+ const o = elOf(hot), n = elOf(h);
255
+ if (o) o.classList.remove("hot");
256
+ if (n) n.classList.add("hot");
257
+ canvas.classList.toggle("near-out", !!h);
258
+ hot = h;
259
+ }
260
+ svg.addEventListener("pointermove", (e) => {
261
+ const p = pt(e);
262
+ if (!drag) { hover(p); return; }
263
+ if (drag.box) { drag.box.x = Math.max(0, Math.round(p.x - drag.dx)); drag.box.y = Math.max(0, Math.round(p.y - drag.dy)); drag.moved = true; render(); }
264
+ else {
265
+ target = dropAt(p, drag.wire[0]);
266
+ render();
267
+ el("path", { class: "wire temp", d: wireD(drag.x0, drag.y0, p.x, p.y) }, svg);
268
+ }
269
+ });
270
+ svg.addEventListener("pointerleave", () => { if (!drag) hover({ x: -1e6, y: -1e6 }); });
271
+ svg.addEventListener("pointerup", (e) => {
272
+ if (!drag) return;
273
+ const p = pt(e), d = drag;
274
+ drag = null;
275
+ if (d.box) { if (d.moved) changed(); return; }
276
+ canvas.classList.remove("wiring");
277
+ target = null;
278
+ const t = dropAt(p, d.wire[0]);
279
+ if (t && !graph.wires.some((w) => w.from[0] === d.wire[0] && w.from[1] === d.wire[1] && w.to[0] === t[0] && w.to[1] === t[1])) {
280
+ graph.wires.push({ from: d.wire, to: t });
281
+ sel = { box: t[0] };
282
+ changed();
283
+ return;
284
+ }
285
+ render();
286
+ });
287
+ canvas.addEventListener("keydown", (e) => {
288
+ if (editing || !sel || !(e.key === "Delete" || e.key === "Backspace")) return;
289
+ e.preventDefault();
290
+ if (sel.wire !== undefined) graph.wires.splice(sel.wire, 1);
291
+ else if (sel.box !== undefined) {
292
+ graph.boxes = graph.boxes.filter((b) => b.id !== sel.box);
293
+ graph.wires = graph.wires.filter((w) => w.from[0] !== sel.box && w.to[0] !== sel.box);
294
+ }
295
+ sel = null;
296
+ changed();
297
+ });
298
+ function edit(b, x, y) {
299
+ if (editing) editing.remove();
300
+ const inp = document.createElement("input");
301
+ inp.className = "fu-editor";
302
+ inp.setAttribute("list", "faust-units-names");
303
+ inp.setAttribute("aria-label", b ? "Change the box" : "A new box");
304
+ inp.value = b ? boxText(b) : "";
305
+ inp.placeholder = "os.osc 440 · + 0.5 · hslider freq 440 20 2000 1 · '";
306
+ inp.style.left = x + "px"; inp.style.top = (y - 2) + "px";
307
+ canvas.appendChild(inp);
308
+ editing = inp;
309
+ inp.focus(); inp.select();
310
+ let done = false;
311
+ const finish = async (ok) => {
312
+ if (done) return; done = true;
313
+ const text = inp.value.trim();
314
+ inp.remove(); editing = null;
315
+ canvas.focus({ preventScroll: true });
316
+ if (!ok || !text) return;
317
+ const r = readBox(text);
318
+ let io;
319
+ if (r.type === "faust") {
320
+ io = await arityOf(r.args[0]);
321
+ if (!io) { sync("bad", "the compiler does not understand: " + r.args[0]); return; }
322
+ }
323
+ if (b) {
324
+ b.type = r.type; b.args = r.args;
325
+ if (io) b.io = io; else delete b.io;
326
+ delete b.name; name(graph, b);
327
+ graph.wires = graph.wires.filter((w) => !(w.to[0] === b.id && w.to[1] >= inlets(b)) && !(w.from[0] === b.id && w.from[1] >= outlets(b)));
328
+ } else {
329
+ if ((r.type === "in" || r.type === "out") && !r.args.length) r.args = [graph.boxes.filter((q) => q.type === r.type).length + 1];
330
+ if (UNITS[r.type] && UNITS[r.type].kind === "ui" && !r.args.length) r.args = UNITS[r.type].defs.slice();
331
+ const nb = newBox(graph, r.type, r.args, Math.round(x), Math.round(y), io ? { io } : {});
332
+ sel = { box: nb.id };
333
+ }
334
+ changed();
335
+ };
336
+ inp.addEventListener("keydown", (e) => { e.stopPropagation(); if (e.key === "Enter") finish(true); if (e.key === "Escape") finish(false); });
337
+ inp.addEventListener("blur", () => finish(true));
338
+ }
339
+
340
+ const ro = typeof ResizeObserver === "function" ? new ResizeObserver(() => render()) : null;
341
+ if (ro) ro.observe(canvas);
342
+ sync("ok", "reading the code…");
343
+ read(code);
344
+ return {
345
+ setCode,
346
+ graph: () => graph,
347
+ focus: () => canvas.focus({ preventScroll: true }),
348
+ destroy() { alive = false; clearTimeout(timer); if (ro) ro.disconnect(); host.innerHTML = ""; }
349
+ };
350
+ }
351
+
352
+ // what api/import-module gives the page (it takes a module's default export)
353
+ export default { mount };
@@ -0,0 +1,9 @@
1
+ // Generated by packages/build.mjs
2
+ export default {
3
+ "package": "@kairotic/faust-units",
4
+ "version": "0.1.5",
5
+ "api": 1,
6
+ "author": "bonuoq",
7
+ "license": "MPL-2.0",
8
+ "components": []
9
+ };